3
0

hush.c 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * sh.c -- a prototype Bourne shell grammar parser
  4. * Intended to follow the original Thompson and Ritchie
  5. * "small and simple is beautiful" philosophy, which
  6. * incidentally is a good match to today's BusyBox.
  7. *
  8. * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
  9. *
  10. * Credits:
  11. * The parser routines proper are all original material, first
  12. * written Dec 2000 and Jan 2001 by Larry Doolittle. The
  13. * execution engine, the builtins, and much of the underlying
  14. * support has been adapted from busybox-0.49pre's lash, which is
  15. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  16. * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
  17. * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
  18. * Troan, which they placed in the public domain. I don't know
  19. * how much of the Johnson/Troan code has survived the repeated
  20. * rewrites.
  21. *
  22. * Other credits:
  23. * simple_itoa() was lifted from boa-0.93.15
  24. * b_addchr() derived from similar w_addchar function in glibc-2.2
  25. * setup_redirect(), redirect_opt_num(), and big chunks of main()
  26. * and many builtins derived from contributions by Erik Andersen
  27. * miscellaneous bugfixes from Matt Kraai
  28. *
  29. * There are two big (and related) architecture differences between
  30. * this parser and the lash parser. One is that this version is
  31. * actually designed from the ground up to understand nearly all
  32. * of the Bourne grammar. The second, consequential change is that
  33. * the parser and input reader have been turned inside out. Now,
  34. * the parser is in control, and asks for input as needed. The old
  35. * way had the input reader in control, and it asked for parsing to
  36. * take place as needed. The new way makes it much easier to properly
  37. * handle the recursion implicit in the various substitutions, especially
  38. * across continuation lines.
  39. *
  40. * Bash grammar not implemented: (how many of these were in original sh?)
  41. * $@ (those sure look like weird quoting rules)
  42. * $_
  43. * ! negation operator for pipes
  44. * &> and >& redirection of stdout+stderr
  45. * Brace Expansion
  46. * Tilde Expansion
  47. * fancy forms of Parameter Expansion
  48. * aliases
  49. * Arithmetic Expansion
  50. * <(list) and >(list) Process Substitution
  51. * reserved words: case, esac, select, function
  52. * Here Documents ( << word )
  53. * Functions
  54. * Major bugs:
  55. * job handling woefully incomplete and buggy
  56. * reserved word execution woefully incomplete and buggy
  57. * to-do:
  58. * port selected bugfixes from post-0.49 busybox lash - done?
  59. * finish implementing reserved words: for, while, until, do, done
  60. * change { and } from special chars to reserved words
  61. * builtins: break, continue, eval, return, set, trap, ulimit
  62. * test magic exec
  63. * handle children going into background
  64. * clean up recognition of null pipes
  65. * check setting of global_argc and global_argv
  66. * control-C handling, probably with longjmp
  67. * follow IFS rules more precisely, including update semantics
  68. * figure out what to do with backslash-newline
  69. * explain why we use signal instead of sigaction
  70. * propagate syntax errors, die on resource errors?
  71. * continuation lines, both explicit and implicit - done?
  72. * memory leak finding and plugging - done?
  73. * more testing, especially quoting rules and redirection
  74. * document how quoting rules not precisely followed for variable assignments
  75. * maybe change map[] to use 2-bit entries
  76. * (eventually) remove all the printf's
  77. *
  78. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  79. */
  80. #include "busybox.h"
  81. #include <ctype.h> /* isalpha, isdigit */
  82. #include <unistd.h> /* getpid */
  83. #include <stdlib.h> /* getenv, atoi */
  84. #include <string.h> /* strchr */
  85. #include <stdio.h> /* popen etc. */
  86. #include <glob.h> /* glob, of course */
  87. #include <stdarg.h> /* va_list */
  88. #include <errno.h>
  89. #include <fcntl.h>
  90. #include <getopt.h> /* should be pretty obvious */
  91. #include <sys/stat.h> /* ulimit */
  92. #include <sys/types.h>
  93. #include <sys/wait.h>
  94. #include <signal.h>
  95. /* #include <dmalloc.h> */
  96. /* #define DEBUG_SHELL */
  97. #include "cmdedit.h"
  98. #define SPECIAL_VAR_SYMBOL 03
  99. #define FLAG_EXIT_FROM_LOOP 1
  100. #define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
  101. #define FLAG_REPARSING (1 << 2) /* >=2nd pass */
  102. typedef enum {
  103. REDIRECT_INPUT = 1,
  104. REDIRECT_OVERWRITE = 2,
  105. REDIRECT_APPEND = 3,
  106. REDIRECT_HEREIS = 4,
  107. REDIRECT_IO = 5
  108. } redir_type;
  109. /* The descrip member of this structure is only used to make debugging
  110. * output pretty */
  111. static const struct {int mode; int default_fd; const char *descrip;} redir_table[] = {
  112. { 0, 0, "()" },
  113. { O_RDONLY, 0, "<" },
  114. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  115. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  116. { O_RDONLY, -1, "<<" },
  117. { O_RDWR, 1, "<>" }
  118. };
  119. typedef enum {
  120. PIPE_SEQ = 1,
  121. PIPE_AND = 2,
  122. PIPE_OR = 3,
  123. PIPE_BG = 4,
  124. } pipe_style;
  125. /* might eventually control execution */
  126. typedef enum {
  127. RES_NONE = 0,
  128. RES_IF = 1,
  129. RES_THEN = 2,
  130. RES_ELIF = 3,
  131. RES_ELSE = 4,
  132. RES_FI = 5,
  133. RES_FOR = 6,
  134. RES_WHILE = 7,
  135. RES_UNTIL = 8,
  136. RES_DO = 9,
  137. RES_DONE = 10,
  138. RES_XXXX = 11,
  139. RES_IN = 12,
  140. RES_SNTX = 13
  141. } reserved_style;
  142. #define FLAG_END (1<<RES_NONE)
  143. #define FLAG_IF (1<<RES_IF)
  144. #define FLAG_THEN (1<<RES_THEN)
  145. #define FLAG_ELIF (1<<RES_ELIF)
  146. #define FLAG_ELSE (1<<RES_ELSE)
  147. #define FLAG_FI (1<<RES_FI)
  148. #define FLAG_FOR (1<<RES_FOR)
  149. #define FLAG_WHILE (1<<RES_WHILE)
  150. #define FLAG_UNTIL (1<<RES_UNTIL)
  151. #define FLAG_DO (1<<RES_DO)
  152. #define FLAG_DONE (1<<RES_DONE)
  153. #define FLAG_IN (1<<RES_IN)
  154. #define FLAG_START (1<<RES_XXXX)
  155. /* This holds pointers to the various results of parsing */
  156. struct p_context {
  157. struct child_prog *child;
  158. struct pipe *list_head;
  159. struct pipe *pipe;
  160. struct redir_struct *pending_redirect;
  161. reserved_style w;
  162. int old_flag; /* for figuring out valid reserved words */
  163. struct p_context *stack;
  164. int type; /* define type of parser : ";$" common or special symbol */
  165. /* How about quoting status? */
  166. };
  167. struct redir_struct {
  168. redir_type type; /* type of redirection */
  169. int fd; /* file descriptor being redirected */
  170. int dup; /* -1, or file descriptor being duplicated */
  171. struct redir_struct *next; /* pointer to the next redirect in the list */
  172. glob_t word; /* *word.gl_pathv is the filename */
  173. };
  174. struct child_prog {
  175. pid_t pid; /* 0 if exited */
  176. char **argv; /* program name and arguments */
  177. struct pipe *group; /* if non-NULL, first in group or subshell */
  178. int subshell; /* flag, non-zero if group must be forked */
  179. struct redir_struct *redirects; /* I/O redirections */
  180. glob_t glob_result; /* result of parameter globbing */
  181. int is_stopped; /* is the program currently running? */
  182. struct pipe *family; /* pointer back to the child's parent pipe */
  183. int sp; /* number of SPECIAL_VAR_SYMBOL */
  184. int type;
  185. };
  186. struct pipe {
  187. int jobid; /* job number */
  188. int num_progs; /* total number of programs in job */
  189. int running_progs; /* number of programs running */
  190. char *text; /* name of job */
  191. char *cmdbuf; /* buffer various argv's point into */
  192. pid_t pgrp; /* process group ID for the job */
  193. struct child_prog *progs; /* array of commands in pipe */
  194. struct pipe *next; /* to track background commands */
  195. int stopped_progs; /* number of programs alive, but stopped */
  196. int job_context; /* bitmask defining current context */
  197. pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  198. reserved_style r_mode; /* supports if, for, while, until */
  199. };
  200. struct close_me {
  201. int fd;
  202. struct close_me *next;
  203. };
  204. struct variables {
  205. char *name;
  206. char *value;
  207. int flg_export;
  208. int flg_read_only;
  209. struct variables *next;
  210. };
  211. /* globals, connect us to the outside world
  212. * the first three support $?, $#, and $1 */
  213. static char **global_argv;
  214. static int global_argc;
  215. static int last_return_code;
  216. extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
  217. /* "globals" within this file */
  218. static char *ifs;
  219. static unsigned char map[256];
  220. static int fake_mode;
  221. static int interactive;
  222. static struct close_me *close_me_head;
  223. static const char *cwd;
  224. static struct pipe *job_list;
  225. static unsigned int last_bg_pid;
  226. static int last_jobid;
  227. static unsigned int shell_terminal;
  228. static char *PS1;
  229. static char *PS2;
  230. static struct variables shell_ver = { "HUSH_VERSION", "0.01", 1, 1, 0 };
  231. static struct variables *top_vars = &shell_ver;
  232. #define B_CHUNK (100)
  233. #define B_NOSPAC 1
  234. typedef struct {
  235. char *data;
  236. int length;
  237. int maxlen;
  238. int quote;
  239. int nonnull;
  240. } o_string;
  241. #define NULL_O_STRING {NULL,0,0,0,0}
  242. /* used for initialization:
  243. o_string foo = NULL_O_STRING; */
  244. /* I can almost use ordinary FILE *. Is open_memstream() universally
  245. * available? Where is it documented? */
  246. struct in_str {
  247. const char *p;
  248. char peek_buf[2];
  249. int __promptme;
  250. int promptmode;
  251. FILE *file;
  252. int (*get) (struct in_str *);
  253. int (*peek) (struct in_str *);
  254. };
  255. #define b_getch(input) ((input)->get(input))
  256. #define b_peek(input) ((input)->peek(input))
  257. #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
  258. struct built_in_command {
  259. const char *cmd; /* name */
  260. const char *descr; /* description */
  261. int (*function) (struct child_prog *); /* function ptr */
  262. };
  263. /* belongs in busybox.h */
  264. static int max(int a, int b) {
  265. return (a>b)?a:b;
  266. }
  267. /* This should be in utility.c */
  268. #ifdef DEBUG_SHELL
  269. static void debug_printf(const char *format, ...)
  270. {
  271. va_list args;
  272. va_start(args, format);
  273. vfprintf(stderr, format, args);
  274. va_end(args);
  275. }
  276. /* broken, of course, but OK for testing */
  277. static char *indenter(int i)
  278. {
  279. static char blanks[]=" ";
  280. return &blanks[sizeof(blanks)-i-1];
  281. }
  282. #else
  283. #define debug_printf(...) do {;} while(0);
  284. #endif
  285. #define final_printf debug_printf
  286. static void __syntax(char *file, int line) {
  287. bb_error_msg("syntax error %s:%d", file, line);
  288. }
  289. // NB: was __FILE__, but that produces full path sometimess, so...
  290. #define syntax() __syntax("hush.c", __LINE__)
  291. /* Index of subroutines: */
  292. /* function prototypes for builtins */
  293. static int builtin_cd(struct child_prog *child);
  294. static int builtin_env(struct child_prog *child);
  295. static int builtin_eval(struct child_prog *child);
  296. static int builtin_exec(struct child_prog *child);
  297. static int builtin_exit(struct child_prog *child);
  298. static int builtin_export(struct child_prog *child);
  299. static int builtin_fg_bg(struct child_prog *child);
  300. static int builtin_help(struct child_prog *child);
  301. static int builtin_jobs(struct child_prog *child);
  302. static int builtin_pwd(struct child_prog *child);
  303. static int builtin_read(struct child_prog *child);
  304. static int builtin_set(struct child_prog *child);
  305. static int builtin_shift(struct child_prog *child);
  306. static int builtin_source(struct child_prog *child);
  307. static int builtin_umask(struct child_prog *child);
  308. static int builtin_unset(struct child_prog *child);
  309. static int builtin_not_written(struct child_prog *child);
  310. /* o_string manipulation: */
  311. static int b_check_space(o_string *o, int len);
  312. static int b_addchr(o_string *o, int ch);
  313. static void b_reset(o_string *o);
  314. static int b_addqchr(o_string *o, int ch, int quote);
  315. static int b_adduint(o_string *o, unsigned int i);
  316. /* in_str manipulations: */
  317. static int static_get(struct in_str *i);
  318. static int static_peek(struct in_str *i);
  319. static int file_get(struct in_str *i);
  320. static int file_peek(struct in_str *i);
  321. static void setup_file_in_str(struct in_str *i, FILE *f);
  322. static void setup_string_in_str(struct in_str *i, const char *s);
  323. /* close_me manipulations: */
  324. static void mark_open(int fd);
  325. static void mark_closed(int fd);
  326. static void close_all(void);
  327. /* "run" the final data structures: */
  328. static int free_pipe_list(struct pipe *head, int indent);
  329. static int free_pipe(struct pipe *pi, int indent);
  330. /* really run the final data structures: */
  331. static int setup_redirects(struct child_prog *prog, int squirrel[]);
  332. static int run_list_real(struct pipe *pi);
  333. static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
  334. static int run_pipe_real(struct pipe *pi);
  335. /* extended glob support: */
  336. static int globhack(const char *src, int flags, glob_t *pglob);
  337. static int glob_needed(const char *s);
  338. static int xglob(o_string *dest, int flags, glob_t *pglob);
  339. /* variable assignment: */
  340. static int is_assignment(const char *s);
  341. /* data structure manipulation: */
  342. static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
  343. static void initialize_context(struct p_context *ctx);
  344. static int done_word(o_string *dest, struct p_context *ctx);
  345. static int done_command(struct p_context *ctx);
  346. static int done_pipe(struct p_context *ctx, pipe_style type);
  347. /* primary string parsing: */
  348. static int redirect_dup_num(struct in_str *input);
  349. static int redirect_opt_num(o_string *o);
  350. static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
  351. static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
  352. static char *lookup_param(char *src);
  353. static char *make_string(char **inp);
  354. static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
  355. static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
  356. static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
  357. /* setup: */
  358. static int parse_stream_outer(struct in_str *inp, int flag);
  359. static int parse_string_outer(const char *s, int flag);
  360. static int parse_file_outer(FILE *f);
  361. /* job management: */
  362. static int checkjobs(struct pipe* fg_pipe);
  363. static void insert_bg_job(struct pipe *pi);
  364. static void remove_bg_job(struct pipe *pi);
  365. /* local variable support */
  366. static char **make_list_in(char **inp, char *name);
  367. static char *insert_var_value(char *inp);
  368. static char *get_local_var(const char *var);
  369. static void unset_local_var(const char *name);
  370. static int set_local_var(const char *s, int flg_export);
  371. /* Table of built-in functions. They can be forked or not, depending on
  372. * context: within pipes, they fork. As simple commands, they do not.
  373. * When used in non-forking context, they can change global variables
  374. * in the parent shell process. If forked, of course they cannot.
  375. * For example, 'unset foo | whatever' will parse and run, but foo will
  376. * still be set at the end. */
  377. static const struct built_in_command bltins[] = {
  378. {"bg", "Resume a job in the background", builtin_fg_bg},
  379. {"break", "Exit for, while or until loop", builtin_not_written},
  380. {"cd", "Change working directory", builtin_cd},
  381. {"continue", "Continue for, while or until loop", builtin_not_written},
  382. {"env", "Print all environment variables", builtin_env},
  383. {"eval", "Construct and run shell command", builtin_eval},
  384. {"exec", "Exec command, replacing this shell with the exec'd process",
  385. builtin_exec},
  386. {"exit", "Exit from shell()", builtin_exit},
  387. {"export", "Set environment variable", builtin_export},
  388. {"fg", "Bring job into the foreground", builtin_fg_bg},
  389. {"jobs", "Lists the active jobs", builtin_jobs},
  390. {"pwd", "Print current directory", builtin_pwd},
  391. {"read", "Input environment variable", builtin_read},
  392. {"return", "Return from a function", builtin_not_written},
  393. {"set", "Set/unset shell local variables", builtin_set},
  394. {"shift", "Shift positional parameters", builtin_shift},
  395. {"trap", "Trap signals", builtin_not_written},
  396. {"ulimit","Controls resource limits", builtin_not_written},
  397. {"umask","Sets file creation mask", builtin_umask},
  398. {"unset", "Unset environment variable", builtin_unset},
  399. {".", "Source-in and run commands in a file", builtin_source},
  400. {"help", "List shell built-in commands", builtin_help},
  401. {NULL, NULL, NULL}
  402. };
  403. static const char *set_cwd(void)
  404. {
  405. if(cwd==bb_msg_unknown)
  406. cwd = NULL; /* xgetcwd(arg) called free(arg) */
  407. cwd = xgetcwd((char *)cwd);
  408. if (!cwd)
  409. cwd = bb_msg_unknown;
  410. return cwd;
  411. }
  412. /* built-in 'eval' handler */
  413. static int builtin_eval(struct child_prog *child)
  414. {
  415. char *str = NULL;
  416. int rcode = EXIT_SUCCESS;
  417. if (child->argv[1]) {
  418. str = make_string(child->argv + 1);
  419. parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
  420. FLAG_PARSE_SEMICOLON);
  421. free(str);
  422. rcode = last_return_code;
  423. }
  424. return rcode;
  425. }
  426. /* built-in 'cd <path>' handler */
  427. static int builtin_cd(struct child_prog *child)
  428. {
  429. char *newdir;
  430. if (child->argv[1] == NULL)
  431. newdir = getenv("HOME");
  432. else
  433. newdir = child->argv[1];
  434. if (chdir(newdir)) {
  435. printf("cd: %s: %s\n", newdir, strerror(errno));
  436. return EXIT_FAILURE;
  437. }
  438. set_cwd();
  439. return EXIT_SUCCESS;
  440. }
  441. /* built-in 'env' handler */
  442. static int builtin_env(struct child_prog *dummy ATTRIBUTE_UNUSED)
  443. {
  444. char **e = environ;
  445. if (e == NULL) return EXIT_FAILURE;
  446. for (; *e; e++) {
  447. puts(*e);
  448. }
  449. return EXIT_SUCCESS;
  450. }
  451. /* built-in 'exec' handler */
  452. static int builtin_exec(struct child_prog *child)
  453. {
  454. if (child->argv[1] == NULL)
  455. return EXIT_SUCCESS; /* Really? */
  456. child->argv++;
  457. pseudo_exec(child);
  458. /* never returns */
  459. }
  460. /* built-in 'exit' handler */
  461. static int builtin_exit(struct child_prog *child)
  462. {
  463. if (child->argv[1] == NULL)
  464. exit(last_return_code);
  465. exit (atoi(child->argv[1]));
  466. }
  467. /* built-in 'export VAR=value' handler */
  468. static int builtin_export(struct child_prog *child)
  469. {
  470. int res = 0;
  471. char *name = child->argv[1];
  472. if (name == NULL) {
  473. return builtin_env(child);
  474. }
  475. name = strdup(name);
  476. if(name) {
  477. char *value = strchr(name, '=');
  478. if (!value) {
  479. char *tmp;
  480. /* They are exporting something without an =VALUE */
  481. value = get_local_var(name);
  482. if (value) {
  483. size_t ln = strlen(name);
  484. tmp = realloc(name, ln+strlen(value)+2);
  485. if(tmp==NULL)
  486. res = -1;
  487. else {
  488. sprintf(tmp+ln, "=%s", value);
  489. name = tmp;
  490. }
  491. } else {
  492. /* bash does not return an error when trying to export
  493. * an undefined variable. Do likewise. */
  494. res = 1;
  495. }
  496. }
  497. }
  498. if (res<0)
  499. bb_perror_msg("export");
  500. else if(res==0)
  501. res = set_local_var(name, 1);
  502. else
  503. res = 0;
  504. free(name);
  505. return res;
  506. }
  507. /* built-in 'fg' and 'bg' handler */
  508. static int builtin_fg_bg(struct child_prog *child)
  509. {
  510. int i, jobnum;
  511. struct pipe *pi=NULL;
  512. if (!interactive)
  513. return EXIT_FAILURE;
  514. /* If they gave us no args, assume they want the last backgrounded task */
  515. if (!child->argv[1]) {
  516. for (pi = job_list; pi; pi = pi->next) {
  517. if (pi->jobid == last_jobid) {
  518. break;
  519. }
  520. }
  521. if (!pi) {
  522. bb_error_msg("%s: no current job", child->argv[0]);
  523. return EXIT_FAILURE;
  524. }
  525. } else {
  526. if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) {
  527. bb_error_msg("%s: bad argument '%s'", child->argv[0], child->argv[1]);
  528. return EXIT_FAILURE;
  529. }
  530. for (pi = job_list; pi; pi = pi->next) {
  531. if (pi->jobid == jobnum) {
  532. break;
  533. }
  534. }
  535. if (!pi) {
  536. bb_error_msg("%s: %d: no such job", child->argv[0], jobnum);
  537. return EXIT_FAILURE;
  538. }
  539. }
  540. if (*child->argv[0] == 'f') {
  541. /* Put the job into the foreground. */
  542. tcsetpgrp(shell_terminal, pi->pgrp);
  543. }
  544. /* Restart the processes in the job */
  545. for (i = 0; i < pi->num_progs; i++)
  546. pi->progs[i].is_stopped = 0;
  547. if ( (i=kill(- pi->pgrp, SIGCONT)) < 0) {
  548. if (i == ESRCH) {
  549. remove_bg_job(pi);
  550. } else {
  551. bb_perror_msg("kill (SIGCONT)");
  552. }
  553. }
  554. pi->stopped_progs = 0;
  555. return EXIT_SUCCESS;
  556. }
  557. /* built-in 'help' handler */
  558. static int builtin_help(struct child_prog *dummy ATTRIBUTE_UNUSED)
  559. {
  560. const struct built_in_command *x;
  561. printf("\nBuilt-in commands:\n");
  562. printf("-------------------\n");
  563. for (x = bltins; x->cmd; x++) {
  564. if (x->descr==NULL)
  565. continue;
  566. printf("%s\t%s\n", x->cmd, x->descr);
  567. }
  568. printf("\n\n");
  569. return EXIT_SUCCESS;
  570. }
  571. /* built-in 'jobs' handler */
  572. static int builtin_jobs(struct child_prog *child ATTRIBUTE_UNUSED)
  573. {
  574. struct pipe *job;
  575. char *status_string;
  576. for (job = job_list; job; job = job->next) {
  577. if (job->running_progs == job->stopped_progs)
  578. status_string = "Stopped";
  579. else
  580. status_string = "Running";
  581. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
  582. }
  583. return EXIT_SUCCESS;
  584. }
  585. /* built-in 'pwd' handler */
  586. static int builtin_pwd(struct child_prog *dummy ATTRIBUTE_UNUSED)
  587. {
  588. puts(set_cwd());
  589. return EXIT_SUCCESS;
  590. }
  591. /* built-in 'read VAR' handler */
  592. static int builtin_read(struct child_prog *child)
  593. {
  594. int res;
  595. if (child->argv[1]) {
  596. char string[BUFSIZ];
  597. char *var = 0;
  598. string[0] = 0; /* In case stdin has only EOF */
  599. /* read string */
  600. fgets(string, sizeof(string), stdin);
  601. chomp(string);
  602. var = malloc(strlen(child->argv[1])+strlen(string)+2);
  603. if(var) {
  604. sprintf(var, "%s=%s", child->argv[1], string);
  605. res = set_local_var(var, 0);
  606. } else
  607. res = -1;
  608. if (res)
  609. bb_perror_msg("read");
  610. free(var); /* So not move up to avoid breaking errno */
  611. return res;
  612. } else {
  613. do res=getchar(); while(res!='\n' && res!=EOF);
  614. return 0;
  615. }
  616. }
  617. /* built-in 'set VAR=value' handler */
  618. static int builtin_set(struct child_prog *child)
  619. {
  620. char *temp = child->argv[1];
  621. struct variables *e;
  622. if (temp == NULL)
  623. for(e = top_vars; e; e=e->next)
  624. printf("%s=%s\n", e->name, e->value);
  625. else
  626. set_local_var(temp, 0);
  627. return EXIT_SUCCESS;
  628. }
  629. /* Built-in 'shift' handler */
  630. static int builtin_shift(struct child_prog *child)
  631. {
  632. int n=1;
  633. if (child->argv[1]) {
  634. n=atoi(child->argv[1]);
  635. }
  636. if (n>=0 && n<global_argc) {
  637. /* XXX This probably breaks $0 */
  638. global_argc -= n;
  639. global_argv += n;
  640. return EXIT_SUCCESS;
  641. } else {
  642. return EXIT_FAILURE;
  643. }
  644. }
  645. /* Built-in '.' handler (read-in and execute commands from file) */
  646. static int builtin_source(struct child_prog *child)
  647. {
  648. FILE *input;
  649. int status;
  650. if (child->argv[1] == NULL)
  651. return EXIT_FAILURE;
  652. /* XXX search through $PATH is missing */
  653. input = fopen(child->argv[1], "r");
  654. if (!input) {
  655. bb_error_msg("cannot open '%s'", child->argv[1]);
  656. return EXIT_FAILURE;
  657. }
  658. /* Now run the file */
  659. /* XXX argv and argc are broken; need to save old global_argv
  660. * (pointer only is OK!) on this stack frame,
  661. * set global_argv=child->argv+1, recurse, and restore. */
  662. mark_open(fileno(input));
  663. status = parse_file_outer(input);
  664. mark_closed(fileno(input));
  665. fclose(input);
  666. return status;
  667. }
  668. static int builtin_umask(struct child_prog *child)
  669. {
  670. mode_t new_umask;
  671. const char *arg = child->argv[1];
  672. char *end;
  673. if (arg) {
  674. new_umask=strtoul(arg, &end, 8);
  675. if (*end!='\0' || end == arg) {
  676. return EXIT_FAILURE;
  677. }
  678. } else {
  679. printf("%.3o\n", (unsigned int) (new_umask=umask(0)));
  680. }
  681. umask(new_umask);
  682. return EXIT_SUCCESS;
  683. }
  684. /* built-in 'unset VAR' handler */
  685. static int builtin_unset(struct child_prog *child)
  686. {
  687. /* bash returned already true */
  688. unset_local_var(child->argv[1]);
  689. return EXIT_SUCCESS;
  690. }
  691. static int builtin_not_written(struct child_prog *child)
  692. {
  693. printf("builtin_%s not written\n",child->argv[0]);
  694. return EXIT_FAILURE;
  695. }
  696. static int b_check_space(o_string *o, int len)
  697. {
  698. /* It would be easy to drop a more restrictive policy
  699. * in here, such as setting a maximum string length */
  700. if (o->length + len > o->maxlen) {
  701. char *old_data = o->data;
  702. /* assert (data == NULL || o->maxlen != 0); */
  703. o->maxlen += max(2*len, B_CHUNK);
  704. o->data = realloc(o->data, 1 + o->maxlen);
  705. if (o->data == NULL) {
  706. free(old_data);
  707. }
  708. }
  709. return o->data == NULL;
  710. }
  711. static int b_addchr(o_string *o, int ch)
  712. {
  713. debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
  714. if (b_check_space(o, 1)) return B_NOSPAC;
  715. o->data[o->length] = ch;
  716. o->length++;
  717. o->data[o->length] = '\0';
  718. return 0;
  719. }
  720. static void b_reset(o_string *o)
  721. {
  722. o->length = 0;
  723. o->nonnull = 0;
  724. if (o->data != NULL) *o->data = '\0';
  725. }
  726. static void b_free(o_string *o)
  727. {
  728. b_reset(o);
  729. free(o->data);
  730. o->data = NULL;
  731. o->maxlen = 0;
  732. }
  733. /* My analysis of quoting semantics tells me that state information
  734. * is associated with a destination, not a source.
  735. */
  736. static int b_addqchr(o_string *o, int ch, int quote)
  737. {
  738. if (quote && strchr("*?[\\",ch)) {
  739. int rc;
  740. rc = b_addchr(o, '\\');
  741. if (rc) return rc;
  742. }
  743. return b_addchr(o, ch);
  744. }
  745. /* belongs in utility.c */
  746. static char *simple_itoa(unsigned int i)
  747. {
  748. /* 21 digits plus null terminator, good for 64-bit or smaller ints */
  749. static char local[22];
  750. char *p = &local[21];
  751. *p-- = '\0';
  752. do {
  753. *p-- = '0' + i % 10;
  754. i /= 10;
  755. } while (i > 0);
  756. return p + 1;
  757. }
  758. static int b_adduint(o_string *o, unsigned int i)
  759. {
  760. int r;
  761. char *p = simple_itoa(i);
  762. /* no escape checking necessary */
  763. do r=b_addchr(o, *p++); while (r==0 && *p);
  764. return r;
  765. }
  766. static int static_get(struct in_str *i)
  767. {
  768. int ch=*i->p++;
  769. if (ch=='\0') return EOF;
  770. return ch;
  771. }
  772. static int static_peek(struct in_str *i)
  773. {
  774. return *i->p;
  775. }
  776. static void cmdedit_set_initial_prompt(void)
  777. {
  778. #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
  779. PS1 = NULL;
  780. #else
  781. PS1 = getenv("PS1");
  782. if(PS1==0)
  783. PS1 = "\\w \\$ ";
  784. #endif
  785. }
  786. static void setup_prompt_string(int promptmode, char **prompt_str)
  787. {
  788. debug_printf("setup_prompt_string %d ",promptmode);
  789. #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
  790. /* Set up the prompt */
  791. if (promptmode == 1) {
  792. free(PS1);
  793. PS1=xmalloc(strlen(cwd)+4);
  794. sprintf(PS1, "%s %s", cwd, ( geteuid() != 0 ) ? "$ ":"# ");
  795. *prompt_str = PS1;
  796. } else {
  797. *prompt_str = PS2;
  798. }
  799. #else
  800. *prompt_str = (promptmode==1)? PS1 : PS2;
  801. #endif
  802. debug_printf("result %s\n",*prompt_str);
  803. }
  804. static void get_user_input(struct in_str *i)
  805. {
  806. char *prompt_str;
  807. static char the_command[BUFSIZ];
  808. setup_prompt_string(i->promptmode, &prompt_str);
  809. #ifdef CONFIG_FEATURE_COMMAND_EDITING
  810. /*
  811. ** enable command line editing only while a command line
  812. ** is actually being read; otherwise, we'll end up bequeathing
  813. ** atexit() handlers and other unwanted stuff to our
  814. ** child processes (rob@sysgo.de)
  815. */
  816. cmdedit_read_input(prompt_str, the_command);
  817. #else
  818. fputs(prompt_str, stdout);
  819. fflush(stdout);
  820. the_command[0]=fgetc(i->file);
  821. the_command[1]='\0';
  822. #endif
  823. fflush(stdout);
  824. i->p = the_command;
  825. }
  826. /* This is the magic location that prints prompts
  827. * and gets data back from the user */
  828. static int file_get(struct in_str *i)
  829. {
  830. int ch;
  831. ch = 0;
  832. /* If there is data waiting, eat it up */
  833. if (i->p && *i->p) {
  834. ch=*i->p++;
  835. } else {
  836. /* need to double check i->file because we might be doing something
  837. * more complicated by now, like sourcing or substituting. */
  838. if (i->__promptme && interactive && i->file == stdin) {
  839. while(! i->p || (interactive && strlen(i->p)==0) ) {
  840. get_user_input(i);
  841. }
  842. i->promptmode=2;
  843. i->__promptme = 0;
  844. if (i->p && *i->p) {
  845. ch=*i->p++;
  846. }
  847. } else {
  848. ch = fgetc(i->file);
  849. }
  850. debug_printf("b_getch: got a %d\n", ch);
  851. }
  852. if (ch == '\n') i->__promptme=1;
  853. return ch;
  854. }
  855. /* All the callers guarantee this routine will never be
  856. * used right after a newline, so prompting is not needed.
  857. */
  858. static int file_peek(struct in_str *i)
  859. {
  860. if (i->p && *i->p) {
  861. return *i->p;
  862. } else {
  863. i->peek_buf[0] = fgetc(i->file);
  864. i->peek_buf[1] = '\0';
  865. i->p = i->peek_buf;
  866. debug_printf("b_peek: got a %d\n", *i->p);
  867. return *i->p;
  868. }
  869. }
  870. static void setup_file_in_str(struct in_str *i, FILE *f)
  871. {
  872. i->peek = file_peek;
  873. i->get = file_get;
  874. i->__promptme=1;
  875. i->promptmode=1;
  876. i->file = f;
  877. i->p = NULL;
  878. }
  879. static void setup_string_in_str(struct in_str *i, const char *s)
  880. {
  881. i->peek = static_peek;
  882. i->get = static_get;
  883. i->__promptme=1;
  884. i->promptmode=1;
  885. i->p = s;
  886. }
  887. static void mark_open(int fd)
  888. {
  889. struct close_me *new = xmalloc(sizeof(struct close_me));
  890. new->fd = fd;
  891. new->next = close_me_head;
  892. close_me_head = new;
  893. }
  894. static void mark_closed(int fd)
  895. {
  896. struct close_me *tmp;
  897. if (close_me_head == NULL || close_me_head->fd != fd)
  898. bb_error_msg_and_die("corrupt close_me");
  899. tmp = close_me_head;
  900. close_me_head = close_me_head->next;
  901. free(tmp);
  902. }
  903. static void close_all(void)
  904. {
  905. struct close_me *c;
  906. for (c=close_me_head; c; c=c->next) {
  907. close(c->fd);
  908. }
  909. close_me_head = NULL;
  910. }
  911. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  912. * and stderr if they are redirected. */
  913. static int setup_redirects(struct child_prog *prog, int squirrel[])
  914. {
  915. int openfd, mode;
  916. struct redir_struct *redir;
  917. for (redir=prog->redirects; redir; redir=redir->next) {
  918. if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
  919. /* something went wrong in the parse. Pretend it didn't happen */
  920. continue;
  921. }
  922. if (redir->dup == -1) {
  923. mode=redir_table[redir->type].mode;
  924. openfd = open(redir->word.gl_pathv[0], mode, 0666);
  925. if (openfd < 0) {
  926. /* this could get lost if stderr has been redirected, but
  927. bash and ash both lose it as well (though zsh doesn't!) */
  928. bb_perror_msg("error opening %s", redir->word.gl_pathv[0]);
  929. return 1;
  930. }
  931. } else {
  932. openfd = redir->dup;
  933. }
  934. if (openfd != redir->fd) {
  935. if (squirrel && redir->fd < 3) {
  936. squirrel[redir->fd] = dup(redir->fd);
  937. }
  938. if (openfd == -3) {
  939. close(openfd);
  940. } else {
  941. dup2(openfd, redir->fd);
  942. if (redir->dup == -1)
  943. close (openfd);
  944. }
  945. }
  946. }
  947. return 0;
  948. }
  949. static void restore_redirects(int squirrel[])
  950. {
  951. int i, fd;
  952. for (i=0; i<3; i++) {
  953. fd = squirrel[i];
  954. if (fd != -1) {
  955. /* No error checking. I sure wouldn't know what
  956. * to do with an error if I found one! */
  957. dup2(fd, i);
  958. close(fd);
  959. }
  960. }
  961. }
  962. /* never returns */
  963. /* XXX no exit() here. If you don't exec, use _exit instead.
  964. * The at_exit handlers apparently confuse the calling process,
  965. * in particular stdin handling. Not sure why? */
  966. static void pseudo_exec(struct child_prog *child)
  967. {
  968. int i, rcode;
  969. char *p;
  970. const struct built_in_command *x;
  971. if (child->argv) {
  972. for (i=0; is_assignment(child->argv[i]); i++) {
  973. debug_printf("pid %d environment modification: %s\n",getpid(),child->argv[i]);
  974. p = insert_var_value(child->argv[i]);
  975. putenv(strdup(p));
  976. if (p != child->argv[i]) free(p);
  977. }
  978. child->argv+=i; /* XXX this hack isn't so horrible, since we are about
  979. to exit, and therefore don't need to keep data
  980. structures consistent for free() use. */
  981. /* If a variable is assigned in a forest, and nobody listens,
  982. * was it ever really set?
  983. */
  984. if (child->argv[0] == NULL) {
  985. _exit(EXIT_SUCCESS);
  986. }
  987. /*
  988. * Check if the command matches any of the builtins.
  989. * Depending on context, this might be redundant. But it's
  990. * easier to waste a few CPU cycles than it is to figure out
  991. * if this is one of those cases.
  992. */
  993. for (x = bltins; x->cmd; x++) {
  994. if (strcmp(child->argv[0], x->cmd) == 0 ) {
  995. debug_printf("builtin exec %s\n", child->argv[0]);
  996. rcode = x->function(child);
  997. fflush(stdout);
  998. _exit(rcode);
  999. }
  1000. }
  1001. /* Check if the command matches any busybox internal commands
  1002. * ("applets") here.
  1003. * FIXME: This feature is not 100% safe, since
  1004. * BusyBox is not fully reentrant, so we have no guarantee the things
  1005. * from the .bss are still zeroed, or that things from .data are still
  1006. * at their defaults. We could exec ourself from /proc/self/exe, but I
  1007. * really dislike relying on /proc for things. We could exec ourself
  1008. * from global_argv[0], but if we are in a chroot, we may not be able
  1009. * to find ourself... */
  1010. #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
  1011. {
  1012. int argc_l;
  1013. char** argv_l=child->argv;
  1014. char *name = child->argv[0];
  1015. /* Count argc for use in a second... */
  1016. for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++);
  1017. optind = 1;
  1018. debug_printf("running applet %s\n", name);
  1019. run_applet_by_name(name, argc_l, child->argv);
  1020. }
  1021. #endif
  1022. debug_printf("exec of %s\n",child->argv[0]);
  1023. execvp(child->argv[0],child->argv);
  1024. bb_perror_msg("cannot exec: %s",child->argv[0]);
  1025. _exit(1);
  1026. } else if (child->group) {
  1027. debug_printf("runtime nesting to group\n");
  1028. interactive=0; /* crucial!!!! */
  1029. rcode = run_list_real(child->group);
  1030. /* OK to leak memory by not calling free_pipe_list,
  1031. * since this process is about to exit */
  1032. _exit(rcode);
  1033. } else {
  1034. /* Can happen. See what bash does with ">foo" by itself. */
  1035. debug_printf("trying to pseudo_exec null command\n");
  1036. _exit(EXIT_SUCCESS);
  1037. }
  1038. }
  1039. static void insert_bg_job(struct pipe *pi)
  1040. {
  1041. struct pipe *thejob;
  1042. /* Linear search for the ID of the job to use */
  1043. pi->jobid = 1;
  1044. for (thejob = job_list; thejob; thejob = thejob->next)
  1045. if (thejob->jobid >= pi->jobid)
  1046. pi->jobid = thejob->jobid + 1;
  1047. /* add thejob to the list of running jobs */
  1048. if (!job_list) {
  1049. thejob = job_list = xmalloc(sizeof(*thejob));
  1050. } else {
  1051. for (thejob = job_list; thejob->next; thejob = thejob->next) /* nothing */;
  1052. thejob->next = xmalloc(sizeof(*thejob));
  1053. thejob = thejob->next;
  1054. }
  1055. /* physically copy the struct job */
  1056. memcpy(thejob, pi, sizeof(struct pipe));
  1057. thejob->next = NULL;
  1058. thejob->running_progs = thejob->num_progs;
  1059. thejob->stopped_progs = 0;
  1060. thejob->text = xmalloc(BUFSIZ); /* cmdedit buffer size */
  1061. //if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0])
  1062. {
  1063. char *bar=thejob->text;
  1064. char **foo=pi->progs[0].argv;
  1065. while(foo && *foo) {
  1066. bar += sprintf(bar, "%s ", *foo++);
  1067. }
  1068. }
  1069. /* we don't wait for background thejobs to return -- append it
  1070. to the list of backgrounded thejobs and leave it alone */
  1071. printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid);
  1072. last_bg_pid = thejob->progs[0].pid;
  1073. last_jobid = thejob->jobid;
  1074. }
  1075. /* remove a backgrounded job */
  1076. static void remove_bg_job(struct pipe *pi)
  1077. {
  1078. struct pipe *prev_pipe;
  1079. if (pi == job_list) {
  1080. job_list = pi->next;
  1081. } else {
  1082. prev_pipe = job_list;
  1083. while (prev_pipe->next != pi)
  1084. prev_pipe = prev_pipe->next;
  1085. prev_pipe->next = pi->next;
  1086. }
  1087. if (job_list)
  1088. last_jobid = job_list->jobid;
  1089. else
  1090. last_jobid = 0;
  1091. pi->stopped_progs = 0;
  1092. free_pipe(pi, 0);
  1093. free(pi);
  1094. }
  1095. /* Checks to see if any processes have exited -- if they
  1096. have, figure out why and see if a job has completed */
  1097. static int checkjobs(struct pipe* fg_pipe)
  1098. {
  1099. int attributes;
  1100. int status;
  1101. int prognum = 0;
  1102. struct pipe *pi;
  1103. pid_t childpid;
  1104. attributes = WUNTRACED;
  1105. if (fg_pipe==NULL) {
  1106. attributes |= WNOHANG;
  1107. }
  1108. while ((childpid = waitpid(-1, &status, attributes)) > 0) {
  1109. if (fg_pipe) {
  1110. int i, rcode = 0;
  1111. for (i=0; i < fg_pipe->num_progs; i++) {
  1112. if (fg_pipe->progs[i].pid == childpid) {
  1113. if (i==fg_pipe->num_progs-1)
  1114. rcode=WEXITSTATUS(status);
  1115. (fg_pipe->num_progs)--;
  1116. return rcode;
  1117. }
  1118. }
  1119. }
  1120. for (pi = job_list; pi; pi = pi->next) {
  1121. prognum = 0;
  1122. while (prognum < pi->num_progs && pi->progs[prognum].pid != childpid) {
  1123. prognum++;
  1124. }
  1125. if (prognum < pi->num_progs)
  1126. break;
  1127. }
  1128. if(pi==NULL) {
  1129. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  1130. continue;
  1131. }
  1132. if (WIFEXITED(status) || WIFSIGNALED(status)) {
  1133. /* child exited */
  1134. pi->running_progs--;
  1135. pi->progs[prognum].pid = 0;
  1136. if (!pi->running_progs) {
  1137. printf(JOB_STATUS_FORMAT, pi->jobid, "Done", pi->text);
  1138. remove_bg_job(pi);
  1139. }
  1140. } else {
  1141. /* child stopped */
  1142. pi->stopped_progs++;
  1143. pi->progs[prognum].is_stopped = 1;
  1144. }
  1145. }
  1146. if (childpid == -1 && errno != ECHILD)
  1147. bb_perror_msg("waitpid");
  1148. /* move the shell to the foreground */
  1149. //if (interactive && tcsetpgrp(shell_terminal, getpgid(0)))
  1150. // bb_perror_msg("tcsetpgrp-2");
  1151. return -1;
  1152. }
  1153. /* run_pipe_real() starts all the jobs, but doesn't wait for anything
  1154. * to finish. See checkjobs().
  1155. *
  1156. * return code is normally -1, when the caller has to wait for children
  1157. * to finish to determine the exit status of the pipe. If the pipe
  1158. * is a simple builtin command, however, the action is done by the
  1159. * time run_pipe_real returns, and the exit code is provided as the
  1160. * return value.
  1161. *
  1162. * The input of the pipe is always stdin, the output is always
  1163. * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
  1164. * because it tries to avoid running the command substitution in
  1165. * subshell, when that is in fact necessary. The subshell process
  1166. * now has its stdout directed to the input of the appropriate pipe,
  1167. * so this routine is noticeably simpler.
  1168. */
  1169. static int run_pipe_real(struct pipe *pi)
  1170. {
  1171. int i;
  1172. int nextin, nextout;
  1173. int pipefds[2]; /* pipefds[0] is for reading */
  1174. struct child_prog *child;
  1175. const struct built_in_command *x;
  1176. char *p;
  1177. nextin = 0;
  1178. pi->pgrp = -1;
  1179. /* Check if this is a simple builtin (not part of a pipe).
  1180. * Builtins within pipes have to fork anyway, and are handled in
  1181. * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
  1182. */
  1183. child = & (pi->progs[0]);
  1184. if (pi->num_progs == 1 && child->group && child->subshell == 0) {
  1185. int squirrel[] = {-1, -1, -1};
  1186. int rcode;
  1187. debug_printf("non-subshell grouping\n");
  1188. setup_redirects(child, squirrel);
  1189. /* XXX could we merge code with following builtin case,
  1190. * by creating a pseudo builtin that calls run_list_real? */
  1191. rcode = run_list_real(child->group);
  1192. restore_redirects(squirrel);
  1193. return rcode;
  1194. } else if (pi->num_progs == 1 && pi->progs[0].argv != NULL) {
  1195. for (i=0; is_assignment(child->argv[i]); i++) { /* nothing */ }
  1196. if (i!=0 && child->argv[i]==NULL) {
  1197. /* assignments, but no command: set the local environment */
  1198. for (i=0; child->argv[i]!=NULL; i++) {
  1199. /* Ok, this case is tricky. We have to decide if this is a
  1200. * local variable, or an already exported variable. If it is
  1201. * already exported, we have to export the new value. If it is
  1202. * not exported, we need only set this as a local variable.
  1203. * This junk is all to decide whether or not to export this
  1204. * variable. */
  1205. int export_me=0;
  1206. char *name, *value;
  1207. name = xstrdup(child->argv[i]);
  1208. debug_printf("Local environment set: %s\n", name);
  1209. value = strchr(name, '=');
  1210. if (value)
  1211. *value=0;
  1212. if ( get_local_var(name)) {
  1213. export_me=1;
  1214. }
  1215. free(name);
  1216. p = insert_var_value(child->argv[i]);
  1217. set_local_var(p, export_me);
  1218. if (p != child->argv[i]) free(p);
  1219. }
  1220. return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
  1221. }
  1222. for (i = 0; is_assignment(child->argv[i]); i++) {
  1223. p = insert_var_value(child->argv[i]);
  1224. putenv(strdup(p));
  1225. if (p != child->argv[i]) {
  1226. child->sp--;
  1227. free(p);
  1228. }
  1229. }
  1230. if (child->sp) {
  1231. char * str = NULL;
  1232. str = make_string((child->argv + i));
  1233. parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
  1234. free(str);
  1235. return last_return_code;
  1236. }
  1237. for (x = bltins; x->cmd; x++) {
  1238. if (strcmp(child->argv[i], x->cmd) == 0 ) {
  1239. int squirrel[] = {-1, -1, -1};
  1240. int rcode;
  1241. if (x->function == builtin_exec && child->argv[i+1]==NULL) {
  1242. debug_printf("magic exec\n");
  1243. setup_redirects(child,NULL);
  1244. return EXIT_SUCCESS;
  1245. }
  1246. debug_printf("builtin inline %s\n", child->argv[0]);
  1247. /* XXX setup_redirects acts on file descriptors, not FILEs.
  1248. * This is perfect for work that comes after exec().
  1249. * Is it really safe for inline use? Experimentally,
  1250. * things seem to work with glibc. */
  1251. setup_redirects(child, squirrel);
  1252. child->argv+=i; /* XXX horrible hack */
  1253. rcode = x->function(child);
  1254. child->argv-=i; /* XXX restore hack so free() can work right */
  1255. restore_redirects(squirrel);
  1256. return rcode;
  1257. }
  1258. }
  1259. }
  1260. for (i = 0; i < pi->num_progs; i++) {
  1261. child = & (pi->progs[i]);
  1262. /* pipes are inserted between pairs of commands */
  1263. if ((i + 1) < pi->num_progs) {
  1264. if (pipe(pipefds)<0) bb_perror_msg_and_die("pipe");
  1265. nextout = pipefds[1];
  1266. } else {
  1267. nextout=1;
  1268. pipefds[0] = -1;
  1269. }
  1270. /* XXX test for failed fork()? */
  1271. #if !defined(__UCLIBC__) || defined(__ARCH_HAS_MMU__)
  1272. if (!(child->pid = fork()))
  1273. #else
  1274. if (!(child->pid = vfork()))
  1275. #endif
  1276. {
  1277. /* Set the handling for job control signals back to the default. */
  1278. signal(SIGINT, SIG_DFL);
  1279. signal(SIGQUIT, SIG_DFL);
  1280. signal(SIGTERM, SIG_DFL);
  1281. signal(SIGTSTP, SIG_DFL);
  1282. signal(SIGTTIN, SIG_DFL);
  1283. signal(SIGTTOU, SIG_DFL);
  1284. signal(SIGCHLD, SIG_DFL);
  1285. close_all();
  1286. if (nextin != 0) {
  1287. dup2(nextin, 0);
  1288. close(nextin);
  1289. }
  1290. if (nextout != 1) {
  1291. dup2(nextout, 1);
  1292. close(nextout);
  1293. }
  1294. if (pipefds[0]!=-1) {
  1295. close(pipefds[0]); /* opposite end of our output pipe */
  1296. }
  1297. /* Like bash, explicit redirects override pipes,
  1298. * and the pipe fd is available for dup'ing. */
  1299. setup_redirects(child,NULL);
  1300. if (interactive && pi->followup!=PIPE_BG) {
  1301. /* If we (the child) win the race, put ourselves in the process
  1302. * group whose leader is the first process in this pipe. */
  1303. if (pi->pgrp < 0) {
  1304. pi->pgrp = getpid();
  1305. }
  1306. if (setpgid(0, pi->pgrp) == 0) {
  1307. tcsetpgrp(2, pi->pgrp);
  1308. }
  1309. }
  1310. pseudo_exec(child);
  1311. }
  1312. /* put our child in the process group whose leader is the
  1313. first process in this pipe */
  1314. if (pi->pgrp < 0) {
  1315. pi->pgrp = child->pid;
  1316. }
  1317. /* Don't check for errors. The child may be dead already,
  1318. * in which case setpgid returns error code EACCES. */
  1319. setpgid(child->pid, pi->pgrp);
  1320. if (nextin != 0)
  1321. close(nextin);
  1322. if (nextout != 1)
  1323. close(nextout);
  1324. /* If there isn't another process, nextin is garbage
  1325. but it doesn't matter */
  1326. nextin = pipefds[0];
  1327. }
  1328. return -1;
  1329. }
  1330. static int run_list_real(struct pipe *pi)
  1331. {
  1332. char *save_name = NULL;
  1333. char **list = NULL;
  1334. char **save_list = NULL;
  1335. struct pipe *rpipe;
  1336. int flag_rep = 0;
  1337. int save_num_progs;
  1338. int rcode=0, flag_skip=1;
  1339. int flag_restore = 0;
  1340. int if_code=0, next_if_code=0; /* need double-buffer to handle elif */
  1341. reserved_style rmode, skip_more_in_this_rmode=RES_XXXX;
  1342. /* check syntax for "for" */
  1343. for (rpipe = pi; rpipe; rpipe = rpipe->next) {
  1344. if ((rpipe->r_mode == RES_IN ||
  1345. rpipe->r_mode == RES_FOR) &&
  1346. (rpipe->next == NULL)) {
  1347. syntax();
  1348. return 1;
  1349. }
  1350. if ((rpipe->r_mode == RES_IN &&
  1351. (rpipe->next->r_mode == RES_IN &&
  1352. rpipe->next->progs->argv != NULL))||
  1353. (rpipe->r_mode == RES_FOR &&
  1354. rpipe->next->r_mode != RES_IN)) {
  1355. syntax();
  1356. return 1;
  1357. }
  1358. }
  1359. for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
  1360. if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL ||
  1361. pi->r_mode == RES_FOR) {
  1362. flag_restore = 0;
  1363. if (!rpipe) {
  1364. flag_rep = 0;
  1365. rpipe = pi;
  1366. }
  1367. }
  1368. rmode = pi->r_mode;
  1369. debug_printf("rmode=%d if_code=%d next_if_code=%d skip_more=%d\n", rmode, if_code, next_if_code, skip_more_in_this_rmode);
  1370. if (rmode == skip_more_in_this_rmode && flag_skip) {
  1371. if (pi->followup == PIPE_SEQ) flag_skip=0;
  1372. continue;
  1373. }
  1374. flag_skip = 1;
  1375. skip_more_in_this_rmode = RES_XXXX;
  1376. if (rmode == RES_THEN || rmode == RES_ELSE) if_code = next_if_code;
  1377. if (rmode == RES_THEN && if_code) continue;
  1378. if (rmode == RES_ELSE && !if_code) continue;
  1379. if (rmode == RES_ELIF && !if_code) break;
  1380. if (rmode == RES_FOR && pi->num_progs) {
  1381. if (!list) {
  1382. /* if no variable values after "in" we skip "for" */
  1383. if (!pi->next->progs->argv) continue;
  1384. /* create list of variable values */
  1385. list = make_list_in(pi->next->progs->argv,
  1386. pi->progs->argv[0]);
  1387. save_list = list;
  1388. save_name = pi->progs->argv[0];
  1389. pi->progs->argv[0] = NULL;
  1390. flag_rep = 1;
  1391. }
  1392. if (!(*list)) {
  1393. free(pi->progs->argv[0]);
  1394. free(save_list);
  1395. list = NULL;
  1396. flag_rep = 0;
  1397. pi->progs->argv[0] = save_name;
  1398. pi->progs->glob_result.gl_pathv[0] =
  1399. pi->progs->argv[0];
  1400. continue;
  1401. } else {
  1402. /* insert new value from list for variable */
  1403. if (pi->progs->argv[0])
  1404. free(pi->progs->argv[0]);
  1405. pi->progs->argv[0] = *list++;
  1406. pi->progs->glob_result.gl_pathv[0] =
  1407. pi->progs->argv[0];
  1408. }
  1409. }
  1410. if (rmode == RES_IN) continue;
  1411. if (rmode == RES_DO) {
  1412. if (!flag_rep) continue;
  1413. }
  1414. if ((rmode == RES_DONE)) {
  1415. if (flag_rep) {
  1416. flag_restore = 1;
  1417. } else {
  1418. rpipe = NULL;
  1419. }
  1420. }
  1421. if (pi->num_progs == 0) continue;
  1422. save_num_progs = pi->num_progs; /* save number of programs */
  1423. rcode = run_pipe_real(pi);
  1424. debug_printf("run_pipe_real returned %d\n",rcode);
  1425. if (rcode!=-1) {
  1426. /* We only ran a builtin: rcode was set by the return value
  1427. * of run_pipe_real(), and we don't need to wait for anything. */
  1428. } else if (pi->followup==PIPE_BG) {
  1429. /* XXX check bash's behavior with nontrivial pipes */
  1430. /* XXX compute jobid */
  1431. /* XXX what does bash do with attempts to background builtins? */
  1432. insert_bg_job(pi);
  1433. rcode = EXIT_SUCCESS;
  1434. } else {
  1435. if (interactive) {
  1436. /* move the new process group into the foreground */
  1437. if (tcsetpgrp(shell_terminal, pi->pgrp) && errno != ENOTTY)
  1438. bb_perror_msg("tcsetpgrp-3");
  1439. rcode = checkjobs(pi);
  1440. /* move the shell to the foreground */
  1441. if (tcsetpgrp(shell_terminal, getpgid(0)) && errno != ENOTTY)
  1442. bb_perror_msg("tcsetpgrp-4");
  1443. } else {
  1444. rcode = checkjobs(pi);
  1445. }
  1446. debug_printf("checkjobs returned %d\n",rcode);
  1447. }
  1448. last_return_code=rcode;
  1449. pi->num_progs = save_num_progs; /* restore number of programs */
  1450. if ( rmode == RES_IF || rmode == RES_ELIF )
  1451. next_if_code=rcode; /* can be overwritten a number of times */
  1452. if (rmode == RES_WHILE)
  1453. flag_rep = !last_return_code;
  1454. if (rmode == RES_UNTIL)
  1455. flag_rep = last_return_code;
  1456. if ( (rcode==EXIT_SUCCESS && pi->followup==PIPE_OR) ||
  1457. (rcode!=EXIT_SUCCESS && pi->followup==PIPE_AND) )
  1458. skip_more_in_this_rmode=rmode;
  1459. checkjobs(NULL);
  1460. }
  1461. return rcode;
  1462. }
  1463. /* return code is the exit status of the pipe */
  1464. static int free_pipe(struct pipe *pi, int indent)
  1465. {
  1466. char **p;
  1467. struct child_prog *child;
  1468. struct redir_struct *r, *rnext;
  1469. int a, i, ret_code=0;
  1470. if (pi->stopped_progs > 0)
  1471. return ret_code;
  1472. final_printf("%s run pipe: (pid %d)\n",indenter(indent),getpid());
  1473. for (i=0; i<pi->num_progs; i++) {
  1474. child = &pi->progs[i];
  1475. final_printf("%s command %d:\n",indenter(indent),i);
  1476. if (child->argv) {
  1477. for (a=0,p=child->argv; *p; a++,p++) {
  1478. final_printf("%s argv[%d] = %s\n",indenter(indent),a,*p);
  1479. }
  1480. globfree(&child->glob_result);
  1481. child->argv=NULL;
  1482. } else if (child->group) {
  1483. final_printf("%s begin group (subshell:%d)\n",indenter(indent), child->subshell);
  1484. ret_code = free_pipe_list(child->group,indent+3);
  1485. final_printf("%s end group\n",indenter(indent));
  1486. } else {
  1487. final_printf("%s (nil)\n",indenter(indent));
  1488. }
  1489. for (r=child->redirects; r; r=rnext) {
  1490. final_printf("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
  1491. if (r->dup == -1) {
  1492. /* guard against the case >$FOO, where foo is unset or blank */
  1493. if (r->word.gl_pathv) {
  1494. final_printf(" %s\n", *r->word.gl_pathv);
  1495. globfree(&r->word);
  1496. }
  1497. } else {
  1498. final_printf("&%d\n", r->dup);
  1499. }
  1500. rnext=r->next;
  1501. free(r);
  1502. }
  1503. child->redirects=NULL;
  1504. }
  1505. free(pi->progs); /* children are an array, they get freed all at once */
  1506. pi->progs=NULL;
  1507. return ret_code;
  1508. }
  1509. static int free_pipe_list(struct pipe *head, int indent)
  1510. {
  1511. int rcode=0; /* if list has no members */
  1512. struct pipe *pi, *next;
  1513. for (pi=head; pi; pi=next) {
  1514. final_printf("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
  1515. rcode = free_pipe(pi, indent);
  1516. final_printf("%s pipe followup code %d\n", indenter(indent), pi->followup);
  1517. next=pi->next;
  1518. pi->next=NULL;
  1519. free(pi);
  1520. }
  1521. return rcode;
  1522. }
  1523. /* Select which version we will use */
  1524. static int run_list(struct pipe *pi)
  1525. {
  1526. int rcode=0;
  1527. if (fake_mode==0) {
  1528. rcode = run_list_real(pi);
  1529. }
  1530. /* free_pipe_list has the side effect of clearing memory
  1531. * In the long run that function can be merged with run_list_real,
  1532. * but doing that now would hobble the debugging effort. */
  1533. free_pipe_list(pi,0);
  1534. return rcode;
  1535. }
  1536. /* The API for glob is arguably broken. This routine pushes a non-matching
  1537. * string into the output structure, removing non-backslashed backslashes.
  1538. * If someone can prove me wrong, by performing this function within the
  1539. * original glob(3) api, feel free to rewrite this routine into oblivion.
  1540. * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
  1541. * XXX broken if the last character is '\\', check that before calling.
  1542. */
  1543. static int globhack(const char *src, int flags, glob_t *pglob)
  1544. {
  1545. int cnt=0, pathc;
  1546. const char *s;
  1547. char *dest;
  1548. for (cnt=1, s=src; s && *s; s++) {
  1549. if (*s == '\\') s++;
  1550. cnt++;
  1551. }
  1552. dest = malloc(cnt);
  1553. if (!dest) return GLOB_NOSPACE;
  1554. if (!(flags & GLOB_APPEND)) {
  1555. pglob->gl_pathv=NULL;
  1556. pglob->gl_pathc=0;
  1557. pglob->gl_offs=0;
  1558. pglob->gl_offs=0;
  1559. }
  1560. pathc = ++pglob->gl_pathc;
  1561. pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
  1562. if (pglob->gl_pathv == NULL) return GLOB_NOSPACE;
  1563. pglob->gl_pathv[pathc-1]=dest;
  1564. pglob->gl_pathv[pathc]=NULL;
  1565. for (s=src; s && *s; s++, dest++) {
  1566. if (*s == '\\') s++;
  1567. *dest = *s;
  1568. }
  1569. *dest='\0';
  1570. return 0;
  1571. }
  1572. /* XXX broken if the last character is '\\', check that before calling */
  1573. static int glob_needed(const char *s)
  1574. {
  1575. for (; *s; s++) {
  1576. if (*s == '\\') s++;
  1577. if (strchr("*[?",*s)) return 1;
  1578. }
  1579. return 0;
  1580. }
  1581. static int xglob(o_string *dest, int flags, glob_t *pglob)
  1582. {
  1583. int gr;
  1584. /* short-circuit for null word */
  1585. /* we can code this better when the debug_printf's are gone */
  1586. if (dest->length == 0) {
  1587. if (dest->nonnull) {
  1588. /* bash man page calls this an "explicit" null */
  1589. gr = globhack(dest->data, flags, pglob);
  1590. debug_printf("globhack returned %d\n",gr);
  1591. } else {
  1592. return 0;
  1593. }
  1594. } else if (glob_needed(dest->data)) {
  1595. gr = glob(dest->data, flags, NULL, pglob);
  1596. debug_printf("glob returned %d\n",gr);
  1597. if (gr == GLOB_NOMATCH) {
  1598. /* quote removal, or more accurately, backslash removal */
  1599. gr = globhack(dest->data, flags, pglob);
  1600. debug_printf("globhack returned %d\n",gr);
  1601. }
  1602. } else {
  1603. gr = globhack(dest->data, flags, pglob);
  1604. debug_printf("globhack returned %d\n",gr);
  1605. }
  1606. if (gr == GLOB_NOSPACE)
  1607. bb_error_msg_and_die("out of memory during glob");
  1608. if (gr != 0) { /* GLOB_ABORTED ? */
  1609. bb_error_msg("glob(3) error %d",gr);
  1610. }
  1611. /* globprint(glob_target); */
  1612. return gr;
  1613. }
  1614. /* This is used to get/check local shell variables */
  1615. static char *get_local_var(const char *s)
  1616. {
  1617. struct variables *cur;
  1618. if (!s)
  1619. return NULL;
  1620. for (cur = top_vars; cur; cur=cur->next)
  1621. if(strcmp(cur->name, s)==0)
  1622. return cur->value;
  1623. return NULL;
  1624. }
  1625. /* This is used to set local shell variables
  1626. flg_export==0 if only local (not exporting) variable
  1627. flg_export==1 if "new" exporting environ
  1628. flg_export>1 if current startup environ (not call putenv()) */
  1629. static int set_local_var(const char *s, int flg_export)
  1630. {
  1631. char *name, *value;
  1632. int result=0;
  1633. struct variables *cur;
  1634. name=strdup(s);
  1635. /* Assume when we enter this function that we are already in
  1636. * NAME=VALUE format. So the first order of business is to
  1637. * split 's' on the '=' into 'name' and 'value' */
  1638. value = strchr(name, '=');
  1639. if (value==0 && ++value==0) {
  1640. free(name);
  1641. return -1;
  1642. }
  1643. *value++ = 0;
  1644. for(cur = top_vars; cur; cur = cur->next) {
  1645. if(strcmp(cur->name, name)==0)
  1646. break;
  1647. }
  1648. if(cur) {
  1649. if(strcmp(cur->value, value)==0) {
  1650. if(flg_export>0 && cur->flg_export==0)
  1651. cur->flg_export=flg_export;
  1652. else
  1653. result++;
  1654. } else {
  1655. if(cur->flg_read_only) {
  1656. bb_error_msg("%s: readonly variable", name);
  1657. result = -1;
  1658. } else {
  1659. if(flg_export>0 || cur->flg_export>1)
  1660. cur->flg_export=1;
  1661. free(cur->value);
  1662. cur->value = strdup(value);
  1663. }
  1664. }
  1665. } else {
  1666. cur = malloc(sizeof(struct variables));
  1667. if(!cur) {
  1668. result = -1;
  1669. } else {
  1670. cur->name = strdup(name);
  1671. if(cur->name == 0) {
  1672. free(cur);
  1673. result = -1;
  1674. } else {
  1675. struct variables *bottom = top_vars;
  1676. cur->value = strdup(value);
  1677. cur->next = 0;
  1678. cur->flg_export = flg_export;
  1679. cur->flg_read_only = 0;
  1680. while(bottom->next) bottom=bottom->next;
  1681. bottom->next = cur;
  1682. }
  1683. }
  1684. }
  1685. if(result==0 && cur->flg_export==1) {
  1686. *(value-1) = '=';
  1687. result = putenv(name);
  1688. } else {
  1689. free(name);
  1690. if(result>0) /* equivalent to previous set */
  1691. result = 0;
  1692. }
  1693. return result;
  1694. }
  1695. static void unset_local_var(const char *name)
  1696. {
  1697. struct variables *cur;
  1698. if (name) {
  1699. for (cur = top_vars; cur; cur=cur->next) {
  1700. if(strcmp(cur->name, name)==0)
  1701. break;
  1702. }
  1703. if(cur!=0) {
  1704. struct variables *next = top_vars;
  1705. if(cur->flg_read_only) {
  1706. bb_error_msg("%s: readonly variable", name);
  1707. return;
  1708. } else {
  1709. if(cur->flg_export)
  1710. unsetenv(cur->name);
  1711. free(cur->name);
  1712. free(cur->value);
  1713. while (next->next != cur)
  1714. next = next->next;
  1715. next->next = cur->next;
  1716. }
  1717. free(cur);
  1718. }
  1719. }
  1720. }
  1721. static int is_assignment(const char *s)
  1722. {
  1723. if (s==NULL || !isalpha(*s)) return 0;
  1724. ++s;
  1725. while(isalnum(*s) || *s=='_') ++s;
  1726. return *s=='=';
  1727. }
  1728. /* the src parameter allows us to peek forward to a possible &n syntax
  1729. * for file descriptor duplication, e.g., "2>&1".
  1730. * Return code is 0 normally, 1 if a syntax error is detected in src.
  1731. * Resource errors (in xmalloc) cause the process to exit */
  1732. static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
  1733. struct in_str *input)
  1734. {
  1735. struct child_prog *child=ctx->child;
  1736. struct redir_struct *redir = child->redirects;
  1737. struct redir_struct *last_redir=NULL;
  1738. /* Create a new redir_struct and drop it onto the end of the linked list */
  1739. while(redir) {
  1740. last_redir=redir;
  1741. redir=redir->next;
  1742. }
  1743. redir = xmalloc(sizeof(struct redir_struct));
  1744. redir->next=NULL;
  1745. redir->word.gl_pathv=NULL;
  1746. if (last_redir) {
  1747. last_redir->next=redir;
  1748. } else {
  1749. child->redirects=redir;
  1750. }
  1751. redir->type=style;
  1752. redir->fd= (fd==-1) ? redir_table[style].default_fd : fd ;
  1753. debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
  1754. /* Check for a '2>&1' type redirect */
  1755. redir->dup = redirect_dup_num(input);
  1756. if (redir->dup == -2) return 1; /* syntax error */
  1757. if (redir->dup != -1) {
  1758. /* Erik had a check here that the file descriptor in question
  1759. * is legit; I postpone that to "run time"
  1760. * A "-" representation of "close me" shows up as a -3 here */
  1761. debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
  1762. } else {
  1763. /* We do _not_ try to open the file that src points to,
  1764. * since we need to return and let src be expanded first.
  1765. * Set ctx->pending_redirect, so we know what to do at the
  1766. * end of the next parsed word.
  1767. */
  1768. ctx->pending_redirect = redir;
  1769. }
  1770. return 0;
  1771. }
  1772. static struct pipe *new_pipe(void) {
  1773. struct pipe *pi;
  1774. pi = xmalloc(sizeof(struct pipe));
  1775. pi->num_progs = 0;
  1776. pi->progs = NULL;
  1777. pi->next = NULL;
  1778. pi->followup = 0; /* invalid */
  1779. pi->r_mode = RES_NONE;
  1780. return pi;
  1781. }
  1782. static void initialize_context(struct p_context *ctx)
  1783. {
  1784. ctx->pipe=NULL;
  1785. ctx->pending_redirect=NULL;
  1786. ctx->child=NULL;
  1787. ctx->list_head=new_pipe();
  1788. ctx->pipe=ctx->list_head;
  1789. ctx->w=RES_NONE;
  1790. ctx->stack=NULL;
  1791. ctx->old_flag=0;
  1792. done_command(ctx); /* creates the memory for working child */
  1793. }
  1794. /* normal return is 0
  1795. * if a reserved word is found, and processed, return 1
  1796. * should handle if, then, elif, else, fi, for, while, until, do, done.
  1797. * case, function, and select are obnoxious, save those for later.
  1798. */
  1799. static int reserved_word(o_string *dest, struct p_context *ctx)
  1800. {
  1801. struct reserved_combo {
  1802. char *literal;
  1803. int code;
  1804. long flag;
  1805. };
  1806. /* Mostly a list of accepted follow-up reserved words.
  1807. * FLAG_END means we are done with the sequence, and are ready
  1808. * to turn the compound list into a command.
  1809. * FLAG_START means the word must start a new compound list.
  1810. */
  1811. static struct reserved_combo reserved_list[] = {
  1812. { "if", RES_IF, FLAG_THEN | FLAG_START },
  1813. { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  1814. { "elif", RES_ELIF, FLAG_THEN },
  1815. { "else", RES_ELSE, FLAG_FI },
  1816. { "fi", RES_FI, FLAG_END },
  1817. { "for", RES_FOR, FLAG_IN | FLAG_START },
  1818. { "while", RES_WHILE, FLAG_DO | FLAG_START },
  1819. { "until", RES_UNTIL, FLAG_DO | FLAG_START },
  1820. { "in", RES_IN, FLAG_DO },
  1821. { "do", RES_DO, FLAG_DONE },
  1822. { "done", RES_DONE, FLAG_END }
  1823. };
  1824. struct reserved_combo *r;
  1825. for (r=reserved_list;
  1826. #define NRES sizeof(reserved_list)/sizeof(struct reserved_combo)
  1827. r<reserved_list+NRES; r++) {
  1828. if (strcmp(dest->data, r->literal) == 0) {
  1829. debug_printf("found reserved word %s, code %d\n",r->literal,r->code);
  1830. if (r->flag & FLAG_START) {
  1831. struct p_context *new = xmalloc(sizeof(struct p_context));
  1832. debug_printf("push stack\n");
  1833. if (ctx->w == RES_IN || ctx->w == RES_FOR) {
  1834. syntax();
  1835. free(new);
  1836. ctx->w = RES_SNTX;
  1837. b_reset(dest);
  1838. return 1;
  1839. }
  1840. *new = *ctx; /* physical copy */
  1841. initialize_context(ctx);
  1842. ctx->stack=new;
  1843. } else if ( ctx->w == RES_NONE || ! (ctx->old_flag & (1<<r->code))) {
  1844. syntax();
  1845. ctx->w = RES_SNTX;
  1846. b_reset(dest);
  1847. return 1;
  1848. }
  1849. ctx->w=r->code;
  1850. ctx->old_flag = r->flag;
  1851. if (ctx->old_flag & FLAG_END) {
  1852. struct p_context *old;
  1853. debug_printf("pop stack\n");
  1854. done_pipe(ctx,PIPE_SEQ);
  1855. old = ctx->stack;
  1856. old->child->group = ctx->list_head;
  1857. old->child->subshell = 0;
  1858. *ctx = *old; /* physical copy */
  1859. free(old);
  1860. }
  1861. b_reset (dest);
  1862. return 1;
  1863. }
  1864. }
  1865. return 0;
  1866. }
  1867. /* normal return is 0.
  1868. * Syntax or xglob errors return 1. */
  1869. static int done_word(o_string *dest, struct p_context *ctx)
  1870. {
  1871. struct child_prog *child=ctx->child;
  1872. glob_t *glob_target;
  1873. int gr, flags = 0;
  1874. debug_printf("done_word: %s %p\n", dest->data, child);
  1875. if (dest->length == 0 && !dest->nonnull) {
  1876. debug_printf(" true null, ignored\n");
  1877. return 0;
  1878. }
  1879. if (ctx->pending_redirect) {
  1880. glob_target = &ctx->pending_redirect->word;
  1881. } else {
  1882. if (child->group) {
  1883. syntax();
  1884. return 1; /* syntax error, groups and arglists don't mix */
  1885. }
  1886. if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
  1887. debug_printf("checking %s for reserved-ness\n",dest->data);
  1888. if (reserved_word(dest,ctx)) return ctx->w==RES_SNTX;
  1889. }
  1890. glob_target = &child->glob_result;
  1891. if (child->argv) flags |= GLOB_APPEND;
  1892. }
  1893. gr = xglob(dest, flags, glob_target);
  1894. if (gr != 0) return 1;
  1895. b_reset(dest);
  1896. if (ctx->pending_redirect) {
  1897. ctx->pending_redirect=NULL;
  1898. if (glob_target->gl_pathc != 1) {
  1899. bb_error_msg("ambiguous redirect");
  1900. return 1;
  1901. }
  1902. } else {
  1903. child->argv = glob_target->gl_pathv;
  1904. }
  1905. if (ctx->w == RES_FOR) {
  1906. done_word(dest,ctx);
  1907. done_pipe(ctx,PIPE_SEQ);
  1908. }
  1909. return 0;
  1910. }
  1911. /* The only possible error here is out of memory, in which case
  1912. * xmalloc exits. */
  1913. static int done_command(struct p_context *ctx)
  1914. {
  1915. /* The child is really already in the pipe structure, so
  1916. * advance the pipe counter and make a new, null child.
  1917. * Only real trickiness here is that the uncommitted
  1918. * child structure, to which ctx->child points, is not
  1919. * counted in pi->num_progs. */
  1920. struct pipe *pi=ctx->pipe;
  1921. struct child_prog *prog=ctx->child;
  1922. if (prog && prog->group == NULL
  1923. && prog->argv == NULL
  1924. && prog->redirects == NULL) {
  1925. debug_printf("done_command: skipping null command\n");
  1926. return 0;
  1927. } else if (prog) {
  1928. pi->num_progs++;
  1929. debug_printf("done_command: num_progs incremented to %d\n",pi->num_progs);
  1930. } else {
  1931. debug_printf("done_command: initializing\n");
  1932. }
  1933. pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
  1934. prog = pi->progs + pi->num_progs;
  1935. prog->redirects = NULL;
  1936. prog->argv = NULL;
  1937. prog->is_stopped = 0;
  1938. prog->group = NULL;
  1939. prog->glob_result.gl_pathv = NULL;
  1940. prog->family = pi;
  1941. prog->sp = 0;
  1942. ctx->child = prog;
  1943. prog->type = ctx->type;
  1944. /* but ctx->pipe and ctx->list_head remain unchanged */
  1945. return 0;
  1946. }
  1947. static int done_pipe(struct p_context *ctx, pipe_style type)
  1948. {
  1949. struct pipe *new_p;
  1950. done_command(ctx); /* implicit closure of previous command */
  1951. debug_printf("done_pipe, type %d\n", type);
  1952. ctx->pipe->followup = type;
  1953. ctx->pipe->r_mode = ctx->w;
  1954. new_p=new_pipe();
  1955. ctx->pipe->next = new_p;
  1956. ctx->pipe = new_p;
  1957. ctx->child = NULL;
  1958. done_command(ctx); /* set up new pipe to accept commands */
  1959. return 0;
  1960. }
  1961. /* peek ahead in the in_str to find out if we have a "&n" construct,
  1962. * as in "2>&1", that represents duplicating a file descriptor.
  1963. * returns either -2 (syntax error), -1 (no &), or the number found.
  1964. */
  1965. static int redirect_dup_num(struct in_str *input)
  1966. {
  1967. int ch, d=0, ok=0;
  1968. ch = b_peek(input);
  1969. if (ch != '&') return -1;
  1970. b_getch(input); /* get the & */
  1971. ch=b_peek(input);
  1972. if (ch == '-') {
  1973. b_getch(input);
  1974. return -3; /* "-" represents "close me" */
  1975. }
  1976. while (isdigit(ch)) {
  1977. d = d*10+(ch-'0');
  1978. ok=1;
  1979. b_getch(input);
  1980. ch = b_peek(input);
  1981. }
  1982. if (ok) return d;
  1983. bb_error_msg("ambiguous redirect");
  1984. return -2;
  1985. }
  1986. /* If a redirect is immediately preceded by a number, that number is
  1987. * supposed to tell which file descriptor to redirect. This routine
  1988. * looks for such preceding numbers. In an ideal world this routine
  1989. * needs to handle all the following classes of redirects...
  1990. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  1991. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  1992. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  1993. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  1994. * A -1 output from this program means no valid number was found, so the
  1995. * caller should use the appropriate default for this redirection.
  1996. */
  1997. static int redirect_opt_num(o_string *o)
  1998. {
  1999. int num;
  2000. if (o->length==0) return -1;
  2001. for(num=0; num<o->length; num++) {
  2002. if (!isdigit(*(o->data+num))) {
  2003. return -1;
  2004. }
  2005. }
  2006. /* reuse num (and save an int) */
  2007. num=atoi(o->data);
  2008. b_reset(o);
  2009. return num;
  2010. }
  2011. static FILE *generate_stream_from_list(struct pipe *head)
  2012. {
  2013. FILE *pf;
  2014. int pid, channel[2];
  2015. if (pipe(channel)<0) bb_perror_msg_and_die("pipe");
  2016. #if !defined(__UCLIBC__) || defined(__ARCH_HAS_MMU__)
  2017. pid=fork();
  2018. #else
  2019. pid=vfork();
  2020. #endif
  2021. if (pid<0) {
  2022. bb_perror_msg_and_die("fork");
  2023. } else if (pid==0) {
  2024. close(channel[0]);
  2025. if (channel[1] != 1) {
  2026. dup2(channel[1],1);
  2027. close(channel[1]);
  2028. }
  2029. _exit(run_list_real(head)); /* leaks memory */
  2030. }
  2031. debug_printf("forked child %d\n",pid);
  2032. close(channel[1]);
  2033. pf = fdopen(channel[0],"r");
  2034. debug_printf("pipe on FILE *%p\n",pf);
  2035. return pf;
  2036. }
  2037. /* this version hacked for testing purposes */
  2038. /* return code is exit status of the process that is run. */
  2039. static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
  2040. {
  2041. int retcode;
  2042. o_string result=NULL_O_STRING;
  2043. struct p_context inner;
  2044. FILE *p;
  2045. struct in_str pipe_str;
  2046. initialize_context(&inner);
  2047. /* recursion to generate command */
  2048. retcode = parse_stream(&result, &inner, input, subst_end);
  2049. if (retcode != 0) return retcode; /* syntax error or EOF */
  2050. done_word(&result, &inner);
  2051. done_pipe(&inner, PIPE_SEQ);
  2052. b_free(&result);
  2053. p=generate_stream_from_list(inner.list_head);
  2054. if (p==NULL) return 1;
  2055. mark_open(fileno(p));
  2056. setup_file_in_str(&pipe_str, p);
  2057. /* now send results of command back into original context */
  2058. retcode = parse_stream(dest, ctx, &pipe_str, '\0');
  2059. /* XXX In case of a syntax error, should we try to kill the child?
  2060. * That would be tough to do right, so just read until EOF. */
  2061. if (retcode == 1) {
  2062. while (b_getch(&pipe_str)!=EOF) { /* discard */ };
  2063. }
  2064. debug_printf("done reading from pipe, pclose()ing\n");
  2065. /* This is the step that wait()s for the child. Should be pretty
  2066. * safe, since we just read an EOF from its stdout. We could try
  2067. * to better, by using wait(), and keeping track of background jobs
  2068. * at the same time. That would be a lot of work, and contrary
  2069. * to the KISS philosophy of this program. */
  2070. mark_closed(fileno(p));
  2071. retcode=pclose(p);
  2072. free_pipe_list(inner.list_head,0);
  2073. debug_printf("pclosed, retcode=%d\n",retcode);
  2074. /* XXX this process fails to trim a single trailing newline */
  2075. return retcode;
  2076. }
  2077. static int parse_group(o_string *dest, struct p_context *ctx,
  2078. struct in_str *input, int ch)
  2079. {
  2080. int rcode, endch=0;
  2081. struct p_context sub;
  2082. struct child_prog *child = ctx->child;
  2083. if (child->argv) {
  2084. syntax();
  2085. return 1; /* syntax error, groups and arglists don't mix */
  2086. }
  2087. initialize_context(&sub);
  2088. switch(ch) {
  2089. case '(': endch=')'; child->subshell=1; break;
  2090. case '{': endch='}'; break;
  2091. default: syntax(); /* really logic error */
  2092. }
  2093. rcode=parse_stream(dest,&sub,input,endch);
  2094. done_word(dest,&sub); /* finish off the final word in the subcontext */
  2095. done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
  2096. child->group = sub.list_head;
  2097. return rcode;
  2098. /* child remains "open", available for possible redirects */
  2099. }
  2100. /* basically useful version until someone wants to get fancier,
  2101. * see the bash man page under "Parameter Expansion" */
  2102. static char *lookup_param(char *src)
  2103. {
  2104. char *p=NULL;
  2105. if (src) {
  2106. p = getenv(src);
  2107. if (!p)
  2108. p = get_local_var(src);
  2109. }
  2110. return p;
  2111. }
  2112. /* return code: 0 for OK, 1 for syntax error */
  2113. static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
  2114. {
  2115. int i, advance=0;
  2116. char sep[]=" ";
  2117. int ch = input->peek(input); /* first character after the $ */
  2118. debug_printf("handle_dollar: ch=%c\n",ch);
  2119. if (isalpha(ch)) {
  2120. b_addchr(dest, SPECIAL_VAR_SYMBOL);
  2121. ctx->child->sp++;
  2122. while(ch=b_peek(input),isalnum(ch) || ch=='_') {
  2123. b_getch(input);
  2124. b_addchr(dest,ch);
  2125. }
  2126. b_addchr(dest, SPECIAL_VAR_SYMBOL);
  2127. } else if (isdigit(ch)) {
  2128. i = ch-'0'; /* XXX is $0 special? */
  2129. if (i<global_argc) {
  2130. parse_string(dest, ctx, global_argv[i]); /* recursion */
  2131. }
  2132. advance = 1;
  2133. } else switch (ch) {
  2134. case '$':
  2135. b_adduint(dest,getpid());
  2136. advance = 1;
  2137. break;
  2138. case '!':
  2139. if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
  2140. advance = 1;
  2141. break;
  2142. case '?':
  2143. b_adduint(dest,last_return_code);
  2144. advance = 1;
  2145. break;
  2146. case '#':
  2147. b_adduint(dest,global_argc ? global_argc-1 : 0);
  2148. advance = 1;
  2149. break;
  2150. case '{':
  2151. b_addchr(dest, SPECIAL_VAR_SYMBOL);
  2152. ctx->child->sp++;
  2153. b_getch(input);
  2154. /* XXX maybe someone will try to escape the '}' */
  2155. while(ch=b_getch(input),ch!=EOF && ch!='}') {
  2156. b_addchr(dest,ch);
  2157. }
  2158. if (ch != '}') {
  2159. syntax();
  2160. return 1;
  2161. }
  2162. b_addchr(dest, SPECIAL_VAR_SYMBOL);
  2163. break;
  2164. case '(':
  2165. b_getch(input);
  2166. process_command_subs(dest, ctx, input, ')');
  2167. break;
  2168. case '*':
  2169. sep[0]=ifs[0];
  2170. for (i=1; i<global_argc; i++) {
  2171. parse_string(dest, ctx, global_argv[i]);
  2172. if (i+1 < global_argc) parse_string(dest, ctx, sep);
  2173. }
  2174. break;
  2175. case '@':
  2176. case '-':
  2177. case '_':
  2178. /* still unhandled, but should be eventually */
  2179. bb_error_msg("unhandled syntax: $%c",ch);
  2180. return 1;
  2181. break;
  2182. default:
  2183. b_addqchr(dest,'$',dest->quote);
  2184. }
  2185. /* Eat the character if the flag was set. If the compiler
  2186. * is smart enough, we could substitute "b_getch(input);"
  2187. * for all the "advance = 1;" above, and also end up with
  2188. * a nice size-optimized program. Hah! That'll be the day.
  2189. */
  2190. if (advance) b_getch(input);
  2191. return 0;
  2192. }
  2193. int parse_string(o_string *dest, struct p_context *ctx, const char *src)
  2194. {
  2195. struct in_str foo;
  2196. setup_string_in_str(&foo, src);
  2197. return parse_stream(dest, ctx, &foo, '\0');
  2198. }
  2199. /* return code is 0 for normal exit, 1 for syntax error */
  2200. int parse_stream(o_string *dest, struct p_context *ctx,
  2201. struct in_str *input, int end_trigger)
  2202. {
  2203. int ch, m;
  2204. int redir_fd;
  2205. redir_type redir_style;
  2206. int next;
  2207. /* Only double-quote state is handled in the state variable dest->quote.
  2208. * A single-quote triggers a bypass of the main loop until its mate is
  2209. * found. When recursing, quote state is passed in via dest->quote. */
  2210. debug_printf("parse_stream, end_trigger=%d\n",end_trigger);
  2211. while ((ch=b_getch(input))!=EOF) {
  2212. m = map[ch];
  2213. next = (ch == '\n') ? 0 : b_peek(input);
  2214. debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d\n",
  2215. ch,ch,m,dest->quote);
  2216. if (m==0 || ((m==1 || m==2) && dest->quote)) {
  2217. b_addqchr(dest, ch, dest->quote);
  2218. } else {
  2219. if (m==2) { /* unquoted IFS */
  2220. if (done_word(dest, ctx)) {
  2221. return 1;
  2222. }
  2223. /* If we aren't performing a substitution, treat a newline as a
  2224. * command separator. */
  2225. if (end_trigger != '\0' && ch=='\n')
  2226. done_pipe(ctx,PIPE_SEQ);
  2227. }
  2228. if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) {
  2229. debug_printf("leaving parse_stream (triggered)\n");
  2230. return 0;
  2231. }
  2232. if (m!=2) switch (ch) {
  2233. case '#':
  2234. if (dest->length == 0 && !dest->quote) {
  2235. while(ch=b_peek(input),ch!=EOF && ch!='\n') { b_getch(input); }
  2236. } else {
  2237. b_addqchr(dest, ch, dest->quote);
  2238. }
  2239. break;
  2240. case '\\':
  2241. if (next == EOF) {
  2242. syntax();
  2243. return 1;
  2244. }
  2245. b_addqchr(dest, '\\', dest->quote);
  2246. b_addqchr(dest, b_getch(input), dest->quote);
  2247. break;
  2248. case '$':
  2249. if (handle_dollar(dest, ctx, input)!=0) return 1;
  2250. break;
  2251. case '\'':
  2252. dest->nonnull = 1;
  2253. while(ch=b_getch(input),ch!=EOF && ch!='\'') {
  2254. b_addchr(dest,ch);
  2255. }
  2256. if (ch==EOF) {
  2257. syntax();
  2258. return 1;
  2259. }
  2260. break;
  2261. case '"':
  2262. dest->nonnull = 1;
  2263. dest->quote = !dest->quote;
  2264. break;
  2265. case '`':
  2266. process_command_subs(dest, ctx, input, '`');
  2267. break;
  2268. case '>':
  2269. redir_fd = redirect_opt_num(dest);
  2270. done_word(dest, ctx);
  2271. redir_style=REDIRECT_OVERWRITE;
  2272. if (next == '>') {
  2273. redir_style=REDIRECT_APPEND;
  2274. b_getch(input);
  2275. } else if (next == '(') {
  2276. syntax(); /* until we support >(list) Process Substitution */
  2277. return 1;
  2278. }
  2279. setup_redirect(ctx, redir_fd, redir_style, input);
  2280. break;
  2281. case '<':
  2282. redir_fd = redirect_opt_num(dest);
  2283. done_word(dest, ctx);
  2284. redir_style=REDIRECT_INPUT;
  2285. if (next == '<') {
  2286. redir_style=REDIRECT_HEREIS;
  2287. b_getch(input);
  2288. } else if (next == '>') {
  2289. redir_style=REDIRECT_IO;
  2290. b_getch(input);
  2291. } else if (next == '(') {
  2292. syntax(); /* until we support <(list) Process Substitution */
  2293. return 1;
  2294. }
  2295. setup_redirect(ctx, redir_fd, redir_style, input);
  2296. break;
  2297. case ';':
  2298. done_word(dest, ctx);
  2299. done_pipe(ctx,PIPE_SEQ);
  2300. break;
  2301. case '&':
  2302. done_word(dest, ctx);
  2303. if (next=='&') {
  2304. b_getch(input);
  2305. done_pipe(ctx,PIPE_AND);
  2306. } else {
  2307. done_pipe(ctx,PIPE_BG);
  2308. }
  2309. break;
  2310. case '|':
  2311. done_word(dest, ctx);
  2312. if (next=='|') {
  2313. b_getch(input);
  2314. done_pipe(ctx,PIPE_OR);
  2315. } else {
  2316. /* we could pick up a file descriptor choice here
  2317. * with redirect_opt_num(), but bash doesn't do it.
  2318. * "echo foo 2| cat" yields "foo 2". */
  2319. done_command(ctx);
  2320. }
  2321. break;
  2322. case '(':
  2323. case '{':
  2324. if (parse_group(dest, ctx, input, ch)!=0) return 1;
  2325. break;
  2326. case ')':
  2327. case '}':
  2328. syntax(); /* Proper use of this character caught by end_trigger */
  2329. return 1;
  2330. break;
  2331. default:
  2332. syntax(); /* this is really an internal logic error */
  2333. return 1;
  2334. }
  2335. }
  2336. }
  2337. /* complain if quote? No, maybe we just finished a command substitution
  2338. * that was quoted. Example:
  2339. * $ echo "`cat foo` plus more"
  2340. * and we just got the EOF generated by the subshell that ran "cat foo"
  2341. * The only real complaint is if we got an EOF when end_trigger != '\0',
  2342. * that is, we were really supposed to get end_trigger, and never got
  2343. * one before the EOF. Can't use the standard "syntax error" return code,
  2344. * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
  2345. debug_printf("leaving parse_stream (EOF)\n");
  2346. if (end_trigger != '\0') return -1;
  2347. return 0;
  2348. }
  2349. static void mapset(const char *set, int code)
  2350. {
  2351. const unsigned char *s;
  2352. for (s = (const unsigned char *)set; *s; s++) map[(int)*s] = code;
  2353. }
  2354. static void update_ifs_map(void)
  2355. {
  2356. /* char *ifs and char map[256] are both globals. */
  2357. ifs = getenv("IFS");
  2358. if (ifs == NULL) ifs=" \t\n";
  2359. /* Precompute a list of 'flow through' behavior so it can be treated
  2360. * quickly up front. Computation is necessary because of IFS.
  2361. * Special case handling of IFS == " \t\n" is not implemented.
  2362. * The map[] array only really needs two bits each, and on most machines
  2363. * that would be faster because of the reduced L1 cache footprint.
  2364. */
  2365. memset(map,0,sizeof(map)); /* most characters flow through always */
  2366. mapset("\\$'\"`", 3); /* never flow through */
  2367. mapset("<>;&|(){}#", 1); /* flow through if quoted */
  2368. mapset(ifs, 2); /* also flow through if quoted */
  2369. }
  2370. /* most recursion does not come through here, the exception is
  2371. * from builtin_source() */
  2372. int parse_stream_outer(struct in_str *inp, int flag)
  2373. {
  2374. struct p_context ctx;
  2375. o_string temp=NULL_O_STRING;
  2376. int rcode;
  2377. do {
  2378. ctx.type = flag;
  2379. initialize_context(&ctx);
  2380. update_ifs_map();
  2381. if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING)) mapset(";$&|", 0);
  2382. inp->promptmode=1;
  2383. rcode = parse_stream(&temp, &ctx, inp, '\n');
  2384. if (rcode != 1 && ctx.old_flag != 0) {
  2385. syntax();
  2386. }
  2387. if (rcode != 1 && ctx.old_flag == 0) {
  2388. done_word(&temp, &ctx);
  2389. done_pipe(&ctx,PIPE_SEQ);
  2390. run_list(ctx.list_head);
  2391. } else {
  2392. if (ctx.old_flag != 0) {
  2393. free(ctx.stack);
  2394. b_reset(&temp);
  2395. }
  2396. temp.nonnull = 0;
  2397. temp.quote = 0;
  2398. inp->p = NULL;
  2399. free_pipe_list(ctx.list_head,0);
  2400. }
  2401. b_free(&temp);
  2402. } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
  2403. return 0;
  2404. }
  2405. static int parse_string_outer(const char *s, int flag)
  2406. {
  2407. struct in_str input;
  2408. setup_string_in_str(&input, s);
  2409. return parse_stream_outer(&input, flag);
  2410. }
  2411. static int parse_file_outer(FILE *f)
  2412. {
  2413. int rcode;
  2414. struct in_str input;
  2415. setup_file_in_str(&input, f);
  2416. rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
  2417. return rcode;
  2418. }
  2419. /* Make sure we have a controlling tty. If we get started under a job
  2420. * aware app (like bash for example), make sure we are now in charge so
  2421. * we don't fight over who gets the foreground */
  2422. static void setup_job_control(void)
  2423. {
  2424. static pid_t shell_pgrp;
  2425. /* Loop until we are in the foreground. */
  2426. while (tcgetpgrp (shell_terminal) != (shell_pgrp = getpgrp ()))
  2427. kill (- shell_pgrp, SIGTTIN);
  2428. /* Ignore interactive and job-control signals. */
  2429. signal(SIGINT, SIG_IGN);
  2430. signal(SIGQUIT, SIG_IGN);
  2431. signal(SIGTERM, SIG_IGN);
  2432. signal(SIGTSTP, SIG_IGN);
  2433. signal(SIGTTIN, SIG_IGN);
  2434. signal(SIGTTOU, SIG_IGN);
  2435. signal(SIGCHLD, SIG_IGN);
  2436. /* Put ourselves in our own process group. */
  2437. setsid();
  2438. shell_pgrp = getpid ();
  2439. setpgid (shell_pgrp, shell_pgrp);
  2440. /* Grab control of the terminal. */
  2441. tcsetpgrp(shell_terminal, shell_pgrp);
  2442. }
  2443. int hush_main(int argc, char **argv)
  2444. {
  2445. int opt;
  2446. FILE *input;
  2447. char **e = environ;
  2448. /* XXX what should these be while sourcing /etc/profile? */
  2449. global_argc = argc;
  2450. global_argv = argv;
  2451. /* (re?) initialize globals. Sometimes hush_main() ends up calling
  2452. * hush_main(), therefore we cannot rely on the BSS to zero out this
  2453. * stuff. Reset these to 0 every time. */
  2454. ifs = NULL;
  2455. /* map[] is taken care of with call to update_ifs_map() */
  2456. fake_mode = 0;
  2457. interactive = 0;
  2458. close_me_head = NULL;
  2459. last_bg_pid = 0;
  2460. job_list = NULL;
  2461. last_jobid = 0;
  2462. /* Initialize some more globals to non-zero values */
  2463. set_cwd();
  2464. if (ENABLE_FEATURE_COMMAND_EDITING) cmdedit_set_initial_prompt();
  2465. else PS1 = NULL;
  2466. PS2 = "> ";
  2467. /* initialize our shell local variables with the values
  2468. * currently living in the environment */
  2469. if (e) {
  2470. for (; *e; e++)
  2471. set_local_var(*e, 2); /* without call putenv() */
  2472. }
  2473. last_return_code=EXIT_SUCCESS;
  2474. if (argv[0] && argv[0][0] == '-') {
  2475. debug_printf("\nsourcing /etc/profile\n");
  2476. if ((input = fopen("/etc/profile", "r")) != NULL) {
  2477. mark_open(fileno(input));
  2478. parse_file_outer(input);
  2479. mark_closed(fileno(input));
  2480. fclose(input);
  2481. }
  2482. }
  2483. input=stdin;
  2484. while ((opt = getopt(argc, argv, "c:xif")) > 0) {
  2485. switch (opt) {
  2486. case 'c':
  2487. {
  2488. global_argv = argv+optind;
  2489. global_argc = argc-optind;
  2490. opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
  2491. goto final_return;
  2492. }
  2493. break;
  2494. case 'i':
  2495. interactive++;
  2496. break;
  2497. case 'f':
  2498. fake_mode++;
  2499. break;
  2500. default:
  2501. #ifndef BB_VER
  2502. fprintf(stderr, "Usage: sh [FILE]...\n"
  2503. " or: sh -c command [args]...\n\n");
  2504. exit(EXIT_FAILURE);
  2505. #else
  2506. bb_show_usage();
  2507. #endif
  2508. }
  2509. }
  2510. /* A shell is interactive if the `-i' flag was given, or if all of
  2511. * the following conditions are met:
  2512. * no -c command
  2513. * no arguments remaining or the -s flag given
  2514. * standard input is a terminal
  2515. * standard output is a terminal
  2516. * Refer to Posix.2, the description of the `sh' utility. */
  2517. if (argv[optind]==NULL && input==stdin &&
  2518. isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  2519. interactive++;
  2520. }
  2521. debug_printf("\ninteractive=%d\n", interactive);
  2522. if (interactive) {
  2523. /* Looks like they want an interactive shell */
  2524. #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
  2525. printf( "\n\n%s hush - the humble shell v0.01 (testing)\n",
  2526. BB_BANNER);
  2527. printf( "Enter 'help' for a list of built-in commands.\n\n");
  2528. #endif
  2529. setup_job_control();
  2530. }
  2531. if (argv[optind]==NULL) {
  2532. opt=parse_file_outer(stdin);
  2533. goto final_return;
  2534. }
  2535. debug_printf("\nrunning script '%s'\n", argv[optind]);
  2536. global_argv = argv+optind;
  2537. global_argc = argc-optind;
  2538. input = xfopen(argv[optind], "r");
  2539. opt = parse_file_outer(input);
  2540. #ifdef CONFIG_FEATURE_CLEAN_UP
  2541. fclose(input);
  2542. if (cwd && cwd != bb_msg_unknown)
  2543. free((char*)cwd);
  2544. {
  2545. struct variables *cur, *tmp;
  2546. for(cur = top_vars; cur; cur = tmp) {
  2547. tmp = cur->next;
  2548. if (!cur->flg_read_only) {
  2549. free(cur->name);
  2550. free(cur->value);
  2551. free(cur);
  2552. }
  2553. }
  2554. }
  2555. #endif
  2556. final_return:
  2557. return opt ? opt : last_return_code;
  2558. }
  2559. static char *insert_var_value(char *inp)
  2560. {
  2561. int res_str_len = 0;
  2562. int len;
  2563. int done = 0;
  2564. char *p, *p1, *res_str = NULL;
  2565. while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
  2566. if (p != inp) {
  2567. len = p - inp;
  2568. res_str = xrealloc(res_str, (res_str_len + len));
  2569. strncpy((res_str + res_str_len), inp, len);
  2570. res_str_len += len;
  2571. }
  2572. inp = ++p;
  2573. p = strchr(inp, SPECIAL_VAR_SYMBOL);
  2574. *p = '\0';
  2575. if ((p1 = lookup_param(inp))) {
  2576. len = res_str_len + strlen(p1);
  2577. res_str = xrealloc(res_str, (1 + len));
  2578. strcpy((res_str + res_str_len), p1);
  2579. res_str_len = len;
  2580. }
  2581. *p = SPECIAL_VAR_SYMBOL;
  2582. inp = ++p;
  2583. done = 1;
  2584. }
  2585. if (done) {
  2586. res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
  2587. strcpy((res_str + res_str_len), inp);
  2588. while ((p = strchr(res_str, '\n'))) {
  2589. *p = ' ';
  2590. }
  2591. }
  2592. return (res_str == NULL) ? inp : res_str;
  2593. }
  2594. static char **make_list_in(char **inp, char *name)
  2595. {
  2596. int len, i;
  2597. int name_len = strlen(name);
  2598. int n = 0;
  2599. char **list;
  2600. char *p1, *p2, *p3;
  2601. /* create list of variable values */
  2602. list = xmalloc(sizeof(*list));
  2603. for (i = 0; inp[i]; i++) {
  2604. p3 = insert_var_value(inp[i]);
  2605. p1 = p3;
  2606. while (*p1) {
  2607. if ((*p1 == ' ')) {
  2608. p1++;
  2609. continue;
  2610. }
  2611. if ((p2 = strchr(p1, ' '))) {
  2612. len = p2 - p1;
  2613. } else {
  2614. len = strlen(p1);
  2615. p2 = p1 + len;
  2616. }
  2617. /* we use n + 2 in realloc for list,because we add
  2618. * new element and then we will add NULL element */
  2619. list = xrealloc(list, sizeof(*list) * (n + 2));
  2620. list[n] = xmalloc(2 + name_len + len);
  2621. strcpy(list[n], name);
  2622. strcat(list[n], "=");
  2623. strncat(list[n], p1, len);
  2624. list[n++][name_len + len + 1] = '\0';
  2625. p1 = p2;
  2626. }
  2627. if (p3 != inp[i]) free(p3);
  2628. }
  2629. list[n] = NULL;
  2630. return list;
  2631. }
  2632. /* Make new string for parser */
  2633. static char * make_string(char ** inp)
  2634. {
  2635. char *p;
  2636. char *str = NULL;
  2637. int n;
  2638. int len = 2;
  2639. for (n = 0; inp[n]; n++) {
  2640. p = insert_var_value(inp[n]);
  2641. str = xrealloc(str, (len + strlen(p)));
  2642. if (n) {
  2643. strcat(str, " ");
  2644. } else {
  2645. *str = '\0';
  2646. }
  2647. strcat(str, p);
  2648. len = strlen(str) + 3;
  2649. if (p != inp[n]) free(p);
  2650. }
  2651. len = strlen(str);
  2652. *(str + len) = '\n';
  2653. *(str + len + 1) = '\0';
  2654. return str;
  2655. }