aboutsummaryrefslogtreecommitdiff
path: root/miscutils/devfsd.c
blob: 9f998e72348c2fec274f8200d8cce71cc1481a60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
/*
	devfsd implementation for busybox

	Copyright (C) 2003 by Tito Ragusa <farmatito@tiscali.it>

	Busybox version is based on some previous work and ideas
	Copyright (C) [2003] by [Matteo Croce] <3297627799@wind.it>

	devfsd.c

	Main file for  devfsd  (devfs daemon for Linux).

    Copyright (C) 1998-2002  Richard Gooch

	devfsd.h

    Header file for  devfsd  (devfs daemon for Linux).

    Copyright (C) 1998-2000  Richard Gooch

	compat_name.c

    Compatibility name file for  devfsd  (build compatibility names).

    Copyright (C) 1998-2002  Richard Gooch

	expression.c

    This code provides Borne Shell-like expression expansion.

    Copyright (C) 1997-1999  Richard Gooch

	This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    Richard Gooch may be reached by email at  rgooch@atnf.csiro.au
    The postal address is:
      Richard Gooch, c/o ATNF, P. O. Box 76, Epping, N.S.W., 2121, Australia.
*/

#include "libbb.h"
#include "busybox.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <dirent.h>
#include <fcntl.h>
#include <syslog.h>
#include <signal.h>
#include <regex.h>
#include <errno.h>
#include <sys/sysmacros.h>


/* Various defines taken from linux/major.h */
#define IDE0_MAJOR	3
#define IDE1_MAJOR	22
#define IDE2_MAJOR	33
#define IDE3_MAJOR	34
#define IDE4_MAJOR	56
#define IDE5_MAJOR	57
#define IDE6_MAJOR	88
#define IDE7_MAJOR	89
#define IDE8_MAJOR	90
#define IDE9_MAJOR	91


/* Various defines taken from linux/devfs_fs.h */
#define DEVFSD_PROTOCOL_REVISION_KERNEL  5
#define	DEVFSD_IOCTL_BASE	'd'
/*  These are the various ioctls  */
#define DEVFSDIOC_GET_PROTO_REV         _IOR(DEVFSD_IOCTL_BASE, 0, int)
#define DEVFSDIOC_SET_EVENT_MASK        _IOW(DEVFSD_IOCTL_BASE, 2, int)
#define DEVFSDIOC_RELEASE_EVENT_QUEUE   _IOW(DEVFSD_IOCTL_BASE, 3, int)
#define DEVFSDIOC_SET_DEBUG_MASK        _IOW(DEVFSD_IOCTL_BASE, 4, int)
#define DEVFSD_NOTIFY_REGISTERED    0
#define DEVFSD_NOTIFY_UNREGISTERED  1
#define DEVFSD_NOTIFY_ASYNC_OPEN    2
#define DEVFSD_NOTIFY_CLOSE         3
#define DEVFSD_NOTIFY_LOOKUP        4
#define DEVFSD_NOTIFY_CHANGE        5
#define DEVFSD_NOTIFY_CREATE        6
#define DEVFSD_NOTIFY_DELETE        7
#define DEVFS_PATHLEN               1024  /*  Never change this otherwise the
					      binary interface will change   */
struct devfsd_notify_struct
{   /*  Use native C types to ensure same types in kernel and user space     */
    unsigned int type;           /*  DEVFSD_NOTIFY_* value                   */
    unsigned int mode;           /*  Mode of the inode or device entry       */
    unsigned int major;          /*  Major number of device entry            */
    unsigned int minor;          /*  Minor number of device entry            */
    unsigned int uid;            /*  Uid of process, inode or device entry   */
    unsigned int gid;            /*  Gid of process, inode or device entry   */
    unsigned int overrun_count;  /*  Number of lost events                   */
    unsigned int namelen;        /*  Number of characters not including '\0' */
    /*  The device name MUST come last                                       */
    char devname[DEVFS_PATHLEN]; /*  This will be '\0' terminated            */
};



/* These are now in Config.in */
/* define this if you want to have more output on stderr and syslog at the same time */
/*#define CONFIG_DEVFSD_VERBOSE*/
/* define this if you want to have the function names in output */
/*#define CONFIG_DEVFSD_DEBUG*/

#define BUFFER_SIZE 16384
#define DEVFSD_VERSION "1.3.25"
#define CONFIG_FILE  "/etc/devfsd.conf"
#define MODPROBE 		"/sbin/modprobe"
#define CONFIG_MODULES_DEVFS "/etc/modules.devfs"
#define MAX_ARGS     (6 + 1)
#define MAX_SUBEXPR  10
#define STRING_LENGTH 255

/* for get_uid_gid() */
#define UID			0
#define GID			1

/* 	for msg_logger(), do_ioctl(),
	fork_and_execute() */
# define DIE			1
# define NO_DIE			0

/* for dir_operation() */
#define RESTORE		0
#define SERVICE		1
#define READ_CONFIG 2

/*  Update only after changing code to reflect new protocol  */
#define DEVFSD_PROTOCOL_REVISION_DAEMON  5

/*  Compile-time check  */
#if DEVFSD_PROTOCOL_REVISION_KERNEL != DEVFSD_PROTOCOL_REVISION_DAEMON
#error protocol version mismatch. Update your kernel headers
#endif

#define AC_PERMISSIONS				0
#define AC_MODLOAD					1
#define AC_EXECUTE					2
#define AC_MFUNCTION				3	/* not supported by busybox */
#define AC_CFUNCTION				4	/* not supported by busybox */
#define AC_COPY						5
#define AC_IGNORE					6
#define AC_MKOLDCOMPAT				7
#define AC_MKNEWCOMPAT				8
#define AC_RMOLDCOMPAT				9
#define AC_RMNEWCOMPAT				10
#define AC_RESTORE					11


struct permissions_type
{
    mode_t mode;
    uid_t uid;
    gid_t gid;
};

struct execute_type
{
    char *argv[MAX_ARGS + 1];  /*  argv[0] must always be the programme  */
};

struct copy_type
{
    const char *source;
    const char *destination;
};

struct action_type
{
    unsigned int what;
    unsigned int when;
};

struct config_entry_struct
{
    struct action_type action;
    regex_t preg;
    union
    {
	struct permissions_type permissions;
	struct execute_type execute;
	struct copy_type copy;
    }
    u;
    struct config_entry_struct *next;
};

struct get_variable_info
{
    const struct devfsd_notify_struct *info;
    const char *devname;
    char devpath[STRING_LENGTH];
};

static void dir_operation(int , const char * , int,  unsigned long* );
static void service(struct stat statbuf, char *path);
static int st_expr_expand(char *, unsigned, const char *, const char *(*) (const char *, void *), void *);
static const char *get_old_name(const char *, unsigned, char *, unsigned, unsigned);
static int mksymlink (const char *oldpath, const char *newpath);
static void read_config_file (const char *path, int optional, unsigned long *event_mask);
static void process_config_line (const char *, unsigned long *);
static int  do_servicing (int, unsigned long);
static void service_name (const struct devfsd_notify_struct *);
static void action_permissions (const struct devfsd_notify_struct *, const struct config_entry_struct *);
static void action_execute (const struct devfsd_notify_struct *, const struct config_entry_struct *,
							const regmatch_t *, unsigned);
#ifdef CONFIG_DEVFSD_MODLOAD
static void action_modload (const struct devfsd_notify_struct *info, const struct config_entry_struct *entry);
#endif
static void action_copy (const struct devfsd_notify_struct *, const struct config_entry_struct *,
						 const regmatch_t *, unsigned);
static void action_compat (const struct devfsd_notify_struct *, unsigned);
static void free_config (void);
static void restore(char *spath, struct stat source_stat, int rootlen);
static int copy_inode (const char *, const struct stat *, mode_t, const char *, const struct stat *);
static mode_t get_mode (const char *);
static void signal_handler (int);
static const char *get_variable (const char *, void *);
static int make_dir_tree (const char *);
static int expand_expression(char *, unsigned, const char *, const char *(*)(const char *, void *), void *,
							 const char *, const regmatch_t *, unsigned );
static void expand_regexp (char *, size_t, const char *, const char *, const regmatch_t *, unsigned );
static const char *expand_variable(	char *, unsigned, unsigned *, const char *,
									const char *(*) (const char *, void *), void * );
static const char *get_variable_v2(const char *, const char *(*) (const char *, void *), void *);
static char get_old_ide_name (unsigned , unsigned);
static char *write_old_sd_name (char *, unsigned, unsigned, char *);

/* busybox functions */
static void msg_logger(int die, int pri, const char * fmt, ... );
static void do_ioctl(int die, int fd, int request, unsigned long event_mask_flag);
static void fork_and_execute(int die, char *arg0, char **arg );
static int get_uid_gid ( int, const char *);
static void safe_memcpy( char * dest, const char * src, int len);

/* Structs and vars */
static struct config_entry_struct *first_config = NULL;
static struct config_entry_struct *last_config = NULL;
static const char *mount_point = NULL;
static volatile int caught_signal = FALSE;
static volatile int caught_sighup = FALSE;
static struct initial_symlink_struct
{
    char *dest;
    char *name;
} initial_symlinks[] =
{
    {"/proc/self/fd", "fd"},
    {"fd/0", "stdin"},
    {"fd/1", "stdout"},
    {"fd/2", "stderr"},
    {NULL, NULL},
};

static struct event_type
{
    unsigned int type;        /*  The DEVFSD_NOTIFY_* value                  */
    const char *config_name;  /*  The name used in the config file           */
} event_types[] =
{
    {DEVFSD_NOTIFY_REGISTERED,   "REGISTER"},
    {DEVFSD_NOTIFY_UNREGISTERED, "UNREGISTER"},
    {DEVFSD_NOTIFY_ASYNC_OPEN,   "ASYNC_OPEN"},
    {DEVFSD_NOTIFY_CLOSE,        "CLOSE"},
    {DEVFSD_NOTIFY_LOOKUP,       "LOOKUP"},
    {DEVFSD_NOTIFY_CHANGE,       "CHANGE"},
    {DEVFSD_NOTIFY_CREATE,       "CREATE"},
    {DEVFSD_NOTIFY_DELETE,       "DELETE"},
    {0xffffffff,                 NULL}
};

/* busybox functions and messages */

extern void xregcomp(regex_t * preg, const char *regex, int cflags);

const char * const bb_msg_bad_config   		= "bad %s config file: %s\n";
const char * const bb_msg_proto_rev			= "protocol revision";
#ifdef CONFIG_DEVFSD_VERBOSE
const char * const bb_msg_small_buffer		= "buffer too small\n";
const char * const bb_msg_variable_not_found= "variable: %s not found\n";
#endif

static void msg_logger(int die, int pri, const char * fmt, ... )
{
	va_list ap;

	va_start(ap, fmt);
	if (access ("/dev/log", F_OK) == 0)
	{
		openlog(bb_applet_name, 0, LOG_DAEMON);
		vsyslog( pri , fmt , ap);
		closelog();
 	}
#ifndef CONFIG_DEVFSD_VERBOSE
	else
#endif
		bb_verror_msg(fmt, ap);
	va_end(ap);
	if(die==DIE)
		exit(EXIT_FAILURE);
}


static void do_ioctl(int die, int fd, int request, unsigned long event_mask_flag)
{
	if (ioctl (fd, request, event_mask_flag) != 0)
		msg_logger(die, LOG_ERR, "ioctl(): %m\n");
}

static void fork_and_execute(int die, char *arg0, char **arg )
{
	switch ( fork () )
	{
	case 0:
		/*  Child  */
		break;
	case -1:
		/*  Parent: Error  : die or return */
		msg_logger(die, LOG_ERR,(char *) bb_msg_memory_exhausted);
		return;
	default:
		/*  Parent : ok : return or exit  */
		if(arg0 != NULL)
		{
			wait (NULL);
			return;
		}
		exit (EXIT_SUCCESS);
	}
	 /* Child : if arg0 != NULL do execvp */
	if(arg0 != NULL )
	{
		execvp (arg0, arg);
		msg_logger(DIE, LOG_ERR, "execvp(): %s: %m\n", arg0);
	}
}

static void safe_memcpy( char *dest, const char *src, int len)
{
	memcpy (dest , src , len );
	dest[len] = '\0';
}

/*  Public functions follow  */

int devfsd_main (int argc, char **argv)
{
	int print_version = FALSE;
	int do_daemon = TRUE;
	int no_polling = FALSE;
	int fd, proto_rev, count;
	unsigned long event_mask = 0;
	struct sigaction new_action;
	struct initial_symlink_struct *curr;

	if (argc < 2)
		bb_show_usage();

	for (count = 2; count < argc; ++count)
	{
		if (strcmp (argv[count], "-v") == 0)
			print_version = TRUE;
		else if (strcmp (argv[count], "-fg") == 0)
			do_daemon = FALSE;
		else if (strcmp (argv[count], "-np") == 0)
			no_polling = TRUE;
		else
			bb_show_usage();
	}

	mount_point = argv[1];

	if (chdir (mount_point) != 0)
		bb_error_msg_and_die( " %s: %m", mount_point);

	fd = bb_xopen (".devfsd", O_RDONLY);

	if (fcntl (fd, F_SETFD, FD_CLOEXEC) != 0)
		bb_error_msg( "FD_CLOEXEC");

	do_ioctl(DIE, fd, DEVFSDIOC_GET_PROTO_REV,(int )&proto_rev);

	/*setup initial entries */
    for (curr = initial_symlinks; curr->dest != NULL; ++curr)
		symlink (curr->dest, curr->name);

	/* NB: The check for CONFIG_FILE is done in read_config_file() */

	if ( print_version  || (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev) )
	{
		bb_printf( "%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n",
					 bb_applet_name,DEVFSD_VERSION,bb_msg_proto_rev,
					 DEVFSD_PROTOCOL_REVISION_DAEMON,bb_msg_proto_rev, proto_rev);
		if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)
			bb_error_msg_and_die( "%s mismatch!",bb_msg_proto_rev);
		exit(EXIT_SUCCESS); /* -v */
	}
	/*  Tell kernel we are special (i.e. we get to see hidden entries)  */
	do_ioctl(DIE, fd, DEVFSDIOC_SET_EVENT_MASK, 0);

	sigemptyset (&new_action.sa_mask);
	new_action.sa_flags = 0;

	/*  Set up SIGHUP and SIGUSR1 handlers  */
	new_action.sa_handler = signal_handler;
	if (sigaction (SIGHUP, &new_action, NULL) != 0 || sigaction (SIGUSR1, &new_action, NULL) != 0 )
		bb_error_msg_and_die( "sigaction()");

	bb_printf("%s v%s  started for %s\n",bb_applet_name, DEVFSD_VERSION, mount_point);

	/*  Set umask so that mknod(2), open(2) and mkdir(2) have complete control 	over permissions  */
	umask (0);
	read_config_file (CONFIG_FILE, FALSE, &event_mask);
	/*  Do the scan before forking, so that boot scripts see the finished product  */
	dir_operation(SERVICE,mount_point,0,NULL);
	if (no_polling)
		exit (0);
	if (do_daemon)
	{
		/*  Release so that the child can grab it  */
		do_ioctl(DIE, fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0);
		fork_and_execute(DIE, NULL, NULL);
		setsid ();        /*  Prevent hangups and become pgrp leader         */
	}
	else
		setpgid (0, 0);  /*  Become process group leader                    */

	while (TRUE)
	{
		int do_scan = do_servicing (fd, event_mask);

		free_config ();
		read_config_file (CONFIG_FILE, FALSE, &event_mask);
		if (do_scan)
			dir_operation(SERVICE,mount_point,0,NULL);
	}
}   /*  End Function main  */


/*  Private functions follow  */

static void read_config_file (const char *path, int optional, unsigned long *event_mask)
/*  [SUMMARY] Read a configuration database.
    <path> The path to read the database from. If this is a directory, all
    entries in that directory will be read (except hidden entries).
    <optional> If TRUE, the routine will silently ignore a missing config file.
    <event_mask> The event mask is written here. This is not initialised.
    [RETURNS] Nothing.
*/
{
	struct stat statbuf;
	FILE *fp;
	char buf[STRING_LENGTH];
	char *line=NULL;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "read_config_file()\n");
#endif
	if (stat (path, &statbuf) != 0 || statbuf.st_size == 0 )
		goto read_config_file_err;

	if ( S_ISDIR (statbuf.st_mode) )
	{
		dir_operation(READ_CONFIG, path, 0, event_mask);
		return;
	}

	if ( ( fp = fopen (path, "r") ) != NULL )
	{
		while (fgets (buf, STRING_LENGTH, fp) != NULL)
		{
			/*  GETS(3)       Linux Programmer's Manual
			fgets() reads in at most one less than size characters from stream  and
			stores  them  into  the buffer pointed to by s.  Reading stops after an
			EOF or a newline.  If a newline is read, it is stored into the  buffer.
			A '\0' is stored after the last character in the buffer.
			*/
			/*buf[strlen (buf) - 1] = '\0';*/
			/*  Skip whitespace  */
			for (line = buf; isspace (*line); ++line)
				/*VOID*/;
			if (line[0] == '\0' || line[0] == '#' )
				continue;
			process_config_line (line, event_mask);
		}
		fclose (fp);
		errno=0;
	}
read_config_file_err:
#ifdef CONFIG_DEVFSD_VERBOSE
	msg_logger(((optional ==  0 ) && (errno == ENOENT))? DIE : NO_DIE, LOG_ERR, "read config file: %s: %m\n", path);
#endif
	return;
}   /*  End Function read_config_file   */

static void process_config_line (const char *line, unsigned long *event_mask)
/*  [SUMMARY] Process a line from a configuration file.
    <line> The configuration line.
    <event_mask> The event mask is written here. This is not initialised.
    [RETURNS] Nothing.
*/
{
	int  num_args, count;
	struct config_entry_struct *new;
	char p[MAX_ARGS][STRING_LENGTH];
	char when[STRING_LENGTH], what[STRING_LENGTH];
	char name[STRING_LENGTH];
	char * msg="";
	char *ptr;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "process_config_line()\n");
#endif

	for (count = 0; count < MAX_ARGS; ++count) p[count][0] = '\0';
	num_args = sscanf (line, "%s %s %s %s %s %s %s %s %s %s",
			when, name, what,
			p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
	if (strcasecmp (when, "CLEAR_CONFIG") == 0)
	{
		free_config ();
		*event_mask = 0;
		return;
	}
	if (num_args < 2)
		goto process_config_line_err;

	if ( (strcasecmp (when, "INCLUDE") == 0) ||
		 (strcasecmp (when, "OPTIONAL_INCLUDE") == 0) )
	{
		st_expr_expand (name, STRING_LENGTH, name, get_variable, NULL );
#ifdef CONFIG_DEVFSD_VERBOSE
		msg_logger( NO_DIE, LOG_INFO, "%sinclude: %s\n",(toupper (when[0]) == 'I') ? "": "optional_", name);
#endif
		read_config_file (name, (toupper (when[0]) == 'I') ? FALSE : TRUE, event_mask);
		return;
	}
	if (strcasecmp (when, "RESTORE") == 0)
	{
		dir_operation(RESTORE,name, strlen (name),NULL);
		return;
	}
	if (num_args < 3)
		goto process_config_line_err;

	new = xmalloc (sizeof *new);
	memset (new, 0, sizeof *new);

	for (count = 0; event_types[count].config_name != NULL; ++count)
	{
		if (strcasecmp (when, event_types[count].config_name) != 0)
			continue;
		new->action.when = event_types[count].type;
		break;
	}
	if (event_types[count].config_name == NULL)
	{
		msg="WHEN in";
		goto process_config_line_err;
	}

	if (strcasecmp (what, "PERMISSIONS") == 0)
	{
		new->action.what = AC_PERMISSIONS;
		/*  Get user and group  */
		if ( ( ptr = strchr (p[0], '.') ) == NULL )
		{
			msg="UID.GID";
			goto process_config_line_err; /*"missing '.' in UID.GID */
		}

		*ptr++ = '\0';
		new->u.permissions.uid = get_uid_gid (UID, p[0]);
		new->u.permissions.gid = get_uid_gid (GID, ptr);
		/*  Get mode  */
		new->u.permissions.mode = get_mode (p[1]);
	}
#ifdef CONFIG_DEVFSD_MODLOAD
	else if (strcasecmp (what, "MODLOAD") == 0)
		/*This  action will pass "/dev/$devname" (i.e. "/dev/" prefixed to
		the device name) to the module loading  facility.  In  addition,
		the /etc/modules.devfs configuration file is used.*/

		 new->action.what = AC_MODLOAD;
#endif
	else if (strcasecmp (what, "EXECUTE") == 0)
	{
		new->action.what = AC_EXECUTE;
		num_args -= 3;

		for (count = 0; count < num_args; ++count)
			new->u.execute.argv[count] = bb_xstrdup (p[count]);

		new->u.execute.argv[num_args] = NULL;
	}
	else if (strcasecmp (what, "COPY") == 0)
	{
		new->action.what = AC_COPY;
		num_args -= 3;
		if (num_args != 2)
			goto process_config_line_err; /* missing path and function in line */

		new->u.copy.source = bb_xstrdup (p[0]);
		new->u.copy.destination = bb_xstrdup (p[1]);
	}
	else if (strcasecmp (what, "IGNORE") == 0)
		new->action.what = AC_IGNORE;
	else if (strcasecmp (what, "MKOLDCOMPAT") == 0)
		new->action.what = AC_MKOLDCOMPAT;
	else if (strcasecmp (what, "MKNEWCOMPAT") == 0)
		new->action.what = AC_MKNEWCOMPAT;
	else if (strcasecmp (what, "RMOLDCOMPAT") == 0)
		new->action.what = AC_RMOLDCOMPAT;
	else if (strcasecmp (what, "RMNEWCOMPAT") == 0)
		new->action.what = AC_RMNEWCOMPAT;
	else
	{
		msg ="WHAT in";
		goto process_config_line_err;
	}

	xregcomp( &new->preg, name, REG_EXTENDED);

	*event_mask |= 1 << new->action.when;
	new->next = NULL;
	if (first_config == NULL)
		first_config = new;
	else
		last_config->next = new;
	last_config = new;
	return;
process_config_line_err:
	msg_logger( DIE, LOG_ERR, bb_msg_bad_config, msg , line);
}  /*  End Function process_config_line   */

static int do_servicing (int fd, unsigned long event_mask)
/*  [SUMMARY] Service devfs changes until a signal is received.
    <fd> The open control file.
    <event_mask> The event mask.
    [RETURNS] TRUE if SIGHUP was caught, else FALSE.
*/
{
	ssize_t bytes;
	struct devfsd_notify_struct info;
	unsigned long tmp_event_mask;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "do_servicing()\n");
#endif
	/*  Tell devfs what events we care about  */
	tmp_event_mask = event_mask;
	do_ioctl(DIE, fd, DEVFSDIOC_SET_EVENT_MASK, tmp_event_mask);
	while (!caught_signal)
	{
		errno = 0;
		bytes = read (fd, (char *) &info, sizeof info);
		if (caught_signal)
			break;      /*  Must test for this first     */
		if (errno == EINTR)
			continue;  /*  Yes, the order is important  */
		if (bytes < 1)
			break;
		service_name (&info);
	}
	if (caught_signal)
	{
		int c_sighup = caught_sighup;

		caught_signal = FALSE;
		caught_sighup = FALSE;
		return (c_sighup);
	}
#ifdef CONFIG_DEVFSD_VERBOSE
	msg_logger( NO_DIE, LOG_ERR, "read error on control file: %m\n");
#endif
	/* This is to shut up a compiler warning */
	exit(1);
}   /*  End Function do_servicing  */

static void service_name (const struct devfsd_notify_struct *info)
/*  [SUMMARY] Service a single devfs change.
    <info> The devfs change.
    [RETURNS] Nothing.
*/
{
	unsigned int n;
	regmatch_t mbuf[MAX_SUBEXPR];
	struct config_entry_struct *entry;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "service_name()\n");
#endif
#ifdef CONFIG_DEVFSD_VERBOSE
	if (info->overrun_count > 0)
		msg_logger( NO_DIE, LOG_ERR, "lost %u events\n", info->overrun_count);
#endif

	/*  Discard lookups on "/dev/log" and "/dev/initctl"  */
	if	(info->type == DEVFSD_NOTIFY_LOOKUP &&
		(( (strcmp (info->devname, "log") == 0) ||
		(strcmp (info->devname, "initctl") == 0))))
			return;
	for (entry = first_config; entry != NULL; entry = entry->next)
	{
		/*  First check if action matches the type, then check if name matches */
		if (info->type != entry->action.when || regexec (&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0 )
			continue;
		for (n = 0; (n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n)
			/* VOID */;
		switch (entry->action.what)
		{
			case AC_PERMISSIONS:
#ifdef CONFIG_DEVFSD_DEBUG
				msg_logger( NO_DIE, LOG_INFO, "AC_PERMISSIONS\n");
#endif
				action_permissions (info, entry);
				break;
#ifdef CONFIG_DEVFSD_MODLOAD
			case AC_MODLOAD:
				#ifdef CONFIG_DEVFSD_DEBUG
				msg_logger( NO_DIE, LOG_INFO, "AC_MODLOAD\n");
				#endif
				action_modload (info, entry);
				break;
#endif
			case AC_EXECUTE:
#ifdef CONFIG_DEVFSD_DEBUG
				msg_logger( NO_DIE, LOG_INFO, "AC_EXECUTE\n");
#endif
				action_execute (info, entry, mbuf, n);
				break;
			case AC_COPY:
#ifdef CONFIG_DEVFSD_DEBUG
				msg_logger( NO_DIE, LOG_INFO, "AC_COPY\n");
#endif
				action_copy (info, entry, mbuf, n);
				break;
			case AC_IGNORE:
#ifdef CONFIG_DEVFSD_DEBUG
				msg_logger( NO_DIE, LOG_INFO, "AC_IGNORE\n");
#endif
				return;
				/*break;*/
			case AC_MKOLDCOMPAT:
			case AC_MKNEWCOMPAT:
			case AC_RMOLDCOMPAT:
			case AC_RMNEWCOMPAT:
#ifdef CONFIG_DEVFSD_DEBUG
				msg_logger( NO_DIE, LOG_INFO, "AC_COMPAT\n");
#endif
				action_compat (info, entry->action.what);
				break;
			default:
				msg_logger( DIE, LOG_ERR, "Unknown action\n");
				/*break;*/
		}
	}
}   /*  End Function service_name  */

static void action_permissions (const struct devfsd_notify_struct *info,
				const struct config_entry_struct *entry)
/*  [SUMMARY] Update permissions for a device entry.
    <info> The devfs change.
    <entry> The config file entry.
    [RETURNS] Nothing.
*/
{
	struct stat statbuf;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "action_permission()\n");
#endif

	if ( stat (info->devname, &statbuf) != 0	||
		 chmod (info->devname,(statbuf.st_mode & S_IFMT) | (entry->u.permissions.mode & ~S_IFMT)) != 0 ||
		 chown (info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0)
	{
#ifdef CONFIG_DEVFSD_VERBOSE
			msg_logger( NO_DIE, LOG_ERR, "chmod() or chown(): %s: %m\n",info->devname);
#endif
		return;
	}

}   /*  End Function action_permissions  */

#ifdef CONFIG_DEVFSD_MODLOAD
static void action_modload (const struct devfsd_notify_struct *info,
			    const struct config_entry_struct *entry)
/*  [SUMMARY] Load a module.
    <info> The devfs change.
    <entry> The config file entry.
    [RETURNS] Nothing.
*/
{
	char *argv[6];
	char device[STRING_LENGTH];

	argv[0] = MODPROBE;
	argv[1] = "-k";
	argv[2] = "-C";
	argv[3] = CONFIG_MODULES_DEVFS;
	argv[4] = device;
	argv[5] = NULL;
	#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "action_modload()\n");
	#endif
	snprintf (device, sizeof (device), "/dev/%s", info->devname);
	fork_and_execute(DIE, argv[0], argv);
}  /*  End Function action_modload  */
#endif

static void action_execute (const struct devfsd_notify_struct *info,
			    const struct config_entry_struct *entry,
			    const regmatch_t *regexpr, unsigned int numexpr)
/*  [SUMMARY] Execute a programme.
    <info> The devfs change.
    <entry> The config file entry.
    <regexpr> The number of subexpression (start, end) offsets within the
    device name.
    <numexpr> The number of elements within <<regexpr>>.
    [RETURNS] Nothing.
*/
{
	unsigned int count;
	struct get_variable_info gv_info;
	char *argv[MAX_ARGS + 1];
	char largv[MAX_ARGS + 1][STRING_LENGTH];

#ifdef CONFIG_DEVFSD_DEBUG
	int i;
	char buff[1024];

	msg_logger( NO_DIE, LOG_INFO, "action_execute()\n");
#endif

	gv_info.info = info;
	gv_info.devname = info->devname;
	snprintf (gv_info.devpath, sizeof (gv_info.devpath), "%s/%s", mount_point, info->devname);
	for (count = 0; entry->u.execute.argv[count] != NULL; ++count)
	{
		expand_expression (largv[count], STRING_LENGTH,
				entry->u.execute.argv[count],
				get_variable, &gv_info,
				gv_info.devname, regexpr, numexpr );
		argv[count] = largv[count];
	}
	argv[count] = NULL;

#ifdef CONFIG_DEVFSD_DEBUG
	buff[0]='\0';
	for(i=0;argv[i]!=NULL;i++) /* argv[i] < MAX_ARGS + 1 */
	{
		strcat(buff," ");
		if( (strlen(buff)+ 1 + strlen(argv[i])) >= 1024)
			break;
		strcat(buff,argv[i]);
	}
	strcat(buff,"\n");
	msg_logger( NO_DIE, LOG_INFO, "action_execute(): %s",buff);
#endif

	fork_and_execute(NO_DIE, argv[0], argv);
}   /*  End Function action_execute  */


static void action_copy (const struct devfsd_notify_struct *info,
			 const struct config_entry_struct *entry,
                         const regmatch_t *regexpr, unsigned int numexpr)
/*  [SUMMARY] Copy permissions.
    <info> The devfs change.
    <entry> The config file entry.
    <regexpr> This list of subexpression (start, end) offsets within the
    device name.
    <numexpr> The number of elements in <<regexpr>>.
    [RETURNS] Nothing.
*/
{
	mode_t new_mode;
	struct get_variable_info gv_info;
	struct stat source_stat, dest_stat;
	char source[STRING_LENGTH], destination[STRING_LENGTH];
	dest_stat.st_mode = 0;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "action_copy()\n");
#endif

	if ( (info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK (info->mode) )
		return;
	gv_info.info = info;
	gv_info.devname = info->devname;
	snprintf (gv_info.devpath, sizeof (gv_info.devpath), "%s/%s", mount_point, info->devname);

	expand_expression (source, STRING_LENGTH, entry->u.copy.source,
				get_variable, &gv_info, gv_info.devname,
				regexpr, numexpr);

	expand_expression (destination, STRING_LENGTH, entry->u.copy.destination,
				get_variable, &gv_info, gv_info.devname,
				regexpr, numexpr);

	if ( !make_dir_tree (destination) || lstat (source, &source_stat) != 0)
			return;
	lstat (destination, &dest_stat);
	new_mode = source_stat.st_mode & ~S_ISVTX;
	if (info->type == DEVFSD_NOTIFY_CREATE)
		new_mode |= S_ISVTX;
	else if ( (info->type == DEVFSD_NOTIFY_CHANGE) && (dest_stat.st_mode & S_ISVTX) )
		new_mode |= S_ISVTX;
#ifdef CONFIG_DEVFSD_VERBOSE
	if ( !copy_inode (destination, &dest_stat, new_mode, source, &source_stat) )
		msg_logger( NO_DIE, LOG_ERR, "copy_inode(): %s to %s: %m\n", source, destination);
#else
	copy_inode (destination, &dest_stat, new_mode, source, &source_stat);
#endif
	return;
}   /*  End Function action_copy  */

static void action_compat (const struct devfsd_notify_struct *info,
			   unsigned int action)
/*  [SUMMARY] Process a compatibility request.
    <info> The devfs change.
    <action> The action to take.
    [RETURNS] Nothing.
*/
{
	const char *compat_name = NULL;
	const char *dest_name = info->devname;
	char *ptr;
	char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH];

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "action_compat()\n");
#endif

	/*  First construct compatibility name  */
	switch (action)
	{
		case AC_MKOLDCOMPAT:
		case AC_RMOLDCOMPAT:
			compat_name = get_old_name (info->devname, info->namelen, compat_buf, info->major, info->minor);
			break;
		case AC_MKNEWCOMPAT:
		case AC_RMNEWCOMPAT:
		if (strncmp (info->devname, "scsi/", 5) == 0)
		{
			int mode, host, bus, target, lun;

			sscanf (info->devname + 5, "host%d/bus%d/target%d/lun%d/",
				&host, &bus, &target, &lun);
			compat_name = compat_buf;
			snprintf (dest_buf, sizeof (dest_buf), "../%s", info->devname);
			dest_name = dest_buf;
			if (strncmp (ptr = (strrchr (info->devname, '/') + 1), "mt", 2)== 0)
			{
				char rewind_ = info->devname[info->namelen - 1];

				if (rewind_ != 'n')
					rewind_ = '\0';

				switch (ptr[2])
				{
					default:
						mode = 0;
						break;
					case 'l':
						mode = 1;
						break;
					case 'm':
						mode = 2;
						break;
					case 'a':
						mode = 3;
						break;
				}
				sprintf (compat_buf, "st/c%db%dt%du%dm%d%c", host, bus, target, lun, mode, rewind_);
			}
			else if (strcmp (info->devname + info->namelen - 7,"generic") == 0)
				sprintf (compat_buf, "sg/c%db%dt%du%d",
						host, bus, target, lun);
			else if (strcmp (info->devname + info->namelen - 2, "cd") == 0)
				sprintf (compat_buf, "sr/c%db%dt%du%d",
						host, bus, target, lun);
			else if (strcmp (info->devname + info->namelen - 4, "disc") == 0)
				sprintf (compat_buf, "sd/c%db%dt%du%d",
						host, bus, target, lun);
			else if (strncmp (ptr = (strrchr (info->devname, '/') + 1), "part", 4) == 0)
				sprintf ( compat_buf, "sd/c%db%dt%du%dp%d",
						host, bus, target, lun, atoi (ptr + 4) );
			else compat_name = NULL;
		}
		else if (strncmp (info->devname, "ide/host", 8) == 0)
		{
			int host, bus, target, lun;

			sscanf (info->devname + 4, "host%d/bus%d/target%d/lun%d/",
				&host, &bus, &target, &lun);
			compat_name = compat_buf;
			snprintf (dest_buf, sizeof (dest_buf), "../%s", info->devname + 4);
			dest_name = dest_buf;
			if (strcmp (info->devname + info->namelen - 4, "disc") == 0)
				sprintf (compat_buf, "ide/hd/c%db%dt%du%d",
					host, bus, target, lun);
			else if (strncmp (ptr = (strrchr (info->devname, '/') + 1), "part", 4) == 0)
				sprintf ( compat_buf, "ide/hd/c%db%dt%du%dp%d",
					host, bus, target, lun, atoi (ptr + 4) );
			else if (strcmp (info->devname + info->namelen - 2, "cd") == 0)
				sprintf (compat_buf, "ide/cd/c%db%dt%du%d",
					host, bus, target,lun);
			else if (strncmp (ptr = (strrchr (info->devname, '/') + 1), "mt", 2) == 0)
				snprintf (compat_buf, sizeof (compat_buf), "ide/mt/c%db%dt%du%d%s",
					host, bus, target, lun, ptr + 2);
			else compat_name = NULL;
		}
		break;
	}
	if (compat_name == NULL)
		return;
	/*  Now decide what to do with it  */
	switch (action)
	{
		case AC_MKOLDCOMPAT:
		case AC_MKNEWCOMPAT:
			mksymlink (dest_name, compat_name);
			break;
		case AC_RMOLDCOMPAT:
		case AC_RMNEWCOMPAT:
#ifdef CONFIG_DEVFSD_VERBOSE
			if (unlink (compat_name) != 0)
				msg_logger( NO_DIE, LOG_ERR, "unlink(): %s: %m\n", compat_name);
#else
			unlink (compat_name);
#endif
			break;
	}
}   /*  End Function action_compat  */

static void restore(char *spath, struct stat source_stat, int rootlen)
{
	char dpath[STRING_LENGTH];
	struct stat dest_stat;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "restore()\n");
#endif

	dest_stat.st_mode = 0;
	snprintf (dpath, sizeof dpath, "%s%s", mount_point, spath + rootlen);
	lstat (dpath, &dest_stat);

	if ( S_ISLNK (source_stat.st_mode) || (source_stat.st_mode & S_ISVTX) )
		copy_inode (dpath, &dest_stat, (source_stat.st_mode & ~S_ISVTX) , spath, &source_stat);

	if ( S_ISDIR (source_stat.st_mode) )
		dir_operation(RESTORE, spath, rootlen,NULL);
}


static int copy_inode (const char *destpath, const struct stat *dest_stat,
			mode_t new_mode,
			const char *sourcepath, const struct stat *source_stat)
/*  [SUMMARY] Copy an inode.
    <destpath> The destination path. An existing inode may be deleted.
    <dest_stat> The destination stat(2) information.
    <new_mode> The desired new mode for the destination.
    <sourcepath> The source path.
    <source_stat> The source stat(2) information.
    [RETURNS] TRUE on success, else FALSE.
*/
{

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "copy_inode()\n");
#endif

	if ( (source_stat->st_mode & S_IFMT) == (dest_stat->st_mode & S_IFMT) )
	{
		/*  Same type  */
		if ( S_ISLNK (source_stat->st_mode) )
		{
			int source_len, dest_len;
			char source_link[STRING_LENGTH], dest_link[STRING_LENGTH];


			if (( source_len = readlink (sourcepath, source_link, STRING_LENGTH - 1) ) < 0 ||
				( dest_len   = readlink (destpath  , dest_link  , STRING_LENGTH - 1) ) < 0 )
				return (FALSE);
			source_link[source_len]	= '\0';
			dest_link[dest_len] 	= '\0';
			if ( (source_len != dest_len) || (strcmp (source_link, dest_link) != 0) )
			{
				unlink (destpath);
				symlink (source_link, destpath);
			}
			return (TRUE);
		}   /*  Else not a symlink  */
		chmod (destpath, new_mode & ~S_IFMT);
		chown (destpath, source_stat->st_uid, source_stat->st_gid);
		return (TRUE);
	}
	/*  Different types: unlink and create  */
	unlink (destpath);
	switch (source_stat->st_mode & S_IFMT)
	{
		int fd, val;
		struct sockaddr_un un_addr;
		char symlink_val[STRING_LENGTH];

		case S_IFSOCK:
			if ( ( fd = socket (AF_UNIX, SOCK_STREAM, 0) ) < 0 )
				break;
			un_addr.sun_family = AF_UNIX;
			snprintf (un_addr.sun_path, sizeof (un_addr.sun_path), "%s", destpath);
			val = bind (fd, (struct sockaddr *) &un_addr, (int) sizeof un_addr);
			close (fd);
			if (val != 0 || chmod (destpath, new_mode & ~S_IFMT) != 0)
				break;
			goto do_chown;
		case S_IFLNK:
			if ( ( val = readlink (sourcepath, symlink_val, STRING_LENGTH - 1) ) < 0 )
				break;
			symlink_val[val] = '\0';
			if (symlink (symlink_val, destpath) == 0)
				return (TRUE);
			break;
		case S_IFREG:
			if ( ( fd = open (destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT) ) < 0 )
				break;
			close (fd);
			if (chmod (destpath, new_mode & ~S_IFMT) != 0)
				break;
			goto do_chown;
		case S_IFBLK:
		case S_IFCHR:
		case S_IFIFO:
			if (mknod (destpath, new_mode, source_stat->st_rdev) != 0)
				break;
			goto do_chown;
		case S_IFDIR:
			if (mkdir (destpath, new_mode & ~S_IFMT) != 0)
				break;
do_chown:
			if (chown (destpath, source_stat->st_uid, source_stat->st_gid) == 0)
				return (TRUE);
		/*break;*/
	}
	return (FALSE);
}   /*  End Function copy_inode  */

static void free_config ()
/*  [SUMMARY] Free the configuration information.
    [RETURNS] Nothing.
*/
{
	struct config_entry_struct *c_entry;
	void *next;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "free_config()\n");
#endif

	for (c_entry = first_config; c_entry != NULL; c_entry = next)
	{
		unsigned int count;

		next = c_entry->next;
		regfree (&c_entry->preg);
		if (c_entry->action.what == AC_EXECUTE)
		{
			for (count = 0; count < MAX_ARGS; ++count)
			{
				if (c_entry->u.execute.argv[count] == NULL)
					break;
				free (c_entry->u.execute.argv[count]);
			}
		}
		free (c_entry);
	}
	first_config = NULL;
	last_config = NULL;
}   /*  End Function free_config  */

static int get_uid_gid (int flag, const char *string)
/*  [SUMMARY] Convert a string to a UID or GID value.
	<flag> "UID" or "GID".
	<string> The string.
    [RETURNS] The UID or GID value.
*/
{
	struct passwd *pw_ent;
	struct group *grp_ent;
	char * msg="user";

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "get_uid_gid()\n");


	if(flag != UID && flag != GID )
		msg_logger( DIE, LOG_ERR,"get_uid_gid(): flag != UID && flag != GID\n");
#endif

	if ( isdigit (string[0]) || ( (string[0] == '-') && isdigit (string[1]) ) )
		return atoi (string);

	if ( flag == UID && ( pw_ent  = getpwnam (string) ) != NULL )
		return (pw_ent->pw_uid);

	if ( flag == GID && ( grp_ent = getgrnam (string) ) != NULL )
		return (grp_ent->gr_gid);
	else
		msg="group";

	msg_logger( NO_DIE, LOG_ERR,"unknown %s: %s, defaulting to %cID=0\n", msg, string, msg[0] - 32);
	return (0);
}/*  End Function get_uid_gid  */

static mode_t get_mode (const char *string)
/*  [SUMMARY] Convert a string to a mode value.
    <string> The string.
    [RETURNS] The mode value.
*/
{
	mode_t mode;
	int i;
#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "get_mode()\n");
#endif

	if ( isdigit (string[0]) )
		return strtoul (string, NULL, 8);
	if (strlen (string) != 9)
		msg_logger( DIE, LOG_ERR, "bad mode: %s\n", string);
	mode = 0;
	i= S_IRUSR;
	while(i>0)
	{
		if(string[0]=='r'||string[0]=='w'||string[0]=='x')
			mode+=i;
		i=i/2;
		string++;
	}
	return (mode);
}   /*  End Function get_mode  */

static void signal_handler (int sig)
{
#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "signal_handler()\n");
#endif

	caught_signal = TRUE;
	if (sig == SIGHUP)
		caught_sighup = TRUE;
#ifdef CONFIG_DEVFSD_VERBOSE
	msg_logger( NO_DIE, LOG_INFO, "Caught %s\n",(sig == SIGHUP)?"SIGHUP" : "SIGUSR1");
#endif
}   /*  End Function signal_handler  */

static const char *get_variable (const char *variable, void *info)
{
	struct get_variable_info *gv_info = info;
	static char hostname[STRING_LENGTH], sbuf[STRING_LENGTH];

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "get_variable()\n");
#endif

	if (gethostname (hostname, STRING_LENGTH - 1) != 0)
		msg_logger( DIE, LOG_ERR, "gethostname(): %m\n");
		/* Here on error we should do exit(RV_SYS_ERROR), instead we do exit(EXIT_FAILURE) */
	hostname[STRING_LENGTH - 1] = '\0';
	if (strcmp (variable, "hostname") == 0)
		return (hostname);
	if (strcmp (variable, "mntpnt") == 0)
		return (mount_point);
	if (gv_info == NULL)
		return (NULL);
	if (strcmp (variable, "devpath") == 0)
		return (gv_info->devpath);
	if (strcmp (variable, "devname") == 0)
		return (gv_info->devname);
	if (strcmp (variable, "mode") == 0)
	{
		sprintf (sbuf, "%o", gv_info->info->mode);
		return (sbuf);
	}
	if (strcmp (variable, "uid") == 0)
	{
		sprintf (sbuf, "%u", gv_info->info->uid);
		return (sbuf);
	}
	if (strcmp (variable, "gid") == 0)
	{
		sprintf (sbuf, "%u", gv_info->info->gid);
		return (sbuf);
	}
	return (NULL);
}   /*  End Function get_variable  */

static void service(struct stat statbuf, char *path)
{
	struct devfsd_notify_struct info;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "service()\n");
#endif

	memset (&info, 0, sizeof info);
	info.type = DEVFSD_NOTIFY_REGISTERED;
	info.mode = statbuf.st_mode;
	info.major = major (statbuf.st_rdev);
	info.minor = minor (statbuf.st_rdev);
	info.uid = statbuf.st_uid;
	info.gid = statbuf.st_gid;
	snprintf (info.devname, sizeof (info.devname), "%s", path + strlen (mount_point) + 1);
	info.namelen = strlen (info.devname);
	service_name (&info);
	if ( S_ISDIR (statbuf.st_mode) )
		dir_operation(SERVICE,path,0,NULL);
}

static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask)
/*  [SUMMARY] Scan a directory tree and generate register events on leaf nodes.
	<flag> To choose which function to perform
	<dp> The directory pointer. This is closed upon completion.
    <dir_name> The name of the directory.
	<rootlen> string length parameter.
    [RETURNS] Nothing.
*/
{
	struct stat statbuf;
	DIR *dp;
	struct dirent *de;
	char path[STRING_LENGTH];


#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "dir_operation()\n");
#endif

	if((dp = opendir( dir_name))==NULL)
	{
		msg_logger( NO_DIE, LOG_ERR, "opendir(): %s: %m\n", dir_name);
		return;
	}

	while ( (de = readdir (dp) ) != NULL )
	{

		if ( (strcmp (de->d_name, ".") == 0)  || (strcmp (de->d_name, "..") == 0)  )
			continue;
		snprintf (path, sizeof (path), "%s%s%s", dir_name,(last_char_is(dir_name,'/')==NULL)?"/":"", de->d_name);

		if (lstat (path, &statbuf) != 0)
		{
#ifdef CONFIG_DEVFSD_VERBOSE
			msg_logger( NO_DIE, LOG_ERR, "%s: %m\n", path);
#endif
			continue;
		}
		switch(type)
		{
			case SERVICE:
				service(statbuf,path);
				break;
			case RESTORE:
				restore(path, statbuf, var);
				break;
			case READ_CONFIG:
				read_config_file (path, var, event_mask);
				break;
		}
	}
	closedir (dp);
}   /*  End Function do_scan_and_service  */

static int mksymlink (const char *oldpath, const char *newpath)
/*  [SUMMARY] Create a symlink, creating intervening directories as required.
    <oldpath> The string contained in the symlink.
    <newpath> The name of the new symlink.
    [RETURNS] 0 on success, else -1.
*/
{
#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "mksymlink()\n", newpath);
#endif


	if ( !make_dir_tree (newpath) )
		return (-1);

	if (symlink (oldpath, newpath) != 0)
    {
#ifdef CONFIG_DEVFSD_VERBOSE
		msg_logger( NO_DIE, LOG_ERR, "symlink(): %s to %s: %m\n", oldpath, newpath);
#endif
		if (errno != EEXIST)
			return (-1);
	}
    return (0);
}   /*  End Function mksymlink  */


static int make_dir_tree (const char *path)
/*  [SUMMARY] Creating intervening directories for a path as required.
    <path> The full pathname (including the leaf node).
    [RETURNS] TRUE on success, else FALSE.
*/
{
#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "make_dir_tree()\n");
#endif
	if (bb_make_directory( dirname((char *)path),  S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH ,FILEUTILS_RECUR )==-1)
	{
#ifdef CONFIG_DEVFSD_VERBOSE
		msg_logger( NO_DIE, LOG_ERR, "make_dir_tree(): %s: %m\n", path);
#endif
		return (FALSE);
	}
	return(TRUE);
} /*  End Function make_dir_tree  */

static int expand_expression(char *output, unsigned int outsize,
			      const char *input,
			      const char *(*get_variable_func)(const char *variable, void *info),
                              void *info,
                              const char *devname,
                              const regmatch_t *ex, unsigned int numexp)
/*  [SUMMARY] Expand enviroment variables and regular subexpressions in string.
    <output> The output expanded expression is written here.
    <length> The size of the output buffer.
    <input> The input expression. This may equal <<output>>.
    <get_variable> A function which will be used to get variable values. If
    this returns NULL, the environment is searched instead. If this is NULL,
    only the environment is searched.
    <info> An arbitrary pointer passed to <<get_variable>>.
    <devname> Device name; specifically, this is the string that contains all
    of the regular subexpressions.
    <ex> Array of start / end offsets into info->devname for each subexpression
    <numexp> Number of regular subexpressions found in <<devname>>.
    [RETURNS] TRUE on success, else FALSE.
*/
{
	char temp[STRING_LENGTH];

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "expand_expression()\n");
#endif

	if ( !st_expr_expand (temp, STRING_LENGTH, input, get_variable_func, info) )
		return (FALSE);
	expand_regexp (output, outsize, temp, devname, ex, numexp);
	return (TRUE);
}   /*  End Function expand_expression  */

static void expand_regexp (char *output, size_t outsize, const char *input,
			   const char *devname,
			   const regmatch_t *ex, unsigned int numex )
/*  [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
    <output> The output expanded expression is written here.
    <outsize> The size of the output buffer.
    <input> The input expression. This may NOT equal <<output>>, because
    supporting that would require yet another string-copy. However, it's not
    hard to write a simple wrapper function to add this functionality for those
    few cases that need it.
    <devname> Device name; specifically, this is the string that contains all
    of the regular subexpressions.
    <ex> An array of start and end offsets into <<devname>>, one for each
    subexpression
    <numex> Number of subexpressions in the offset-array <<ex>>.
    [RETURNS] Nothing.
*/
{
	const char last_exp = '0' - 1 + numex;
	int c = -1;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "expand_regexp()\n");
#endif

	/*  Guarantee NULL termination by writing an explicit '\0' character into
	the very last byte  */
	if (outsize)
		output[--outsize] = '\0';
	/*  Copy the input string into the output buffer, replacing '\\' with '\'
	and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
	codes are deleted  */
	while ( (c != '\0') && (outsize != 0) )
	{
		c = *input;
		++input;
		if (c == '\\')
		{
			c = *input;
			++input;
			if (c != '\\')
			{
				if ((c >= '0') && (c <= last_exp))
				{
					const regmatch_t *subexp = ex + (c - '0');
					unsigned int sublen = subexp->rm_eo - subexp->rm_so;

					/*  Range checking  */
					if (sublen > outsize)
						sublen = outsize;
					strncpy (output, devname + subexp->rm_so, sublen);
					output += sublen;
					outsize -= sublen;
				}
				continue;
			}
		}
		*output = c;
		++output;
		--outsize;
	} /* while */
}   /*  End Function expand_regexp  */


/* from compat_name.c */

struct translate_struct
{
	char *match;    /*  The string to match to (up to length)                */
	char *format;   /*  Format of output, "%s" takes data past match string,
			NULL is effectively "%s" (just more efficient)       */
};

static struct translate_struct translate_table[] =
{
	{"sound/",     NULL},
	{"printers/",  "lp%s"},
	{"v4l/",       NULL},
	{"parports/",  "parport%s"},
	{"fb/",        "fb%s"},
	{"netlink/",   NULL},
	{"loop/",      "loop%s"},
	{"floppy/",    "fd%s"},
	{"rd/",        "ram%s"},
	{"md/",        "md%s"},         /*  Meta-devices                         */
	{"vc/",        "tty%s"},
	{"misc/",      NULL},
	{"isdn/",      NULL},
	{"pg/",        "pg%s"},         /*  Parallel port generic ATAPI interface*/
	{"i2c/",       "i2c-%s"},
	{"staliomem/", "staliomem%s"},  /*  Stallion serial driver control       */
	{"tts/E",      "ttyE%s"},       /*  Stallion serial driver               */
	{"cua/E",      "cue%s"},        /*  Stallion serial driver callout       */
	{"tts/R",      "ttyR%s"},       /*  Rocketport serial driver             */
	{"cua/R",      "cur%s"},        /*  Rocketport serial driver callout     */
	{"ip2/",       "ip2%s"},        /*  Computone serial driver control      */
	{"tts/F",      "ttyF%s"},       /*  Computone serial driver              */
	{"cua/F",      "cuf%s"},        /*  Computone serial driver callout      */
	{"tts/C",      "ttyC%s"},       /*  Cyclades serial driver               */
	{"cua/C",      "cub%s"},        /*  Cyclades serial driver callout       */
	{"tts/",       "ttyS%s"},       /*  Generic serial: must be after others */
	{"cua/",       "cua%s"},        /*  Generic serial: must be after others */
	{"input/js",   "js%s"},         /*  Joystick driver                      */
	{NULL,         NULL}
};

const char *get_old_name (const char *devname, unsigned int namelen,
			  char *buffer, unsigned int major, unsigned int minor)
/*  [SUMMARY] Translate a kernel-supplied name into an old name.
    <devname> The device name provided by the kernel.
    <namelen> The length of the name.
    <buffer> A buffer that may be used. This should be at least 128 bytes long.
    <major> The major number for the device.
    <minor> The minor number for the device.
    [RETURNS] A pointer to the old name if known, else NULL.
*/
{
	const char *compat_name = NULL;
	char *ptr;
	struct translate_struct *trans;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "get_old_name()\n");
#endif

	for (trans = translate_table; trans->match != NULL; ++trans)
	{
		size_t len = strlen (trans->match);

		if (strncmp (devname, trans->match, len) == 0)
		{
			if (trans->format == NULL)
				return (devname + len);
			sprintf (buffer, trans->format, devname + len);
			return (buffer);
		}
	}
	if (strncmp (devname, "sbp/", 4) == 0)
	{
		sprintf (buffer, "sbpcd%u", minor);
		compat_name = buffer;
	}
	else if (strncmp (devname, "scsi/", 5) == 0)
	{   /*  All SCSI devices  */
		if (strcmp (devname + namelen - 7, "generic") == 0)
		{
			sprintf (buffer, "sg%u", minor);
			compat_name = buffer;
		}
		else if (strncmp (ptr = (strrchr (devname, '/') + 1), "mt", 2) == 0)
		{
			char mode = ptr[2];

			if (mode == 'n')
				mode = '\0';
			sprintf (buffer, "nst%u%c", minor & 0x1f, mode);
			compat_name = buffer;
			if (devname[namelen - 1] != 'n')
				++compat_name;
		}
		else if (strcmp (devname + namelen - 2, "cd") == 0)
		{
			sprintf (buffer, "sr%u", minor);
			compat_name = buffer;
		}
		else if (strcmp (devname + namelen - 4, "disc") == 0)
			compat_name = write_old_sd_name (buffer, major, minor, "");
		else if (strncmp (ptr = (strrchr (devname, '/') + 1), "part", 4) == 0)
			compat_name = write_old_sd_name (buffer, major, minor, ptr + 4);
		return (compat_name);
	}
	else if (strncmp (devname, "ide/host", 8) == 0)
	{   /*  All IDE devices  */
		if (strncmp (ptr = (strrchr (devname, '/') + 1), "mt", 2) == 0)
		{
			sprintf (buffer, "%sht%d", ptr + 2, minor & 0x7f);
			compat_name = buffer;
		}
		else if (strcmp (devname + namelen - 4, "disc") == 0)
		{
			sprintf ( buffer, "hd%c", get_old_ide_name (major, minor) );
			compat_name = buffer;
		}
		else if (strncmp (ptr = (strrchr (devname, '/') + 1), "part", 4) == 0)
		{
			sprintf (buffer, "hd%c%s", get_old_ide_name (major, minor), ptr + 4);
			compat_name = buffer;
		}
		else if (strcmp (devname + namelen - 2, "cd") == 0)
		{
			sprintf ( buffer, "hd%c", get_old_ide_name (major, minor) );
			compat_name = buffer;
		}
		return (compat_name);
	}
	else if (strncmp (devname, "vcc/", 4) == 0)
	{
		sprintf (buffer, "vcs%s", devname + 4);
		if (buffer[3] == '0')
			buffer[3] = '\0';
		compat_name = buffer;
	}
	else if (strncmp (devname, "pty/", 4) == 0)
	{
		int indexx = atoi (devname + 5);
		const char *pty1 = "pqrstuvwxyzabcde";
		const char *pty2 = "0123456789abcdef";

		sprintf (buffer, "%cty%c%c", (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
		compat_name = buffer;
	}
	return (compat_name);
}   /*  End Function get_old_name  */

static char get_old_ide_name (unsigned int major, unsigned int minor)
/*  [SUMMARY] Get the old IDE name for a device.
    <major> The major number for the device.
    <minor> The minor number for the device.
    [RETURNS] The drive letter.
*/
{
	char letter='y';	/* 121 */
	char c='a'; 		/*  97 */
	int i=IDE0_MAJOR;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "get_old_ide_name()\n");
#endif

	/* I hope it works like the previous code as it saves a few bytes. Tito ;P */
	do {
		if(	i==IDE0_MAJOR || i==IDE1_MAJOR || i==IDE2_MAJOR ||
			i==IDE3_MAJOR || i==IDE4_MAJOR || i==IDE5_MAJOR ||
			i==IDE6_MAJOR || i==IDE7_MAJOR || i==IDE8_MAJOR ||
			i==IDE9_MAJOR )
		{
			if(i==major)
			{
				letter=c;
				break;
			}
			c+=2;
		}
		i++;
	} while(i<=IDE9_MAJOR);

	if (minor > 63)
		++letter;
	return (letter);
}   /*  End Function get_old_ide_name  */

static char *write_old_sd_name (char *buffer,
				unsigned int major, unsigned int minor,
				char *part)
/*  [SUMMARY] Write the old SCSI disc name to a buffer.
    <buffer> The buffer to write to.
    <major> The major number for the device.
    <minor> The minor number for the device.
    <part> The partition string. Must be "" for a whole-disc entry.
    [RETURNS] A pointer to the buffer on success, else NULL.
*/
{
	unsigned int disc_index;

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "write_old_sd_name()\n");
#endif

	if (major == 8)
	{
		sprintf (buffer, "sd%c%s", 'a' + (minor >> 4), part);
		return (buffer);
	}
	if ( (major > 64) && (major < 72) )
	{
		disc_index = ( (major - 64) << 4 ) + (minor >> 4);
		if (disc_index < 26)
			sprintf (buffer, "sd%c%s", 'a' + disc_index, part);
		else
			sprintf (buffer, "sd%c%c%s", 'a' + (disc_index / 26) - 1, 'a' + disc_index % 26,part);
		return (buffer);
	}
	return (NULL);
}   /*  End Function write_old_sd_name  */


/*  expression.c */

/*EXPERIMENTAL_FUNCTION*/

int st_expr_expand (char *output, unsigned int length, const char *input,
		     const char *(*get_variable_func) (const char *variable,
						  void *info),
		     void *info)
/*  [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
    <output> The output expanded expression is written here.
    <length> The size of the output buffer.
    <input> The input expression. This may equal <<output>>.
    <get_variable> A function which will be used to get variable values. If
    this returns NULL, the environment is searched instead. If this is NULL,
    only the environment is searched.
    <info> An arbitrary pointer passed to <<get_variable>>.
    [RETURNS] TRUE on success, else FALSE.
*/
{
	char ch;
	unsigned int len;
	unsigned int out_pos = 0;
	const char *env;
	const char *ptr;
	struct passwd *pwent;
	char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "st_expr_expand()\n");
#endif

	if (length > BUFFER_SIZE)
		length = BUFFER_SIZE;
	for (; TRUE; ++input)
	{
		switch (ch = *input)
		{
			case '$':
				/*  Variable expansion  */
				input = expand_variable (buffer, length, &out_pos, ++input, get_variable_func, info);
				if (input == NULL)
					return (FALSE);
				break;
			case '~':
				/*  Home directory expansion  */
				ch = input[1];
				if ( isspace (ch) || (ch == '/') || (ch == '\0') )
				{
					/* User's own home directory: leave separator for next time */
					if ( ( env = getenv ("HOME") ) == NULL )
					{
#ifdef CONFIG_DEVFSD_VERBOSE
						msg_logger( NO_DIE, LOG_INFO, bb_msg_variable_not_found, "HOME");
#endif
						return (FALSE);
					}
					len = strlen (env);
					if (len + out_pos >= length)
						goto st_expr_expand_out;
					memcpy (buffer + out_pos, env, len + 1);
					out_pos += len;
					continue;
				}
				/*  Someone else's home directory  */
				for (ptr = ++input; !isspace (ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
					/* VOID */ ;
				len = ptr - input;
				if (len >= sizeof tmp)
					goto st_expr_expand_out;
				safe_memcpy (tmp, input, len);
				input = ptr - 1;
				if ( ( pwent = getpwnam (tmp) ) == NULL )
				{
#ifdef CONFIG_DEVFSD_VERBOSE
					msg_logger( NO_DIE, LOG_INFO, "getpwnam(): %s\n", tmp);
#endif
					return (FALSE);
				}
				len = strlen (pwent->pw_dir);
				if (len + out_pos >= length)
					goto st_expr_expand_out;
				memcpy (buffer + out_pos, pwent->pw_dir, len + 1);
				out_pos += len;
				break;
			case '\0':
			/* Falltrough */
			default:
				if (out_pos >= length)
					goto st_expr_expand_out;
				buffer[out_pos++] = ch;
				if (ch == '\0')
				{
					memcpy (output, buffer, out_pos);
					return (TRUE);
				}
				break;
			/* esac */
		}
	}
	return (FALSE);
st_expr_expand_out:
#ifdef CONFIG_DEVFSD_VERBOSE
	msg_logger( NO_DIE, LOG_INFO, bb_msg_small_buffer);
#endif
	return (FALSE);
}   /*  End Function st_expr_expand  */


/*  Private functions follow  */

static const char *expand_variable (char *buffer, unsigned int length,
				    unsigned int *out_pos, const char *input,
				    const char *(*func) (const char *variable,
							 void *info),
				    void *info)
/*  [SUMMARY] Expand a variable.
    <buffer> The buffer to write to.
    <length> The length of the output buffer.
    <out_pos> The current output position. This is updated.
    <input> A pointer to the input character pointer.
    <func> A function which will be used to get variable values. If this
    returns NULL, the environment is searched instead. If this is NULL, only
    the environment is searched.
    <info> An arbitrary pointer passed to <<func>>.
    <errfp> Diagnostic messages are written here.
    [RETURNS] A pointer to the end of this subexpression on success, else NULL.
*/
{
	char ch;
	int len;
	unsigned int open_braces;
	const char *env, *ptr;
	char tmp[STRING_LENGTH];

#ifdef CONFIG_DEVFSD_DEBUG
	msg_logger( NO_DIE, LOG_INFO, "expand_variable()\n");
#endif

	ch = input[0];
	if (ch == '$')
	{
		/*  Special case for "$$": PID  */
		sprintf ( tmp, "%d", (int) getpid () );
		len = strlen (tmp);
		if (len + *out_pos >= length)
			goto expand_variable_out;

		memcpy (buffer + *out_pos, tmp, len + 1);
		out_pos += len;
		return (input);
	}
	/*  Ordinary variable expansion, possibly in braces  */
	if (ch != '{')
	{
		/*  Simple variable expansion  */
		for (ptr = input; isalnum (ch) || (ch == '_') || (ch == ':');ch = *++ptr)
			/* VOID */ ;
		len = ptr - input;
		if (len >= sizeof tmp)
			goto expand_variable_out;

		safe_memcpy (tmp, input, len);
		input = ptr - 1;
		if ( ( env = get_variable_v2 (tmp, func, info) ) == NULL )
		{
#ifdef CONFIG_DEVFSD_VERBOSE
			msg_logger( NO_DIE, LOG_INFO, bb_msg_variable_not_found, tmp);
#endif
			return (NULL);
		}
		len = strlen (env);
		if (len + *out_pos >= length)
			goto expand_variable_out;

		memcpy (buffer + *out_pos, env, len + 1);
		*out_pos += len;
		return (input);
	}
	/*  Variable in braces: check for ':' tricks  */
	ch = *++input;
	for (ptr = input; isalnum (ch) || (ch == '_'); ch = *++ptr)
		/* VOID */;
	if (ch == '}')
	{
		/*  Must be simple variable expansion with "${var}"  */
		len = ptr - input;
		if (len >= sizeof tmp)
			goto expand_variable_out;

		safe_memcpy (tmp, input, len);
		ptr = expand_variable (buffer, length, out_pos, tmp, func, info );
		if (ptr == NULL)
			return (NULL);
		return (input + len);
	}
	if (ch != ':' || ptr[1] != '-' )
	{
#ifdef CONFIG_DEVFSD_VERBOSE
		msg_logger( NO_DIE, LOG_INFO,"illegal char in var name\n");
#endif
		return (NULL);
	}
	/*  It's that handy "${var:-word}" expression. Check if var is defined  */
	len = ptr - input;
	if (len >= sizeof tmp)
		goto expand_variable_out;

	safe_memcpy (tmp, input, len);
	/*  Move input pointer to ':'  */
	input = ptr;
	/*  First skip to closing brace, taking note of nested expressions  */
	ptr += 2;
	ch = ptr[0];
	for (open_braces = 1; open_braces > 0; ch = *++ptr)
	{
		switch (ch)
		{
			case '{':
				++open_braces;
				break;
			case '}':
				--open_braces;
				break;
			case '\0':
#ifdef CONFIG_DEVFSD_VERBOSE
				msg_logger( NO_DIE, LOG_INFO,"\"}\" not found in: %s\n", input);
#endif
				return (NULL);
			default:
				break;
		}
	}
	--ptr;
	/*  At this point ptr should point to closing brace of "${var:-word}"  */
	if ( ( env = get_variable_v2 (tmp, func, info) ) != NULL )
	{
		/*  Found environment variable, so skip the input to the closing brace
			and return the variable  */
		input = ptr;
		len = strlen (env);
		if (len + *out_pos >= length)
			goto expand_variable_out;

		memcpy (buffer + *out_pos, env, len + 1);
		*out_pos += len;
		return (input);
	}
	/*  Environment variable was not found, so process word. Advance input
	pointer to start of word in "${var:-word}"  */
	input += 2;
	len = ptr - input;
	if (len >= sizeof tmp)
		goto expand_variable_out;

	safe_memcpy (tmp, input, len);
	input = ptr;
	if ( !st_expr_expand (tmp, STRING_LENGTH, tmp, func, info ) )
		return (NULL);
	len = strlen (tmp);
	if (len + *out_pos >= length)
		goto expand_variable_out;

	memcpy (buffer + *out_pos, tmp, len + 1);
	*out_pos += len;
	return (input);
expand_variable_out:
#ifdef CONFIG_DEVFSD_VERBOSE
	msg_logger( NO_DIE, LOG_INFO, bb_msg_small_buffer);
#endif
	return (NULL);
}   /*  End Function expand_variable  */


static const char *get_variable_v2 (const char *variable,
				  const char *(*func) (const char *variable, void *info),
				 void *info)
/*  [SUMMARY] Get a variable from the environment or .
    <variable> The variable name.
    <func> A function which will be used to get the variable. If this returns
    NULL, the environment is searched instead. If this is NULL, only the
    environment is searched.
    [RETURNS] The value of the variable on success, else NULL.
*/
{
	const char *value;

#ifdef CONFIG_DEVFSD_DEBUG
		msg_logger( NO_DIE, LOG_INFO, "get_variable_v2()\n");
#endif

	if (func != NULL)
	{
		value = (*func) (variable, info);
		if (value != NULL)
			return (value);
	}
	return getenv (variable);
}   /*  End Function get_variable  */

/* END OF CODE */