File: utils.c

package info (click to toggle)
mnogosearch 3.3.7-3
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 17,484 kB
  • ctags: 4,565
  • sloc: ansic: 94,097; xml: 16,864; sh: 8,915; makefile: 1,727; perl: 801; php: 561; sql: 15
file content (2557 lines) | stat: -rw-r--r-- 56,921 bytes parent folder | download
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
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
/* Copyright (C) 2000-2006 Lavtech.com corp. All rights reserved.

   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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
*/

#include "udm_config.h"

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#include <errno.h>

#ifdef HAVE_IO_H
#include <io.h>  /* for Win */
#endif

#ifdef HAVE_DIRECT_H
#include <direct.h> /* for Win */
#endif

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

#ifdef HAVE_SYS_TIMES_H
#include <sys/times.h>
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <signal.h>

#include "udm_signals.h"
#include "udm_utils.h"

#ifdef WIN32
#include <assert.h>
#endif

long tz_offset=0;	/* EXT */
char udm_null_char= 0;

char *UdmStrStore (char *dest, const char *src) {
	size_t d_size = (dest ? strlen(dest) : 0);
	size_t s_size = strlen(src) + 1;
	char *d = UdmRealloc(dest, d_size + s_size);

	if (d) memcpy(d + d_size, src, s_size);
	else UDM_FREE(dest);
	return(d);
}

UDM_DSTR *UdmDSTRInit (UDM_DSTR *dstr, size_t size_page) {
	if (! size_page) return(NULL);

	if (! dstr) {
		dstr = UdmMalloc(sizeof(UDM_DSTR));
		if (! dstr) return(NULL);
		dstr->free = 1;
	} else {
		dstr->free = 0;
	}

	dstr->data = UdmMalloc(size_page);
	if (! dstr->data) {
		if (dstr->free) UdmFree(dstr);
		return(NULL);
	}
        dstr->data[0] = 0;
	dstr->size_page = size_page;
	dstr->size_data = 0;
	dstr->size_total = size_page;
	return(dstr);
}

void UdmDSTRFree (UDM_DSTR *dstr) {
	dstr->size_total= dstr->size_data= 0;
	UdmFree(dstr->data);
	if (dstr->free) UdmFree(dstr);
}


int UdmDSTRAlloc (UDM_DSTR *dstr, size_t size_data)
{
  size_t asize;
 
  if (size_data <= dstr->size_total) return(UDM_OK);
  asize= (size_data / dstr->size_page + 1) * dstr->size_page;
  dstr->size_total= dstr->size_data= 0;
  UdmFree(dstr->data);
  if (!(dstr->data= UdmMalloc(asize)))
    return UDM_ERROR;
  dstr->size_total= asize;
  return UDM_OK;
}


int UdmDSTRRealloc (UDM_DSTR *dstr, size_t size_data)
{
  char *tmp;
  size_t asize;
 
  if (size_data <= dstr->size_total) return(UDM_OK);
  asize= (size_data / dstr->size_page + 1) * dstr->size_page;
  tmp= UdmRealloc(dstr->data, asize);
  if (! tmp) return(UDM_ERROR);
  dstr->size_total= asize;
  dstr->data= tmp;
  return(UDM_OK);
}

size_t UdmDSTRAppend (UDM_DSTR *dstr, const char *data, size_t size_data) {
	size_t bytes_left = dstr->size_total - dstr->size_data;
	size_t asize;
	char *tmp;

	if (! data || ! size_data) return(0);

	if (bytes_left <= size_data) {
		asize = dstr->size_total + ((size_data - bytes_left) / dstr->size_page + 1) * dstr->size_page;
		tmp = UdmRealloc(dstr->data, asize);
		if (! tmp) return(0);
		dstr->data = tmp;
		dstr->size_total = asize;
	}
	memcpy(dstr->data + dstr->size_data, data, size_data);
	dstr->size_data += size_data;
	dstr->data[dstr->size_data] = 0;
	return(size_data);
}


static char hex_digits[]= "0123456789ABCDEF";

/*
  This function does not put trailing \x00 character.
*/
size_t
UdmDSTRAppendHex(UDM_DSTR *dstr, const char *s, size_t slen)
{
  char *d;
  size_t new_size= dstr->size_data + 2 * slen;
  if (!slen || (UDM_OK != UdmDSTRRealloc(dstr, new_size)))
    return 0;
  for (d= dstr->data + dstr->size_data; slen; slen--, s++)
  {
    unsigned char ch= *((const unsigned char*) s);
    *d++= hex_digits[(ch >> 4) & 0x0F];
    *d++= hex_digits[ch & 0x0F];
  }
  dstr->size_data= new_size;
  return dstr->size_data;
}


size_t UdmDSTRAppendSTR (UDM_DSTR *dstr, const char *data) {
	return(UdmDSTRAppend(dstr, data, strlen(data)));
}

int UdmDSTRAppendf (UDM_DSTR *dstr, const char *fmt, ...) {
	va_list ap;
	size_t bytes_left;
	int nc;
	char *tmp;
	size_t asize;

	while (1) {
		bytes_left = dstr->size_total - dstr->size_data;
		va_start(ap, fmt);
		nc = vsnprintf(dstr->data + dstr->size_data, bytes_left, fmt, ap);
		va_end(ap);
		if (nc > -1 && nc + 1 < bytes_left) break;

		if (nc < 0 || nc + 1 == bytes_left) asize = dstr->size_total + dstr->size_page;
		else asize = dstr->size_total + ((nc - bytes_left) / dstr->size_page + 1) * dstr->size_page;

		tmp = UdmRealloc(dstr->data, asize);
		if (! tmp) {
			nc = 0;
			break;
		}
		dstr->size_total = asize;
		dstr->data = tmp;
	}

	dstr->size_data += nc;
	return(nc);
}

void UdmDSTRReset (UDM_DSTR *dstr) {
	dstr->size_data = 0;
}

/*** str functions implementation which may be missing on some OS ***/

#ifndef HAVE_BZERO
__C_LINK void __UDMCALL bzero(void *b, size_t len) {
	memset(b,0,len);
}
#endif

#ifndef HAVE_STRCASECMP
__C_LINK int __UDMCALL strcasecmp(const char *s1, const char *s2) {
	register const unsigned char
			*us1 = (const unsigned char *)s1,
			*us2 = (const unsigned char *)s2;

	while (tolower(*us1) == tolower(*us2++))
		if (*us1++ == '\0')
			return (0);
	return (tolower(*us1) - tolower(*--us2));
}
#endif

#ifndef HAVE_STRNCASECMP
int strncasecmp(const char *s1, const char *s2, size_t n)
{
	if (n != 0) {
		register const unsigned char
				*us1 = (const unsigned char *)s1,
				*us2 = (const unsigned char *)s2;

		do {
			if (tolower(*us1) != tolower(*us2++))
				return (tolower(*us1) - tolower(*--us2));
			if (*us1++ == '\0')
				break;
		} while (--n != 0);
	}
	return (0);
}
#endif

#if !defined(HAVE_STRNDUP) || defined(EFENCE)
char * UdmStrndup(const char * str,size_t len){
	char * res;
	res=(char*)UdmMalloc(len+1);
	strncpy(res,str,len);
	res[len]='\0';
	return res;
}
#endif


#ifndef HAVE_STRCASESTR
char * strcasestr(register const char *s, register const char *find) {
        register char c, sc;
        register size_t len;

        if ((c = *find++) != 0) {
                c = tolower((unsigned char)c);
                len = strlen(find);
                do {
                        do {
                                if ((sc = *s++) == 0)
                                        return (NULL);
                        } while ((char)tolower((unsigned char)sc) != c);
                } while (strncasecmp(s, find, len) != 0);
                s--;
        }
        return ((char *)s);
}
#endif

/**************** RFC 1522 ******************************************/
static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

int __UDMCALL UdmHex2Int(int h){
	if((h>='0')&&(h<='9'))return(h-'0');
	if((h>='A')&&(h<='F'))return(h-'A'+10);
	if((h>='a')&&(h<='f'))return(h-'a'+10);
	return(0);
}

int __UDMCALL UdmInt2Hex(int i){
	if((i>=0)&&(i<=9))return(i+'0');
	if((i>=10)&&(i<=15))return(i+'A'-10);
	return '0';
}	

char * udm_rfc1522_decode(char * dst, const char *src){
	const char *s;
	char  *d;

	s=src;
	d=dst;
	*dst=0;

	while(*s){
		char *e;

		if((e=strstr(s,"=?"))){
			char *schema;
			char *data;

			if(e>s){
				/* Copy last plain text buffer */
				strncpy(d,s,(size_t)(e-s));
				d+=(e-s);
				*d=0;
			}
			e+=2;
			if(!(schema=strchr(e,'?'))){
				/* Error */
				break;
			}
			schema++;
			data=schema+2;

			if(!(e=strstr(data,"?="))){
				/* This is an error */
				break;
			}
			switch(*schema){
				case 'Q':
				case 'q':
					while(data<e){
						char c;
						if(*data=='='){
							c=(char)(UdmHex2Int(data[1])*16+UdmHex2Int(data[2]));
							data+=3;
						}else{
							c=data[0];
							data++;
						}
						/* Copy one char to dst */
						*d=c;d++;*d=0;
					}
					break;
				case 'B':
				case 'b':
					while(data<e){
						char *p;
						int x0,x1,x2,x3,res;

						p=strchr(base64,data[0]);x0=p?p-base64:0;
						p=strchr(base64,data[1]);x1=p?p-base64:0;
						p=strchr(base64,data[2]);x2=p?p-base64:0;
						p=strchr(base64,data[3]);x3=p?p-base64:0;

						res=x3+x2*64+x1*64*64+x0*64*64*64;

						p=(char*)(&res);

						if(p[2])*d=p[2];d++;*d=0;
						if(p[1])*d=p[1];d++;*d=0;
						if(p[0])*d=p[0];d++;*d=0;

						data+=4;
					}
					break;
				default:
					/* Error */
					schema=NULL;
					break;
			}
			if(schema==NULL){
				/* Error */
				break;
			}
			s=e+2;
		}else{
			/* Copy plain text tail */
			strcpy(d,s);
			break;
		}
	}
	return(dst);
}


/************* Base 64 *********************************************/
/* BASE64 encoding converts  3x8 bits into 4x6 bits                */

__C_LINK size_t __UDMCALL udm_base64_encode (const char *src, char *store,
                                             size_t length)
{
  unsigned char *p= (unsigned char *)store;
  unsigned const char *s= (unsigned const char *)src;

  for ( ; length > 2 ; length-= 3, s+= 3)
  {
    *p++ = base64[s[0] >> 2];
    *p++ = base64[((s[0] & 3) << 4) + (s[1] >> 4)];
    *p++ = base64[((s[1] & 0xf) << 2) + (s[2] >> 6)];
    *p++ = base64[s[2] & 0x3f];
  }

  if (length > 0)
  {
    *p++= base64[s[0] >> 2];
    if (length > 1)
    {
      *p++ = base64[((s[0] & 3) << 4) + (s[1] >> 4)];
      *p++ = base64[(s[1] & 0xf) << 2];
      *p++ = '=';
    }
    else
    {
      *p++ = base64[(s[0] & 0x03) << 4];
      *p++ = '=';
      *p++ = '=';
    }
  }

  *p= '\0';
  return p - (unsigned char*)store;
}


static char from_base64[]=
{
/*00*/   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
/*10*/   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
/*20*/   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,62, 0, 0, 0,63, /*  !"#$%&'()*+,-./ */
/*30*/  52,53,54,55,56,57,58,59,60,61, 0, 0, 0, 0, 0, 0, /* 0123456789:;<=>? */
/*40*/   0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* @ABCDEFGHIJKLMNO */
/*50*/  15,16,17,18,19,20,21,22,23,24,25, 0, 0, 0, 0, 0, /* PQRSTUVWXYZ[\]^_ */
/*60*/   0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, /* `abcdefghijklmno */
/*70*/  41,42,43,44,45,46,47,48,49,50,51, 0, 0, 0, 0, 0, /* pqrstuvwxyz{|}~  */
/*80*/   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
/*90*/   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
/*A0*/   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
/*B0*/   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
/*C0*/   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
/*D0*/   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
/*E0*/   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
/*F0*/   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};


__C_LINK size_t __UDMCALL
udm_base64_decode(char *dst, const char *src, size_t len)
{
  char *dst0= dst;
  
  for( ; *src && len > 3 ; )
  {
    int b0= from_base64[(unsigned char) *src++];
    int b1= from_base64[(unsigned char) *src++];
    int b2= from_base64[(unsigned char) *src++];
    int b3= from_base64[(unsigned char) *src++];
    int res= b3 + b2*64 + b1*64*64 + b0*64*64*64;

    *dst++= (res>>16)&0xFF;
    *dst++= (res>>8)&0xFF;
    *dst++= res&0xFF;
  }
  *dst= '\0';
  return dst - dst0;
}


unsigned long UdmStartTimer(void){
#ifdef WIN32
	return clock();
#else
  struct timeval tv;
  struct timezone tz;
  gettimeofday(&tv, &tz);
  return((tv.tv_sec % 100000) * 1000 + (tv.tv_usec / 1000));

/*
#undef CLOCKS_PER_SEC
#define CLOCKS_PER_SEC (sysconf(_SC_CLK_TCK))
	struct tms tms_tmp;
	return (float)times(&tms_tmp)*1000/CLOCKS_PER_SEC;
*/
#endif
}

char * UdmTrim(char *p, const char *delim){
int len;
	len = strlen(p);
	while ((len > 0) && strchr(delim, p[len - 1] )) {
		p[len - 1] = '\0';
		len--;
	}
	while((*p)&&(strchr(delim,*p)))p++;
	return(p);
}

char * UdmRTrim(char* p, const char *delim){
int len;
	len = strlen(p);
	while ((len > 0) && strchr(delim, p[len - 1] )) {
		p[len - 1] = '\0';
		len--;
	}
	return(p);
}


/* strtok_r clone */
char * udm_strtok_r(char *s, const char *delim, char **last) {
    const char *spanp;
    int c, sc;
    char *tok;

    if (s == NULL && (s = *last) == NULL)
	return NULL;

cont:
    c = *s++;
    for (spanp = delim; (sc = *spanp++) != 0; )
    {
	if (c == sc)
	{
	    goto cont;
	}
    }

    if (c == 0)		/* no non-delimiter characters */
    {
	*last = NULL;
	return NULL;
    }
    tok = s - 1;

    for (;;)
    {
	c = *s++;
	spanp = delim;
	do
	{
	    if ((sc = *spanp++) == c)
	    {
		if (c == 0)
		{
		    s = NULL;
		}
		else
		{
		    char *w = s - 1;
		    *w = '\0';
		}
		*last = s;
		return tok;
	    }
	}
	while (sc != 0);
    }
}

/* This function parses string tokens      */
/* It understands: text 'text' "text"      */
/* I.e. Words, tokens enclosed in ' and "  */
/* Behavior is the same with strtok_r()    */
char * UdmGetStrToken(char * s,char ** last){
	char * tbeg,lch;
	if (s == NULL && (s = *last) == NULL)
		return NULL;

	/* Find the beginning of token */
	for(;(*s)&&(strchr(" \r\n\t",*s));s++);

	if(!*s)return(NULL);

	lch=*s;
	if((lch=='\'')||(lch=='"'))s++;
	else	lch=' ';
	tbeg=s;

	while(1){
		switch(*s){
			case '\0': *last=NULL;break;
/*			case '\\': memmove(s,s+1,strlen(s+1)+1);break;*/
			case '"':
			case '\'':
				if(lch==*s){
					*s='\0';
					*last=s+1;	
				}
				break;
			case ' ':
			case '\r':
			case '\n':
			case '\t':
				if(lch==' '){
					*s='\0';
					*last=s+1;
				}
				break;
			default:;
		}
		if(*s)s++;
		else break;
	}
	return(tbeg);
}


static int ch2x(int ch)
{
  if (ch >= '0' && ch <= '9')
    return ch - '0';
  
  if (ch >= 'a' && ch <= 'f')
    return 10 + ch - 'a';
  
  if (ch >= 'A' && ch <= 'F')
    return 10 + ch - 'A';
  
  return -1;
}

char * UdmUnescapeCGIQuery(char *d, const char *s)
{
  char *dd;
  
  for (dd= d; *s; s++)
  {
    if(*s == '%' && ch2x(s[1]) >= 0 && ch2x(s[2]) >= 0)
    {	
      *d++= ch2x(s[1]) * 16 + ch2x(s[2]);
      s+= 2;
    }
    else if(*s=='+')
    {
      *d++=' ';
    }
    else
    {
      *d++=*s;
    }
  }
  *d=0;
  return(dd);
}

char * __UDMCALL UdmEscapeURL(char *d,const char *s){
	char *dd;
	if((d==NULL)||(s==NULL))return(0);
	dd=d;
	while(*s){
		if((*s & 0x80) || strchr("%&<>+[](){}/?#'\"\\;,",*s)) {
			sprintf(d,"%%%X",(int) (unsigned char)*s);
			d+=2;
		}else
		if(*s==' '){
			*d='+';
		}else{
			*d=*s;
		}
		s++;d++;
	}
	*d=0;
	return(dd);
}

char * UdmEscapeURI(char *d,const char *s){
	char *dd;
	if((d==NULL)||(s==NULL))return(0);
	dd=d;
	while(*s){
		if(strchr(" ",*s)){
			sprintf(d,"%%%X",(int)*s);
			d+=2;
		}else{
			*d=*s;
		}
		s++;d++;
	}
	*d=0;
	return(dd);
}


/* Oh,no! We have to remove parent level like /parent/../index.html from path
   Let's do it recursively! */
char * UdmRemove2Dot(char *path){
        char *ptr;
	char *tail;
    
        if(!(ptr=strstr(path,"../"))) return path;
	if(ptr==path) return path; /* How could it be? */
        tail=ptr+2;
	ptr--;
        *ptr=0;
	if(!(ptr=strrchr(path,'/'))) *path=0; else *ptr=0;
        path=strcat(path,tail);
	return UdmRemove2Dot(path);
}

/* Function to convert date returned by web-server to time_t
 *
 * Earlier we used strptime, but it seems to be completely broken
 * on Solaris 2.6. Thanks to Maciek Uhlig <muhlig@us.edu.pl> for pointing
 * out this and bugfix proposal (to use Apache's ap_parseHTTPdate).
 *
 * 10 July 2000 kir.
 */

#define BAD_DATE 0

/*****
 *  BEGIN: Below is taken from Apache's util_date.c
 */

/* ====================================================================
 * Copyright (c) 1996-1999 The Apache Group.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the Apache Group
 *    for use in the Apache HTTP server project (http://www.apache.org/)."
 *
 * 4. The names "Apache Server" and "Apache Group" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the Apache Group
 *    for use in the Apache HTTP server project (http://www.apache.org/)."
 *
 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE APACHE GROUP OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Group and was originally based
 * on public domain software written at the National Center for
 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
 * For more information on the Apache Group and the Apache HTTP server
 * project, please see <http://www.apache.org/>.
 *
 */

/********
 * BEGIN
 * This is taken from ap_ctype.h
 * --kir.
 */

#include <ctype.h>

#ifdef __cplusplus
extern "C" {
#endif

/* These macros allow correct support of 8-bit characters on systems which
 * support 8-bit characters.  Pretty dumb how the cast is required, but
 * that's legacy libc for ya.  These new macros do not support EOF like
 * the standard macros do.  Tough.
 */
#define ap_isalnum(c) (isalnum(((unsigned char)(c))))
#define ap_isalpha(c) (isalpha(((unsigned char)(c))))
#define ap_iscntrl(c) (iscntrl(((unsigned char)(c))))
#define ap_isdigit(c) (isdigit(((unsigned char)(c))))
#define ap_isgraph(c) (isgraph(((unsigned char)(c))))
#define ap_islower(c) (islower(((unsigned char)(c))))
#define ap_isprint(c) (isprint(((unsigned char)(c))))
#define ap_ispunct(c) (ispunct(((unsigned char)(c))))
#define ap_isspace(c) (isspace(((unsigned char)(c))))
#define ap_isupper(c) (isupper(((unsigned char)(c))))
#define ap_isxdigit(c) (isxdigit(((unsigned char)(c))))
#define ap_tolower(c) (tolower(((unsigned char)(c))))
#define ap_toupper(c) (toupper(((unsigned char)(c))))

#ifdef __cplusplus
}
#endif

/*******
 * END of taken from ap_ctype.h
 */

/*
 * Compare a string to a mask
 * Mask characters (arbitrary maximum is 256 characters, just in case):
 *   @ - uppercase letter
 *   $ - lowercase letter
 *   & - hex digit
 *   # - digit
 *   ~ - digit or space
 *   * - swallow remaining characters 
 *  <x> - exact match for any other character
 */
static int ap_checkmask(const char *data, const char *mask)
{
    int i;
    char d;

    for (i = 0; i < 256; i++) {
	d = data[i];
	switch (mask[i]) {
	case '\0':
	    return (d == '\0');

	case '*':
	    return 1;

	case '@':
	    if (!ap_isupper(d))
		return 0;
	    break;
	case '$':
	    if (!ap_islower(d))
		return 0;
	    break;
	case '#':
	    if (!ap_isdigit(d))
		return 0;
	    break;
	case '&':
	    if (!ap_isxdigit(d))
		return 0;
	    break;
	case '~':
	    if ((d != ' ') && !ap_isdigit(d))
		return 0;
	    break;
	default:
	    if (mask[i] != d)
		return 0;
	    break;
	}
    }
    return 0;			/* We only get here if mask is corrupted (exceeds 256) */
}

/*
 * tm2sec converts a GMT tm structure into the number of seconds since
 * 1st January 1970 UT.  Note that we ignore tm_wday, tm_yday, and tm_dst.
 * 
 * The return value is always a valid time_t value -- (time_t)0 is returned
 * if the input date is outside that capable of being represented by time(),
 * i.e., before Thu, 01 Jan 1970 00:00:00 for all systems and 
 * beyond 2038 for 32bit systems.
 *
 * This routine is intended to be very fast, much faster than mktime().
 */
static time_t ap_tm2sec(const struct tm * t)
{
    int year;
    time_t days;
    static const int dayoffset[12] =
    {306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275};

    year = t->tm_year;

    if (year < 70 || ((sizeof(time_t) <= 4) && (year >= 138)))
	return BAD_DATE;

    /* shift new year to 1st March in order to make leap year calc easy */

    if (t->tm_mon < 2)
	year--;

    /* Find number of days since 1st March 1900 (in the Gregorian calendar). */

    days = year * 365 + year / 4 - year / 100 + (year / 100 + 3) / 4;
    days += dayoffset[t->tm_mon] + t->tm_mday - 1;
    days -= 25508;		/* 1 jan 1970 is 25508 days since 1 mar 1900 */

    days = ((days * 24 + t->tm_hour) * 60 + t->tm_min) * 60 + t->tm_sec;

    if (days < 0)
	return BAD_DATE;	/* must have overflowed */
    else
	return days;		/* must be a valid time */
}


/*
  Scan date string: YYYY-MM-DD
*/
static void
scan_yyyy_mm_dd(struct tm *ds, const char *date)
{
  ds->tm_year= ((date[0] - '0') * 10 + (date[1] - '0') - 19) * 100 +
               (date[2] - '0') * 10 + date[3] - '0';
  ds->tm_mon=  (date[5] - '0') * 10 + (date[6] - '0') - 1;
  ds->tm_mday= (date[8] - '0') * 10 + (date[9] - '0');
}


/*
  Scan year: YYYY
*/
static void
scan_yyyy(struct tm *ds, const char *date)
{
  ds->tm_year= ((date[0] - '0') * 10 + (date[1] - '0') - 19) * 100 +
               (date[2] - '0') * 10 + date[3] - '0';
}


/*
  Scan time string:   hh:mm:ss
*/
static void
scan_hh_mm_ss(struct tm *ds, const char *timstr)
{
  ds->tm_hour= ((timstr[0] - '0') * 10) + (timstr[1] - '0');
  ds->tm_min= ((timstr[3] - '0') * 10) + (timstr[4] - '0');
  ds->tm_sec= ((timstr[6] - '0') * 10) + (timstr[7] - '0');
}

static const int months[12] =
{
  ('J' << 16) | ('a' << 8) | 'n', ('F' << 16) | ('e' << 8) | 'b',
  ('M' << 16) | ('a' << 8) | 'r', ('A' << 16) | ('p' << 8) | 'r',
  ('M' << 16) | ('a' << 8) | 'y', ('J' << 16) | ('u' << 8) | 'n',
  ('J' << 16) | ('u' << 8) | 'l', ('A' << 16) | ('u' << 8) | 'g',
  ('S' << 16) | ('e' << 8) | 'p', ('O' << 16) | ('c' << 8) | 't',
  ('N' << 16) | ('o' << 8) | 'v', ('D' << 16) | ('e' << 8) | 'c'
};

/*
  Convert month name to month, 0..11
*/
static void
scan_month_name(struct tm *ds, const char *monstr)
{
  int mon, mint= (monstr[0] << 16) | (monstr[1] << 8) | monstr[2];
  for (mon= 0; mon < 12; mon++)
    if (mint == months[mon])
      break;
  ds->tm_mon= mon;
}

/*
 * Parses an HTTP date in one of three standard forms:
 *
 *     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
 *     Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
 *     Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
 *
 * and returns the time_t number of seconds since 1 Jan 1970 GMT, or
 * 0 if this would be out of range or if the date is invalid.
 *
 * The restricted HTTP syntax is
 * 
 *     HTTP-date    = rfc1123-date | rfc850-date | asctime-date
 *
 *     rfc1123-date = wkday "," SP date1 SP time SP "GMT"
 *     rfc850-date  = weekday "," SP date2 SP time SP "GMT"
 *     asctime-date = wkday SP date3 SP time SP 4DIGIT
 *
 *     date1        = 2DIGIT SP month SP 4DIGIT
 *                    ; day month year (e.g., 02 Jun 1982)
 *     date2        = 2DIGIT "-" month "-" 2DIGIT
 *                    ; day-month-year (e.g., 02-Jun-82)
 *     date3        = month SP ( 2DIGIT | ( SP 1DIGIT ))
 *                    ; month day (e.g., Jun  2)
 *
 *     time         = 2DIGIT ":" 2DIGIT ":" 2DIGIT
 *                    ; 00:00:00 - 23:59:59
 *
 *     wkday        = "Mon" | "Tue" | "Wed"
 *                  | "Thu" | "Fri" | "Sat" | "Sun"
 *
 *     weekday      = "Monday" | "Tuesday" | "Wednesday"
 *                  | "Thursday" | "Friday" | "Saturday" | "Sunday"
 *
 *     month        = "Jan" | "Feb" | "Mar" | "Apr"
 *                  | "May" | "Jun" | "Jul" | "Aug"
 *                  | "Sep" | "Oct" | "Nov" | "Dec"
 *
 * However, for the sake of robustness (and Netscapeness), we ignore the
 * weekday and anything after the time field (including the timezone).
 *
 * This routine is intended to be very fast; 10x faster than using sscanf.
 *
 * Originally from Andrew Daviel <andrew@vancouver-webpages.com>, 29 Jul 96
 * but many changes since then.
 *
 */
time_t UdmHttpDate2Time_t(const char *date){
  struct tm ds;

  if (!date)
    return BAD_DATE;

  while (*date && ap_isspace(*date))	/* Find first non-whitespace char */
    ++date;

  if (*date == '\0')
    return BAD_DATE;

  if (ap_checkmask(date, "####-##-##"))
  {
    /*
       2004-01-02 non-standard format,
       but we can meet it quit often in user meta tags.
    */
    scan_yyyy_mm_dd(&ds, date);
    ds.tm_hour= ds.tm_min= ds.tm_sec= 0;
    goto check_valid_date;
  }
  else if (ap_checkmask(date, "##.##.####"))
  {
    /*
       0123456789
       02.01.2005 non-standard format,
       but we can meet it quit often in
       user meta tags in Germany.
    */
    scan_yyyy(&ds, date + 6);
    ds.tm_mon= (date[3] - '0') * 10 + (date[4] - '0') - 1;
    ds.tm_mday= (date[0] - '0') * 10 + (date[1] - '0');
    ds.tm_hour= ds.tm_min= ds.tm_sec= 0;
    goto check_valid_date;
  }                         /* 01234567890123456789 */
  else if (ap_checkmask(date, "####-##-##T##:##:##Z"))
  {
    /*
      W3C format, also used by OpenSearch
      http://www.w3.org/TR/NOTE-datetime
      http://opensearch.a9.com/spec/1.1/response/

      Complete date plus hours, minutes, seconds
      and UTC timezone designator
      2005-01-02T10:20:30Z
    */
    scan_yyyy_mm_dd(&ds, date);
    scan_hh_mm_ss(&ds, date + 11);
    goto check_valid_time;
  }

  if ((date = strchr(date, ' ')) == NULL)	/* Find space after weekday */
    return BAD_DATE;

  ++date;

  /*
    Now date points to first char after space, which should be
    start of the actual date information for all formats.
  */
  if (ap_checkmask(date, "## @$$ #### ##:##:## *"))
  {
    /*
      RFC 1123 format
      Sun, 06 Nov 1994 08:49:37 GMT
    */
    scan_yyyy(&ds, date + 7);
    ds.tm_mday= ((date[0] - '0') * 10) + (date[1] - '0');
    scan_month_name(&ds, date + 3);
    scan_hh_mm_ss(&ds, date + 12);
  }                          /*0123456789ABCDEFGHIJK*/
  else if (ap_checkmask(date, "# @$$ #### ##:##:## *"))
  {
    /*
     The same as above, but with a one-digit day
     Sun, 6 Nov 1994 08:49:37 GMT
    */
    scan_yyyy(&ds, date + 6);
    ds.tm_mday= date[0] - '0';
    scan_month_name(&ds, date + 2);
    scan_hh_mm_ss(&ds, date + 11);
  }
  else if (ap_checkmask(date, "##-@$$-## ##:##:## *"))
  {
    /*
      RFC 850 format:
      Sunday, 06-Nov-94 08:49:37 GMT
    */
    ds.tm_year= ((date[7] - '0') * 10) + (date[8] - '0');
    if (ds.tm_year < 70)
      ds.tm_year+= 100;
    ds.tm_mday= ((date[0] - '0') * 10) + (date[1] - '0');
    scan_month_name(&ds, date + 3);
    scan_hh_mm_ss(&ds, date + 10);
  }
  else if (ap_checkmask(date, "@$$ ~# ##:##:## ####*"))
  {
    /*
      ANSI C's asctime() format
      Sun Nov  6 08:49:37 1994
    */
    scan_yyyy(&ds, date + 16);
    ds.tm_mday= (date[4] == ' ') ? 0 : (date[4] - '0') * 10;
    ds.tm_mday+= (date[5] - '0');
    scan_month_name(&ds, date);
    scan_hh_mm_ss(&ds, date + 7);
  }
  else
    return BAD_DATE;

check_valid_time:

  if ((ds.tm_hour > 23) || (ds.tm_min > 59) || (ds.tm_sec > 61))
    return BAD_DATE;

check_valid_date:

  if (ds.tm_mday <= 0 || ds.tm_mday > 31)
    return BAD_DATE;

  if (ds.tm_mon > 11)
    return BAD_DATE;

  if ((ds.tm_mday == 31) &&
      (ds.tm_mon == 3 || ds.tm_mon == 5 || ds.tm_mon == 8 || ds.tm_mon == 10))
    return BAD_DATE;

  /* February gets special check for leapyear */

  if ((ds.tm_mon == 1) &&
      ((ds.tm_mday > 29)
      || ((ds.tm_mday == 29)
       && ((ds.tm_year & 3)
      || (((ds.tm_year % 100) == 0)
       && (((ds.tm_year % 400) != 100)))))))
    return BAD_DATE;

#if 0
  {
    int res= ap_tm2sec(&ds);
    char buf[128];
    strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &ds);
    printf("parseHTTPdate: '%s' is %lu: strftime=%s, month=%d\n", date, res, buf, ds.tm_mon);
  }
#endif

  return ap_tm2sec(&ds);
}

/********
 * END: Above is taken from Apache's util_date.c
 */

time_t UdmFTPDate2Time_t(char *date){
	struct tm ds;

	if (!(ap_checkmask(date+4, "##############*")))
		return BAD_DATE;

/*        strptime(date+6, "%y%m%d%H%M%S", &tm_s); */

	ds.tm_year = (((date[4] - '0') * 10) + (date[5] - '0') - 19)*100;
	ds.tm_year += ((date[6] - '0') * 10) + (date[7] - '0');

	ds.tm_mon = ((date[8] - '0') * 10) + (date[9] - '0') - 1;
	ds.tm_mday = ((date[10] - '0') * 10) + (date[11] - '0');

	ds.tm_hour = ((date[12] - '0') * 10) + (date[13] - '0');
	ds.tm_min = ((date[14] - '0') * 10) + (date[15] - '0');
	ds.tm_sec = ((date[16] - '0') * 10) + (date[17] - '0');

	/* printf("parseFTPdate: %s is %lu\n", date, ap_tm2sec(&ds)); */

	return ap_tm2sec(&ds);
}

time_t Udm_dp2time_t(const char * time_str){
	time_t t=0;
	long i;
	char *s;
	const char *ts;

	/* flag telling us that time_str is exactly <num> without any char
	 * so we think it's seconds
	 * flag==0 means not defined yet
	 * flag==1 means ordinary format (XXXmYYYs)
	 * flag==2 means seconds only
	 */
	int flag=0;
	
	ts = time_str;
	do{
		i=strtol(ts, &s, 10);
		if (s==ts){ /* falied to find a number */
			/* FIXME: report error */
			return -1;
		}
		
		/* ignore spaces */
		while (isspace(*s))
			s++;
	    
		switch(*s){
			case 's': /* seconds */
				t+=i; flag=1; break;
			case 'M': /* minutes */
				t+=i*60; flag=1; break;
			case 'h': /* hours */
				t+=i*60*60; flag=1; break;
			case 'd': /* days */
				t+=i*60*60*24; flag=1; break;
			case 'm': /* months */
				/* I assume month is 30 days */
				t+=i*60*60*24*30; flag=1; break;
			case 'y': /* years */
				t+=i*60*60*24*365; flag=1; break;
			case '\0': /* end of string */
				if (flag==1)
					return -1;
				else{
					t=i;
					flag=2;
					return t;
				}    
			default:
				/* FIXME: report error here! */
				return -1;
		}
		/* go to next char */
		ts=++s;
	/* is it end? */
	} while (*s);
	
	return t;
}

/* * * * * * * * * * * * *
 * DEBUG CRAP...
 */

/*
#define DEBUG_DP2TIME
*/

#ifdef DEBUG_DP2TIME
int main(int argc, char **argv){

	char *dp;
	
	if (argc>1)
		dp=argv[1];
	else{
		printf("Usage: %s time_string\n", argv[0]);
		return 1;
	}
	
	printf("str='%s'\ttime=%li\n", dp, Udm_dp2time_t(dp));
	return 0;
}
#endif /* DEBUG_DP2TIME */


void UdmTime_t2HttpStr(time_t t, char *str){
    struct tm *tim;
/*    if (t==0)
	*str='\0';
    else*/ {
	/* FIXME: I suspect that gmtime IS NOT REENTRANT */

	tim=gmtime(&t);

#ifdef WIN32
	if (!strftime(str, UDM_MAXTIMESTRLEN, "%a, %d %b %Y %H:%M:%S GMT", tim))
#else
	if (!strftime(str, UDM_MAXTIMESTRLEN, "%a, %d %b %Y %H:%M:%S %Z", tim))
#endif
		*str='\0';
	/* /FIXME end of BAD code */
    }
}

/* Find out tz_offset for the functions above
 */
int UdmInitTZ(void){

/*
        time_t tt;
	struct tm *tms;

	tzset();
	tms=localtime(&tt);*/
	/* localtime sets the external variable timezone */
/*	tz_offset = tms->tm_gmtoff;
	return 0;
*/
#ifdef HAVE_TM_GMTOFF
	time_t tclock;
	struct tm *tim;
        
	tzset();
	tclock = time(NULL);
	tim=localtime(&tclock);
        tz_offset = (long)tim->tm_gmtoff;
	return 0;
#else      
	time_t tt;
	struct tm t, gmt;
	int days, hours, minutes;

	tzset();
	tt = time(NULL);
        gmt = *gmtime(&tt);
        t = *localtime(&tt);
        days = t.tm_yday - gmt.tm_yday;
        hours = ((days < -1 ? 24 : 1 < days ? -24 : days * 24)
                + t.tm_hour - gmt.tm_hour);
        minutes = hours * 60 + t.tm_min - gmt.tm_min;
        tz_offset = 60L * minutes;
	return 0;
#endif /* HAVE_TM_GMTOFF */

/* ONE MORE VARIANT - how many do we have?
    struct timezone tz;

    gettimeofday(NULL, &tz);
    tz_offset=tz.tz_minuteswest*60;
    return 0;
*/
}


__C_LINK int __UDMCALL UdmInit(){
	UdmInitTZ();
	return(0);
}


#ifndef HAVE_VSNPRINTF

#ifndef HAVE_STRNLEN
static int strnlen(const char *s, int max){
	const char *e;
	e=s;
	if (max>=0) {
	    while((*e)&&((e-s)<max))e++;
	} else {
	    while(*e)e++;
	}	
	return(e-s);
}
#endif /* ifndef HAVE_STRNLEN */


/* we use this so that we can do without the ctype library */
#define is_digit(c)	((c) >= '0' && (c) <= '9')
#define ZEROPAD	1		/* pad with zero */
#define SIGN	2		/* unsigned/signed long */
#define PLUS	4		/* show plus */
#define SPACE	8		/* space if plus */
#define LEFT	16		/* left justified */
#define SPECIAL	32		/* 0x */
#define LARGE	64		/* use 'ABCDEF' instead of 'abcdef' */

#define do_div(n,base) ({ \
int __res; \
__res = ((unsigned long) n) % (unsigned) base; \
n = ((unsigned long) n) / (unsigned) base; \
__res; })

static int skip_atoi(const char **s){
	int i=0;

	while (is_digit(**s))
		i = i*10 + *((*s)++) - '0';
	return i;
}

static int number(long num, int base, int size, int precision ,int type)
{
	int buflen=0;
	char c,sign,tmp[66];
	const char *digits="0123456789abcdefghijklmnopqrstuvwxyz";
	int i;

	if (type & LARGE)
		digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	if (type & LEFT)
		type &= ~ZEROPAD;
	if (base < 2 || base > 36)
		return 0;
	c = (type & ZEROPAD) ? '0' : ' ';
	sign = 0;
	if (type & SIGN) {
		if (num < 0) {
			sign = '-';
			num = -num;
			size--;
		} else if (type & PLUS) {
			sign = '+';
			size--;
		} else if (type & SPACE) {
			sign = ' ';
			size--;
		}
	}
	if (type & SPECIAL) {
		if (base == 16)
			size -= 2;
		else if (base == 8)
			size--;
	}
	i = 0;
	if (num == 0)
		tmp[i++]='0';
	else while (num != 0){
		tmp[i++] = digits[(unsigned long) num % (unsigned) base];
                (unsigned long) num /= (unsigned) base;
             }
	if (i > precision)
		precision = i;
	size -= precision;
	if (!(type&(ZEROPAD+LEFT)))
		while(size-->0)
			buflen++;
	if (sign)
		buflen++;
	if (type & SPECIAL) {
		if (base==8)
			buflen++;
		else if (base==16) {
			buflen++;
			buflen++;
		}
	}
	if (!(type & LEFT))
		while (size-- > 0)
			buflen++;
	while (i < precision--)
		buflen++;
	while (i-- > 0)
		buflen++;
	while (size-- > 0)
		buflen++;
	return buflen;
}

static size_t udm_vsnprintf_len(const char *fmt, va_list args)
{
	size_t buflen=0;
	int len;
	unsigned long num;
	int i, base;
	const char *s;
	int ichar;
	double ifloat;

	int flags;		/* flags to number() */

	int field_width;	/* width of output field */
	int precision;		/* min. # of digits for integers; max
				   number of chars for from string */
	int qualifier;		/* 'h', 'l', or 'L' for integer fields */

	for (; *fmt ; ++fmt) {
		if (*fmt != '%') {
			buflen++;
			continue;
		}
			
		/* process flags */
		flags = 0;
		repeat:
			++fmt;		/* this also skips first '%' */
			switch (*fmt) {
				case '-': flags |= LEFT; goto repeat;
				case '+': flags |= PLUS; goto repeat;
				case ' ': flags |= SPACE; goto repeat;
				case '#': flags |= SPECIAL; goto repeat;
				case '0': flags |= ZEROPAD; goto repeat;
				}
		
		/* get field width */
		field_width = -1;
		if (is_digit(*fmt))
			field_width = skip_atoi(&fmt);
		else if (*fmt == '*') {
			++fmt;
			/* it's the next argument */
			field_width = va_arg(args, int);
			if (field_width < 0) {
				field_width = -field_width;
				flags |= LEFT;
			}
		}

		/* get the precision */
		precision = -1;
		if (*fmt == '.') {
			++fmt;	
			if (is_digit(*fmt))
				precision = skip_atoi(&fmt);
			else if (*fmt == '*') {
				++fmt;
				/* it's the next argument */
				precision = va_arg(args, int);
			}
			if (precision < 0)
				precision = 0;
		}

		/* get the conversion qualifier */
		qualifier = -1;
		if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') {
			qualifier = *fmt;
			++fmt;
		}

		/* default base */
		base = 10;

		switch (*fmt) {
		case 'f':
                        if (precision < 0)
                                precision = 6;
                        buflen += precision;
                        if ((flags & SPECIAL) && (precision == 0))
                                buflen++;
                        if (flags & (PLUS || SPACE))
                                buflen++;
                        ifloat = va_arg(args, double);
                        while ((ifloat >= 1.) || (field_width-- > 0)) {
                                ifloat /= base;
                                buflen++;
                        };
 
                        continue;
		case 'c':
			if (!(flags & LEFT))
				while (--field_width > 0)
					buflen++;
			ichar = va_arg(args, int);
			buflen+= sizeof((unsigned char) ichar);
			while (--field_width > 0)
				buflen++;
			continue;

		case 's':
			s = va_arg(args, char *);
			if (!s)
				s = "<NULL>";

			len = strnlen(s, precision);

			if (!(flags & LEFT))
				while (len < field_width--)
					buflen++;
			for (i = 0; i < len; ++i){
				buflen++;
				s++;
			}
			while (len < field_width--)
				buflen++;
			continue;

		case 'p':
			if (field_width == -1) {
				field_width = 2*sizeof(void *);
				flags |= ZEROPAD;
			}
			buflen += number(
				(long) va_arg(args, void *), 16,
				field_width, precision, flags);
			continue;


		case '%':
			buflen++;
			continue;

		/* integer number formats - set up the flags and "break" */
		case 'o':
			base = 8;
			break;

		case 'X':
			flags |= LARGE;
		case 'x':
			base = 16;
			break;

		case 'd':
		case 'i':
			flags |= SIGN;
		case 'u':
			break;

		default:
			buflen++;
			if (*fmt)
				buflen++;
			else
				--fmt;
			continue;
		}
		if (qualifier == 'l')
			num = va_arg(args, unsigned long);
		else if (qualifier == 'h') {
			num = (unsigned short) va_arg(args, int);
			if (flags & SIGN)
				num = (short) num;
		} else if (flags & SIGN)
			num = va_arg(args, int);
		else
			num = va_arg(args, unsigned int);
		buflen += number((long)num, base, field_width, precision, flags);
	}
	return buflen;
}

int vsnprintf(char *str, size_t size, const char  *fmt,  va_list ap){
	if (udm_vsnprintf_len(fmt, ap)<size){
                return(vsprintf(str, fmt, ap));
        }else{
                strncpy(str, "Oops! Buffer overflow in vsnprintf()", size);
                return(-1);
        }
}
#endif /* ifndef HAVE_VSNPRINTF */



/* This snprintf function has been written
 * by Murray Jensen <Murray.Jensen@cmst.csiro.au>
 * So if it works for you - praise him, 
 * and if it doesn't - blame him...  
 *   --kir.
 */

__C_LINK int __UDMCALL udm_snprintf(char *buf, size_t len, const char *fmt, ...){
#ifndef HAVE_VSNPRINTF
       char *tmpbuf;
       size_t need;
#endif /* ifndef HAVE_VSNPRINTF */
       va_list ap;
       int ret;

       va_start(ap, fmt);

#ifdef HAVE_VSNPRINTF
       ret = vsnprintf(buf, len, fmt, ap);
       buf[len-1] = '\0';
#else

       need = udm_vsnprintf_len(fmt, ap);

       if ((tmpbuf = (char *) UdmMalloc(need + 1)) == NULL)
               strncpy(buf, "Oops! Out of memory in snprintf", len-1);
       else {
               vsprintf(tmpbuf, fmt, ap);
               strncpy(buf, tmpbuf, len-1);
               UDM_FREE(tmpbuf);
       }

       ret = strlen(buf);
#endif /* HAVE_VSNPRINTF */

       va_end(ap);

       return ret;
}




#ifdef WIN32
int UdmBuild(char *path, int omode) {
	struct stat sb;
	int last, retval, ret_code;
	char *p;

	p = path;
	retval = 0;
	if (p[0] == UDMSLASH)		/* Skip leading slashes. */
		++p;
	for (last = 0; !last ; ++p) {
		if (p[0] == '\0')
			last = 1;
		else
		if (p[0] != UDMSLASH)
			continue;
		*p = '\0';
		if (p[1] == '\0')
			last = 1;

		if(path[strlen(path)-1]==':'){
			char buf[5*1024];

			sprintf(buf,"%s",path);
			strcat(buf, "\\");
			ret_code=stat(buf, &sb);
		}else{
			ret_code=stat(path, &sb);
		}

		if (ret_code) {
			if (errno != ENOENT || mkdir(path) < 0 ){
				/* warn("%s", path); */
				retval = 1;
				break;
			}
		}
		else if ((sb.st_mode & S_IFMT) != S_IFDIR) {
			if (last)
				errno = EEXIST;
			else
				errno = ENOTDIR;
			/* warn("%s", path); */
			retval = 1;
			break;
		}
		if (!last)
			*p = UDMSLASH;
	}
	return (retval);
}

#else

int UdmBuild(char *path, int omode) {
	struct stat sb;
	mode_t numask, oumask;
	int first, last, retval;
	char *p;

	p = path;
	oumask = 0;
	retval = 0;
	if (p[0] == UDMSLASH)		/* Skip leading slashes. */
		++p;
	for (first = 1, last = 0; !last ; ++p) {
		if (p[0] == '\0')
			last = 1;
		else if (p[0] != UDMSLASH)
			continue;
		*p = '\0';
		if (p[1] == '\0')
			last = 1;
		if (first) {
			/*
			 * POSIX 1003.2:
			 * For each dir operand that does not name an existing
			 * directory, effects equivalent to those cased by the
			 * following command shall occcur:
			 *
			 * mkdir -p -m $(umask -S),u+wx $(dirname dir) &&
			 *    mkdir [-m mode] dir
			 *
			 * We change the user's umask and then restore it,
			 * instead of doing chmod's.
			 */
			oumask = umask(0);
			numask = oumask & ~(S_IWUSR | S_IXUSR);
			(void)umask(numask);
			first = 0;
		}
		if (last)
			(void)umask(oumask);
		if (stat(path, &sb)) {
			if (errno != ENOENT ||
			    mkdir(path, last ? omode :
				  S_IRWXU | S_IRWXG | S_IRWXO) < 0
				 ){
				/* warn("%s", path); */
				retval = 1;
				break;
			}
		}
		else if ((sb.st_mode & S_IFMT) != S_IFDIR) {
			if (last)
				errno = EEXIST;
			else
				errno = ENOTDIR;
			/* warn("%s", path); */
			retval = 1;
			break;
		}
		if (!last)
			*p = UDMSLASH;
	}
	if (!first && !last)
		(void)umask(oumask);
	return (retval);
}

#endif


char * UdmBuildParamStr(char * dst,size_t len,const char * src,char ** argv,size_t argc){
	const char * s;
	char * d;
	size_t argn;
	size_t curlen;

	*dst='\0';
	s=src;
	d=dst;
	curlen=0;
	
	while(*s){
		if(*s=='$'){
			argn=atoi(s+1);
			if((argn<=argc)&&(argn>0)){
				size_t arglen;
				arglen=strlen(argv[argn-1]);
				if(arglen+curlen+1<len){
					strcpy(d,argv[argn-1]);
					d+=strlen(d);
					curlen+=arglen;
				}else{
					break;
				}
			}
			s++;
			while(*s>='0'&&*s<='9')
				s++;
		}else
#ifdef WIN32
#else
		if(*s=='\\'){
			s++;
			if(*s){
				if(curlen+2<len){
					*d=*s;
					s++;
					d++;
					*d='\0';
					curlen++;
				}else{
					break;
				}
			}
		}else
#endif
		{
			if(curlen+2<len){
				*d=*s;
				s++;
				d++;
				*d='\0';
				curlen++;
			}else{
				break;
			}
		}
	}
	return(dst);
}

/************************************************/

int UdmSetEnv(const char * name,const char * value){
#ifdef HAVE_SETENV
	return(setenv(name,value,1));
#else
#ifdef HAVE_PUTENV
	int res;
	char * s;
	s=(char*)UdmMalloc(strlen(name)+strlen(value)+3);
	sprintf(s,"%s=%s",name,value);
	res=putenv(s);
	UDM_FREE(s);
	return res;
#else
	return 0;
#endif
#endif

}

void UdmUnsetEnv(const char * name){
#ifdef HAVE_UNSETENV
	unsetenv(name);
#else
	UdmSetEnv(name,"");
#endif
}

/****************************************************/

char * UdmStrRemoveChars(char * str, const char * sep){
	char * s, *e;
	int has_sep=0;

	e=s=str;  
	while(*s){
		if(strchr(sep,*s)){
			if(!has_sep){
				e=s;
				has_sep=1;
			}
		}else{
			if(has_sep){
				memmove(e,s,strlen(s)+1);
				s=e;
				has_sep=0;
			}
		}
		s++;
	}
	/* End spaces */
	if(has_sep)*e='\0';
	
	return(str);
}


char * UdmStrRemoveDoubleChars(char * str, const char * sep){
	char * s, *e;
	int has_sep=0;
	
	/* Initial spaces */
	for(s=str;(*s)&&(strchr(sep,*s));s++);
	if(s!=str)memmove(str,s,strlen(s)+1);
	e=s=str;
	
	/* Middle spaces */
	while(*s){
		if(strchr(sep,*s)){
			if(!has_sep){
				e=s;
				has_sep=1;
			}
		}else{
			if(has_sep){
				*e=' ';
				memmove(e+1,s,strlen(s)+1);
				s=e+1;
				has_sep=0;
			}
		}
		s++;
	}
	
	/* End spaces */
	if(has_sep)*e='\0';
	
	return(str);
}


size_t UdmUniRemoveDoubleSpaces(int *ustr)
{
  int *u, *e, addspace=0;
  
  for(u= e= ustr; *u ;)
  {
    switch(*u)
    {
      case ' ':
      case '\t':
      case '\r':
      case '\n':
      case 0xA0: /* nbsp */
        addspace=1;
        u++;
        break;
      
      default:
        if(addspace)
        {
          if(e > ustr)
          {
            *e=' ';
            e++;
          }
          addspace= 0;
        }
        *e= *u;
        e++;
        u++;
        break;
    }
  }
  *e= 0;
  return e - ustr;
}

void UdmUniPrint(int * ustr){
	int * lt;
	for(lt=ustr;*lt;lt++){
		fprintf(stderr,"%04X ",*lt);
	}
	fprintf(stderr,"\n");
}



ssize_t UdmRecvall(int s, void *buf, size_t len){

#ifdef MSG_WAITALL
	if (len == 0) return 0;
	return recv(s, buf, len, MSG_WAITALL);
#else
	ssize_t received = 0, r=0;
	char *b = buf;
	time_t start = time(NULL);
	if (len == 0) return received;
	while ( ((size_t)received < len) && ((r = recv(s, b+received, len-received,0)) >= 0)){
		received+=r;
		if (have_sigint || have_sigterm 
#ifndef WIN32
		    || have_sigpipe
#endif
		    ) break;
		if (time(NULL) - start > 300) break;
	}
	return (r < 0) ? r : received;
#endif
}

/* To bust performance you may increase this value, but be sure, that kernel can handle it */
#define UDM_BLKLEN 8196

ssize_t UdmSend(int s, const void *msg, size_t len, int flags) {
  ssize_t o = 0;
  size_t olen, slen;
  const char *p = msg;

  while(len) {
    slen = (len < UDM_BLKLEN) ? len : UDM_BLKLEN;
    olen = send(s, p, slen, flags);
    if (olen == (size_t)-1) return olen;
    len -= olen;
    p += olen;
    o += olen;
  }
  return o;
}

/***********/

#ifndef WIN32


static struct flock* file_lock(struct flock *ret, int type, int whence) {
    ret->l_type = type ;
    ret->l_start = 0 ;
    ret->l_whence = whence ;
    ret->l_len = 0 ;
    ret->l_pid = getpid() ;
    return ret ;
}

#endif

void UdmWriteLock(int fd) {  /* an exclusive lock on an entire file */

#ifndef WIN32

    static struct flock ret ;
    fcntl(fd, F_SETLKW, file_lock(&ret, F_WRLCK, SEEK_SET));

#else
	/* Windows routine */
	
	DWORD filelen_high;
	DWORD filelen_low;
	OVERLAPPED overlap_str;
	int lock_res;

	overlap_str.Offset = 0;
	overlap_str.OffsetHigh = 0;
	overlap_str.hEvent = 0;

	filelen_low = GetFileSize((HANDLE)fd, &filelen_high);
	lock_res = LockFileEx((HANDLE)fd, LOCKFILE_EXCLUSIVE_LOCK, 0, filelen_low, filelen_high, &overlap_str);
	assert(lock_res);	

#endif

}

void UdmUnLock(int fd) { /* ulock an entire file */

#ifndef WIN32
    
	static struct flock ret ;
    fcntl(fd, F_SETLKW, file_lock(&ret, F_UNLCK, SEEK_SET));

#else
	/* Windows routine */

	DWORD filelen_high;
	DWORD filelen_low;
	int lock_res;

	filelen_low = GetFileSize((HANDLE)fd, &filelen_high);
	lock_res = UnlockFile((HANDLE)fd, 0, 0, filelen_low, filelen_high);
	assert(lock_res);	 

#endif

}

void UdmReadLock(int fd) {   /* a shared lock on an entire file */

#ifndef WIN32
    
    static struct flock ret ;
    fcntl(fd, F_SETLKW, file_lock(&ret, F_RDLCK, SEEK_SET));

#else
	/* Windows routine */
	
	DWORD filelen_high;
	DWORD filelen_low;
	OVERLAPPED overlap_str;
	int lock_res;

	overlap_str.Offset = 0;
	overlap_str.OffsetHigh = 0;
	overlap_str.hEvent = 0;

	filelen_low = GetFileSize((HANDLE)fd, &filelen_high);
	lock_res = LockFileEx((HANDLE)fd, 0, 0, filelen_low, filelen_high, &overlap_str);
	assert(lock_res);

#endif

}

void UdmReadLockFILE(FILE *f) {   /* a shared lock on an entire file */

#ifndef WIN32
    
	static struct flock ret ;
    fcntl(fileno(f), F_SETLKW, file_lock(&ret, F_RDLCK, SEEK_SET));

#else
	/* Windows routine */
	int file_desc = fileno(f);
	UdmReadLock(file_desc);

#endif

}

void __UDMCALL UdmWriteLockFILE(FILE *f) {  /* an exclusive lock on an entire file */

#ifndef WIN32

    static struct flock ret ;
    fcntl(fileno(f), F_SETLKW, file_lock(&ret, F_WRLCK, SEEK_SET));

#else
	/* Windows routine */

	int file_desc = fileno(f);
	UdmWriteLock(file_desc);

#endif

}

void __UDMCALL UdmUnLockFILE(FILE *f) { /* ulock an entire file */

#ifndef WIN32

    static struct flock ret ;
    fcntl(fileno(f), F_SETLKW, file_lock(&ret, F_UNLCK, SEEK_SET));

#else
	/* Windows routine */

	int file_desc = fileno(f);
	UdmUnLock(file_desc);

#endif

}


#ifdef USE_PARANOIA

/* NOTE: gcc optimization should be switched off */

#define NSAVE 10
/*#define PRINTF_DEBUGINFO*/

#ifdef USE_SYSLOG
extern char * __progname;
#endif

typedef struct {
  unsigned long save[NSAVE];
  unsigned long saveip[NSAVE];
  unsigned invflag;

#ifdef PARANOIDAL_ROOT
  int paranoidal_check;
#endif

} UDM_PARANOIA_PARAM;

static unsigned 
getbp()
{ 
	__asm__("movl %ebp,%eax");
	__asm__("movl (%eax),%eax");
}

#ifdef USE_SYSLOG
#define SUICIDE \
	openlog(__progname,LOG_NDELAY|LOG_PERROR|LOG_PID|LOG_CONS,LOG_USER);\
        syslog(LOG_ERR,"Stack violation - exiting");\
        closelog();\
        kill(SIGSEGV,getpid());\
        exit(1) ;
#else
#define SUICIDE \
        kill(SIGSEGV,getpid());\
        exit(1) ;
#endif




void * UdmViolationEnter(void) { 
	unsigned bp = getbp();
	int i = 0;
	UDM_PARANOIA_PARAM *p = (UDM_PARANOIA_PARAM*)UdmMalloc(sizeof(UDM_PARANOIA_PARAM));

#if defined(PRINTF_DEBUGINFO)
	printf("\nEnter p: %lx\n", p);
#endif
	if (p == NULL) exit(2);

	bzero(p, sizeof(UDM_PARANOIA_PARAM));
#ifdef PARANOIDAL_ROOT
	p->paranoidal_check = -1;
#endif

#ifdef PARANOIDAL_ROOT
	if(p->paranoidal_check == -1) 
	  p->paranoidal_check = issetugid() || (!geteuid()) || (!getuid());
	if(!p->paranoidal_check) return (void*)p; 
#endif

	p->invflag++;
	if(p->invflag > 1) return (void*)p;
	bzero(p->save, sizeof(p->save));
	bzero(p->saveip, sizeof(p->saveip));
	bp = *((unsigned*)bp);
	for(i = 0; i < NSAVE; i++) { 
#if defined(PRINTF_DEBUGINFO)
		printf("saving %lx (%i,%d)\n", bp, p->invflag, i);
#endif
		p->save[i] = bp;
		if(!bp) break;
		/* this is bogus, but... Sometimes we got stack entries
		 * points to low addresses. 0x20000000 - is a shared 
		 * library maping start */ 
		if(bp<0x20000000) {
			p->save[i] = 0;
			break;
		};
		p->saveip[i] = *((long unsigned*)bp + 1);
#if defined(PRINTF_DEBUGINFO)
		printf("storing   ip %lx : %x \n", p->saveip[i], *((unsigned*)bp + 1));
#endif
		bp = *(long unsigned*)bp;
	}
	return (void *)p;
};


void UdmViolationExit(void *v) { 
	unsigned bp = getbp();
	int i = 2;
	UDM_PARANOIA_PARAM *p = (UDM_PARANOIA_PARAM*)v;

#if defined(PRINTF_DEBUGINFO)
	printf("Exit p: %lx\n", p);
#endif
#ifdef PARANOIDAL_ROOT
	/* at exit_violation we always have paranoidal_check set to 0 or 1 */
	if(!p->paranoidal_check) {
	  UDM_FREE(p);
	  return; 
	}
#endif

	if(p->invflag > 1) { 
		p->invflag--;
		return;
	};
	bp = *((unsigned*)bp);
	for(i = 0; i < NSAVE; i++) { 
#if defined(PRINTF_DEBUGINFO)
		printf("processing %lx (%i, %d)\n", bp, p->invflag, i);
#endif
		if(!p->save[i]) break;
		if(bp != p->save[i]) { 
			SUICIDE;
		};
		if(!bp) break;
#if defined(PRINTF_DEBUGINFO)
		printf("restoring ip %lx : %x \n", p->saveip[i], *((unsigned*)bp + 1));
#endif
		if(p->saveip[i] != *((unsigned*)bp+1)) { 
			SUICIDE;
		};
		bp = *(unsigned*)bp;
	};
	p->invflag--;
	if (p->invflag == 0) UDM_FREE(p);
	return;
};


#endif /* USE_PARANOIA */


/*
 * Note that buf must be at least X * 5 + 5 bytes. Where X is
 * number of integers in array.
 */
void udm_zint4_init(UDM_ZINT4_STATE *state, char *buf)
{
  state->bits_left= 8;
  state->prev= 0;
  state->end= state->buf= (unsigned char *)buf;
}


static inline void udm_zint4_write_bits(UDM_ZINT4_STATE *state,
    unsigned char byte, unsigned char nbits)
{
  if (state->bits_left == 8)
    *state->end= 0;
  if (state->bits_left >= nbits)
  {
    *state->end+= byte << (state->bits_left - nbits);
    if (nbits == state->bits_left)
    {
      state->end++;
      state->bits_left= 8;
    }
    else
      state->bits_left-= nbits;
    return;
  }
  *state->end+= byte >> (nbits - state->bits_left);
  state->end++;
  state->bits_left+= 8 - nbits;
  *state->end= byte << state->bits_left;
}


void udm_zint4(UDM_ZINT4_STATE *state, int next)
{
  unsigned int n= (unsigned int)(next - state->prev);
  state->prev= next;
  if (n < 0x10) /* compressed to 5 bits, 1 block */
  {
    udm_zint4_write_bits(state, n, 5);
  }
  else if (n < 0x110) /* compressed to 10 bits, 2 blocks */
  {
    n-= 0x10;
    udm_zint4_write_bits(state, 2, 2);
    udm_zint4_write_bits(state, n, 8);
  }
  else if (n < 0x1110) /* compressed to 15 bits, 3 blocks */
  {
    n-= 0x110;
    udm_zint4_write_bits(state, 6, 3);
    udm_zint4_write_bits(state, n >> 8, 4);
    udm_zint4_write_bits(state, n & 0xff, 8);
  }
  else if (n < 0x11110) /* compressed to 20 bits, 4 blocks */
  {
    n-= 0x1110;
    udm_zint4_write_bits(state, 0xe, 4);
    udm_zint4_write_bits(state, n >> 8, 8);
    udm_zint4_write_bits(state, n & 0xff, 8);
  }
  else if (n < 0x111110) /* compressed to 25 bits, 5 blocks */
  {
    n-= 0x11110;
    udm_zint4_write_bits(state, 0x1e, 5);
    udm_zint4_write_bits(state, n >> 16, 4);
    udm_zint4_write_bits(state, (n >> 8) & 0xff, 8);
    udm_zint4_write_bits(state, n & 0xff, 8);
  }
  else if (n < 0x1111110) /* compressed to 30 bits, 6 blocks */
  {
    n-= 0x111110;
    udm_zint4_write_bits(state, 0x3e, 6);
    udm_zint4_write_bits(state, n >> 16, 8);
    udm_zint4_write_bits(state, (n >> 8) & 0xff, 8);
    udm_zint4_write_bits(state, n & 0xff, 8);
  }
  else if (n < 0x11111110) /* compressed to 35 bits */
  {
    n-= 0x1111110;
    udm_zint4_write_bits(state, 0x7e, 7);
    udm_zint4_write_bits(state, n >> 24, 4);
    udm_zint4_write_bits(state, (n >> 16) & 0xff, 8);
    udm_zint4_write_bits(state, (n >> 8) & 0xff, 8);
    udm_zint4_write_bits(state, n & 0xff, 8);
  }
  else /* compressed to 40 bits */
  {
    n-= 0x11111110;
    udm_zint4_write_bits(state, 0xfe, 8);
    udm_zint4_write_bits(state, n >> 24, 8);
    udm_zint4_write_bits(state, (n >> 16) & 0xff, 8);
    udm_zint4_write_bits(state, (n >> 8) & 0xff, 8);
    udm_zint4_write_bits(state, n & 0xff, 8);
 }
}


void udm_zint4_finalize(UDM_ZINT4_STATE *state)
{
  if (state->bits_left < 8)
    udm_zint4_write_bits(state, 0xff, 8);
  *state->end++= 0xff;
  *state->end++= 0xff;
  *state->end++= 0xff;
  *state->end++= 0xff;
  *state->end++= 0xff;
}


int udm_dezint4(const char *buf, int4 *array, int buf_len)
{
  unsigned char next_byte= *buf;
  unsigned char bit_idx= 8;
  char nblocks= 1;
  int4 prev= 0, *array_end;
  if ((unsigned char)buf[buf_len - 1] != 0xff ||
      (unsigned char)buf[buf_len - 2] != 0xff ||
      (unsigned char)buf[buf_len - 3] != 0xff ||
      (unsigned char)buf[buf_len - 4] != 0xff ||
      (unsigned char)buf[buf_len - 5] != 0xff)
    return(0);
  for (array_end= array;; array_end++)
  {
    uint4 next= 0;
    /* Extract number of blocks */
    while (next_byte & (1 << --bit_idx))
    {
      if (++nblocks == 9)
        return(array_end - array);
      if (! bit_idx)
      {
        bit_idx= 8;
        next_byte= *++buf;
      }
    }
    if (! bit_idx)
    {
      bit_idx= 8;
      next_byte= *++buf;
    }

    for (;; nblocks--)
    {
      switch (bit_idx) {
        case 1:
          next+= (next_byte & 1) << 3;
          bit_idx= 5;
          next_byte= *++buf;
          next+= (next_byte >> 5) & 0xf;
          break;
        case 2:
          next+= (next_byte & 3) << 2;
          bit_idx= 6;
          next_byte= *++buf;
          next+= (next_byte >> 6) & 7;
          break;
        case 3:
          next+= (next_byte & 7) << 1;
          bit_idx= 7;
          next_byte= *++buf;
          next+= (next_byte >> 7) & 3;
          break;
        case 4:
          next+= next_byte & 0xf;
          bit_idx= 8;
          next_byte= *++buf;
          break;
        case 5:
          bit_idx= 1;
          next+= (next_byte >> 1) & 0xf;
          break;
        case 6:
          bit_idx= 2;
          next+= (next_byte >> 2) & 0xf;
          break;
        case 7:
          bit_idx= 3;
          next+= (next_byte >> 3) & 0xf;
          break;
        case 8:
          bit_idx= 4;
          next+= (next_byte >> 4) & 0xf;
          break;
      }
      if (nblocks > 1)
        next= (next + 1) << 4;
      else
        break;
    }
    prev+= next;
    *array_end= prev;
  }
  return(array_end - array);
}

#ifdef HAVE_DEBUG
void UdmSort(void *base, size_t nmemb, size_t size,
             int(*compar)(const void *, const void *))
{
  UDM_ASSERT(nmemb > 0);
  qsort(base, nmemb, size, compar);
}

void *UdmBSearch(const void *key, const void *base, size_t nmemb,
                 size_t size, int (*compar)(const void *, const void *))
{
  UDM_ASSERT(nmemb > 0);
  return bsearch(key, base, nmemb, size, compar);
}
#endif