devfsd.c 56 KB

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