File: util.c

package info (click to toggle)
xmcd 2.6-17sarge1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,464 kB
  • ctags: 5,075
  • sloc: ansic: 51,322; sh: 4,039; makefile: 82; pascal: 67
file content (1909 lines) | stat: -rw-r--r-- 33,781 bytes parent folder | download | duplicates (5)
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
/*
 *   util.c - Common utility routines for xmcd, cda and libdi.
 *
 *   xmcd  - Motif(tm) CD Audio Player
 *   cda   - Command-line CD Audio Player
 *   libdi - CD Audio Player Device Interface Library
 *
 *
 *   Copyright (C) 1993-2000  Ti Kan
 *   E-mail: ti@amb.org
 *
 *   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.
 *
 */
#ifndef LINT
static char *_util_c_ident_ = "@(#)util.c	6.63 00/01/09";
#endif

#include "common_d/appenv.h"
#include "common_d/util.h"

#if !defined(USE_SELECT) && !defined(USE_POLL) && \
    !defined(USE_NAP) && !defined(USE_USLEEP)
#define USE_SELECT	/* Make USE_SELECT the default if not specified */
#endif

#ifdef USE_SELECT
#include <sys/time.h>
#ifdef _AIX
#include <sys/select.h>
#endif
#endif

#ifdef __VMS
#include <fscndef.h>
STATIC int		context;
#endif


extern appdata_t	app_data;
extern FILE		*errfp;


STATIC uid_t		ouid = 30001;	/* Default to something safe */
STATIC gid_t		ogid = 30001;	/* Default to something safe */
STATIC struct utsname	un;		/* utsname */

/*
 * Data used by util_text_reduce()
 */
STATIC int		excnt,
			delcnt,
			*exlen,
			*dellen;
STATIC char		**exclude_words;
STATIC char		*delete_words[] = {
	"\\n", "\\r", "\\t"
};

/*
 * For util_monname()
 */
STATIC char		*mon_name[] = {
	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};



/***********************
 *   public routines   *
 ***********************/


/*
 * util_init
 *	Initialize the libutil module.  This should be called before
 *	the calling program does a setuid.
 *
 * Args:
 *	None
 *
 * Return:
 *	Nothing
 */
void
util_init(void)
{
	/* Save original uid and gid */
	ouid = getuid();
	ogid = getgid();

	/* Set uname */
	if (uname(&un) < 0) {
		DBGPRN(errfp, "uname(2) failed (errno=%d)\n", errno);
	}
}


/*
 * util_start
 *	Start up the libutil module.
 *
 * Args:
 *	None
 *
 * Return:
 *	Nothing
 */
void
util_start(void)
{
	int	n,
		i;
	char	*p,
		*q;
	char	c;

	/* Initializations for util_text_reduce() */
	p = app_data.exclude_words;
	n = 1;
	if (p != NULL) {
		for (; *p != '\0'; p++) {
			if (isspace(*p)) {
				n++;
				while (isspace(*p))
					p++;
			}
		}
	}
	excnt = n;

	exclude_words = (char **) MEM_ALLOC(
		"exclude_words",
		excnt * sizeof(char *)
	);
	if (exclude_words == NULL) {
		fprintf(errfp, "Out of virtual memory.\n");
		exit(1);
	}

	p = app_data.exclude_words;
	if (p == NULL)
		exclude_words[0] = "";
	else {
		n = 0;
		for (q = p; *q != '\0'; q++) {
			if (!isspace(*q))
				continue;
			c = *q;
			*q = '\0';
			exclude_words[n] = (char *) MEM_ALLOC(
				"exclude_words[n]",
				strlen(p) + 1
			);
			if (exclude_words[n] == NULL) {
				fprintf(errfp, "Out of virtual memory.\n");
				exit(1);
			}
			(void) strcpy(exclude_words[n], p);
			n++;
			*q = c;
			p = q + 1;
			while (isspace(*p))
				p++;
			q = p;
		}
		exclude_words[n] = (char *) MEM_ALLOC(
			"exclude_words[n]",
			strlen(p) + 1
		);
		if (exclude_words[n] == NULL) {
			fprintf(errfp, "Out of virtual memory.\n");
			exit(1);
		}
		(void) strcpy(exclude_words[n], p);
	}

	exlen = (int *) MEM_ALLOC("exlen", sizeof(int) * excnt);
	if (exlen == NULL) {
		fprintf(errfp, "Out of virtual memory.\n");
		exit(1);
	}

	for (i = 0; i < excnt; i++)
		exlen[i] = strlen(exclude_words[i]);

	delcnt = sizeof(delete_words) / sizeof(char *);

	dellen = (int *) MEM_ALLOC("dellen", sizeof(int) * delcnt);
	if (dellen == NULL) {
		fprintf(errfp, "Out of virtual memory.\n");
		exit(1);
	}

	for (i = 0; i < delcnt; i++)
		dellen[i] = strlen(delete_words[i]);
}


/*
 * util_get_ouid
 *	Get original user ID
 *
 * Args:
 *	None
 *
 * Return:
 *	Original uid value.
 */
uid_t
util_get_ouid(void)
{
	return (ouid);
}


/*
 * util_get_ogid
 *	Get original group ID
 *
 * Args:
 *	None
 *
 * Return:
 *	Original gid value.
 */
gid_t
util_get_ogid(void)
{
	return (ogid);
}


/*
 * util_set_ougid
 *	Change user ID and group ID to original setting.
 *
 * Args:
 *	None.
 *
 * Return:
 *	TRUE on success, FALSE on failure.
 */
bool_t
util_set_ougid(void)
{
	DBGPRN(errfp, "\nSetting uid/gid: %d/%d\n", (int) ouid, (int) ogid);

	/* Force uid and gid to original setting */
	if (setuid(ouid) < 0) {
		DBGPRN(errfp, "Failed to set uid.\n");
		return FALSE;
	}
	if (setgid(ogid) < 0) {
		DBGPRN(errfp, "Failed to set gid.\n");
		return FALSE;
	}
	return (TRUE);
}


/*
 * util_get_uname
 *	Get the utsname structure for the running system
 *	(See uname(2)).
 *
 * Args:
 *	None
 *
 * Return:
 *	Pointer to the utsname structure.
 */
struct utsname *
util_get_uname(void)
{
	return (&un);
}


/*
 * util_ltobcd
 *	32-bit integer to BCD conversion routine
 *
 * Args:
 *	n - 32-bit integer
 *
 * Return:
 *	BCD representation of n
 */
sword32_t
util_ltobcd(sword32_t n)
{
	return ((n % 10) | ((n / 10) << 4));
}


/*
 * util_bcdtol
 *	BCD to 32-bit integer conversion routine
 *
 * Args:
 *	n - BCD value
 *
 * Return:
 *	integer representation of n
 */
sword32_t
util_bcdtol(sword32_t n)
{
	return ((n & 0x0f) + ((n >> 4) * 10));
}


/*
 * util_stob
 *	String to boolean conversion routine
 *
 * Args:
 *	s - text string "True", "true", "False" or "false"
 *
 * Return:
 *	Boolean value representing the string
 */
bool_t
util_stob(char *s)
{
	if (strcmp(s, "True") == 0 || strcmp(s, "true") == 0 ||
	    strcmp(s, "TRUE") == 0)
		return TRUE;

	return FALSE;
}


/*
 * util_basename
 *	Return the basename of a file path
 *
 * Args:
 *	path - The file path string
 *
 * Return:
 *	The basename string
 */
char *
util_basename(char *path)
{
	char		*p;
#ifdef __VMS
	char		*q;
#endif
	static char	buf[FILE_PATH_SZ];

	if (path == NULL)
		return NULL;

	if ((int) strlen(path) >= FILE_PATH_SZ)
		/* Error: path name too long */
		return NULL;

	(void) strcpy(buf, path);

#ifndef __VMS
	if ((p = strrchr(buf, '/')) == NULL)
#else
	if ((p = strrchr(buf, ']')) == NULL)
#endif
		return (buf);

	p++;

#ifdef __VMS
	if (*p == '\0') {
		/* The supplied path is a directory - special handling */
		*--p = '\0';
		if ((q = strrchr(buf, '.')) != NULL)
			p = q + 1;
		else if ((q = strrchr(buf, '[')) != NULL)
			p = q + 1;
		else if ((q = strrchr(buf, ':')) != NULL)
			p = q + 1;
		else {
			p = buf;
			*p = '\0';
		}
	}
#endif

	return (p);
}


/*
 * util_dirname
 *	Return the dirname of a file path
 *
 * Args:
 *	path - The file path string
 *
 * Return:
 *	The dirname string
 */
char *
util_dirname(char *path)
{
	char		*p;
#ifdef __VMS
	char		*q;
#endif
	static char	buf[FILE_PATH_SZ];

	if (path == NULL)
		return NULL;

	if ((int) strlen(path) >= FILE_PATH_SZ)
		/* Error: path name too long */
		return NULL;

	(void) strcpy(buf, path);

#ifdef __VMS
	if ((p = strrchr(buf, ']')) == NULL)
#else
	if ((p = strrchr(buf, '/')) == NULL)
#endif
		return (buf);

#ifdef __VMS
	if (*++p == '\0') {
		/* The supplied path is a directory - special handling */
		if ((q = strrchr(buf, '.')) != NULL) {
			*q = ']';
			*++q = '\0';
		}
		else if ((q = strrchr(buf, ':')) != NULL)
			*++q = '\0';
		else
			p = buf;
	}
	*p = '\0';
#else
	if (p == buf)
		*++p = '\0';
	else
		*p = '\0';
#endif

	return (buf);
}


/*
 * util_loginname
 *	Return the login name of the current user
 *
 * Args:
 *	None.
 *
 * Return:
 *	The login name string.
 */
char *
util_loginname(void)
{
	char		*cp;
#ifdef __VMS
	cp = getlogin();
	if (cp != NULL)
		return (cp);
#else
	struct passwd	*pw;

	/* Get login name from the password file if possible */
	setpwent();
	if ((pw = getpwuid(ouid)) != NULL) {
		endpwent();
		return (pw->pw_name);
	}
	endpwent();

	/* Try the LOGNAME environment variable */
	if ((cp = (char *) getenv("LOGNAME")) != NULL)
		return (cp);

	/* Try the USER environment variable */
	if ((cp = (char *) getenv("USER")) != NULL)
		return (cp);
#endif
	/* If we still can't get the login name, just set it
	 * to "nobody" (shrug).
	 */
	return ("nobody");
}


/*
 * util_homedir
 *	Return the home directory path of a user given the uid
 *
 * Args:
 *	uid - The uid of the user
 *
 * Return:
 *	The home directory path name string
 */
char *
util_homedir(uid_t uid)
{
#ifndef __VMS
	struct passwd	*pw;
	char		*cp;

	/* Get home directory from the password file if possible */
	setpwent();
	if ((pw = getpwuid(uid)) != NULL) {
		endpwent();
		return (pw->pw_dir);
	}
	endpwent();

	/* Try the HOME environment variable */
	if (uid == ouid && (cp = (char *) getenv("HOME")) != NULL)
		return (cp);

	/* If we still can't get the home directory, just set it to the
	 * current directory (shrug).
	 */
	return (".");
#else
	char		*cp;
	static char	buf[FILE_PATH_SZ];

	if ((cp = (char *) getenv("HOME")) != NULL &&
	    (int) strlen(cp) < sizeof(buf)) {
		(void) strcpy(buf, cp);
		buf[strlen(buf)-1] = '\0';	/* Drop the "]" */
	}
	else
		(void) strcpy(buf, "SYS$DISK:[");

	return (buf);
#endif	/* __VMS */
}


/*
 * util_uhomedir
 *	Return the home directory path of a user given the name
 *
 * Args:
 *	name - The name of the user
 *
 * Return:
 *	The home directory path name string
 */
char *
util_uhomedir(char *name)
{
#ifndef __VMS
	struct passwd	*pw;

	/* Get home directory from the password file if possible */
	setpwent();
	if ((pw = getpwnam(name)) != NULL) {
		endpwent();
		return (pw->pw_dir);
	}
	endpwent();

	/* If we still can't get the home directory, just set it to the
	 * current directory (shrug).
	 */
	return (".");
#else
	char		*cp;
	static char	buf[FILE_PATH_SZ];

	if ((cp = (char *) getenv("HOME")) != NULL &&
	    (int) strlen(cp) < FILE_PATH_SZ) {
		(void) strcpy(buf, cp);
		buf[strlen(buf)-1] = '\0';	/* Drop the "]" */
	}
	else
		(void) strcpy(buf, "SYS$DISK:[");

	return (buf);
#endif
}


/*
 * util_mkdir
 *	Wrapper for the mkdir() call.
 *
 * Args:
 *	path - The directory path to make
 *	mode - The permissions
 *
 * Return:
 *	TRUE - mkdir succeeded or directory already exists
 *	FALSE - mkdir failed
 */
bool_t
util_mkdir(char *path, mode_t mode)
{
	struct stat	stbuf;

	/*
	 * Make sure directory exists.  If not, create it.
	 */
	if (stat(path, &stbuf) < 0) {
		if (errno == ENOENT) {
			if (mkdir(path, 0777) < 0)
				return FALSE;
		}
		else
			return FALSE;
	}
	else if (!S_ISDIR(stbuf.st_mode))
		return FALSE;

	(void) chmod(path, mode);
	return TRUE;
}


/*
 * util_setperm
 *	Set the file permissions of a file.
 *
 * Args:
 *	path - file path name
 *
 * Return:
 *	Nothing
 */
void
util_setperm(char *path, char *modestr)
{
	unsigned int	mode;

	/* Set the database file permissions */
	(void) sscanf(modestr, "%o", &mode);

	/* Make sure the file is at least readable to the user just
	 * in case mode is bogus.
	 */
	mode |= S_IRUSR;

	/* Turn off extraneous bits */
	mode &= ~(S_ISUID | S_ISGID | S_IXUSR | S_IXGRP | S_IXOTH);

	/* Set file permission */
	(void) chmod(path, (mode_t) mode);
}


/*
 * util_monname
 *	Convert an interger month to an abbreviated 3-letter month
 *	name string.
 *
 * Args:
 *	mon - The integer month (0 is January, 11 is December).
 *
 * Return:
 *	The month name string
 */
char *
util_monname(int mon)
{
	if (mon < 0 || mon >= 12)
		return ("???");
	return (mon_name[mon]);
}


/*
 * util_isexecutable
 *	Verify executability, given a path to a program
 *
 * Args:
 *	path - the absolute path to the program executable
 *
 * Return:
 *	TRUE - It is executable
 *	FALSE - It is not executable
 */
bool_t
util_isexecutable(char *path)
{
#ifdef __VMS
	return TRUE;	/* shrug */
#else
	char		**cp;
	struct group	*gr;
	struct stat	stbuf;

	if (stat(path, &stbuf) < 0 || !S_ISREG(stbuf.st_mode))
		/* Cannot access file or file is not regular */
		return FALSE;

	if (ouid == 0)
		/* Root can execute any file */
		return TRUE;

	if ((stbuf.st_mode & S_IXUSR) == S_IXUSR && ouid == stbuf.st_uid)
		/* The file is executable, and is owned by the user */
		return TRUE;

	if ((stbuf.st_mode & S_IXGRP) == S_IXGRP) {
		if (ogid == stbuf.st_gid)
			/* The file is group executable, and the
			 * user's current gid matches the group.
			 */
			return TRUE;

		setgrent();
		if ((gr = getgrgid(stbuf.st_gid)) != NULL) {
			for (cp = gr->gr_mem; cp != NULL && *cp != '\0'; cp++) {
				/* The file is group executable, and the
				 * user is a member of that group.
				 */
				if (strcmp(*cp, util_loginname()) == 0)
					return TRUE;
			}
		}
		endgrent();
	}

	if ((stbuf.st_mode & S_IXOTH) == S_IXOTH)
		/* The file is executable by everyone */
		return TRUE;

	return FALSE;
#endif	/* __VMS */
}


/*
 * util_checkcmd
 *	Check a command for sanity before running it.
 *
 * Args:
 *	cmd - The command string
 *
 * Return:
 *	TRUE - Command is sane
 *	FALSE - Command is not sane
 */
bool_t
util_checkcmd(char *cmd)
{
#ifdef __VMS
	return TRUE;	/* shrug */
#else
	char	*p,
		*q,
		*r,
		*env,
		*path,
		c,
		c2;
	bool_t	isexe;

	if (cmd == NULL)
		return FALSE;

	/* Cut out just the argv[0] portion */
	c = '\0';
	if ((p = strchr(cmd,' ')) != NULL || (p = strchr(cmd,'\t')) != NULL) {
		c = *p;
		*p = '\0';
	}

	if (cmd[0] == '/') {
		/* Absolute path specified */
		isexe = util_isexecutable(cmd);
	}
	else {
		/* Relative path: walk PATH and look for the executable */
		if ((env = getenv("PATH")) == NULL) {
			if (p != NULL)
				*p = c;
			/* PATH unknown */
			return FALSE;
		}

		isexe = FALSE;

		/* Walk the PATH */
		for (q = env; (r = strchr(q, ':')) != NULL; *r = c2, q = ++r) {
			c2 = *r;
			*r = '\0';

			path = (char *) MEM_ALLOC(
				"checkcmd_path",
				strlen(q) + strlen(cmd) + 2
			);
			if (path == NULL)
				return FALSE;	/* shrug */

			(void) sprintf(path, "%s/%s", q, cmd);

			if (util_isexecutable(path)) {
				isexe = TRUE;
				MEM_FREE(path);
				*r = c2;
				break;
			}

			MEM_FREE(path);
		}
		if (!isexe) {
			/* Check last component in PATH */
			path = (char *) MEM_ALLOC(
				"checkcmd_path",
				strlen(q) + strlen(cmd) + 2
			);
			if (path == NULL)
				return FALSE;	/* shrug */

			(void) sprintf(path, "%s/%s", q, cmd);

			if (util_isexecutable(path))
				isexe = TRUE;

			MEM_FREE(path);
		}
	}

	if (p != NULL)
		*p = c;

	return (isexe);
#endif	/* __VMS */
}


/*
 * util_runcmd
 *	Set uid and gid to the original user and spawn an external command.
 *
 * Args:
 *	cmd - Command string.
 *	workproc - Function to call when waiting for child process,
 *		   or NULL if no workproc.
 *	workarg - Argument to pass to workproc.
 *
 * Return:
 *	The exit status of the command.
 */
int
util_runcmd(char *cmd, void (*workproc)(int), int workarg)
{
	int		ret;
#ifndef __VMS
	pid_t		cpid;
	waitret_t	stat_val;

	if (!util_checkcmd(cmd))
		return EXE_ERR;

	/* Fork child to invoke external command */
	switch (cpid = FORK()) {
	case 0:
		/* Child process */
		break;

	case -1:
		/* Fork failed */
		perror("util_runcmd: fork() failed");
		return EXE_ERR;

	default:
		/* Parent process: wait for child to exit */
		while ((ret = WAITPID(cpid, &stat_val, 0)) != cpid) {
			if (ret < 0) {
				DBGPRN(errfp, "waitpid() failed (errno=%d)\n",
				       errno);
				return 0;
			}

			/* If a workproc is defined, run it */
			if (workproc != NULL)
				(*workproc)(workarg);
		}

		if (WIFEXITED(stat_val))
			ret = WEXITSTATUS(stat_val);
		else
			ret = EXE_ERR;

		DBGPRN(errfp, "\nCommand exit status %d\n", ret);
		return (ret);
	}

	/* Force uid and gid to original setting */
	if (!util_set_ougid())
		exit(errno);
#endif	/* __VMS */

	/* Do the command */
	DBGPRN(errfp, "Command: [%s]\n", cmd);
	ret = system(cmd);

#ifdef __VMS
	DBGPRN(errfp, "Command exit status %d\n", ret);
	return (ret);
#else
	stat_val = (waitret_t) ret;

	if (WIFEXITED(stat_val))
		ret = WEXITSTATUS(stat_val);
	else
		ret = EXE_ERR;

	exit(ret);
	/*NOTREACHED*/
#endif	/* __VMS */
}


/*
 * util_isqrt
 *	Fast integer-based square root routine
 *
 * Args:
 *	n - The integer value whose square-root is to be taken
 *
 * Return:
 *	Resultant square-root integer value
 */
int
util_isqrt(int n)
{
	int	a, b, c, as, bs;

	a = 1;
	b = 1;
	while (a <= n) {
		a = a << 2;
		b = b << 1;
	}
	as = 0;
	bs = 0;
	while (b > 1 && n > 0) {
		a = a >> 2;
		b = b >> 1;
		c = n - (as | a);
		if (c >= 0) {
			n = c;
			as |= (a << 1);
			bs |= b;
		}
		as >>= 1;
	}

	return (bs);
}


/*
 * util_blktomsf
 *	CD logical block to MSF conversion routine
 *
 * Args:
 *	blk - The logical block address
 *	ret_min - Minute (return)
 *	ret_sec - Second (return)
 *	ret_frame - Frame (return)
 *	offset - Additional logical block address offset
 *
 * Return:
 *	Nothing.
 */
void
util_blktomsf(
	word32_t	blk,
	byte_t		*ret_min,
	byte_t		*ret_sec,
	byte_t		*ret_frame,
	word32_t	offset)
{
	*ret_min = (blk + offset) / FRAME_PER_SEC / 60;
	*ret_sec = ((blk + offset) / FRAME_PER_SEC) % 60;
	*ret_frame = (blk + offset) % FRAME_PER_SEC;
}


/*
 * util_msftoblk
 *	CD MSF to logical block conversion routine
 *
 * Args:
 *	min - Minute
 *	sec - Second
 *	frame - Frame
 *	ret_blk - The logical block address (return)
 *	offset - Additional logical block address offset
 *
 * Return:
 *	Nothing.
 */
void
util_msftoblk(
	byte_t		min,
	byte_t		sec,
	byte_t		frame,
	word32_t	*ret_blk,
	word32_t	offset)
{
	*ret_blk = FRAME_PER_SEC * (min * 60 + sec) + frame - offset;
}


/*
 * util_delayms
 *	Suspend execution for the specified number of milliseconds
 *
 * Args:
 *	msec - The number of milliseconds
 *
 * Return:
 *	Nothing.
 */
void
util_delayms(unsigned long msec)
{
#ifdef USE_SELECT
	struct timeval	to;

	to.tv_sec = (long) msec / 1000;
	to.tv_usec = ((long) msec % 1000) * 1000;

	(void) select(0, NULL, NULL, NULL, &to);
#else
#ifdef USE_POLL
	(void) poll(NULL, 0, (int) msec);
#else
#ifdef USE_NAP
	(void) nap((long) msec);
#else
#ifdef USE_USLEEP
	(void) usleep((long) msec * 1000);
#else
	/* shrug: Rounded to the nearest second, with a minimum of 1 second */
	if (msec < 1000)
		(void) sleep(1);
	else
		(void) sleep(((unsigned int) msec + 500) / 1000);
#endif	/* USE_USLEEP */
#endif	/* USE_NAP */
#endif	/* USE_POLL */
#endif	/* USE_SELECT */
}


/*
 * util_strcasecmp
 *	Compare two strings a la strcmp(), except it is case-insensitive.
 *
 * Args:
 *	s1 - The first text string.
 *	s2 - The second text string.
 *
 * Return:
 *	Compare value.  See strcmp(3).
 */
int
util_strcasecmp(char *s1, char *s2)
{
	char	*buf1,
		*buf2,
		*p;
	int	ret;

	if (s1 == NULL || s2 == NULL)
		return 0;

	/* Allocate tmp buffers */
	buf1 = (char *) MEM_ALLOC("strcasecmp_buf1", strlen(s1)+1);
	buf2 = (char *) MEM_ALLOC("strcasecmp_buf2", strlen(s2)+1);
	if (buf1 == NULL || buf2 == NULL) {
		fprintf(errfp, "Error: %s\n", app_data.str_nomemory);
		exit(1);
	}

	/* Convert both strings to lower case and store in tmp buffer */
	for (p = buf1; *s1 != '\0'; s1++, p++)
		*p = (char) ((isupper(*s1)) ? tolower(*s1) : *s1);
	*p = '\0';
	for (p = buf2; *s2 != '\0'; s2++, p++)
		*p = (char) ((isupper(*s2)) ? tolower(*s2) : *s2);
	*p = '\0';

	ret = strcmp(buf1, buf2);

	MEM_FREE(buf1);
	MEM_FREE(buf2);

	return (ret);
}


/*
 * util_strncasecmp
 *	Compare two strings a la strncmp(), except it is case-insensitive.
 *
 * Args:
 *	s1 - The first text string.
 *	s2 - The second text string.
 *	n - number of characters to compare.
 *
 * Return:
 *	Compare value.  See strncmp(3).
 */
int
util_strncasecmp(char *s1, char *s2, int n)
{
	char	*buf1,
		*buf2,
		*p;
	int	ret;

	if (s1 == NULL || s2 == NULL)
		return 0;

	/* Allocate tmp buffers */
	buf1 = (char *) MEM_ALLOC("strncasecmp_buf1", strlen(s1)+1);
	buf2 = (char *) MEM_ALLOC("strncasecmp_buf2", strlen(s2)+1);
	if (buf1 == NULL || buf2 == NULL) {
		fprintf(errfp, "Error: %s\n", app_data.str_nomemory);
		exit(1);
	}

	/* Convert both strings to lower case and store in tmp buffer */
	for (p = buf1; *s1 != '\0'; s1++, p++)
		*p = (char) ((isupper(*s1)) ? tolower(*s1) : *s1);
	*p = '\0';
	for (p = buf2; *s2 != '\0'; s2++, p++)
		*p = (char) ((isupper(*s2)) ? tolower(*s2) : *s2);
	*p = '\0';

	ret = strncmp(buf1, buf2, n);

	MEM_FREE(buf1);
	MEM_FREE(buf2);

	return (ret);
}


/*
 * Data used by b64encode
 */
STATIC char	b64map[] = {
	'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
	'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
	'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
	'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
	'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
	'8', '9', '+', '/'
};

#define B64_PAD		'='


/*
 * util_b64encode
 *	Base64 encoding function
 *
 * Args:
 *	ibuf - Input buffer pointer
 &	len - Length of data in input buffer
 &	obuf - Output buffer pointer
 *	brklines - Whether the encoded output should be broken
 *		   up into multiple lines (i.e., newlines are
 *		   inserted every 64 characters in accordance
 *		   to RFC 1521
 *
 *	It is assumed that the caller has pre-allocated an output
 *	buffer large enough to hold the encoded data, which should
 *	be 33% larger than the input data length (i.e., for every
 *	three bytes of input, there will be four bytes of output).
 *
 * Return:
 *	Nothing.
 */
void
util_b64encode(byte_t *ibuf, int len, byte_t *obuf, bool_t brklines)
{
	int	i, j, k, n,
		c[4];
	byte_t	sbuf[4];

	for (i = k = 0; (i + 3) <= len; i += 3, ibuf += 3) {
		c[0] = ((int) ibuf[0] >> 2);
		c[1] = ((((int) ibuf[0] & 0x03) << 4) |
			(((int) ibuf[1] & 0xf0) >> 4));
		c[2] = ((((int) ibuf[1] & 0x0f) << 2) |
			(((int) ibuf[2] & 0xc0) >> 6));
		c[3] = ((int) ibuf[2] & 0x3f);

		for (j = 0; j < 4; j++)
			*obuf++ = b64map[c[j]];

		if (brklines && ++k == 16) {
			k = 0;
			*obuf++ = '\n';
		}
	}

	if (i < len) {
		n = len - i;
		(void) strncpy((char *) sbuf, (char *) ibuf, n);
		for (j = n; j < 3; j++)
			sbuf[j] = (unsigned char) 0;

		n++;
		ibuf = sbuf;
		c[0] = ((int) ibuf[0] >> 2);
		c[1] = ((((int) ibuf[0] & 0x03) << 4) |
			(((int) ibuf[1] & 0xf0) >> 4));
		c[2] = ((((int) ibuf[1] & 0x0f) << 2) |
			(((int) ibuf[2] & 0xc0) >> 6));
		c[3] = ((int) ibuf[2] & 0x3f);

		for (j = 0; j < 4; j++)
			*obuf++ = (j < n) ? b64map[c[j]] : B64_PAD;

		if (brklines && ++k == 16)
			*obuf++ = '\n';
	}

	if (brklines)
		*obuf++ = '\n';

	*obuf = '\0';
}


/*
 * util_text_reduce
 *	Reduce a text string to become suitable for use in a keyword search
 *	operation.
 *
 * Args:
 *	str - The input text string
 *
 * Return:
 *	The output text string.  The string buffer is allocated internally
 *	and should be freed by the caller via MEM_FREE().  If an error
 *	occurs, NULL is returned.
 */
char *
util_text_reduce(char *str)
{
	int		i,
			lastex,
			*len;
	char		last,
			next,
			*p1,
			*p2,
			*pr,
			**t,
			*newstr;

	if ((newstr = (char *) MEM_ALLOC("text_reduce_newstr",
					 strlen(str) + 1)) == NULL)
		return NULL;

	p1 = str;
	p2 = newstr;
	pr = newstr;

	last = ' ';
	lastex = -1;

	while (*p1 != '\0') {
		next = *p1;

		for (i = 0, t = delete_words, len = dellen; i < delcnt;
		     i++, t++, len++) {
			if (strncmp(p1, *t, *len) == 0) {
				p1 += *len - 1;
				next = ' ';
				break;
			}
		}

		if (!isalnum(last) && !isalnum(next)) {
			p1++;
			continue;
		}

		for (i = 0, t = exclude_words, len = exlen; i < excnt;
		    i++, t++, len++) {
			if (lastex != i && !isalnum(last) &&
			    util_strncasecmp(p1, *t, *len) == 0 &&
			    !isalnum(p1[*len])) {
				p1 += *len;
				lastex = i;
				break;
			}
		}

		if (i < excnt)
			continue;

		if (isalnum(next))
			*p2 = next;
		else
			*p2 = ' ';

		last = next;
		p2++;
		p1++;

		if (isalnum(next)) {
			lastex = -1;
			pr = p2;
		}
	}

	*pr = '\0';
	return (newstr);
}


/*
 * util_cgi_xlate
 *	Translate a keyword string into CGI form.  It substitutes whitespaces
 *	with the proper separator, conversion to lower case, handles non-
 *	alphanumerdic character translations, etc.
 *
 * Args:
 *	str - The input keywords string, separated by whitespace
 *
 * Return:
 *	The output text string.  The string buffer is allocated internally
 *	and should be freed by the caller via MEM_FREE().  If an error
 *	occurs, NULL is returned.
 */
char *
util_cgi_xlate(char *str)
{
	char	*p,
		*q,
		*new_str;

	if ((q = new_str = (char *) MEM_ALLOC("cgi_xlate_newstr",
					      (strlen(str) * 3) + 5)) == NULL)
		return NULL;

	/* Skip leading whitespaces */
	p = str;
	while (isspace(*p))
		p++;

	/* Process the string */
	while (*p != '\0') {
		if (isspace(*p)) {
			/* Skip remaining consecutive white spaces */
			while (isspace(*(++p)))
				;
			if (*p == '\0')
				break;	/* End of string reached */
			else {
				/* Substitute white spaces with separator */
				*q = '+';
				q++;
			}
		}
		else if ((ispunct(*p) &&
			  *p != '_' && *p != '.' &&
			  *p != '*' && *p != '@') ||
			 (*p & 0x80)) {
			/* Need URL-encoding */
			(void) sprintf(q, "%%%02X", (int) (*p));
			q += 3;
			p++;
		}
		else if (isprint(*p)) {
			/* Printable character */
			*q = (char) (isupper(*p) ? tolower(*p) : (*p));
			q++;
			p++;
		}
		else
			p++;
	}
	*q = '\0';

	return (new_str);
}


/*
 * util_bswap16
 *	16-bit little-endian to big-endian byte-swap routine.
 *	On a big-endian system architecture this routines has no effect.
 *
 * Args:
 *	x - The data to be swapped
 *
 * Return:
 *	The swapped data.
 */
word16_t
util_bswap16(word16_t x)
{
#if _BYTE_ORDER_ == _L_ENDIAN_
	word16_t	ret;

	ret  = (x & 0x00ff) << 8;
	ret |= (word16_t) (x & 0xff00) >> 8;
	return (ret);
#else
	return (x);
#endif
}


/*
 * util_bswap24
 *	24-bit little-endian to big-endian byte-swap routine.
 *	On a big-endian system architecture this routines has no effect.
 *
 * Args:
 *	x - The data to be swapped
 *
 * Return:
 *	The swapped data.
 */
word32_t
util_bswap24(word32_t x)
{
#if _BYTE_ORDER_ == _L_ENDIAN_
	word32_t	ret;

	ret  = (x & 0x0000ff) << 16;
	ret |= (x & 0x00ff00);
	ret |= (x & 0xff0000) >> 16;
	return (ret);
#else
	return (x);
#endif
}


/*
 * util_bswap32
 *	32-bit little-endian to big-endian byte-swap routine.
 *	On a big-endian system architecture this routines has no effect.
 *
 * Args:
 *	x - The data to be swapped
 *
 * Return:
 *	The swapped data.
 */
word32_t
util_bswap32(word32_t x)
{
#if _BYTE_ORDER_ == _L_ENDIAN_
	word32_t	ret;

	ret  = (x & 0x000000ff) << 24;
	ret |= (x & 0x0000ff00) << 8;
	ret |= (x & 0x00ff0000) >> 8;
	ret |= (x & 0xff000000) >> 24;
	return (ret);
#else
	return (x);
#endif
}


/*
 * util_lswap16
 *	16-bit big-endian to little-endian byte-swap routine.
 *	On a little-endian system architecture this routines has no effect.
 *
 * Args:
 *	x - The data to be swapped
 *
 * Return:
 *	The swapped data.
 */
word16_t
util_lswap16(word16_t x)
{
#if _BYTE_ORDER_ == _L_ENDIAN_
	return (x);
#else
	word16_t	ret;

	ret  = (x & 0x00ff) << 8;
	ret |= (word16_t) (x & 0xff00) >> 8;
	return (ret);
#endif
}


/*
 * util_lswap24
 *	24-bit big-endian to little-endian byte-swap routine.
 *	On a little-endian system architecture this routines has no effect.
 *
 * Args:
 *	x - The data to be swapped
 *
 * Return:
 *	The swapped data.
 */
word32_t
util_lswap24(word32_t x)
{
#if _BYTE_ORDER_ == _L_ENDIAN_
	return (x);
#else
	word32_t	ret;

	ret  = (x & 0x0000ff) << 16;
	ret |= (x & 0x00ff00);
	ret |= (x & 0xff0000) >> 16;
	return (ret);
#endif
}


/*
 * util_lswap32
 *	32-bit big-endian to little-endian byte-swap routine.
 *	On a little-endian system architecture this routines has no effect.
 *
 * Args:
 *	x - The data to be swapped
 *
 * Return:
 *	The swapped data.
 */
word32_t
util_lswap32(word32_t x)
{
#if _BYTE_ORDER_ == _L_ENDIAN_
	return (x);
#else
	word32_t	ret;

	ret  = (x & 0x000000ff) << 24;
	ret |= (x & 0x0000ff00) << 8;
	ret |= (x & 0x00ff0000) >> 8;
	ret |= (x & 0xff000000) >> 24;
	return (ret);
#endif
}


/*
 * util_dbgdump
 *	Dump a data buffer to screen.
 *
 * Args:
 *	title - Message banner
 *	data - Address of data
 *	len - Number of bytes to dump
 *
 * Return:
 *	Nothing.
 */
void
util_dbgdump(char *title, byte_t *data, int len)
{
	int	i, j, k, n,
		lines;

	if (title == NULL || data == NULL || len <= 0)
		return;

	(void) fprintf(errfp, "\n%s:", title);

	lines = ((len - 1) / 16) + 1;

	for (i = 0, k = 0; i < lines; i++) {
		(void) fprintf(errfp, "\n%04x    ", k);

		for (j = 0, n = k; j < 16; j++, k++) {
			if (k < len)
				(void) fprintf(errfp, "%02x ", *(data + k));
			else
				(void) fprintf(errfp, "-- ");

			if (j == 7)
				(void) fprintf(errfp, " ");
		}

		(void) fprintf(errfp, "   ");

		for (j = 0, k = n; j < 16; j++, k++) {
			if (k < len) {
				(void) fprintf(errfp, "%c",
				    isprint(*(data + k)) ? *(data + k) : '.'
				);
			}
			else
				(void) fprintf(errfp, ".");
		}
	}

	(void) fprintf(errfp, "\n");
}


#ifdef __VMS
/*
 * The following section provide UNIX-like functionality for Digital OpenVMS
 */

/* Function prototypes */
extern void	delete();

#ifdef VMS_USE_OWN_DIRENT

extern int	LIB$FIND_FILE();
extern void	LIB$FIND_FILE_END();
extern void	SYS$FILESCAN();

typedef struct {
	short	length;
	short	component;
	int	address;
	int	term;
} item_list;


/*
 * util_opendir
 *	Emulate a UNIX opendir by clearing the context value, and creating
 *	the wild card search by appending *.* to the path name.
 *	(See opendir(2) on UNIX systems)
 *
 * Args:
 *	path - directory path to open
 *
 * Return:
 *	Pointer to the DIR structure descriptor
 */
DIR *
util_opendir(char *path)
{
	static DIR		dir;
	static struct dirent	ent;

	context = 0;
	(void) sprintf(ent.d_name, "%s*.*", path);
	dir.dd_buf = &ent;
 	return (&dir);
}


/*
 * util_closedir
 *	Emulate a UNIX closedir by call LIB$FIND_FILE_END to close 
 *	the file context.  (End the wild card search)
 *	(See closedir(2) on UNIX systems)
 *
 * Args:
 *	dp - pointer to the directory's DIR structure
 *
 * Return:
 *	Nothing.
 */
void
util_closedir(DIR *dp)
{
	LIB$FIND_FILE_END(&context);
}


/*
 * util_readdir
 *	Emulate a UNIX readdir by calling LIB$FIND_FILE, and SYS$FILESCAN
 *	to return the file name back.
 *	(See readdir(2) on UNIX systems)
 *
 * Args:
 *	dp - pointer to the directory's DIR structure
 *
 * Return:
 *	Pointer to the dirent structure pertaining to a directory entry
 */
struct dirent *
util_readdir(DIR *dp)
{
	int			dir_desc[2],
				desc[2],
				i;
	char 			*p,
				*file[FILE_PATH_SZ];
	item_list		list;
	static struct dirent	ent;

	desc[0] = FILE_PATH_SZ;
	desc[1] = (int) file;

	dir_desc[0] = FILE_PATH_SZ;
	dir_desc[1] = (int) dp->dd_buf->d_name;

	if (LIB$FIND_FILE(dir_desc, desc, &context) & 0x01) {
		list.length = 0;
		list.component = FSCN$_NAME;
		list.address = 0;
		list.term = 0;

		SYS$FILESCAN(desc, &list, 0, 0, 0); 

		p = (char *) list.address;
		p[list.length] = '\0';

		for (p = (char *) list.address; *p != '\0'; p++)
			*p = tolower(*p);

		(void) strcpy(ent.d_name, (char *) list.address);
		return (&ent);
	}
	else
		return NULL;
}

#endif	/* VMS_USE_OWN_DIRENT */


/*
 * util_waitpid
 *	Emulate a UNIX waitpid by doing a wait call
 *	(see waitpid(2) on UNIX systems)
 *
 * Args:
 *	pid - process ID to wait for
 *	statloc - pointer to wait status information
 *	options - wait options
 * Return:
 *	The process ID of the process that caused this call to stop
 *	waiting.
 */
pid_t
util_waitpid(pid_t pid, int *statloc, int options)
{
	pid_t	ret;

	ret = wait(statloc);

	/* Under VMS a vfork() call does not create a child process unless
	 * a real process is created.  In the cases where the child does
	 * not follow the vfork with a system() or exec() call to create
	 * a real subprocess, we need to fake things out.
	 */
	if (ret < 0)
		ret = pid;

	/* VMS returns a 1 for success.  Patch it to zero to
	 * make this function compatible with UNIX.
	 */
	if (*statloc == 1)
		*statloc = 0;

	return (ret);
}


/*
 * util_unlink
 *	Emulate a UNIX unlink call
 *	(See unlink(2) on UNIX systems)
 *
 * Args:
 *	file - file path name to unlink
 *
 * Return:
 *	0  - Success
 *	-1 - Failure
 */
int
util_unlink(char *file)
{
	delete(file);
	return 0;
}


/*
 * util_link
 *	Emulate a UNIX link call by copying FILE1 to FILE2
 *	(See link(2) on UNIX systems)
 *
 * Args:
 *	file1 - source file
 *	file2 - destination file
 *
 * Return:
 *	0  - Success
 *	-1 - Failure
 */
int 
util_link(char *file1, char *file2)
{
	FILE	*fp1,
		*fp2;
	char	buf[STR_BUF_SZ * 16];

	fp1 = fopen(file1, "r");
	fp2 = fopen(file2, "w");

	if (fp1 == NULL || fp2 == NULL)
		return -1;

	while (fgets(buf, sizeof(buf), fp1) != NULL)
		(void) fprintf(fp2, "%s", buf);

	(void) fclose(fp1);	
	(void) fclose(fp2);	

	return 0;	
}

#endif	/* __VMS */

#ifdef MEM_DEBUG
/*
 * For memory allocation debugging
 */


/*
 * util_dbg_malloc
 *	Wrapper for malloc(3).
 */
void *
util_dbg_malloc(char *name, size_t size)
{
	void	*ptr;

	ptr = _MEM_ALLOC(size);
	(void) fprintf(stderr, "Malloc(%s, %d) => 0x%x\n", name, size, ptr);
	return (ptr);
}


/*
 * util_dbg_realloc
 *	Wrapper for realloc(3).
 */
void *
util_dbg_realloc(char *name, void *ptr, size_t size)
{
	void	*nptr;

	nptr = _MEM_REALLOC(ptr, size);
	(void) fprintf(stderr, "Realloc(%s, 0x%x, %d) => 0x%x\n",
			name, ptr, size, nptr);
	return (nptr);
}


/*
 * util_dbg_calloc
 *	Wrapper for calloc(3).
 */
void *
util_dbg_calloc(char *name, size_t nelem, size_t elsize)
{
	void	*ptr;

	ptr = _MEM_CALLOC(nelem, elsize);
	(void) fprintf(stderr, "Calloc(%s, %d, %d) => 0x%x\n",
			name, nelem, elsize, ptr);
	return (ptr);
}


/*
 * util_dbg_free
 *	Wrapper for free(3).
 */
void
util_dbg_free(void *ptr)
{
	(void) fprintf(stderr, "Free(0x%x)\n", ptr);
	_MEM_FREE(ptr);
}

#endif	/* MEM_DEBUG */