devfsd.c 56 KB

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