devfsd.c 57 KB

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