devfsd.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  4. */
  5. /*
  6. devfsd implementation for busybox
  7. Copyright (C) 2003 by Tito Ragusa <farmatito@tiscali.it>
  8. Busybox version is based on some previous work and ideas
  9. Copyright (C) [2003] by [Matteo Croce] <3297627799@wind.it>
  10. devfsd.c
  11. Main file for devfsd (devfs daemon for Linux).
  12. Copyright (C) 1998-2002 Richard Gooch
  13. devfsd.h
  14. Header file for devfsd (devfs daemon for Linux).
  15. Copyright (C) 1998-2000 Richard Gooch
  16. compat_name.c
  17. Compatibility name file for devfsd (build compatibility names).
  18. Copyright (C) 1998-2002 Richard Gooch
  19. expression.c
  20. This code provides Borne Shell-like expression expansion.
  21. Copyright (C) 1997-1999 Richard Gooch
  22. This program is free software; you can redistribute it and/or modify
  23. it under the terms of the GNU General Public License as published by
  24. the Free Software Foundation; either version 2 of the License, or
  25. (at your option) any later version.
  26. This program is distributed in the hope that it will be useful,
  27. but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. GNU General Public License for more details.
  30. You should have received a copy of the GNU General Public License
  31. along with this program; if not, write to the Free Software
  32. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  33. Richard Gooch may be reached by email at rgooch@atnf.csiro.au
  34. The postal address is:
  35. Richard Gooch, c/o ATNF, P. O. Box 76, Epping, N.S.W., 2121, Australia.
  36. */
  37. //usage:#define devfsd_trivial_usage
  38. //usage: "mntpnt [-v]" IF_DEVFSD_FG_NP("[-fg][-np]")
  39. //usage:#define devfsd_full_usage "\n\n"
  40. //usage: "Manage devfs permissions and old device name symlinks\n"
  41. //usage: "\n mntpnt The mount point where devfs is mounted"
  42. //usage: "\n -v Print the protocol version numbers for devfsd"
  43. //usage: "\n and the kernel-side protocol version and exit"
  44. //usage: IF_DEVFSD_FG_NP(
  45. //usage: "\n -fg Run in foreground"
  46. //usage: "\n -np Exit after parsing the configuration file"
  47. //usage: "\n and processing synthetic REGISTER events,"
  48. //usage: "\n don't poll for events"
  49. //usage: )
  50. #include "libbb.h"
  51. #include "xregex.h"
  52. #include <syslog.h>
  53. #include <sys/un.h>
  54. #include <sys/sysmacros.h>
  55. /* Various defines taken from linux/major.h */
  56. #define IDE0_MAJOR 3
  57. #define IDE1_MAJOR 22
  58. #define IDE2_MAJOR 33
  59. #define IDE3_MAJOR 34
  60. #define IDE4_MAJOR 56
  61. #define IDE5_MAJOR 57
  62. #define IDE6_MAJOR 88
  63. #define IDE7_MAJOR 89
  64. #define IDE8_MAJOR 90
  65. #define IDE9_MAJOR 91
  66. /* Various defines taken from linux/devfs_fs.h */
  67. #define DEVFSD_PROTOCOL_REVISION_KERNEL 5
  68. #define DEVFSD_IOCTL_BASE 'd'
  69. /* These are the various ioctls */
  70. #define DEVFSDIOC_GET_PROTO_REV _IOR(DEVFSD_IOCTL_BASE, 0, int)
  71. #define DEVFSDIOC_SET_EVENT_MASK _IOW(DEVFSD_IOCTL_BASE, 2, int)
  72. #define DEVFSDIOC_RELEASE_EVENT_QUEUE _IOW(DEVFSD_IOCTL_BASE, 3, int)
  73. #define DEVFSDIOC_SET_CONFIG_DEBUG_MASK _IOW(DEVFSD_IOCTL_BASE, 4, int)
  74. #define DEVFSD_NOTIFY_REGISTERED 0
  75. #define DEVFSD_NOTIFY_UNREGISTERED 1
  76. #define DEVFSD_NOTIFY_ASYNC_OPEN 2
  77. #define DEVFSD_NOTIFY_CLOSE 3
  78. #define DEVFSD_NOTIFY_LOOKUP 4
  79. #define DEVFSD_NOTIFY_CHANGE 5
  80. #define DEVFSD_NOTIFY_CREATE 6
  81. #define DEVFSD_NOTIFY_DELETE 7
  82. #define DEVFS_PATHLEN 1024
  83. /* Never change this otherwise the binary interface will change */
  84. struct devfsd_notify_struct {
  85. /* Use native C types to ensure same types in kernel and user space */
  86. unsigned int type; /* DEVFSD_NOTIFY_* value */
  87. unsigned int mode; /* Mode of the inode or device entry */
  88. unsigned int major; /* Major number of device entry */
  89. unsigned int minor; /* Minor number of device entry */
  90. unsigned int uid; /* Uid of process, inode or device entry */
  91. unsigned int gid; /* Gid of process, inode or device entry */
  92. unsigned int overrun_count; /* Number of lost events */
  93. unsigned int namelen; /* Number of characters not including '\0' */
  94. /* The device name MUST come last */
  95. char devname[DEVFS_PATHLEN]; /* This will be '\0' terminated */
  96. };
  97. #define BUFFER_SIZE 16384
  98. #define DEVFSD_VERSION "1.3.25"
  99. #define CONFIG_FILE "/etc/devfsd.conf"
  100. #define MODPROBE "/sbin/modprobe"
  101. #define MODPROBE_SWITCH_1 "-k"
  102. #define MODPROBE_SWITCH_2 "-C"
  103. #define CONFIG_MODULES_DEVFS "/etc/modules.devfs"
  104. #define MAX_ARGS (6 + 1)
  105. #define MAX_SUBEXPR 10
  106. #define STRING_LENGTH 255
  107. /* for get_uid_gid() */
  108. #define UID 0
  109. #define GID 1
  110. /* fork_and_execute() */
  111. # define DIE 1
  112. # define NO_DIE 0
  113. /* for dir_operation() */
  114. #define RESTORE 0
  115. #define SERVICE 1
  116. #define READ_CONFIG 2
  117. /* Update only after changing code to reflect new protocol */
  118. #define DEVFSD_PROTOCOL_REVISION_DAEMON 5
  119. /* Compile-time check */
  120. #if DEVFSD_PROTOCOL_REVISION_KERNEL != DEVFSD_PROTOCOL_REVISION_DAEMON
  121. #error protocol version mismatch. Update your kernel headers
  122. #endif
  123. #define AC_PERMISSIONS 0
  124. #define AC_MODLOAD 1
  125. #define AC_EXECUTE 2
  126. #define AC_MFUNCTION 3 /* not supported by busybox */
  127. #define AC_CFUNCTION 4 /* not supported by busybox */
  128. #define AC_COPY 5
  129. #define AC_IGNORE 6
  130. #define AC_MKOLDCOMPAT 7
  131. #define AC_MKNEWCOMPAT 8
  132. #define AC_RMOLDCOMPAT 9
  133. #define AC_RMNEWCOMPAT 10
  134. #define AC_RESTORE 11
  135. struct permissions_type {
  136. mode_t mode;
  137. uid_t uid;
  138. gid_t gid;
  139. };
  140. struct execute_type {
  141. char *argv[MAX_ARGS + 1]; /* argv[0] must always be the programme */
  142. };
  143. struct copy_type {
  144. const char *source;
  145. const char *destination;
  146. };
  147. struct action_type {
  148. unsigned int what;
  149. unsigned int when;
  150. };
  151. struct config_entry_struct {
  152. struct action_type action;
  153. regex_t preg;
  154. union
  155. {
  156. struct permissions_type permissions;
  157. struct execute_type execute;
  158. struct copy_type copy;
  159. }
  160. u;
  161. struct config_entry_struct *next;
  162. };
  163. struct get_variable_info {
  164. const struct devfsd_notify_struct *info;
  165. const char *devname;
  166. char devpath[STRING_LENGTH];
  167. };
  168. static void dir_operation(int , const char * , int, unsigned long*);
  169. static void service(struct stat statbuf, char *path);
  170. static int st_expr_expand(char *, unsigned, const char *, const char *(*)(const char *, void *), void *);
  171. static const char *get_old_name(const char *, unsigned, char *, unsigned, unsigned);
  172. static int mksymlink(const char *oldpath, const char *newpath);
  173. static void read_config_file(char *path, int optional, unsigned long *event_mask);
  174. static void process_config_line(const char *, unsigned long *);
  175. static int do_servicing(int, unsigned long);
  176. static void service_name(const struct devfsd_notify_struct *);
  177. static void action_permissions(const struct devfsd_notify_struct *, const struct config_entry_struct *);
  178. static void action_execute(const struct devfsd_notify_struct *, const struct config_entry_struct *,
  179. const regmatch_t *, unsigned);
  180. static void action_modload(const struct devfsd_notify_struct *info, const struct config_entry_struct *entry);
  181. static void action_copy(const struct devfsd_notify_struct *, const struct config_entry_struct *,
  182. const regmatch_t *, unsigned);
  183. static void action_compat(const struct devfsd_notify_struct *, unsigned);
  184. static void free_config(void);
  185. static void restore(char *spath, struct stat source_stat, int rootlen);
  186. static int copy_inode(const char *, const struct stat *, mode_t, const char *, const struct stat *);
  187. static mode_t get_mode(const char *);
  188. static void signal_handler(int);
  189. static const char *get_variable(const char *, void *);
  190. static int make_dir_tree(const char *);
  191. static int expand_expression(char *, unsigned, const char *, const char *(*)(const char *, void *), void *,
  192. const char *, const regmatch_t *, unsigned);
  193. static void expand_regexp(char *, size_t, const char *, const char *, const regmatch_t *, unsigned);
  194. static const char *expand_variable( char *, unsigned, unsigned *, const char *,
  195. const char *(*)(const char *, void *), void *);
  196. static const char *get_variable_v2(const char *, const char *(*)(const char *, void *), void *);
  197. static char get_old_ide_name(unsigned , unsigned);
  198. static char *write_old_sd_name(char *, unsigned, unsigned, const char *);
  199. /* busybox functions */
  200. static int get_uid_gid(int flag, const char *string);
  201. static void safe_memcpy(char * dest, const char * src, int len);
  202. static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr);
  203. static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr);
  204. /* Structs and vars */
  205. static struct config_entry_struct *first_config = NULL;
  206. static struct config_entry_struct *last_config = NULL;
  207. static char *mount_point = NULL;
  208. static volatile int caught_signal = FALSE;
  209. static volatile int caught_sighup = FALSE;
  210. static struct initial_symlink_struct {
  211. const char *dest;
  212. const char *name;
  213. } initial_symlinks[] = {
  214. {"/proc/self/fd", "fd"},
  215. {"fd/0", "stdin"},
  216. {"fd/1", "stdout"},
  217. {"fd/2", "stderr"},
  218. {NULL, NULL},
  219. };
  220. static struct event_type {
  221. unsigned int type; /* The DEVFSD_NOTIFY_* value */
  222. const char *config_name; /* The name used in the config file */
  223. } event_types[] = {
  224. {DEVFSD_NOTIFY_REGISTERED, "REGISTER"},
  225. {DEVFSD_NOTIFY_UNREGISTERED, "UNREGISTER"},
  226. {DEVFSD_NOTIFY_ASYNC_OPEN, "ASYNC_OPEN"},
  227. {DEVFSD_NOTIFY_CLOSE, "CLOSE"},
  228. {DEVFSD_NOTIFY_LOOKUP, "LOOKUP"},
  229. {DEVFSD_NOTIFY_CHANGE, "CHANGE"},
  230. {DEVFSD_NOTIFY_CREATE, "CREATE"},
  231. {DEVFSD_NOTIFY_DELETE, "DELETE"},
  232. {0xffffffff, NULL}
  233. };
  234. /* Busybox messages */
  235. static const char bb_msg_proto_rev[] ALIGN1 = "protocol revision";
  236. static const char bb_msg_bad_config[] ALIGN1 = "bad %s config file: %s";
  237. static const char bb_msg_small_buffer[] ALIGN1 = "buffer too small";
  238. static const char bb_msg_variable_not_found[] ALIGN1 = "variable: %s not found";
  239. /* Busybox stuff */
  240. #if ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG
  241. #define info_logger(p, fmt, args...) bb_info_msg(fmt, ## args)
  242. #define msg_logger(p, fmt, args...) bb_error_msg(fmt, ## args)
  243. #define msg_logger_and_die(p, fmt, args...) bb_error_msg_and_die(fmt, ## args)
  244. #define error_logger(p, fmt, args...) bb_perror_msg(fmt, ## args)
  245. #define error_logger_and_die(p, fmt, args...) bb_perror_msg_and_die(fmt, ## args)
  246. #else
  247. #define info_logger(p, fmt, args...)
  248. #define msg_logger(p, fmt, args...)
  249. #define msg_logger_and_die(p, fmt, args...) exit(EXIT_FAILURE)
  250. #define error_logger(p, fmt, args...)
  251. #define error_logger_and_die(p, fmt, args...) exit(EXIT_FAILURE)
  252. #endif
  253. static void safe_memcpy(char *dest, const char *src, int len)
  254. {
  255. memcpy(dest , src, len);
  256. dest[len] = '\0';
  257. }
  258. static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr)
  259. {
  260. if (d[n - 4] == 'd' && d[n - 3] == 'i' && d[n - 2] == 's' && d[n - 1] == 'c')
  261. return 2 + addendum;
  262. if (d[n - 2] == 'c' && d[n - 1] == 'd')
  263. return 3 + addendum;
  264. if (ptr[0] == 'p' && ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == 't')
  265. return 4 + addendum;
  266. if (ptr[n - 2] == 'm' && ptr[n - 1] == 't')
  267. return 5 + addendum;
  268. return 0;
  269. }
  270. static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr)
  271. {
  272. if (d[0] == 's' && d[1] == 'c' && d[2] == 's' && d[3] == 'i' && d[4] == '/') {
  273. if (d[n - 7] == 'g' && d[n - 6] == 'e' && d[n - 5] == 'n'
  274. && d[n - 4] == 'e' && d[n - 3] == 'r' && d[n - 2] == 'i' && d[n - 1] == 'c'
  275. )
  276. return 1;
  277. return scan_dev_name_common(d, n, 0, ptr);
  278. }
  279. if (d[0] == 'i' && d[1] == 'd' && d[2] == 'e' && d[3] == '/'
  280. && d[4] == 'h' && d[5] == 'o' && d[6] == 's' && d[7] == 't'
  281. )
  282. return scan_dev_name_common(d, n, 4, ptr);
  283. if (d[0] == 's' && d[1] == 'b' && d[2] == 'p' && d[3] == '/')
  284. return 10;
  285. if (d[0] == 'v' && d[1] == 'c' && d[2] == 'c' && d[3] == '/')
  286. return 11;
  287. if (d[0] == 'p' && d[1] == 't' && d[2] == 'y' && d[3] == '/')
  288. return 12;
  289. return 0;
  290. }
  291. /* Public functions follow */
  292. int devfsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  293. int devfsd_main(int argc, char **argv)
  294. {
  295. int print_version = FALSE;
  296. int do_daemon = TRUE;
  297. int no_polling = FALSE;
  298. int do_scan;
  299. int fd, proto_rev, count;
  300. unsigned long event_mask = 0;
  301. struct sigaction new_action;
  302. struct initial_symlink_struct *curr;
  303. if (argc < 2)
  304. bb_show_usage();
  305. for (count = 2; count < argc; ++count) {
  306. if (argv[count][0] == '-') {
  307. if (argv[count][1] == 'v' && !argv[count][2]) /* -v */
  308. print_version = TRUE;
  309. else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'f'
  310. && argv[count][2] == 'g' && !argv[count][3]) /* -fg */
  311. do_daemon = FALSE;
  312. else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'n'
  313. && argv[count][2] == 'p' && !argv[count][3]) /* -np */
  314. no_polling = TRUE;
  315. else
  316. bb_show_usage();
  317. }
  318. }
  319. mount_point = bb_simplify_path(argv[1]);
  320. xchdir(mount_point);
  321. fd = xopen(".devfsd", O_RDONLY);
  322. close_on_exec_on(fd);
  323. xioctl(fd, DEVFSDIOC_GET_PROTO_REV, &proto_rev);
  324. /*setup initial entries */
  325. for (curr = initial_symlinks; curr->dest != NULL; ++curr)
  326. symlink(curr->dest, curr->name);
  327. /* NB: The check for CONFIG_FILE is done in read_config_file() */
  328. if (print_version || (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)) {
  329. printf("%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n",
  330. applet_name, DEVFSD_VERSION, bb_msg_proto_rev,
  331. DEVFSD_PROTOCOL_REVISION_DAEMON, bb_msg_proto_rev, proto_rev);
  332. if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)
  333. bb_error_msg_and_die("%s mismatch!", bb_msg_proto_rev);
  334. exit(EXIT_SUCCESS); /* -v */
  335. }
  336. /* Tell kernel we are special(i.e. we get to see hidden entries) */
  337. xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, 0);
  338. /* Set up SIGHUP and SIGUSR1 handlers */
  339. sigemptyset(&new_action.sa_mask);
  340. new_action.sa_flags = 0;
  341. new_action.sa_handler = signal_handler;
  342. sigaction_set(SIGHUP, &new_action);
  343. sigaction_set(SIGUSR1, &new_action);
  344. printf("%s v%s started for %s\n", applet_name, DEVFSD_VERSION, mount_point);
  345. /* Set umask so that mknod(2), open(2) and mkdir(2) have complete control over permissions */
  346. umask(0);
  347. read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
  348. /* Do the scan before forking, so that boot scripts see the finished product */
  349. dir_operation(SERVICE, mount_point, 0, NULL);
  350. if (ENABLE_DEVFSD_FG_NP && no_polling)
  351. exit(EXIT_SUCCESS);
  352. if (ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG)
  353. logmode = LOGMODE_BOTH;
  354. else if (do_daemon == TRUE)
  355. logmode = LOGMODE_SYSLOG;
  356. /* This is the default */
  357. /*else
  358. logmode = LOGMODE_STDIO; */
  359. if (do_daemon) {
  360. /* Release so that the child can grab it */
  361. xioctl(fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0);
  362. bb_daemonize_or_rexec(0, argv);
  363. } else if (ENABLE_DEVFSD_FG_NP) {
  364. setpgid(0, 0); /* Become process group leader */
  365. }
  366. while (TRUE) {
  367. do_scan = do_servicing(fd, event_mask);
  368. free_config();
  369. read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
  370. if (do_scan)
  371. dir_operation(SERVICE, mount_point, 0, NULL);
  372. }
  373. if (ENABLE_FEATURE_CLEAN_UP) free(mount_point);
  374. } /* End Function main */
  375. /* Private functions follow */
  376. static void read_config_file(char *path, int optional, unsigned long *event_mask)
  377. /* [SUMMARY] Read a configuration database.
  378. <path> The path to read the database from. If this is a directory, all
  379. entries in that directory will be read(except hidden entries).
  380. <optional> If TRUE, the routine will silently ignore a missing config file.
  381. <event_mask> The event mask is written here. This is not initialised.
  382. [RETURNS] Nothing.
  383. */
  384. {
  385. struct stat statbuf;
  386. FILE *fp;
  387. char buf[STRING_LENGTH];
  388. char *line = NULL;
  389. char *p;
  390. if (stat(path, &statbuf) == 0) {
  391. /* Don't read 0 length files: ignored */
  392. /*if (statbuf.st_size == 0)
  393. return;*/
  394. if (S_ISDIR(statbuf.st_mode)) {
  395. p = bb_simplify_path(path);
  396. dir_operation(READ_CONFIG, p, 0, event_mask);
  397. free(p);
  398. return;
  399. }
  400. fp = fopen_for_read(path);
  401. if (fp != NULL) {
  402. while (fgets(buf, STRING_LENGTH, fp) != NULL) {
  403. /* Skip whitespace */
  404. line = buf;
  405. line = skip_whitespace(line);
  406. if (line[0] == '\0' || line[0] == '#')
  407. continue;
  408. process_config_line(line, event_mask);
  409. }
  410. fclose(fp);
  411. } else {
  412. goto read_config_file_err;
  413. }
  414. } else {
  415. read_config_file_err:
  416. if (optional == 0 && errno == ENOENT)
  417. error_logger_and_die(LOG_ERR, "read config file: %s", path);
  418. }
  419. } /* End Function read_config_file */
  420. static void process_config_line(const char *line, unsigned long *event_mask)
  421. /* [SUMMARY] Process a line from a configuration file.
  422. <line> The configuration line.
  423. <event_mask> The event mask is written here. This is not initialised.
  424. [RETURNS] Nothing.
  425. */
  426. {
  427. int num_args, count;
  428. struct config_entry_struct *new;
  429. char p[MAX_ARGS][STRING_LENGTH];
  430. char when[STRING_LENGTH], what[STRING_LENGTH];
  431. char name[STRING_LENGTH];
  432. const char *msg = "";
  433. char *ptr;
  434. int i;
  435. /* !!!! Only Uppercase Keywords in devsfd.conf */
  436. static const char options[] ALIGN1 =
  437. "CLEAR_CONFIG\0""INCLUDE\0""OPTIONAL_INCLUDE\0"
  438. "RESTORE\0""PERMISSIONS\0""MODLOAD\0""EXECUTE\0"
  439. "COPY\0""IGNORE\0""MKOLDCOMPAT\0""MKNEWCOMPAT\0"
  440. "RMOLDCOMPAT\0""RMNEWCOMPAT\0";
  441. for (count = 0; count < MAX_ARGS; ++count)
  442. p[count][0] = '\0';
  443. num_args = sscanf(line, "%s %s %s %s %s %s %s %s %s %s",
  444. when, name, what,
  445. p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
  446. i = index_in_strings(options, when);
  447. /* "CLEAR_CONFIG" */
  448. if (i == 0) {
  449. free_config();
  450. *event_mask = 0;
  451. return;
  452. }
  453. if (num_args < 2)
  454. goto process_config_line_err;
  455. /* "INCLUDE" & "OPTIONAL_INCLUDE" */
  456. if (i == 1 || i == 2) {
  457. st_expr_expand(name, STRING_LENGTH, name, get_variable, NULL);
  458. info_logger(LOG_INFO, "%sinclude: %s", (toupper(when[0]) == 'I') ? "": "optional_", name);
  459. read_config_file(name, (toupper(when[0]) == 'I') ? FALSE : TRUE, event_mask);
  460. return;
  461. }
  462. /* "RESTORE" */
  463. if (i == 3) {
  464. dir_operation(RESTORE, name, strlen(name),NULL);
  465. return;
  466. }
  467. if (num_args < 3)
  468. goto process_config_line_err;
  469. new = xzalloc(sizeof *new);
  470. for (count = 0; event_types[count].config_name != NULL; ++count) {
  471. if (strcasecmp(when, event_types[count].config_name) != 0)
  472. continue;
  473. new->action.when = event_types[count].type;
  474. break;
  475. }
  476. if (event_types[count].config_name == NULL) {
  477. msg = "WHEN in";
  478. goto process_config_line_err;
  479. }
  480. i = index_in_strings(options, what);
  481. switch (i) {
  482. case 4: /* "PERMISSIONS" */
  483. new->action.what = AC_PERMISSIONS;
  484. /* Get user and group */
  485. ptr = strchr(p[0], '.');
  486. if (ptr == NULL) {
  487. msg = "UID.GID";
  488. goto process_config_line_err; /*"missing '.' in UID.GID"*/
  489. }
  490. *ptr++ = '\0';
  491. new->u.permissions.uid = get_uid_gid(UID, p[0]);
  492. new->u.permissions.gid = get_uid_gid(GID, ptr);
  493. /* Get mode */
  494. new->u.permissions.mode = get_mode(p[1]);
  495. break;
  496. case 5: /* MODLOAD */
  497. /*This action will pass "/dev/$devname"(i.e. "/dev/" prefixed to
  498. the device name) to the module loading facility. In addition,
  499. the /etc/modules.devfs configuration file is used.*/
  500. if (ENABLE_DEVFSD_MODLOAD)
  501. new->action.what = AC_MODLOAD;
  502. break;
  503. case 6: /* EXECUTE */
  504. new->action.what = AC_EXECUTE;
  505. num_args -= 3;
  506. for (count = 0; count < num_args; ++count)
  507. new->u.execute.argv[count] = xstrdup(p[count]);
  508. new->u.execute.argv[num_args] = NULL;
  509. break;
  510. case 7: /* COPY */
  511. new->action.what = AC_COPY;
  512. num_args -= 3;
  513. if (num_args != 2)
  514. goto process_config_line_err; /* missing path and function in line */
  515. new->u.copy.source = xstrdup(p[0]);
  516. new->u.copy.destination = xstrdup(p[1]);
  517. break;
  518. case 8: /* IGNORE */
  519. /* FALLTROUGH */
  520. case 9: /* MKOLDCOMPAT */
  521. /* FALLTROUGH */
  522. case 10: /* MKNEWCOMPAT */
  523. /* FALLTROUGH */
  524. case 11:/* RMOLDCOMPAT */
  525. /* FALLTROUGH */
  526. case 12: /* RMNEWCOMPAT */
  527. /* AC_IGNORE 6
  528. AC_MKOLDCOMPAT 7
  529. AC_MKNEWCOMPAT 8
  530. AC_RMOLDCOMPAT 9
  531. AC_RMNEWCOMPAT 10*/
  532. new->action.what = i - 2;
  533. break;
  534. default:
  535. msg = "WHAT in";
  536. goto process_config_line_err;
  537. /*esac*/
  538. } /* switch (i) */
  539. xregcomp(&new->preg, name, REG_EXTENDED);
  540. *event_mask |= 1 << new->action.when;
  541. new->next = NULL;
  542. if (first_config == NULL)
  543. first_config = new;
  544. else
  545. last_config->next = new;
  546. last_config = new;
  547. return;
  548. process_config_line_err:
  549. msg_logger_and_die(LOG_ERR, bb_msg_bad_config, msg , line);
  550. } /* End Function process_config_line */
  551. static int do_servicing(int fd, unsigned long event_mask)
  552. /* [SUMMARY] Service devfs changes until a signal is received.
  553. <fd> The open control file.
  554. <event_mask> The event mask.
  555. [RETURNS] TRUE if SIGHUP was caught, else FALSE.
  556. */
  557. {
  558. ssize_t bytes;
  559. struct devfsd_notify_struct info;
  560. /* (void*) cast is only in order to match prototype */
  561. xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, (void*)event_mask);
  562. while (!caught_signal) {
  563. errno = 0;
  564. bytes = read(fd, (char *) &info, sizeof info);
  565. if (caught_signal)
  566. break; /* Must test for this first */
  567. if (errno == EINTR)
  568. continue; /* Yes, the order is important */
  569. if (bytes < 1)
  570. break;
  571. service_name(&info);
  572. }
  573. if (caught_signal) {
  574. int c_sighup = caught_sighup;
  575. caught_signal = FALSE;
  576. caught_sighup = FALSE;
  577. return c_sighup;
  578. }
  579. msg_logger_and_die(LOG_ERR, "read error on control file");
  580. } /* End Function do_servicing */
  581. static void service_name(const struct devfsd_notify_struct *info)
  582. /* [SUMMARY] Service a single devfs change.
  583. <info> The devfs change.
  584. [RETURNS] Nothing.
  585. */
  586. {
  587. unsigned int n;
  588. regmatch_t mbuf[MAX_SUBEXPR];
  589. struct config_entry_struct *entry;
  590. if (ENABLE_DEBUG && info->overrun_count > 0)
  591. msg_logger(LOG_ERR, "lost %u events", info->overrun_count);
  592. /* Discard lookups on "/dev/log" and "/dev/initctl" */
  593. if (info->type == DEVFSD_NOTIFY_LOOKUP
  594. && ((info->devname[0] == 'l' && info->devname[1] == 'o'
  595. && info->devname[2] == 'g' && !info->devname[3])
  596. || (info->devname[0] == 'i' && info->devname[1] == 'n'
  597. && info->devname[2] == 'i' && info->devname[3] == 't'
  598. && info->devname[4] == 'c' && info->devname[5] == 't'
  599. && info->devname[6] == 'l' && !info->devname[7]))
  600. )
  601. return;
  602. for (entry = first_config; entry != NULL; entry = entry->next) {
  603. /* First check if action matches the type, then check if name matches */
  604. if (info->type != entry->action.when
  605. || regexec(&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0)
  606. continue;
  607. for (n = 0;(n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n)
  608. /* VOID */;
  609. switch (entry->action.what) {
  610. case AC_PERMISSIONS:
  611. action_permissions(info, entry);
  612. break;
  613. case AC_MODLOAD:
  614. if (ENABLE_DEVFSD_MODLOAD)
  615. action_modload(info, entry);
  616. break;
  617. case AC_EXECUTE:
  618. action_execute(info, entry, mbuf, n);
  619. break;
  620. case AC_COPY:
  621. action_copy(info, entry, mbuf, n);
  622. break;
  623. case AC_IGNORE:
  624. return;
  625. /*break;*/
  626. case AC_MKOLDCOMPAT:
  627. case AC_MKNEWCOMPAT:
  628. case AC_RMOLDCOMPAT:
  629. case AC_RMNEWCOMPAT:
  630. action_compat(info, entry->action.what);
  631. break;
  632. default:
  633. msg_logger_and_die(LOG_ERR, "Unknown action");
  634. }
  635. }
  636. } /* End Function service_name */
  637. static void action_permissions(const struct devfsd_notify_struct *info,
  638. const struct config_entry_struct *entry)
  639. /* [SUMMARY] Update permissions for a device entry.
  640. <info> The devfs change.
  641. <entry> The config file entry.
  642. [RETURNS] Nothing.
  643. */
  644. {
  645. struct stat statbuf;
  646. if (stat(info->devname, &statbuf) != 0
  647. || chmod(info->devname, (statbuf.st_mode & S_IFMT) | (entry->u.permissions.mode & ~S_IFMT)) != 0
  648. || chown(info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0
  649. )
  650. error_logger(LOG_ERR, "Can't chmod or chown: %s", info->devname);
  651. } /* End Function action_permissions */
  652. static void action_modload(const struct devfsd_notify_struct *info,
  653. const struct config_entry_struct *entry UNUSED_PARAM)
  654. /* [SUMMARY] Load a module.
  655. <info> The devfs change.
  656. <entry> The config file entry.
  657. [RETURNS] Nothing.
  658. */
  659. {
  660. char *argv[6];
  661. argv[0] = (char*)MODPROBE;
  662. argv[1] = (char*)MODPROBE_SWITCH_1; /* "-k" */
  663. argv[2] = (char*)MODPROBE_SWITCH_2; /* "-C" */
  664. argv[3] = (char*)CONFIG_MODULES_DEVFS;
  665. argv[4] = concat_path_file("/dev", info->devname); /* device */
  666. argv[5] = NULL;
  667. spawn_and_wait(argv);
  668. free(argv[4]);
  669. } /* End Function action_modload */
  670. static void action_execute(const struct devfsd_notify_struct *info,
  671. const struct config_entry_struct *entry,
  672. const regmatch_t *regexpr, unsigned int numexpr)
  673. /* [SUMMARY] Execute a programme.
  674. <info> The devfs change.
  675. <entry> The config file entry.
  676. <regexpr> The number of subexpression(start, end) offsets within the
  677. device name.
  678. <numexpr> The number of elements within <<regexpr>>.
  679. [RETURNS] Nothing.
  680. */
  681. {
  682. unsigned int count;
  683. struct get_variable_info gv_info;
  684. char *argv[MAX_ARGS + 1];
  685. char largv[MAX_ARGS + 1][STRING_LENGTH];
  686. gv_info.info = info;
  687. gv_info.devname = info->devname;
  688. snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
  689. for (count = 0; entry->u.execute.argv[count] != NULL; ++count) {
  690. expand_expression(largv[count], STRING_LENGTH,
  691. entry->u.execute.argv[count],
  692. get_variable, &gv_info,
  693. gv_info.devname, regexpr, numexpr);
  694. argv[count] = largv[count];
  695. }
  696. argv[count] = NULL;
  697. spawn_and_wait(argv);
  698. } /* End Function action_execute */
  699. static void action_copy(const struct devfsd_notify_struct *info,
  700. const struct config_entry_struct *entry,
  701. const regmatch_t *regexpr, unsigned int numexpr)
  702. /* [SUMMARY] Copy permissions.
  703. <info> The devfs change.
  704. <entry> The config file entry.
  705. <regexpr> This list of subexpression(start, end) offsets within the
  706. device name.
  707. <numexpr> The number of elements in <<regexpr>>.
  708. [RETURNS] Nothing.
  709. */
  710. {
  711. mode_t new_mode;
  712. struct get_variable_info gv_info;
  713. struct stat source_stat, dest_stat;
  714. char source[STRING_LENGTH], destination[STRING_LENGTH];
  715. int ret = 0;
  716. dest_stat.st_mode = 0;
  717. if ((info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK(info->mode))
  718. return;
  719. gv_info.info = info;
  720. gv_info.devname = info->devname;
  721. snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
  722. expand_expression(source, STRING_LENGTH, entry->u.copy.source,
  723. get_variable, &gv_info, gv_info.devname,
  724. regexpr, numexpr);
  725. expand_expression(destination, STRING_LENGTH, entry->u.copy.destination,
  726. get_variable, &gv_info, gv_info.devname,
  727. regexpr, numexpr);
  728. if (!make_dir_tree(destination) || lstat(source, &source_stat) != 0)
  729. return;
  730. lstat(destination, &dest_stat);
  731. new_mode = source_stat.st_mode & ~S_ISVTX;
  732. if (info->type == DEVFSD_NOTIFY_CREATE)
  733. new_mode |= S_ISVTX;
  734. else if ((info->type == DEVFSD_NOTIFY_CHANGE) &&(dest_stat.st_mode & S_ISVTX))
  735. new_mode |= S_ISVTX;
  736. ret = copy_inode(destination, &dest_stat, new_mode, source, &source_stat);
  737. if (ENABLE_DEBUG && ret && (errno != EEXIST))
  738. error_logger(LOG_ERR, "copy_inode: %s to %s", source, destination);
  739. } /* End Function action_copy */
  740. static void action_compat(const struct devfsd_notify_struct *info, unsigned int action)
  741. /* [SUMMARY] Process a compatibility request.
  742. <info> The devfs change.
  743. <action> The action to take.
  744. [RETURNS] Nothing.
  745. */
  746. {
  747. int ret;
  748. const char *compat_name = NULL;
  749. const char *dest_name = info->devname;
  750. const char *ptr;
  751. char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH];
  752. int mode, host, bus, target, lun;
  753. unsigned int i;
  754. char rewind_;
  755. /* 1 to 5 "scsi/" , 6 to 9 "ide/host" */
  756. static const char *const fmt[] = {
  757. NULL ,
  758. "sg/c%db%dt%du%d", /* scsi/generic */
  759. "sd/c%db%dt%du%d", /* scsi/disc */
  760. "sr/c%db%dt%du%d", /* scsi/cd */
  761. "sd/c%db%dt%du%dp%d", /* scsi/part */
  762. "st/c%db%dt%du%dm%d%c", /* scsi/mt */
  763. "ide/hd/c%db%dt%du%d", /* ide/host/disc */
  764. "ide/cd/c%db%dt%du%d", /* ide/host/cd */
  765. "ide/hd/c%db%dt%du%dp%d", /* ide/host/part */
  766. "ide/mt/c%db%dt%du%d%s", /* ide/host/mt */
  767. NULL
  768. };
  769. /* First construct compatibility name */
  770. switch (action) {
  771. case AC_MKOLDCOMPAT:
  772. case AC_RMOLDCOMPAT:
  773. compat_name = get_old_name(info->devname, info->namelen, compat_buf, info->major, info->minor);
  774. break;
  775. case AC_MKNEWCOMPAT:
  776. case AC_RMNEWCOMPAT:
  777. ptr = bb_basename(info->devname);
  778. i = scan_dev_name(info->devname, info->namelen, ptr);
  779. /* nothing found */
  780. if (i == 0 || i > 9)
  781. return;
  782. sscanf(info->devname + ((i < 6) ? 5 : 4), "host%d/bus%d/target%d/lun%d/", &host, &bus, &target, &lun);
  783. snprintf(dest_buf, sizeof(dest_buf), "../%s", info->devname + (( i > 5) ? 4 : 0));
  784. dest_name = dest_buf;
  785. compat_name = compat_buf;
  786. /* 1 == scsi/generic 2 == scsi/disc 3 == scsi/cd 6 == ide/host/disc 7 == ide/host/cd */
  787. if (i == 1 || i == 2 || i == 3 || i == 6 || i ==7)
  788. sprintf(compat_buf, fmt[i], host, bus, target, lun);
  789. /* 4 == scsi/part 8 == ide/host/part */
  790. if (i == 4 || i == 8)
  791. sprintf(compat_buf, fmt[i], host, bus, target, lun, atoi(ptr + 4));
  792. /* 5 == scsi/mt */
  793. if (i == 5) {
  794. rewind_ = info->devname[info->namelen - 1];
  795. if (rewind_ != 'n')
  796. rewind_ = '\0';
  797. mode=0;
  798. if (ptr[2] == 'l' /*108*/ || ptr[2] == 'm'/*109*/)
  799. mode = ptr[2] - 107; /* 1 or 2 */
  800. if (ptr[2] == 'a')
  801. mode = 3;
  802. sprintf(compat_buf, fmt[i], host, bus, target, lun, mode, rewind_);
  803. }
  804. /* 9 == ide/host/mt */
  805. if (i == 9)
  806. snprintf(compat_buf, sizeof(compat_buf), fmt[i], host, bus, target, lun, ptr + 2);
  807. /* esac */
  808. } /* switch (action) */
  809. if (compat_name == NULL)
  810. return;
  811. /* Now decide what to do with it */
  812. switch (action) {
  813. case AC_MKOLDCOMPAT:
  814. case AC_MKNEWCOMPAT:
  815. mksymlink(dest_name, compat_name);
  816. break;
  817. case AC_RMOLDCOMPAT:
  818. case AC_RMNEWCOMPAT:
  819. ret = unlink(compat_name);
  820. if (ENABLE_DEBUG && ret)
  821. error_logger(LOG_ERR, "unlink: %s", compat_name);
  822. break;
  823. /*esac*/
  824. } /* switch (action) */
  825. } /* End Function action_compat */
  826. static void restore(char *spath, struct stat source_stat, int rootlen)
  827. {
  828. char *dpath;
  829. struct stat dest_stat;
  830. dest_stat.st_mode = 0;
  831. dpath = concat_path_file(mount_point, spath + rootlen);
  832. lstat(dpath, &dest_stat);
  833. free(dpath);
  834. if (S_ISLNK(source_stat.st_mode) || (source_stat.st_mode & S_ISVTX))
  835. copy_inode(dpath, &dest_stat, (source_stat.st_mode & ~S_ISVTX), spath, &source_stat);
  836. if (S_ISDIR(source_stat.st_mode))
  837. dir_operation(RESTORE, spath, rootlen, NULL);
  838. }
  839. static int copy_inode(const char *destpath, const struct stat *dest_stat,
  840. mode_t new_mode,
  841. const char *sourcepath, const struct stat *source_stat)
  842. /* [SUMMARY] Copy an inode.
  843. <destpath> The destination path. An existing inode may be deleted.
  844. <dest_stat> The destination stat(2) information.
  845. <new_mode> The desired new mode for the destination.
  846. <sourcepath> The source path.
  847. <source_stat> The source stat(2) information.
  848. [RETURNS] TRUE on success, else FALSE.
  849. */
  850. {
  851. int source_len, dest_len;
  852. char source_link[STRING_LENGTH], dest_link[STRING_LENGTH];
  853. int fd, val;
  854. struct sockaddr_un un_addr;
  855. char symlink_val[STRING_LENGTH];
  856. if ((source_stat->st_mode & S_IFMT) ==(dest_stat->st_mode & S_IFMT)) {
  857. /* Same type */
  858. if (S_ISLNK(source_stat->st_mode)) {
  859. source_len = readlink(sourcepath, source_link, STRING_LENGTH - 1);
  860. if ((source_len < 0)
  861. || (dest_len = readlink(destpath, dest_link, STRING_LENGTH - 1)) < 0
  862. )
  863. return FALSE;
  864. source_link[source_len] = '\0';
  865. dest_link[dest_len] = '\0';
  866. if ((source_len != dest_len) || (strcmp(source_link, dest_link) != 0)) {
  867. unlink(destpath);
  868. symlink(source_link, destpath);
  869. }
  870. return TRUE;
  871. } /* Else not a symlink */
  872. chmod(destpath, new_mode & ~S_IFMT);
  873. chown(destpath, source_stat->st_uid, source_stat->st_gid);
  874. return TRUE;
  875. }
  876. /* Different types: unlink and create */
  877. unlink(destpath);
  878. switch (source_stat->st_mode & S_IFMT) {
  879. case S_IFSOCK:
  880. fd = socket(AF_UNIX, SOCK_STREAM, 0);
  881. if (fd < 0)
  882. break;
  883. un_addr.sun_family = AF_UNIX;
  884. snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s", destpath);
  885. val = bind(fd, (struct sockaddr *) &un_addr, (int) sizeof un_addr);
  886. close(fd);
  887. if (val != 0 || chmod(destpath, new_mode & ~S_IFMT) != 0)
  888. break;
  889. goto do_chown;
  890. case S_IFLNK:
  891. val = readlink(sourcepath, symlink_val, STRING_LENGTH - 1);
  892. if (val < 0)
  893. break;
  894. symlink_val[val] = '\0';
  895. if (symlink(symlink_val, destpath) == 0)
  896. return TRUE;
  897. break;
  898. case S_IFREG:
  899. fd = open(destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT);
  900. if (fd < 0)
  901. break;
  902. close(fd);
  903. if (chmod(destpath, new_mode & ~S_IFMT) != 0)
  904. break;
  905. goto do_chown;
  906. case S_IFBLK:
  907. case S_IFCHR:
  908. case S_IFIFO:
  909. if (mknod(destpath, new_mode, source_stat->st_rdev) != 0)
  910. break;
  911. goto do_chown;
  912. case S_IFDIR:
  913. if (mkdir(destpath, new_mode & ~S_IFMT) != 0)
  914. break;
  915. do_chown:
  916. if (chown(destpath, source_stat->st_uid, source_stat->st_gid) == 0)
  917. return TRUE;
  918. /*break;*/
  919. }
  920. return FALSE;
  921. } /* End Function copy_inode */
  922. static void free_config(void)
  923. /* [SUMMARY] Free the configuration information.
  924. [RETURNS] Nothing.
  925. */
  926. {
  927. struct config_entry_struct *c_entry;
  928. void *next;
  929. for (c_entry = first_config; c_entry != NULL; c_entry = next) {
  930. unsigned int count;
  931. next = c_entry->next;
  932. regfree(&c_entry->preg);
  933. if (c_entry->action.what == AC_EXECUTE) {
  934. for (count = 0; count < MAX_ARGS; ++count) {
  935. if (c_entry->u.execute.argv[count] == NULL)
  936. break;
  937. free(c_entry->u.execute.argv[count]);
  938. }
  939. }
  940. free(c_entry);
  941. }
  942. first_config = NULL;
  943. last_config = NULL;
  944. } /* End Function free_config */
  945. static int get_uid_gid(int flag, const char *string)
  946. /* [SUMMARY] Convert a string to a UID or GID value.
  947. <flag> "UID" or "GID".
  948. <string> The string.
  949. [RETURNS] The UID or GID value.
  950. */
  951. {
  952. struct passwd *pw_ent;
  953. struct group *grp_ent;
  954. static const char *msg;
  955. if (ENABLE_DEVFSD_VERBOSE)
  956. msg = "user";
  957. if (isdigit(string[0]) ||((string[0] == '-') && isdigit(string[1])))
  958. return atoi(string);
  959. if (flag == UID && (pw_ent = getpwnam(string)) != NULL)
  960. return pw_ent->pw_uid;
  961. if (flag == GID && (grp_ent = getgrnam(string)) != NULL)
  962. return grp_ent->gr_gid;
  963. else if (ENABLE_DEVFSD_VERBOSE)
  964. msg = "group";
  965. if (ENABLE_DEVFSD_VERBOSE)
  966. msg_logger(LOG_ERR, "unknown %s: %s, defaulting to %cid=0", msg, string, msg[0]);
  967. return 0;
  968. }/* End Function get_uid_gid */
  969. static mode_t get_mode(const char *string)
  970. /* [SUMMARY] Convert a string to a mode value.
  971. <string> The string.
  972. [RETURNS] The mode value.
  973. */
  974. {
  975. mode_t mode;
  976. int i;
  977. if (isdigit(string[0]))
  978. return strtoul(string, NULL, 8);
  979. if (strlen(string) != 9)
  980. msg_logger_and_die(LOG_ERR, "bad mode: %s", string);
  981. mode = 0;
  982. i = S_IRUSR;
  983. while (i > 0) {
  984. if (string[0] == 'r' || string[0] == 'w' || string[0] == 'x')
  985. mode += i;
  986. i = i / 2;
  987. string++;
  988. }
  989. return mode;
  990. } /* End Function get_mode */
  991. static void signal_handler(int sig)
  992. {
  993. caught_signal = TRUE;
  994. if (sig == SIGHUP)
  995. caught_sighup = TRUE;
  996. info_logger(LOG_INFO, "Caught signal %d", sig);
  997. } /* End Function signal_handler */
  998. static const char *get_variable(const char *variable, void *info)
  999. {
  1000. static char sbuf[sizeof(int)*3 + 2]; /* sign and NUL */
  1001. static char *hostname;
  1002. struct get_variable_info *gv_info = info;
  1003. const char *field_names[] = {
  1004. "hostname", "mntpt", "devpath", "devname",
  1005. "uid", "gid", "mode", hostname, mount_point,
  1006. gv_info->devpath, gv_info->devname, NULL
  1007. };
  1008. int i;
  1009. if (!hostname)
  1010. hostname = safe_gethostname();
  1011. /* index_in_str_array returns i>=0 */
  1012. i = index_in_str_array(field_names, variable);
  1013. if (i > 6 || i < 0 || (i > 1 && gv_info == NULL))
  1014. return NULL;
  1015. if (i >= 0 && i <= 3)
  1016. return field_names[i + 7];
  1017. if (i == 4)
  1018. sprintf(sbuf, "%u", gv_info->info->uid);
  1019. else if (i == 5)
  1020. sprintf(sbuf, "%u", gv_info->info->gid);
  1021. else if (i == 6)
  1022. sprintf(sbuf, "%o", gv_info->info->mode);
  1023. return sbuf;
  1024. } /* End Function get_variable */
  1025. static void service(struct stat statbuf, char *path)
  1026. {
  1027. struct devfsd_notify_struct info;
  1028. memset(&info, 0, sizeof info);
  1029. info.type = DEVFSD_NOTIFY_REGISTERED;
  1030. info.mode = statbuf.st_mode;
  1031. info.major = major(statbuf.st_rdev);
  1032. info.minor = minor(statbuf.st_rdev);
  1033. info.uid = statbuf.st_uid;
  1034. info.gid = statbuf.st_gid;
  1035. snprintf(info.devname, sizeof(info.devname), "%s", path + strlen(mount_point) + 1);
  1036. info.namelen = strlen(info.devname);
  1037. service_name(&info);
  1038. if (S_ISDIR(statbuf.st_mode))
  1039. dir_operation(SERVICE, path, 0, NULL);
  1040. }
  1041. static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask)
  1042. /* [SUMMARY] Scan a directory tree and generate register events on leaf nodes.
  1043. <flag> To choose which function to perform
  1044. <dp> The directory pointer. This is closed upon completion.
  1045. <dir_name> The name of the directory.
  1046. <rootlen> string length parameter.
  1047. [RETURNS] Nothing.
  1048. */
  1049. {
  1050. struct stat statbuf;
  1051. DIR *dp;
  1052. struct dirent *de;
  1053. char *path;
  1054. dp = warn_opendir(dir_name);
  1055. if (dp == NULL)
  1056. return;
  1057. while ((de = readdir(dp)) != NULL) {
  1058. if (de->d_name && DOT_OR_DOTDOT(de->d_name))
  1059. continue;
  1060. path = concat_path_file(dir_name, de->d_name);
  1061. if (lstat(path, &statbuf) == 0) {
  1062. switch (type) {
  1063. case SERVICE:
  1064. service(statbuf, path);
  1065. break;
  1066. case RESTORE:
  1067. restore(path, statbuf, var);
  1068. break;
  1069. case READ_CONFIG:
  1070. read_config_file(path, var, event_mask);
  1071. break;
  1072. }
  1073. }
  1074. free(path);
  1075. }
  1076. closedir(dp);
  1077. } /* End Function do_scan_and_service */
  1078. static int mksymlink(const char *oldpath, const char *newpath)
  1079. /* [SUMMARY] Create a symlink, creating intervening directories as required.
  1080. <oldpath> The string contained in the symlink.
  1081. <newpath> The name of the new symlink.
  1082. [RETURNS] 0 on success, else -1.
  1083. */
  1084. {
  1085. if (!make_dir_tree(newpath))
  1086. return -1;
  1087. if (symlink(oldpath, newpath) != 0) {
  1088. if (errno != EEXIST)
  1089. return -1;
  1090. }
  1091. return 0;
  1092. } /* End Function mksymlink */
  1093. static int make_dir_tree(const char *path)
  1094. /* [SUMMARY] Creating intervening directories for a path as required.
  1095. <path> The full pathname(including the leaf node).
  1096. [RETURNS] TRUE on success, else FALSE.
  1097. */
  1098. {
  1099. if (bb_make_directory(dirname((char *)path), -1, FILEUTILS_RECUR) == -1)
  1100. return FALSE;
  1101. return TRUE;
  1102. } /* End Function make_dir_tree */
  1103. static int expand_expression(char *output, unsigned int outsize,
  1104. const char *input,
  1105. const char *(*get_variable_func)(const char *variable, void *info),
  1106. void *info,
  1107. const char *devname,
  1108. const regmatch_t *ex, unsigned int numexp)
  1109. /* [SUMMARY] Expand environment variables and regular subexpressions in string.
  1110. <output> The output expanded expression is written here.
  1111. <length> The size of the output buffer.
  1112. <input> The input expression. This may equal <<output>>.
  1113. <get_variable> A function which will be used to get variable values. If
  1114. this returns NULL, the environment is searched instead. If this is NULL,
  1115. only the environment is searched.
  1116. <info> An arbitrary pointer passed to <<get_variable>>.
  1117. <devname> Device name; specifically, this is the string that contains all
  1118. of the regular subexpressions.
  1119. <ex> Array of start / end offsets into info->devname for each subexpression
  1120. <numexp> Number of regular subexpressions found in <<devname>>.
  1121. [RETURNS] TRUE on success, else FALSE.
  1122. */
  1123. {
  1124. char temp[STRING_LENGTH];
  1125. if (!st_expr_expand(temp, STRING_LENGTH, input, get_variable_func, info))
  1126. return FALSE;
  1127. expand_regexp(output, outsize, temp, devname, ex, numexp);
  1128. return TRUE;
  1129. } /* End Function expand_expression */
  1130. static void expand_regexp(char *output, size_t outsize, const char *input,
  1131. const char *devname,
  1132. const regmatch_t *ex, unsigned int numex)
  1133. /* [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
  1134. <output> The output expanded expression is written here.
  1135. <outsize> The size of the output buffer.
  1136. <input> The input expression. This may NOT equal <<output>>, because
  1137. supporting that would require yet another string-copy. However, it's not
  1138. hard to write a simple wrapper function to add this functionality for those
  1139. few cases that need it.
  1140. <devname> Device name; specifically, this is the string that contains all
  1141. of the regular subexpressions.
  1142. <ex> An array of start and end offsets into <<devname>>, one for each
  1143. subexpression
  1144. <numex> Number of subexpressions in the offset-array <<ex>>.
  1145. [RETURNS] Nothing.
  1146. */
  1147. {
  1148. const char last_exp = '0' - 1 + numex;
  1149. int c = -1;
  1150. /* Guarantee NULL termination by writing an explicit '\0' character into
  1151. the very last byte */
  1152. if (outsize)
  1153. output[--outsize] = '\0';
  1154. /* Copy the input string into the output buffer, replacing '\\' with '\'
  1155. and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
  1156. codes are deleted */
  1157. while ((c != '\0') && (outsize != 0)) {
  1158. c = *input;
  1159. ++input;
  1160. if (c == '\\') {
  1161. c = *input;
  1162. ++input;
  1163. if (c != '\\') {
  1164. if ((c >= '0') && (c <= last_exp)) {
  1165. const regmatch_t *subexp = ex + (c - '0');
  1166. unsigned int sublen = subexp->rm_eo - subexp->rm_so;
  1167. /* Range checking */
  1168. if (sublen > outsize)
  1169. sublen = outsize;
  1170. strncpy(output, devname + subexp->rm_so, sublen);
  1171. output += sublen;
  1172. outsize -= sublen;
  1173. }
  1174. continue;
  1175. }
  1176. }
  1177. *output = c;
  1178. ++output;
  1179. --outsize;
  1180. } /* while */
  1181. } /* End Function expand_regexp */
  1182. /* from compat_name.c */
  1183. struct translate_struct {
  1184. const char *match; /* The string to match to(up to length) */
  1185. const char *format; /* Format of output, "%s" takes data past match string,
  1186. NULL is effectively "%s"(just more efficient) */
  1187. };
  1188. static struct translate_struct translate_table[] =
  1189. {
  1190. {"sound/", NULL},
  1191. {"printers/", "lp%s"},
  1192. {"v4l/", NULL},
  1193. {"parports/", "parport%s"},
  1194. {"fb/", "fb%s"},
  1195. {"netlink/", NULL},
  1196. {"loop/", "loop%s"},
  1197. {"floppy/", "fd%s"},
  1198. {"rd/", "ram%s"},
  1199. {"md/", "md%s"}, /* Meta-devices */
  1200. {"vc/", "tty%s"},
  1201. {"misc/", NULL},
  1202. {"isdn/", NULL},
  1203. {"pg/", "pg%s"}, /* Parallel port generic ATAPI interface*/
  1204. {"i2c/", "i2c-%s"},
  1205. {"staliomem/", "staliomem%s"}, /* Stallion serial driver control */
  1206. {"tts/E", "ttyE%s"}, /* Stallion serial driver */
  1207. {"cua/E", "cue%s"}, /* Stallion serial driver callout */
  1208. {"tts/R", "ttyR%s"}, /* Rocketport serial driver */
  1209. {"cua/R", "cur%s"}, /* Rocketport serial driver callout */
  1210. {"ip2/", "ip2%s"}, /* Computone serial driver control */
  1211. {"tts/F", "ttyF%s"}, /* Computone serial driver */
  1212. {"cua/F", "cuf%s"}, /* Computone serial driver callout */
  1213. {"tts/C", "ttyC%s"}, /* Cyclades serial driver */
  1214. {"cua/C", "cub%s"}, /* Cyclades serial driver callout */
  1215. {"tts/", "ttyS%s"}, /* Generic serial: must be after others */
  1216. {"cua/", "cua%s"}, /* Generic serial: must be after others */
  1217. {"input/js", "js%s"}, /* Joystick driver */
  1218. {NULL, NULL}
  1219. };
  1220. const char *get_old_name(const char *devname, unsigned int namelen,
  1221. char *buffer, unsigned int major, unsigned int minor)
  1222. /* [SUMMARY] Translate a kernel-supplied name into an old name.
  1223. <devname> The device name provided by the kernel.
  1224. <namelen> The length of the name.
  1225. <buffer> A buffer that may be used. This should be at least 128 bytes long.
  1226. <major> The major number for the device.
  1227. <minor> The minor number for the device.
  1228. [RETURNS] A pointer to the old name if known, else NULL.
  1229. */
  1230. {
  1231. const char *compat_name = NULL;
  1232. const char *ptr;
  1233. struct translate_struct *trans;
  1234. unsigned int i;
  1235. char mode;
  1236. int indexx;
  1237. const char *pty1;
  1238. const char *pty2;
  1239. size_t len;
  1240. /* 1 to 5 "scsi/" , 6 to 9 "ide/host", 10 sbp/, 11 vcc/, 12 pty/ */
  1241. static const char *const fmt[] = {
  1242. NULL ,
  1243. "sg%u", /* scsi/generic */
  1244. NULL, /* scsi/disc */
  1245. "sr%u", /* scsi/cd */
  1246. NULL, /* scsi/part */
  1247. "nst%u%c", /* scsi/mt */
  1248. "hd%c" , /* ide/host/disc */
  1249. "hd%c" , /* ide/host/cd */
  1250. "hd%c%s", /* ide/host/part */
  1251. "%sht%d", /* ide/host/mt */
  1252. "sbpcd%u", /* sbp/ */
  1253. "vcs%s", /* vcc/ */
  1254. "%cty%c%c", /* pty/ */
  1255. NULL
  1256. };
  1257. for (trans = translate_table; trans->match != NULL; ++trans) {
  1258. len = strlen(trans->match);
  1259. if (strncmp(devname, trans->match, len) == 0) {
  1260. if (trans->format == NULL)
  1261. return devname + len;
  1262. sprintf(buffer, trans->format, devname + len);
  1263. return buffer;
  1264. }
  1265. }
  1266. ptr = bb_basename(devname);
  1267. i = scan_dev_name(devname, namelen, ptr);
  1268. if (i > 0 && i < 13)
  1269. compat_name = buffer;
  1270. else
  1271. return NULL;
  1272. /* 1 == scsi/generic, 3 == scsi/cd, 10 == sbp/ */
  1273. if (i == 1 || i == 3 || i == 10)
  1274. sprintf(buffer, fmt[i], minor);
  1275. /* 2 ==scsi/disc, 4 == scsi/part */
  1276. if (i == 2 || i == 4)
  1277. compat_name = write_old_sd_name(buffer, major, minor, ((i == 2) ? "" : (ptr + 4)));
  1278. /* 5 == scsi/mt */
  1279. if (i == 5) {
  1280. mode = ptr[2];
  1281. if (mode == 'n')
  1282. mode = '\0';
  1283. sprintf(buffer, fmt[i], minor & 0x1f, mode);
  1284. if (devname[namelen - 1] != 'n')
  1285. ++compat_name;
  1286. }
  1287. /* 6 == ide/host/disc, 7 == ide/host/cd, 8 == ide/host/part */
  1288. if (i == 6 || i == 7 || i == 8)
  1289. /* last arg should be ignored for i == 6 or i== 7 */
  1290. sprintf(buffer, fmt[i] , get_old_ide_name(major, minor), ptr + 4);
  1291. /* 9 == ide/host/mt */
  1292. if (i == 9)
  1293. sprintf(buffer, fmt[i], ptr + 2, minor & 0x7f);
  1294. /* 11 == vcc/ */
  1295. if (i == 11) {
  1296. sprintf(buffer, fmt[i], devname + 4);
  1297. if (buffer[3] == '0')
  1298. buffer[3] = '\0';
  1299. }
  1300. /* 12 == pty/ */
  1301. if (i == 12) {
  1302. pty1 = "pqrstuvwxyzabcde";
  1303. pty2 = "0123456789abcdef";
  1304. indexx = atoi(devname + 5);
  1305. sprintf(buffer, fmt[i], (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
  1306. }
  1307. return compat_name;
  1308. } /* End Function get_old_name */
  1309. static char get_old_ide_name(unsigned int major, unsigned int minor)
  1310. /* [SUMMARY] Get the old IDE name for a device.
  1311. <major> The major number for the device.
  1312. <minor> The minor number for the device.
  1313. [RETURNS] The drive letter.
  1314. */
  1315. {
  1316. char letter = 'y'; /* 121 */
  1317. char c = 'a'; /* 97 */
  1318. int i = IDE0_MAJOR;
  1319. /* I hope it works like the previous code as it saves a few bytes. Tito ;P */
  1320. do {
  1321. if (i == IDE0_MAJOR || i == IDE1_MAJOR || i == IDE2_MAJOR
  1322. || i == IDE3_MAJOR || i == IDE4_MAJOR || i == IDE5_MAJOR
  1323. || i == IDE6_MAJOR || i == IDE7_MAJOR || i == IDE8_MAJOR
  1324. || i == IDE9_MAJOR
  1325. ) {
  1326. if ((unsigned int)i == major) {
  1327. letter = c;
  1328. break;
  1329. }
  1330. c += 2;
  1331. }
  1332. i++;
  1333. } while (i <= IDE9_MAJOR);
  1334. if (minor > 63)
  1335. ++letter;
  1336. return letter;
  1337. } /* End Function get_old_ide_name */
  1338. static char *write_old_sd_name(char *buffer,
  1339. unsigned int major, unsigned int minor,
  1340. const char *part)
  1341. /* [SUMMARY] Write the old SCSI disc name to a buffer.
  1342. <buffer> The buffer to write to.
  1343. <major> The major number for the device.
  1344. <minor> The minor number for the device.
  1345. <part> The partition string. Must be "" for a whole-disc entry.
  1346. [RETURNS] A pointer to the buffer on success, else NULL.
  1347. */
  1348. {
  1349. unsigned int disc_index;
  1350. if (major == 8) {
  1351. sprintf(buffer, "sd%c%s", 'a' + (minor >> 4), part);
  1352. return buffer;
  1353. }
  1354. if ((major > 64) && (major < 72)) {
  1355. disc_index = ((major - 64) << 4) +(minor >> 4);
  1356. if (disc_index < 26)
  1357. sprintf(buffer, "sd%c%s", 'a' + disc_index, part);
  1358. else
  1359. sprintf(buffer, "sd%c%c%s", 'a' +(disc_index / 26) - 1, 'a' + disc_index % 26, part);
  1360. return buffer;
  1361. }
  1362. return NULL;
  1363. } /* End Function write_old_sd_name */
  1364. /* expression.c */
  1365. /*EXPERIMENTAL_FUNCTION*/
  1366. int st_expr_expand(char *output, unsigned int length, const char *input,
  1367. const char *(*get_variable_func)(const char *variable,
  1368. void *info),
  1369. void *info)
  1370. /* [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
  1371. <output> The output expanded expression is written here.
  1372. <length> The size of the output buffer.
  1373. <input> The input expression. This may equal <<output>>.
  1374. <get_variable> A function which will be used to get variable values. If
  1375. this returns NULL, the environment is searched instead. If this is NULL,
  1376. only the environment is searched.
  1377. <info> An arbitrary pointer passed to <<get_variable>>.
  1378. [RETURNS] TRUE on success, else FALSE.
  1379. */
  1380. {
  1381. char ch;
  1382. unsigned int len;
  1383. unsigned int out_pos = 0;
  1384. const char *env;
  1385. const char *ptr;
  1386. struct passwd *pwent;
  1387. char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];
  1388. if (length > BUFFER_SIZE)
  1389. length = BUFFER_SIZE;
  1390. for (; TRUE; ++input) {
  1391. switch (ch = *input) {
  1392. case '$':
  1393. /* Variable expansion */
  1394. input = expand_variable(buffer, length, &out_pos, ++input, get_variable_func, info);
  1395. if (input == NULL)
  1396. return FALSE;
  1397. break;
  1398. case '~':
  1399. /* Home directory expansion */
  1400. ch = input[1];
  1401. if (isspace(ch) ||(ch == '/') ||(ch == '\0')) {
  1402. /* User's own home directory: leave separator for next time */
  1403. env = getenv("HOME");
  1404. if (env == NULL) {
  1405. info_logger(LOG_INFO, bb_msg_variable_not_found, "HOME");
  1406. return FALSE;
  1407. }
  1408. len = strlen(env);
  1409. if (len + out_pos >= length)
  1410. goto st_expr_expand_out;
  1411. memcpy(buffer + out_pos, env, len + 1);
  1412. out_pos += len;
  1413. continue;
  1414. }
  1415. /* Someone else's home directory */
  1416. for (ptr = ++input; !isspace(ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
  1417. /* VOID */;
  1418. len = ptr - input;
  1419. if (len >= sizeof tmp)
  1420. goto st_expr_expand_out;
  1421. safe_memcpy(tmp, input, len);
  1422. input = ptr - 1;
  1423. pwent = getpwnam(tmp);
  1424. if (pwent == NULL) {
  1425. info_logger(LOG_INFO, "no pwent for: %s", tmp);
  1426. return FALSE;
  1427. }
  1428. len = strlen(pwent->pw_dir);
  1429. if (len + out_pos >= length)
  1430. goto st_expr_expand_out;
  1431. memcpy(buffer + out_pos, pwent->pw_dir, len + 1);
  1432. out_pos += len;
  1433. break;
  1434. case '\0':
  1435. /* Falltrough */
  1436. default:
  1437. if (out_pos >= length)
  1438. goto st_expr_expand_out;
  1439. buffer[out_pos++] = ch;
  1440. if (ch == '\0') {
  1441. memcpy(output, buffer, out_pos);
  1442. return TRUE;
  1443. }
  1444. break;
  1445. /* esac */
  1446. }
  1447. }
  1448. return FALSE;
  1449. st_expr_expand_out:
  1450. info_logger(LOG_INFO, bb_msg_small_buffer);
  1451. return FALSE;
  1452. } /* End Function st_expr_expand */
  1453. /* Private functions follow */
  1454. static const char *expand_variable(char *buffer, unsigned int length,
  1455. unsigned int *out_pos, const char *input,
  1456. const char *(*func)(const char *variable,
  1457. void *info),
  1458. void *info)
  1459. /* [SUMMARY] Expand a variable.
  1460. <buffer> The buffer to write to.
  1461. <length> The length of the output buffer.
  1462. <out_pos> The current output position. This is updated.
  1463. <input> A pointer to the input character pointer.
  1464. <func> A function which will be used to get variable values. If this
  1465. returns NULL, the environment is searched instead. If this is NULL, only
  1466. the environment is searched.
  1467. <info> An arbitrary pointer passed to <<func>>.
  1468. <errfp> Diagnostic messages are written here.
  1469. [RETURNS] A pointer to the end of this subexpression on success, else NULL.
  1470. */
  1471. {
  1472. char ch;
  1473. int len;
  1474. unsigned int open_braces;
  1475. const char *env, *ptr;
  1476. char tmp[STRING_LENGTH];
  1477. ch = input[0];
  1478. if (ch == '$') {
  1479. /* Special case for "$$": PID */
  1480. sprintf(tmp, "%d", (int) getpid());
  1481. len = strlen(tmp);
  1482. if (len + *out_pos >= length)
  1483. goto expand_variable_out;
  1484. memcpy(buffer + *out_pos, tmp, len + 1);
  1485. out_pos += len;
  1486. return input;
  1487. }
  1488. /* Ordinary variable expansion, possibly in braces */
  1489. if (ch != '{') {
  1490. /* Simple variable expansion */
  1491. for (ptr = input; isalnum(ch) || (ch == '_') || (ch == ':'); ch = *++ptr)
  1492. /* VOID */;
  1493. len = ptr - input;
  1494. if ((size_t)len >= sizeof tmp)
  1495. goto expand_variable_out;
  1496. safe_memcpy(tmp, input, len);
  1497. input = ptr - 1;
  1498. env = get_variable_v2(tmp, func, info);
  1499. if (env == NULL) {
  1500. info_logger(LOG_INFO, bb_msg_variable_not_found, tmp);
  1501. return NULL;
  1502. }
  1503. len = strlen(env);
  1504. if (len + *out_pos >= length)
  1505. goto expand_variable_out;
  1506. memcpy(buffer + *out_pos, env, len + 1);
  1507. *out_pos += len;
  1508. return input;
  1509. }
  1510. /* Variable in braces: check for ':' tricks */
  1511. ch = *++input;
  1512. for (ptr = input; isalnum(ch) || (ch == '_'); ch = *++ptr)
  1513. /* VOID */;
  1514. if (ch == '}') {
  1515. /* Must be simple variable expansion with "${var}" */
  1516. len = ptr - input;
  1517. if ((size_t)len >= sizeof tmp)
  1518. goto expand_variable_out;
  1519. safe_memcpy(tmp, input, len);
  1520. ptr = expand_variable(buffer, length, out_pos, tmp, func, info);
  1521. if (ptr == NULL)
  1522. return NULL;
  1523. return input + len;
  1524. }
  1525. if (ch != ':' || ptr[1] != '-') {
  1526. info_logger(LOG_INFO, "illegal char in var name");
  1527. return NULL;
  1528. }
  1529. /* It's that handy "${var:-word}" expression. Check if var is defined */
  1530. len = ptr - input;
  1531. if ((size_t)len >= sizeof tmp)
  1532. goto expand_variable_out;
  1533. safe_memcpy(tmp, input, len);
  1534. /* Move input pointer to ':' */
  1535. input = ptr;
  1536. /* First skip to closing brace, taking note of nested expressions */
  1537. ptr += 2;
  1538. ch = ptr[0];
  1539. for (open_braces = 1; open_braces > 0; ch = *++ptr) {
  1540. switch (ch) {
  1541. case '{':
  1542. ++open_braces;
  1543. break;
  1544. case '}':
  1545. --open_braces;
  1546. break;
  1547. case '\0':
  1548. info_logger(LOG_INFO, "\"}\" not found in: %s", input);
  1549. return NULL;
  1550. default:
  1551. break;
  1552. }
  1553. }
  1554. --ptr;
  1555. /* At this point ptr should point to closing brace of "${var:-word}" */
  1556. env = get_variable_v2(tmp, func, info);
  1557. if (env != NULL) {
  1558. /* Found environment variable, so skip the input to the closing brace
  1559. and return the variable */
  1560. input = ptr;
  1561. len = strlen(env);
  1562. if (len + *out_pos >= length)
  1563. goto expand_variable_out;
  1564. memcpy(buffer + *out_pos, env, len + 1);
  1565. *out_pos += len;
  1566. return input;
  1567. }
  1568. /* Environment variable was not found, so process word. Advance input
  1569. pointer to start of word in "${var:-word}" */
  1570. input += 2;
  1571. len = ptr - input;
  1572. if ((size_t)len >= sizeof tmp)
  1573. goto expand_variable_out;
  1574. safe_memcpy(tmp, input, len);
  1575. input = ptr;
  1576. if (!st_expr_expand(tmp, STRING_LENGTH, tmp, func, info))
  1577. return NULL;
  1578. len = strlen(tmp);
  1579. if (len + *out_pos >= length)
  1580. goto expand_variable_out;
  1581. memcpy(buffer + *out_pos, tmp, len + 1);
  1582. *out_pos += len;
  1583. return input;
  1584. expand_variable_out:
  1585. info_logger(LOG_INFO, bb_msg_small_buffer);
  1586. return NULL;
  1587. } /* End Function expand_variable */
  1588. static const char *get_variable_v2(const char *variable,
  1589. const char *(*func)(const char *variable, void *info),
  1590. void *info)
  1591. /* [SUMMARY] Get a variable from the environment or .
  1592. <variable> The variable name.
  1593. <func> A function which will be used to get the variable. If this returns
  1594. NULL, the environment is searched instead. If this is NULL, only the
  1595. environment is searched.
  1596. [RETURNS] The value of the variable on success, else NULL.
  1597. */
  1598. {
  1599. const char *value;
  1600. if (func != NULL) {
  1601. value = (*func)(variable, info);
  1602. if (value != NULL)
  1603. return value;
  1604. }
  1605. return getenv(variable);
  1606. } /* End Function get_variable */
  1607. /* END OF CODE */