devfsd.c 57 KB

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