hush.c 80 KB

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