hush.c 79 KB

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