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

#define ACE_BUILD_DLL
#include "ace/IPC_SAP.h"
#include "ace/Handle_Set.h"
#include "ace/ACE.h"
#include "ace/Thread_Manager.h"
#include "ace/Reactor.h"
#include "ace/Auto_Ptr.h"
#include "ace/INET_Addr.h"

// TESTING ADDITION
// This is needed for AIX 3.2.5 
#if defined(_AIX)
#include /**/ <sys/ioctl.h>
#endif
#if defined(__sun__) && !defined(_SVR4)
#include /**/ <sys/sockio.h>
#endif
// END TESTING ADDITION

// Size of a VM page.
size_t ACE::pagesize_ = 0;

int
ACE::is_process_active (pid_t pid)
{
#if !defined(ACE_WIN32)
  int retval = ACE_OS::kill (pid, 0);
  if (retval == 0)
    {
      return 1;
    }
  else
    {
      if (errno == ESRCH)
	return 0;
      else
	return retval;
    }
#else
  // Create a handle for the given process id.
  ACE_HANDLE process_handle = ::OpenProcess (PROCESS_QUERY_INFORMATION,
					     FALSE,
					     pid);
  if (process_handle == ACE_INVALID_HANDLE 
      || process_handle == NULL)
    return 0;
  else
    {
      DWORD status;

      if (::GetExitCodeProcess (process_handle,
				&status) == 0)
	return 0;
      else
        {
	  if (status == STILL_ACTIVE)
	    return 1;
	  else
	    return 0;
        }
    }
#endif /* ACE_WIN32 */
}

int
ACE::register_stdin_handler (ACE_Event_Handler *eh,
			     ACE_Reactor *reactor,
			     ACE_Thread_Manager *thr_mgr,
			     int flags)
{  
#if defined (ACE_WIN32)
  ACE_Stdin_Args *args = 0;
  ACE_NEW_RETURN (args, ACE_Stdin_Args, -1);
  args->handler_ = eh;
  args->thr_mgr_ = thr_mgr;  
  return thr_mgr->spawn (&ACE::read_adapter, args, flags);
#else  
  // Keep compilers happy.
  ACE_UNUSED_ARG (flags);
  ACE_UNUSED_ARG (thr_mgr);
  ACE_UNUSED_ARG (reactor);
  return reactor->register_handler (ACE_STDIN, eh, ACE_Event_Handler::READ_MASK);
#endif /* ACE_WIN32 */
}

// Used to read from non-socket ACE_HANDLEs in our own thread to work
// around Win32 limitations that don't allow us to select() on
// non-sockets (such as ACE_STDIN).  This is commonly used in
// situations where the Reactor is used to demultiplex read events on
// ACE_STDIN on UNIX.  Note that <event_handler> must be a subclass of
// <ACE_Event_Handler>.  If the <get_handle> method of this event
// handler returns <ACE_INVALID_HANDLE> we default to reading from
// ACE_STDIN.

void *
ACE::read_adapter (void *args)
{
  ACE_Stdin_Args *stdin_adapter_args = (ACE_Stdin_Args *) args;  
  ACE_Thread_Control tc (stdin_adapter_args->thr_mgr_); 

  ACE_Event_Handler *this_ptr = stdin_adapter_args->handler_;
  ACE_HANDLE handle = ACE_STDIN;

  while (this_ptr->handle_input (handle) != -1)
    continue;

  this_ptr->handle_close (handle, ACE_Event_Handler::READ_MASK);
  
  delete stdin_adapter_args;
  return 0;
}

const char *
ACE::execname (const char *old_name)
{
#if defined (ACE_HAS_WIN32)
  if (ACE_OS::strstr (old_name, ".exe") == 0)
    {
      char *new_name;

      ACE_NEW_RETURN (new_name, char[ACE_OS::strlen (old_name) +
				     ACE_OS::strlen (".exe") + 
				     1], -1);
      char *end = new_name;
      end = ACE::strecpy (new_name, old_name);
      // Concatenate the .exe suffix onto the end of the executable.
      ACE_OS::strcpy (end, ".exe");
      return new_name;
    }
#endif /* ACE_HAS_WIN32 */
  return old_name;
}

u_long
ACE::hash_pjw (const char *str)
{
  u_long hash = 0;
   
  for (const char *temp = str; *temp != 0; temp++)
    {
      hash = (hash << 4) + (*temp * 13);

      u_long g = hash & 0xf0000000;

      if (g)
        {
          hash ^= (g >> 24);
          hash ^= g;
        }
    }

  return hash;
}

u_long
ACE::hash_pjw (const ACE_USHORT16 *str)
{
  u_long hash = 0;
   
  for (const ACE_USHORT16 *temp = str; *temp != 0; temp++)
    {
      hash = (hash << 4) + (*temp * 13);

      u_long g = hash & 0xf0000000;

      if (g)
        {
          hash ^= (g >> 24);
          hash ^= g;
        }
    }

  return hash;
}

size_t
ACE::strrepl (char *s, char search, char replace)
{
  ACE_TRACE ("ACE::strrepl");

  size_t replaced = 0;

  for (size_t i = 0; s[i] != '\0'; i++)
    if (s[i] == search)
      {
	s[i] = replace;
	replaced++;
      }

  return replaced;
}

char *
ACE::strenvdup (const char *str)
{
  ACE_TRACE ("ACE::strenvdup");

  char *temp;

  if (str[0] == '$'
      && (temp = ACE_OS::getenv (&str[1])) != 0)
    return ACE_OS::strdup (temp);
  else
    return ACE_OS::strdup (str);
}

/*

Examples:

Source               NT                       UNIX
===============================================================
netsvc               netsvc.dll               libnetsvc.so
		     (PATH will be evaluated) (LD_LIBRARY_PATH evaluated)

libnetsvc.dll        libnetsvc.dll            libnetsvc.dll + warning
netsvc.so            netsvc.so + warning      libnetsvc.so 

..\../libs/netsvc    ..\..\libs\netsvc.dll     ../../libs/netsvc.so
		     (absolute path used)         (absolute path used)

*/

int
ACE::ldfind (const char filename[],
 	     char pathname[], 
	     size_t maxpathnamelen)
{
  ACE_TRACE ("ACE::ldfind");
  
  char tempcopy[MAXPATHLEN];
  char searchpathname[MAXPATHLEN];
  char searchfilename[MAXPATHLEN];

  // Create a copy of filename to work with.
  if (ACE_OS::strlen (filename) + 1 > (sizeof tempcopy / sizeof (char)))
    {
      errno = ENOMEM;
      return -1;
    }
  else
    ACE_OS::strcpy (tempcopy, filename);

  // Insert canonical directory separators.
  char *separator_ptr;

  if (ACE_DIRECTORY_SEPARATOR_CHAR != '/')
    // Make all the directory separators ``canonical'' to simplify
    // subsequent code.
    ACE::strrepl (tempcopy, ACE_DIRECTORY_SEPARATOR_CHAR, '/');

  // Separate filename from pathname.
  separator_ptr = ACE_OS::strrchr (tempcopy, '/');

  // This is a relative path.
  if (separator_ptr == 0)
    {
      searchpathname[0] = '\0';
      ACE_OS::strcpy (searchfilename, tempcopy);
    } 
  else // This is an absolute path.
    {
      ACE_OS::strcpy (searchfilename, separator_ptr + 1);
      separator_ptr[1] = '\0';
      ACE_OS::strcpy (searchpathname, tempcopy);
    }

  int got_suffix = 0;

  // Check to see if this has an appropriate DLL suffix for the OS
  // platform.
  char *s = ACE_OS::strrchr (searchfilename, '.');

  if (s != 0)
    {
      // Check whether this matches the appropriate platform-specific suffix.
      if (ACE_OS::strcmp (s, ACE_DLL_SUFFIX) == 0)
	got_suffix = 1;
      else
	ACE_ERROR ((LM_WARNING, 
		    "Warning: improper suffix for a shared library on this platform: %s\n", 
		    s));
    }

  // Make sure we've got enough space in searchfilename.
  if (ACE_OS::strlen (searchfilename) + 
      ACE_OS::strlen (ACE_DLL_PREFIX) + 
      got_suffix ? 0 : ACE_OS::strlen (ACE_DLL_SUFFIX) >= (sizeof searchfilename / sizeof (char)))
    {
      errno = ENOMEM;
      return -1;
    } 

  // Use absolute pathname if there is one.
  if (ACE_OS::strlen (searchpathname) > 0)
    {
      if (ACE_OS::strlen (searchfilename) 
	  + ACE_OS::strlen (searchpathname) >= maxpathnamelen) 
	{
	  errno = ENOMEM;
	  return -1;
	} 
      else 
	{
	  if (ACE_DIRECTORY_SEPARATOR_CHAR != '/')
	    // Revert to native path name separators
	    ACE::strrepl (searchpathname, '/', ACE_DIRECTORY_SEPARATOR_CHAR);

	  // First, try matching the filename *without* adding a
	  // prefix.
	  ACE_OS::sprintf (pathname, "%s%s%s",
                           searchpathname,
                           searchfilename, 
                           got_suffix ? "" : ACE_DLL_SUFFIX);
	  if (ACE_OS::access (pathname, F_OK) == 0)
	    return 0;

	  // Second, try matching the filename *with* adding a prefix.
	  ACE_OS::sprintf (pathname, "%s%s%s%s", 
                           searchpathname,
                           ACE_DLL_PREFIX,
                           searchfilename, 
                           got_suffix ? "" : ACE_DLL_SUFFIX);
	  if (ACE_OS::access (pathname, F_OK) == 0)
	    return 0;
	}
    }

  // Use relative filenames via LD_LIBRARY_PATH or PATH (depending on
  // OS platform).
  else 
    {
      char *ld_path = ACE_OS::getenv (ACE_LD_SEARCH_PATH);

      if (ld_path != 0 && (ld_path = ACE_OS::strdup (ld_path)) != 0)
	{
	  // Look at each dynamic lib directory in the search path.
	  char *path_entry = ACE_OS::strtok 
	    (ld_path, ACE_LD_SEARCH_PATH_SEPARATOR_STR);
      
	  int result = 0;

	  while (path_entry != 0)
	    {
	      if (ACE_OS::strlen (path_entry) 
		  + 1 + ACE_OS::strlen (searchfilename) >= maxpathnamelen)
		{
		  errno = ENOMEM;
		  result = -1;
		  break;
		}

	      // First, try matching the filename *without* adding a
	      // prefix.
	      ACE_OS::sprintf (pathname, "%s%c%s",
			       path_entry,
			       ACE_DIRECTORY_SEPARATOR_CHAR, 
			       searchfilename);
	      if (ACE_OS::access (pathname, F_OK) == 0)
		break;

	      // Second, try matching the filename *with* adding a
	      // prefix.
	      ACE_OS::sprintf (pathname, "%s%c%s%s",
			       path_entry,
			       ACE_DIRECTORY_SEPARATOR_CHAR, 
			       ACE_DLL_PREFIX,
			       searchfilename);
	      if (ACE_OS::access (pathname, F_OK) == 0)
		break;

	      path_entry = ACE_OS::strtok 
		(0, ACE_LD_SEARCH_PATH_SEPARATOR_STR);
	    }

	  ACE_OS::free ((void *) ld_path);
	  return result;
	}
    }

  errno = ENOENT;
  return -1;
}

FILE *
ACE::ldopen (const char *filename, const char *type)
{
  ACE_TRACE ("ACE::ldopen");
  char buf[MAXPATHLEN];

  if (ACE::ldfind (filename, buf, sizeof buf) == -1)
    return 0;
  else
    return ACE_OS::fopen (buf, type);
}

const char *
ACE::basename (const char *pathname, char delim)
{
  ACE_TRACE ("ACE::basename");
  const char *temp = ::strrchr (pathname, delim);
    
  if (temp == 0)
    return pathname;
  else
    return temp + 1;
}

#if defined (ACE_HAS_UNICODE)
const wchar_t *
ACE::basename (const wchar_t *pathname, wchar_t delim)
{
  ACE_TRACE ("ACE::basename");
  const wchar_t *temp = ACE_OS::strrchr (pathname, delim);
    
  if (temp == 0)
    return pathname;
  else
    return temp + 1;
}
#endif /* ACE_HAS_UNICODE */

// Miscellaneous static methods used throughout ACE.

ssize_t
ACE::send_n (ACE_HANDLE handle, const void *buf, size_t len)
{
  ACE_TRACE ("ACE::send_n");
  size_t bytes_written;
  ssize_t n = 0;

  for (bytes_written = 0; bytes_written < len; bytes_written += n)
    {
      n = ACE::send (handle, (const char *) buf + bytes_written, 
		     len - bytes_written);
      if (n == -1)
	{
	  if (errno != EWOULDBLOCK)
	    return -1;
	  else
	    n = 0; // Keep trying to send.
	}
    }

  return bytes_written;
}

ssize_t
ACE::send_n (ACE_HANDLE handle, 
	     const void *buf, 
	     size_t len, 
	     int flags)
{
  ACE_TRACE ("ACE::send_n");
  size_t bytes_written;
  ssize_t n = 0;

  for (bytes_written = 0; bytes_written < len; bytes_written += n)
    {
      n = ACE_OS::send (handle, (const char *) buf + bytes_written, 
			len - bytes_written, flags);
      
      if (n == -1)
	{
	  if (errno != EWOULDBLOCK)
	    return -1;
	  else
	    n = 0; // Keep trying to send.
	}
    }

  return bytes_written;
}

// Receive <len> bytes into <buf> from <handle> (uses the <write>
// system call on UNIX and the <WriteFile> call on Win32).

ssize_t 
ACE::write_n (ACE_HANDLE handle, 
	      const void *buf, 
	      size_t len)
{
  ACE_TRACE ("ACE::write_n");

  size_t bytes_written;
  ssize_t n = 0;

  for (bytes_written = 0; bytes_written < len; bytes_written += n)
    {
      n = ACE_OS::write (handle, (const char *) buf + bytes_written, 
			 len - bytes_written);
      if (n == -1)
	{
	  if (errno != EWOULDBLOCK)
	    return -1;
	  else
	    n = 0; // Keep trying to send.
	}
    }

  return bytes_written;
}

ssize_t
ACE::recv_n (ACE_HANDLE handle, void *buf, size_t len)
{
  ACE_TRACE ("ACE::recv_n");
  size_t bytes_read;
  ssize_t n = 0;

  for (bytes_read = 0; bytes_read < len; bytes_read += n)
    {
      n = ACE::recv (handle, (char *) buf + bytes_read, len - bytes_read);

      if (n == -1)
	{
	  if (errno != EWOULDBLOCK)
	    return -1;
	  else
	    n = 0; // Keep trying to read.
	}
      else if (n == 0)
	break;
    }
  return bytes_read;      
}

ssize_t
ACE::recv_n (ACE_HANDLE handle, void *buf, size_t len, int flags)
{
  ACE_TRACE ("ACE::recv_n");
  size_t bytes_read;
  ssize_t n = 0;

  for (bytes_read = 0; bytes_read < len; bytes_read += n)
    {
      n = ACE::recv (handle, (char *) buf + bytes_read, len - bytes_read, flags);

      if (n == -1)
	{
	  if (errno != EWOULDBLOCK)
	    return -1;
	  else
	    n = 0; // Keep trying to read.
	}
      else if (n == 0)
	break;
    }

  return bytes_read;      
}

// Receive <len> bytes into <buf> from <handle> (uses the <read>
// system call on UNIX and the <ReadFile> call on Win32).

ssize_t 
ACE::read_n (ACE_HANDLE handle, 
	     void *buf, 
	     size_t len)
{
  ACE_TRACE ("ACE::read_n");

  size_t bytes_read;
  ssize_t n = 0;

  for (bytes_read = 0; bytes_read < len; bytes_read += n)
    {
      n = ACE_OS::read (handle, (char *) buf + bytes_read, len - bytes_read);

      if (n == -1)
	{
	  if (errno != EWOULDBLOCK)
	    return -1;
	  else
	    n = 0; // Keep trying to read.
	}
      else if (n == 0)
	break;
    }

  return bytes_read;      
}

// Format buffer into printable format.  This is useful for debugging.
// Portions taken from mdump by J.P. Knight (J.P.Knight@lut.ac.uk)
// Modifications by Todd Montgomery.

int 
ACE::format_hexdump (const char *buffer, int size, char *obuf, int obuf_sz)
{
  ACE_TRACE ("ACE::format_hexdump");

  u_char c;
  char textver[16 + 1];

  int maxlen = (obuf_sz / 68) * 16;

  if (size > maxlen)
    size = maxlen;

  int i;

  for (i = 0; i < (size >> 4); i++)
    {
      int j;

      for (j = 0 ; j < 16; j++) 
	{
	  c = buffer[(i << 4) + j];
	  ACE_OS::sprintf (obuf, "%02x ", c);
	  obuf += 3;
	  if (j == 7)
	    {
	      ACE_OS::sprintf (obuf, " ");
	      obuf++;
	    }
	  textver[j] = (c < 0x20 || c > 0x7e) ? '.' : c;
	}

      textver[j] = 0;

      ACE_OS::sprintf (obuf, "  %s\n", textver);

      while (*obuf != '\0') 
	obuf++;
    }

  if (size % 16)
    {
      for (i = 0 ; i < size % 16; i++) 
	{
	  c = buffer[size - size % 16 + i];
	  ACE_OS::sprintf (obuf,"%02x ",c);
	  obuf += 3;
	  if (i == 7)
	    {
	      ACE_OS::sprintf (obuf, " ");
	      obuf++;
	    }
	  textver[i] = (c < 0x20 || c > 0x7e) ? '.' : c;
	}

      for (i = size % 16; i < 16; i++) 
	{
	  ACE_OS::sprintf (obuf, "   ");
	  obuf += 3;
	  textver[i] = ' ';
	}	

      textver[i] = 0;
      ACE_OS::sprintf (obuf, "  %s\n", textver);
    }
  return size;
}

// Returns the current timestamp in the form
// "hour:minute:second:microsecond."  The month, day, and year are
// also stored in the beginning of the date_and_time array.  Returns 0
// if unsuccessful, else returns pointer to beginning of the "time"
// portion of <day_and_time>.

char *
ACE::timestamp (char date_and_time[], int date_and_timelen)
{
  //ACE_TRACE ("ACE::timestamp");

  if (date_and_timelen < 35)
    {
      errno = EINVAL;
      return 0;
    }

#if defined (WIN32)
  // @@ Jesper, I think Win32 supports all the UNIX versions below.
  // Therefore, we can probably remove this WIN32 ifdef altogether.
  SYSTEMTIME local;
  ::GetLocalTime (&local);

  ACE_OS::sprintf (date_and_time, "%02d/%02d/%04d %02d.%02d.%02d.%06d",
                   (int) local.wMonth, // new, also the %02d in sprintf
                   (int) local.wDay,   // new, also the %02d in sprintf
                   (int) local.wYear,  // new, also the %02d in sprintf
                   (int) local.wHour,
                   (int) local.wMinute,
                   (int) local.wSecond,
                   (int) local.wMilliseconds * 1000);
#else  /* UNIX */
  char timebuf[26]; // This magic number is based on the ctime(3c) man page.
  ACE_Time_Value cur_time = ACE_OS::gettimeofday ();
  time_t secs = cur_time.sec ();
  ACE_OS::ctime_r (&secs, timebuf, sizeof timebuf);
  ACE_OS::strncpy (date_and_time, timebuf, date_and_timelen);
  ACE_OS::sprintf (&date_and_time[19], ".%06d", cur_time.usec ());
#endif /* WIN32 */
  date_and_time[26] = '\0';        
  return &date_and_time[11];
}

// This function rounds the request to a multiple of the page size.

size_t
ACE::round_to_pagesize (off_t len)
{
  ACE_TRACE ("ACE::round_to_pagesize");

  if (ACE::pagesize_ == 0)
    {
#if defined (ACE_WIN32)
      SYSTEM_INFO sys_info;
      ::GetSystemInfo (&sys_info);
      ACE::pagesize_ = (size_t) sys_info.dwPageSize;
#elif defined (_SC_PAGESIZE)
      ACE::pagesize_ = (size_t) ::sysconf (_SC_PAGESIZE);
#elif defined (ACE_HAS_GETPAGESIZE)
      ACE::pagesize_ = (size_t) ::getpagesize ();
#else
      // Use the default set in config.h
      ACE::pagesize_ = ACE_PAGE_SIZE;
#endif /* ACE_WIN32 */
    }

  return (len + (ACE::pagesize_ - 1)) & ~(ACE::pagesize_ - 1);
}

ACE_HANDLE 
ACE::handle_timed_complete (ACE_HANDLE h,
			    ACE_Time_Value *timeout)
{
  ACE_TRACE ("ACE::handle_timed_complete");
  ACE_Handle_Set rd_handles;
  ACE_Handle_Set wr_handles;

#if defined (ACE_WIN32)
  ACE_Handle_Set ex_handles;
  ex_handles.set_bit (h);
#endif /* ACE_WIN32 */
  rd_handles.set_bit (h);
  wr_handles.set_bit (h);

#if defined (ACE_WIN32)
  int n = ACE_OS::select (int (h) + 1, 
			  rd_handles,
			  wr_handles,
			  ex_handles,
			  timeout);
#else
  int n = ACE_OS::select (int (h) + 1, 
			  rd_handles,
			  wr_handles, 
			  0, timeout);
#endif /* ACE_WIN32 */

  // If we failed to connect within the time period allocated by the
  // caller, then we fail (e.g., the remote host might have been too
  // busy to accept our call).
  if (n <= 0)
    {
      if (n == 0)
	errno = ETIME;
      return ACE_INVALID_HANDLE;
    }
  // Check if the handle is ready for reading and the handle is *not*
  // ready for writing, which may indicate a problem.  But we need to
  // make sure...
#if defined (ACE_WIN32)
  else if (rd_handles.is_set (h) || ex_handles.is_set (h))
#elif defined (ACE_HAS_TLI)
  else if (rd_handles.is_set (h) && !wr_handles.is_set (h))
#else
  else if (rd_handles.is_set (h))
#endif /* ACE_WIN32 */
    {
      char dummy;
      // The following recv() won't block provided that the
      // ACE_NONBLOCK flag has not been turned off .

      n = ACE::recv (h, &dummy, 1, MSG_PEEK);
      if (n <= 0)
	{
	  if (n == 0)
	    errno = ECONNREFUSED;
	  return ACE_INVALID_HANDLE;
	}
    }

  // 1. The HANDLE is ready for writing or 2. recv() returned that
  // there are data to be read, which indicates the connection was
  // successfully established.
  return h;   
}

ACE_HANDLE
ACE::handle_timed_open (ACE_Time_Value *timeout,
			LPCTSTR name,
			int flags, 
			int perms)
{
  ACE_TRACE ("ACE::handle_timed_open");

  if (timeout != 0)
    {
      // Open the named pipe or file using non-blocking mode...
      ACE_HANDLE handle = ACE_OS::open (name, 
					flags | ACE_NONBLOCK, 
					perms);
      if (handle == ACE_INVALID_HANDLE
	  && (errno == EWOULDBLOCK 
	      && (timeout->sec () > 0 || timeout->usec () > 0)))
	// This expression checks if we were polling.
	errno = ETIMEDOUT;

      return handle;
    }
  else
    return ACE_OS::open (name, flags, perms);
}

// Wait up to <timeout> amount of time to accept a connection.

int 
ACE::handle_timed_accept (ACE_HANDLE listener, 
			  ACE_Time_Value *timeout,
			  int restart)
{
  ACE_TRACE ("ACE::handle_timed_accept");
  // Make sure we don't bomb out on erroneous values.
  if (listener == ACE_INVALID_HANDLE)
    return -1;

  // Use the select() implementation rather than poll().
  ACE_Handle_Set rd_handle;
  rd_handle.set_bit (listener);

  // We need a loop here if <restart> is enabled.

  for (;;)
    {
      switch (ACE_OS::select (int (listener) + 1, 
			      rd_handle, 0, 0, 
			      timeout))
	{
	case -1:
	  if (errno == EINTR && restart)
	    continue;
	  else
	    return -1;
	  /* NOTREACHED */
	case 0:
	  if (timeout != 0 && timeout->sec() == 0 && timeout->usec() == 0)
	    errno = EWOULDBLOCK;
	  else
	    errno = ETIMEDOUT;
	  return -1;
	  /* NOTREACHED */
	case 1:
	  return 0;
	  /* NOTREACHED */
	default:
	  errno = EINVAL;
	  return -1;
	  /* NOTREACHED */
	}
    }
  /* NOTREACHED */
  return 0;
}

// Bind socket to an unused port.

int
ACE::bind_port (ACE_HANDLE handle)
{
  ACE_TRACE ("ACE::bind_port");
  sockaddr_in sin;
  // This should be a constant, so I hope they never change the number
  // of bits in a port number!
  static u_short upper_limit = ACE_MAX_DEFAULT_PORT;
  int lower_limit = IPPORT_RESERVED;
  int round_trip = upper_limit;

  ACE_OS::memset ((void *) &sin, 0, sizeof sin);
  sin.sin_family = AF_INET;
#if defined (ACE_HAS_SIN_LEN)
  sin.sin_len = sizeof sin;
#endif /* ACE_HAS_SIN_LEN */
  sin.sin_addr.s_addr = INADDR_ANY;

  for (;;)
    {
      sin.sin_port = htons (upper_limit);

      if (ACE_OS::bind (handle, (sockaddr *) &sin, sizeof sin) >= 0)
	{
#if defined (ACE_WIN32)
	  upper_limit--;
#endif
	  return 0;
	}
      else if (errno != EADDRINUSE)
	return -1;
      else
	{
	  upper_limit--;
		  
	  // Wrap back around when we reach the bottom.
	  if (upper_limit <= lower_limit)
	    upper_limit = ACE_MAX_DEFAULT_PORT;
		  
	  // See if we have already gone around once! 
	  if (upper_limit == round_trip)
	    {
	      errno = EAGAIN;	
	      return -1;
	    }
	}
    }
}

// Make the current process a UNIX daemon.  This is based on Stevens
// code from APUE.

int
ACE::daemonize (const char pathname[])
{
  ACE_TRACE ("ACE::daemonize");
#if !defined (ACE_LACKS_EXEC)
  pid_t pid = ACE_OS::fork ();

  if (pid == -1)
    return -1;
  else if (pid != 0)
    ACE_OS::exit (0); // Parent exits.

  // 1st child continues.
  ACE_OS::setsid (); // Become session leader.

  ACE_OS::signal (SIGHUP, SIG_IGN);

  pid = ACE_OS::fork ();

  if (pid != 0)
    ACE_OS::exit (0); // First child terminates.

  // Second child continues.

  ACE_OS::chdir (pathname); // change working directory.

  ACE_OS::umask (0); // clear our file mode creation mask.

  // Close down the files.
  for (int i = ACE::max_handles () - 1; i >= 0; i--)
    ACE_OS::close (i);
  return 0;
#else
  ACE_NOTSUP_RETURN (-1);
#endif /* ACE_WIN32 */
}

int
ACE::max_handles (void)
{
  ACE_TRACE ("ACE::set_handle_limit");
#if defined (_SC_OPEN_MAX)
  return ACE_OS::sysconf (_SC_OPEN_MAX);
#elif defined (RLIMIT_NOFILE)
  rlimit rl;
  ACE_OS::getrlimit (RLIMIT_NOFILE, &rl);
  rl.rlim_cur;
#else
  ACE_NOTSUP_RETURN (-1);
#endif /* ACE_WIN32 */
}

// Set the number of currently open handles in the process.
//
// If NEW_LIMIT == -1 set the limit to the maximum allowable.
// Otherwise, set it to be the value of NEW_LIMIT.

int 
ACE::set_handle_limit (int new_limit)
{
  ACE_TRACE ("ACE::set_handle_limit");
#if defined (RLIMIT_NOFILE)
  struct rlimit rl;

  int max_handles = ACE::max_handles ();

  if (new_limit < 0 || new_limit > max_handles)
    rl.rlim_cur = max_handles;
  else
    rl.rlim_cur = new_limit;

  return ACE_OS::setrlimit (RLIMIT_NOFILE, &rl);
#else
  new_limit = new_limit;
  ACE_NOTSUP_RETURN (-1);
#endif /* ACE_WIN32 */
}

// Flags are file status flags to turn on.

int
ACE::set_flags (ACE_HANDLE handle, int flags)
{
  ACE_TRACE ("ACE::set_flags");
#if defined (ACE_WIN32) || defined (VXWORKS)
  switch (flags)
    {
    case ACE_NONBLOCK:
      // nonblocking argument (1) 
      // blocking:            (0)
      {
	u_long nonblock = 1;
	return ACE_OS::ioctl (handle, FIONBIO, &nonblock);
      }
    default:
      errno = ENOTSUP;
      return -1;
    }
#else
  int val = ACE_OS::fcntl (handle, F_GETFL, 0);

  if (val == -1)
    return -1;

  // Turn on flags.
  ACE_SET_BITS (val, flags); 

  if (ACE_OS::fcntl (handle, F_SETFL, val) == -1)
    return -1;
  else
    return 0;
#endif /* ACE_WIN32 && VXWORKS */
}

// Flags are the file status flags to turn off.

int
ACE::clr_flags (ACE_HANDLE handle, int flags)
{
  ACE_TRACE ("ACE::clr_flags");

#if defined (ACE_WIN32) || defined (VXWORKS)
  switch (flags)
    {
    case ACE_NONBLOCK:
      // nonblocking argument (1) 
      // blocking:            (0)
      {
	u_long nonblock = 0;
	return ACE_OS::ioctl (handle, FIONBIO, &nonblock);
      }
    default:
      errno = ENOTSUP;
      return -1;
    }
#else
  int val = ACE_OS::fcntl (handle, F_GETFL, 0);

  if (val == -1)
    return -1;

  // Turn flags off.
  ACE_CLR_BITS (val, flags); 

  if (ACE_OS::fcntl (handle, F_SETFL, val) == -1)
    return -1;
  else
    return 0;
#endif /* ACE_WIN32 || VXWORKS */
}

int
ACE::map_errno (int error)
{
  switch (error)
    {
#if defined (ACE_WIN32)
    case WSAEWOULDBLOCK:
      return EAGAIN; // Same as UNIX errno EWOULDBLOCK.
#endif /* ACE_WIN32 */
    }

  return error;
}

ssize_t
ACE::send (ACE_HANDLE handle, 
	   const void *buf, 
	   size_t n, 
	   int flags, 
	   const ACE_Time_Value *timeout)
{
  if (timeout == 0)
    // Use the blocking send.
    return ACE::send (handle, buf, n, flags);
  else
    {
      // On timed writes we always go into select(); only if the
      // descriptor is available for writing within the specified
      // amount of time do we put it in non-blocking mode

      ACE_Handle_Set handle_set;
      handle_set.set_bit (handle);

      switch (ACE_OS::select (int (handle) + 1, 0, handle_set, 0, timeout))
	{
	case 1: // Ok to write now
	  // We need to record whether we are already *in* nonblocking
	  // mode, so that we can correctly reset the state when we're
	  // done.
	  {
	    int val = ACE::get_flags (handle);

	    if (ACE_BIT_ENABLED (val, ACE_NONBLOCK) == 0)
	      // Set the descriptor into non-blocking mode if it's not
	      // already in it.
	      ACE::set_flags (handle, ACE_NONBLOCK);

	    ssize_t bytes_written = ACE_OS::send (handle, (const char *) buf, n, flags);

	    if (ACE_BIT_ENABLED (val, ACE_NONBLOCK) == 0)
	      {
		// We need to stash errno here because ACE::clr_flags() may
		// reset it.
		int error = errno;

		// Only disable ACE_NONBLOCK if we weren't in non-blocking mode
		// originally.
		ACE::clr_flags (handle, ACE_NONBLOCK);
		errno = error;
	      }
	    return bytes_written;
	  }
	case 0: // Timer expired.
	  errno = ETIME;
	  /* FALLTHRU */
	default: // if we got here directly select() must have returned -1.
	  return -1;
	}
    }
}

ssize_t
ACE::send (ACE_HANDLE handle, 
	   const void *buf, 
	   size_t n, 
	   const ACE_Time_Value *timeout)
{
  if (timeout == 0)
    // Use the blocking send.
    return ACE::send (handle, buf, n);
  else
#if defined (ACE_WIN32)
    // Use the socket timed send();
    return ACE::send (handle, buf, n, 0, timeout);
#else
    {
      // On timed writes we always go into select(); only if the
      // descriptor is available for writing within the specified
      // amount of time do we put it in non-blocking mode

      ACE_Handle_Set handle_set;
      handle_set.set_bit (handle);

      switch (ACE_OS::select (int (handle) + 1, 0, handle_set, 0, timeout))
	{
	case 1: // Ok to write now
	  // We need to record whether we are already *in* nonblocking
	  // mode, so that we can correctly reset the state when we're
	  // done.
	  {
	    int val = ACE::get_flags (handle);

	    if (ACE_BIT_ENABLED (val, ACE_NONBLOCK) == 0)
	      // Set the descriptor into non-blocking mode if it's not
	      // already in it.
	      ACE::set_flags (handle, ACE_NONBLOCK);

	    ssize_t bytes_written = ACE_OS::write (handle, (const char *) buf, n);

	    if (ACE_BIT_ENABLED (val, ACE_NONBLOCK) == 0)
	      {
		// We need to stash errno here because ACE::clr_flags() may
		// reset it.
		int error = errno;

		// Only disable ACE_NONBLOCK if we weren't in non-blocking mode
		// originally.
		ACE::clr_flags (handle, ACE_NONBLOCK);
		errno = error;
	      }
	    return bytes_written;
	  }
	case 0: // Timer expired.
	  errno = ETIME;
	  /* FALLTHRU */
	default: // if we got here directly select() must have returned -1.
	  return -1;
	}
    }
#endif /* ACE_WIN32 */
}

ssize_t
ACE::send_n (ACE_HANDLE handle, 
	     const void *buf, 
	     size_t n, 
	     int flags, 
	     const ACE_Time_Value *timeout)
{
  size_t bytes_written;

  // Actual number of bytes written in each attempt.
  ssize_t i = 0;

  for (bytes_written = 0; bytes_written < n; bytes_written += i)
    {
      i = ACE::send (handle, (char *) buf + bytes_written, 
		     n - bytes_written, flags, timeout);
      if (i == -1)
	break;
    }

  return bytes_written;
}

ssize_t
ACE::recv (ACE_HANDLE handle, 
	   void *buf, 
	   size_t n, 
	   int flags, 
	   const ACE_Time_Value *timeout)
{
  if (timeout == 0)
    return ACE::recv (handle, buf, n, flags);
  else
    {
      ACE_Handle_Set handle_set;

      handle_set.set_bit (handle);

      // Wait for input to arrive or for the timeout to elapse.
      switch (ACE_OS::select (int (handle) + 1,
			      (fd_set *) handle_set, // read_fds.
			      (fd_set *) 0, // write_fds.
			      (fd_set *) 0, // exception_fds.
			      timeout))
	{
	case -1:
	  return -1;
	case 0:
	  errno = ETIME;
	  return -1;
	default:
	  return ACE::recv (handle, buf, n, flags);
	}
    }
}

ssize_t
ACE::recv_n (ACE_HANDLE handle, 
	     void *buf, 
	     size_t n, 
	     int flags, 
	     const ACE_Time_Value *timeout)
{
  size_t bytes_received;

  // Actual number of bytes read in each attempt.
  ssize_t i = 0;

  for (bytes_received = 0; bytes_received < n; bytes_received += i)
    {
      i = ACE::recv (handle, (char *) buf + bytes_received, 
		     n - bytes_received, flags, timeout);

      if (i == -1 || i == 0)
	break;
    }

  return bytes_received;
}

u_long
ACE::is_prime (const u_long n,
          const u_long min_factor,
          const u_long max_factor)
{
  if (n > 3)
    {
      for (u_long factor = min_factor; factor <= max_factor; ++factor)
	if (n / factor * factor == n)
	  return factor;

      return 0;
    }
  else
    return 0;
}

const char *
ACE::sock_error (int error)
{
#if defined (ACE_WIN32)
  switch (error)
    {
    case WSAVERNOTSUPPORTED:
      return "version of WinSock not supported";
      /* NOTREACHED */
    case WSASYSNOTREADY:
      return "WinSock not present or not responding";
      /* NOTREACHED */
    case WSAEINVAL:
      return "app version not supported by DLL";
      /* NOTREACHED */
    case WSAHOST_NOT_FOUND:
      return "Authoritive: Host not found";
      /* NOTREACHED */
    case WSATRY_AGAIN:
      return "Non-authoritive: host not found or server failure";
      /* NOTREACHED */
    case WSANO_RECOVERY:
      return "Non-recoverable: refused or not implemented";
      /* NOTREACHED */
    case WSANO_DATA:
      return "Valid name, no data record for type";
      /* NOTREACHED */
      /*
	case WSANO_ADDRESS:
	return "Valid name, no MX record";
	  */
    case WSANOTINITIALISED:
      return "WSA Startup not initialized";
      /* NOTREACHED */
    case WSAENETDOWN:
      return "Network subsystem failed";
      /* NOTREACHED */
    case WSAEINPROGRESS:
      return "Blocking operation in progress";
      /* NOTREACHED */
    case WSAEINTR:
      return "Blocking call cancelled";
      /* NOTREACHED */
    case WSAEAFNOSUPPORT:
      return "address family not supported";
      /* NOTREACHED */
    case WSAEMFILE:
      return "no file descriptors available";
      /* NOTREACHED */
    case WSAENOBUFS:
      return "no buffer space available";
      /* NOTREACHED */
    case WSAEPROTONOSUPPORT:
      return "specified protocol not supported";
      /* NOTREACHED */
    case WSAEPROTOTYPE:
      return "protocol wrong type for this socket";
      /* NOTREACHED */
    case WSAESOCKTNOSUPPORT:
      return "socket type not supported for address family";
      /* NOTREACHED */
    case WSAENOTSOCK:
      return "descriptor is not a socket";
      /* NOTREACHED */
    case WSAEWOULDBLOCK:
      return "socket marked as non-blocking and SO_LINGER set not 0";
      /* NOTREACHED */
    case WSAEADDRINUSE:
      return "address already in use";
      /* NOTREACHED */
    case WSAECONNABORTED:
      return "connection aborted";
      /* NOTREACHED */
    case WSAECONNRESET:
      return "connection reset";
      /* NOTREACHED */
    case WSAENOTCONN:
      return "not connected";
      /* NOTREACHED */
    case WSAETIMEDOUT:
      return "connection timed out";
      /* NOTREACHED */
    case WSAECONNREFUSED:
      return "connection refused";
      /* NOTREACHED */
    case WSAEHOSTDOWN:
      return "host down";
      /* NOTREACHED */
    case WSAEHOSTUNREACH:
      return "host unreachable";
      /* NOTREACHED */
    case WSAEADDRNOTAVAIL:
      return "address not available";
      /* NOTREACHED */
    default:
      return "unknown error";
      /* NOTREACHED */
    }
#else
  ACE_UNUSED_ARG (error);
  ACE_NOTSUP_RETURN (0);
#endif /* ACE_WIN32 */
}

int
ACE::get_bcast_addr (ACE_UINT32 &bcast_addr,
		     const char *host_name,
		     ACE_UINT32 host_addr, 
		     ACE_HANDLE handle)
{
  ACE_TRACE ("ACE::get_bcast_addr");

#if !defined(ACE_WIN32)
  ACE_HANDLE s = handle;

  if (s == ACE_INVALID_HANDLE)
    s = ACE_OS::socket (AF_INET, SOCK_STREAM, 0);

  if (s == ACE_INVALID_HANDLE)
    ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "ACE_OS::socket"), -1);

  struct ifconf ifc;
  char buf[BUFSIZ];

  ifc.ifc_len = sizeof buf;
  ifc.ifc_buf = buf;

  // Get interface structure and initialize the addresses using UNIX
  // techniques
  if (ACE_OS::ioctl (s, SIOCGIFCONF, (char *) &ifc) == -1)
    ACE_ERROR_RETURN ((LM_ERROR, "%p\n",
                      "ACE::get_bcast_addr: ioctl (get interface configuration)"),
                      -1);

  struct ifreq *ifr = ifc.ifc_req;

  struct sockaddr_in ip_addr;

  // Get host ip address if necessary.
  if (host_name)
    {
      hostent *hp = ACE_OS::gethostbyname (host_name);

      if (hp == 0)
	return -1;
      else
	ACE_OS::memcpy ((char *) &ip_addr.sin_addr.s_addr,
			(char *) hp->h_addr, 
			hp->h_length);
    }
  else
    {
      ACE_OS::memset ((void *) &ip_addr, 0, sizeof ip_addr);
      ACE_OS::memcpy ((void *) &ip_addr.sin_addr, 
		      (void*) &host_addr, 
		      sizeof ip_addr.sin_addr);
    }

  for (int n = ifc.ifc_len / sizeof (struct ifreq);
       n > 0; 
       n--, ifr++)
    {
      struct sockaddr_in if_addr;

      // Compare host ip address with interface ip address.
      ACE_OS::memcpy (&if_addr, &ifr->ifr_addr, sizeof if_addr);

      if (ip_addr.sin_addr.s_addr != if_addr.sin_addr.s_addr)
        continue;

      if (ifr->ifr_addr.sa_family != AF_INET)
        {
          ACE_ERROR ((LM_ERROR, "%p\n",
                      "ACE::get_bcast_addr: Not AF_INET"));
          continue;
        }

      struct ifreq flags = *ifr;
      struct ifreq if_req = *ifr;

      if (ACE_OS::ioctl (s, SIOCGIFFLAGS, (char *) &flags) == -1)
        {
          ACE_ERROR ((LM_ERROR, "%p\n",
                     "ACE::get_bcast_addr: ioctl (get interface flags)"));
          continue;
        }

      if (ACE_BIT_ENABLED (flags.ifr_flags, IFF_UP) == 0)
        {
          ACE_ERROR ((LM_ERROR, "%p\n",
                     "ACE::get_bcast_addr: Network interface is not up"));
          continue;
        }

      if (ACE_BIT_ENABLED (flags.ifr_flags, IFF_LOOPBACK))
        continue;

      if (ACE_BIT_ENABLED (flags.ifr_flags, IFF_BROADCAST))
        {
          if (ACE_OS::ioctl (s, SIOCGIFBRDADDR, (char *) &if_req) == -1)
            ACE_ERROR ((LM_ERROR, "%p\n",
                       "ACE::get_bcast_addr: ioctl (get broadaddr)"));
          else
            { 
              ACE_OS::memcpy ((struct sockaddr_in *) &ip_addr,
                              (struct sockaddr_in *) &if_req.ifr_broadaddr,
                              sizeof if_req.ifr_broadaddr);

              ACE_OS::memcpy ((void *) &host_addr, 
			      (void *) &ip_addr.sin_addr,
                              sizeof host_addr);

	      if (handle == ACE_INVALID_HANDLE)
		ACE_OS::close (s);
	      bcast_addr = host_addr;
              return 0;
            }
        }
      else
        ACE_ERROR ((LM_ERROR, "%p\n",
                   "ACE::get_bcast_addr: Broadcast is not enable for this interface."));

      if (handle == ACE_INVALID_HANDLE)
	ACE_OS::close (s);
      bcast_addr = host_addr;
      return 0;
    }

  return 0;
#else
  ACE_UNUSED_ARG (handle);
  ACE_UNUSED_ARG (host_addr);
  ACE_UNUSED_ARG (host_name);
  bcast_addr = (ACE_UINT32 (INADDR_BROADCAST));
  return 0;
#endif /* !ACE_WIN32 */
}

// Helper routine for get_ip_interfaces, differs by UNIX platform so
// put into own subroutine.  perform some ioctls to retrieve ifconf
// list of ifreq structs.

int 
ACE::count_interfaces (ACE_HANDLE handle, 
		       size_t &how_many)
{
#if defined(__SVR4) 
  if (ACE_OS::ioctl (handle, SIOCGIFNUM, (caddr_t) &how_many) == -1) 
    ACE_ERROR_RETURN ((LM_ERROR, "ACE::get_ip_interfaces:ioctl - SIOCGIFNUM failed"), -1);
   return 0;
#elif defined (__unix)
// BSD compatible OS: HP UX, AIX, SunOS 4.x perform some ioctls to
// retrieve ifconf list of ifreq structs no SIOCGIFNUM on SunOS 4.x,
// so use guess and scan algorithm

  const int MAX_IF = 50; // probably hard to put this many ifs in a unix box..
  int num_ifs = MAX_IF; // HACK - set to an unreasonable number
  struct ifconf ifcfg;
  struct ifreq *p_ifs = NULL;
  size_t ifreq_size = 0;
  ACE_UINT32 addr;
  struct in_addr if_addr, if_test; 

  ifreq_size = num_ifs * sizeof (struct ifreq);
  p_ifs = (struct ifreq *) ACE_OS::malloc (ifreq_size);

  if (!p_ifs) 
    {
      errno = ENOMEM;
      return -1;
    }

  ACE_OS::memset (p_ifs, 0, ifreq_size);
  ACE_OS::memset (&ifcfg, 0, sizeof (struct ifconf));
  ifcfg.ifc_req = p_ifs;
  ifcfg.ifc_len = ifreq_size; 
  
  if (ACE_OS::ioctl (handle, SIOCGIFCONF, (caddr_t) &ifcfg) == -1) 
    {
      ACE_OS::free (ifcfg.ifc_req);
      ACE_ERROR_RETURN ((LM_ERROR, "count_interfaces:ioctl - SIOCGIFCONF failed"), -1);
    } 

  int if_count = 0, i ;

  // get if address out of ifreq buffers.
  // ioctl puts a blank-named interface to mark the end of the
  // returned interfaces.
  for (i = 0; i < num_ifs; p_ifs++, i++) 
    {
      if (p_ifs->ifr_name[0] == '\0')
	  break;
      if_count++;
    }

  free(ifcfg.ifc_req);
  how_many = if_count;
  return 0;
#else
   ACE_NOTSUP_RETURN (-1);; // no implmentation
#endif /* __SVR4 */
}

// Routine to return a descriptor from which ioctl() requests can be
// made.

ACE_HANDLE
ACE::get_handle (void)
{
// Solaris 2.x
  ACE_HANDLE handle = ACE_INVALID_HANDLE;
#if defined(__SVR4)
  handle = ACE_OS::open ("/dev/udp", O_RDONLY);
#elif defined(__unix)
// BSD compatible OS: HP UX, AIX, SunOS 4.x
  handle = ACE_OS::socket (PF_INET, SOCK_DGRAM, 0);
#endif /* __SVR4 */
  return handle;
}

// helper routine for get_ip_interfaces
#if defined(ACE_WIN32)
#include <ace/SString.h>
#define NIL_STR TEXT("")

#if defined (UNICODE)
#define STRLEN wcslen
#else
#define STRLEN ACE_OS::strlen
#endif

// Zero terminated strings laid out like argv[], or NT registry
// MULTI_SZ data type note, this object does not.

class string_array 
{
public:
  string_array (const TCHAR *the_str);
  ~string_array (void);
  long count () const;
  const TCHAR *const operator[] (int idx) const;

private:
  string_array (const string_array&);
  void build_object (wchar_t *str, int sz);
  const TCHAR *buffer_;
  long count_;
};

string_array::string_array (const TCHAR * str)
  : count_(0), buffer_(0)
{
  if (str == 0 || *str == '\0')
    return;
  
  buffer_ = str; // 

  const TCHAR *ptr = buffer_;
  
  // determine how many items there are (count_)
  while (*ptr) 
    {
      int len = STRLEN (ptr);
      count_++;  // how may strings
      ptr += len + 1; // move to start of next string
    }
}

string_array::~string_array (void)
{
}

// how many strings
long 
string_array::count (void) const
{
  return count_;
}

// * return a const only ptr

const TCHAR *const 
string_array::operator[] (int idx) const
{
  if (idx < 0 || idx > count_) 
    return (TCHAR *) 0;

  const TCHAR *ptr = buffer_;

  for (int j = 0; j < idx; j++) 
    {
      int len = STRLEN(ptr);
      ptr += len + 1; // move to start of next string (skip past null)
    }

  return (const TCHAR *const) ptr;
}

// Return value in buffer for a key/name pair from the Windows
// Registry up to buf_len size.

static int 
get_reg_value (const TCHAR *key,
	       const TCHAR *name,
	       TCHAR *buffer,
	       DWORD &buf_len)
{
  HKEY hk; 
  DWORD buf_type;
  LONG rc = RegOpenKeyEx (HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hk);

  // 1. open key that defines the interfaces used for TCP/IP?
  if (rc != ERROR_SUCCESS) 
    // print_error_string(TEXT("RegOpenKeyEx"), rc); 
    return -1;

  rc = RegQueryValueEx (hk, name, 0, &buf_type, 
		       (unsigned char *) buffer, &buf_len);

  if (rc != ERROR_SUCCESS) 
    {
      // print_error_string(TEXT("RegEnumKeyEx"), rc);
      RegCloseKey (hk);
      return -2;
    }

  RegCloseKey (hk);
  return 0;
}
#endif /* ACE_WIN32 */

// return an array of all configured IP interfaces on this host, count
// rc = 0 on success (count == number of interfaces else -1 caller is
// responsible for calling delete [] on parray

int 
ACE::get_ip_interfaces (size_t &count,
			ACE_INET_Addr *&addrs)
{
  // code for NT
#if defined (ACE_WIN32)

  // this is ugly but the string classes are not parametrized ...
#if defined (UNICODE)
#define NT_STRING ACE_WString
#else 
#define NT_STRING ACE_CString
#endif /* UNICODE */

// TODO: add windows code here
#define SVCS_KEY1 TEXT("SYSTEM\\CurrentControlSet\\Services\\")
#define LINKAGE_KEY1 TEXT("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Linkage")
#define TCP_PARAM_SUBKEY TEXT("\\Parameters\\Tcpip")
#define BIND_NAME_ID TEXT("Bind")
#define IPADDR_NAME_ID TEXT("IPAddress")
#define PERIOD_STR TEXT(".")
#define BLANK_STR TEXT(" ")

  const int MAX_STRING_SZ = 4096;

  // 1. extract bind=device list 
  TCHAR buffer[MAX_STRING_SZ]; // 45 chars
  DWORD buf_len = MAX_STRING_SZ;

  if (::get_reg_value (LINKAGE_KEY1,
		       BIND_NAME_ID,
		       buffer,
		       buf_len))
    return -1;

  // 2. returned buffer may contain "\\Device\\dev1\0\\device\\dev2\0\0"
  string_array dev_names ((TCHAR *) buffer); // access raw buffer through this class
  int n_interfaces = dev_names.count ();

  // case 1. no interfaces present, empty string? OS version change?
  if (n_interfaces == 0)
    return 0;

  ACE_NEW_RETURN (addrs, ACE_INET_Addr[n_interfaces], -2);
  
  for (int i = 0; i < n_interfaces; i++) 
    {

      // a. construct name to access IPAddress for this interface 
      NT_STRING ifdevkey (SVCS_KEY1);
      NT_STRING the_dev = dev_names[i]; // chop off the "\Device" and keep last name

      if (the_dev.length() < 8)
	return -3;
      else 
	{
	  the_dev = the_dev.substring (8);  // rest of string from offset 8
	  ifdevkey += the_dev;
	  ifdevkey += TCP_PARAM_SUBKEY;

	  // b. extract value 
	  if (get_reg_value (ifdevkey.rep(), IPADDR_NAME_ID, buffer, buf_len)) 
	    return -4;

	  // c. store in hostinfo object array and up the counter
#if defined (UNICODE)
	  const MAX_HOSTNAME_LEN = 256; // per rfc
	  char c_string[MAX_HOSTNAME_LEN +1];
	  ::wcstombs(c_string, buffer, MAX_HOSTNAME_LEN);
	  addrs[i] = ACE_INET_Addr ((unsigned short) 0, c_string);
#else
	  addrs[i] = ACE_INET_Addr ((unsigned short) 0, buffer);
#endif /* UNICODE */
	  count++;
	}
    }
  return 0;
#elif defined(__unix)
  //  COMMON (SVR4 and BSD) UNIX CODE

  ACE_TRACE ("ACE::get_ip_interfaces");
  size_t num_ifs;

  ACE_HANDLE handle = get_handle();	// call specific routine as necessary

  if (handle == ACE_INVALID_HANDLE) 
    ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "ACE::get_ip_interfaces:open"), -1);

  if (ACE::count_interfaces (handle, num_ifs))
    {
      ACE_OS::close (handle);
      return -1;
    }

  // ioctl likes to have an extra ifreq structure to mark the end of what it
  // returned, so increase the num_ifs by one.
  ++num_ifs;

  struct ifreq *ifs;
  ACE_NEW_RETURN (ifs, struct ifreq[num_ifs], -1);
  ACE_OS::memset (ifs, 0, num_ifs * sizeof (struct ifreq));
  auto_array_ptr<struct ifreq> p_ifs (ifs);

  if (p_ifs.get() == 0) 
    {
      ACE_OS::close (handle);
      errno = ENOMEM;
      return -1;
    }
 
  struct ifconf ifcfg;  
  ACE_OS::memset (&ifcfg, 0, sizeof (struct ifconf));
  ifcfg.ifc_req = p_ifs.get ();
  ifcfg.ifc_len = num_ifs * sizeof (struct ifreq); 

  if (ACE_OS::ioctl (handle, SIOCGIFCONF, (caddr_t) &ifcfg) == -1) 
    {
      ACE_OS::close (handle);
      ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "is_address_local:ioctl - SIOCGIFCONF failed"), -1);
    }

  ACE_OS::close (handle);

  // ------------ now create and initialize output array -------------

  ACE_NEW_RETURN (addrs, ACE_INET_Addr[num_ifs], -1); // caller must free

  struct ifreq *pcur = p_ifs.get ();
  // Pull the address out of each INET interface.  Not every interface is
  // for IP, so be careful to count properly.  When setting the INET_Addr,
  // note that the 3rd arg (0) says to leave the byte order (already in net
  // byte order from the interface structure) as is.
  count = 0;
  for (size_t i = 0; i < num_ifs; pcur++, i++) 
    {
      if (pcur->ifr_addr.sa_family == AF_INET)
        {
	  struct sockaddr_in *_addr_ = (struct sockaddr_in *)&(pcur->ifr_addr);
	  addrs[count].set ((u_short)0, _addr_->sin_addr.s_addr, 0);
          count++;
        }
    }
  return 0; 
#else
  ACE_NOTSUP_RETURN (-1);;			// no implentation
#endif /* ACE_WIN32 */
}

#if defined (ACE_TEMPLATES_REQUIRE_SPECIALIZATION)
template class auto_array_ptr<struct ifreq>;
#endif /* ACE_TEMPLATES_REQUIRE_SPECIALIZATION */