devfsd.c 57 KB

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