aboutsummaryrefslogtreecommitdiff
path: root/openssl/vendor/current/MacOS/GetHTTPS.src/MacSocket.cpp
blob: c95d804d5d4834409f122226c4a5552066441445 (plain) (blame)
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
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
****** Installation ******

At present, the entire RPKI tools collection is a single source tree with a
shared autoconf configuration. This may change in the future, but for now, this
means that the build process is essentially the same regardless of which tools
one wants to use. Some of the tools have dependencies on external packages,
although we've tried to keep this to a minimum.

Most of the tools require an RFC-3779-aware version of the OpenSSL libraries.
If necessary, the build process will generate its own private copy of the
OpenSSL libraries for this purpose.

Other than OpenSSL, most of the relying party tools are fairly self-contained.
The CA tools have a few additional dependencies, described below.

Note that initial development of this code has been on FreeBSD, so installation
will probably be easiest on FreeBSD. We do, however, test on other platforms,
such as Fedora, Ubuntu, and MacOSX.

***** Prerequisites *****

Before attempting to build the tools, you need to install any missing
prerequisites.

Some of the relying party tools and most of the CA tools are written in Python.
Note that the Python code requires Python version 2.5, 2.6, or 2.7.

On some platforms (particularly MacOSX) the simplest way to install most of the
Python packages may be the easy_install tool that comes with Python.

Packages you will need:

* We do not (yet) have binary packages for any platform, so you will need a C
  compiler. gcc is fine, others such as Clang may also work.

* http://www.python.org/, the Python interpreter, libraries, and sources. On
  some platforms the Python sources (in particular, the header files and
  libraries needed when building Python extensions) are in a separate
  "development" package, on other platforms they are all part of a single
  package. If you get compilation errors trying to build the POW code later in
  the build process and the error message says something about the file
  "Python.h" being missing, this is almost certainly your problem.

  o FreeBSD:

    # /usr/ports/lang/python27

  o Ubuntu:

    # python
    # python-dev

* http://codespeak.net/lxml/, a Pythonic interface to the Gnome LibXML2
  libraries. lxml in turn requires the LibXML2 C libraries.

  o FreeBSD: /usr/ports/devel/py-lxml
  o Fedora: python-lxml.i386
  o Ubuntu: python-lxml

* http://www.mysql.com/, MySQL client and server. How these are packaged varies
  by platform, on some platforms the client and server are separate packages,
  on others they might be a single monolithic package, or installing the server
  might automatically install the client as a dependency. On MacOSX you might
  be best off installing a binary package for MySQL. The RPKI CA tools have
  been tested with MySQL 5.0, 5.1, and 5.5; they will probably work with any
  other reasonably recent version.

  o FreeBSD:

    # /usr/ports/databases/mysql55-server
    # /usr/ports/databases/mysql55-client

  o Ubuntu:

    # mysql-client
    # mysql-server

* http://sourceforge.net/projects/mysql-python/, the Python "db" interface to
  MySQL.

  o FreeBSD: /usr/ports/databases/py-MySQLdb
  o Fedora: MySQL-python.i386
  o Ubuntu: python-mysqldb

* http://www.djangoproject.com/, the Django web user interface toolkit. The GUI
  interface to the CA tools requires this.

  o FreeBSD: /usr/ports/www/py-django
  o Ubuntu: python-django

* http://vobject.skyhouseconsulting.com/, a Python library for parsing VCards.
  The GUI uses this to parse the payload of RPKI Ghostbuster objects.

  o FreeBSD: /usr/ports/deskutils/py-vobject
  o Ubuntu: python-vobject

* http://pyyaml.org/. Several of the test programs use PyYAML to parse a YAML
  description of a simulated allocation hierarchy to test.

  o FreeBSD: /usr/ports/devel/py-yaml
  o Ubuntu: python-yaml

* http://xmlsoft.org/XSLT/. Some of the test code uses xsltproc, from the Gnome
  LibXSLT package.

  o FreeBSD: /usr/ports/textproc/libxslt
  o Ubuntu: xsltproc

* http://www.rrdtool.org/. The relying party tools use this to generate
  graphics which you may find useful in monitoring the behavior of your
  validator. The rest of the software will work fine without rrdtool, you just
  won't be able to generate those graphics.

  o FreeBSD: /usr/ports/databases/rrdtool
  o Ubuntu: rrdtool

* http://www.freshports.org/www/mod_wsgi3/ If you intend to run the GUI with
  wsgi, its default configuration, you will need to install mod_wsgi v3

  o FreeBSD: /usr/ports/www/mod_wsgi3

* http://south.aeracode.org/ Django South. This tool is used to ease the pain
  of changes to the web portal database schema.

  o FreeBSD: /usr/ports/databases/py-south
  o Ubuntu: python-django-south
  o CentOS/RHEL: Django-south

***** Configure and build *****

Once you have the prerequesite packages installed, you should be able to build
the toolkit. cd to the top-level directory in the distribution, run the
configure script, then run "make":

  $ cd $top
  $ ./configure
  $ make

This should automatically build everything, in the right order, including
building a private copy of the OpenSSL libraries with the right options if
necessary and linking the POW module against either the system OpenSSL
libraries or the private OpenSSL libraries, as appopriate.

In theory, ./configure will complain about any required packages which might be
missing.

If you don't intend to run any of the CA tools, you can simplify the build and
installation process by telling ./configure that you only want to build the
relying party tools:

  $ cd $top
  $ ./configure --disable-ca-tools
  $ make

***** Testing the build *****

Assuming the build stage completed without obvious errors, the next step is to
run some basic regression tests.

Some of the tests for the CA tools require MySQL databases to store their data.
To set up all the databases that the tests will need, run the SQL commands in
rpkid/tests/smoketest.setup.sql. The MySQL command line client is usually the
easiest way to do this, eg:

  $ cd $top/rpkid
  $ mysql -u root -p <tests/smoketest.setup.sql

To run the tests, run "make test":

  $ cd $top
  $ make test

To run a more extensive set of tests on the CA tool, run "make all-tests" in
the rpkid/ directory:

  $ cd $top/rpkid
  $ make all-tests

If nothing explodes, your installation is probably ok. Any Python backtraces in
the output indicate a problem.

***** Installing *****

Assuming the build and test phases went well, you should be ready to install
the code. The ./configure script attempts to figure out the "obvious" places to
install the various programs for your platform: binaries will be installed in /
usr/local/bin or /usr/local/sbin, Python modules will be installed using the
standard Python distutils and should end up wherever your system puts locally-
installed Python libraries, and so forth.

The RPKI validator, rcynic, is a special case, because the install scripts
attempt to build a chroot jail and install rcynic in that environment. This is
straightforward in FreeBSD, somewhat more complicated on other systems,
primarily due to hidden dependencies on dynamic libraries.

To install the code, become root (su, sudo, whatever), then run "make install":

  $ cd $top
  $ sudo make install

***** Tools you should not need to install *****

There's a last set of tools that only developers should need, as they're only
used when modifying schemas or regenerating the documentation. These tools are
listed here for completeness.

* http://www.doxygen.org/. Doxygen in turn pulls in several other tools,
  notably Graphviz, pdfLaTeX, and Ghostscript.

  o FreeBSD: /usr/ports/devel/doxygen
  o Ubuntu: doxygen

* http://www.mbayer.de/html2text/. The documentation build process uses
  xsltproc and html2text to dump flat text versions of a few critical
  documentation pages.

  o FreeBSD: /usr/ports/textproc/html2text

* http://www.thaiopensource.com/relaxng/trang.html. Trang is used to convert
  RelaxNG schemas from the human-readable "compact" form to the XML form that
  LibXML2 understands. Trang in turn requires Java.

  o FreeBSD: /usr/ports/textproc/trang

* http://search.cpan.org/dist/SQL-Translator/. SQL-Translator, also known as
  "SQL Fairy", includes code to parse an SQL schema and dump a description of
  it as Graphviz input. SQL Fairy in turn requires Perl.

  o FreeBSD: /usr/ports/databases/p5-SQL-Translator

* http://www.easysw.com/htmldoc/. The documentation build process uses htmldoc
  to generate PDF from the project's Trac wiki.

  o FreeBSD: /usr/ports/textproc/htmldoc

***** Next steps *****

Once you've finished installing the code, you will need to configure it. Since
CAs are generally also relying parties (if only so that they can check the
results of their own actions), you will generally want to start by configuring
the relying party tools, then configure the CA tools if you're planning to use
them.
ef='#n836'>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
/*
 *	A simple socket-like package.  
 *	This could undoubtedly be improved, since it does polling and busy-waiting.  
 *	At least it uses asynch I/O and implements timeouts!
 *
 *	Other funkiness includes the use of my own (possibly brain-damaged) error-handling infrastructure.
 *
 *	-Roy Wood (roy@centricsystems.ca)
 *
 */


/* ====================================================================
 * Copyright (c) 1998-1999 The OpenSSL Project.  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 OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    openssl-core@openssl.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``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 OpenSSL PROJECT 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 product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */
 




#include "MacSocket.h"

#include <Threads.h>

#include <OpenTransport.h>
#include <OpenTpTInternet.h>
#include <OpenTptClient.h>



#include "CPStringUtils.hpp"
#include "ErrorHandling.hpp"


//	#define MACSOCKET_DEBUG		1

#ifdef MACSOCKET_DEBUG
	#include <stdio.h>
#endif



extern int errno;


#define kMaxNumSockets			4


struct SocketStruct
{
	Boolean						mIsInUse;

	Boolean						mEndpointIsBound;

	Boolean						mLocalEndIsConnected;
	Boolean						mRemoteEndIsConnected;

	Boolean						mReceivedTOpenComplete;
	Boolean						mReceivedTBindComplete;
	Boolean						mReceivedTConnect;
	Boolean						mReceivedTListen;
	Boolean						mReceivedTPassCon;
	Boolean						mReceivedTDisconnect;
	Boolean						mReceivedTOrdRel;
	Boolean						mReceivedTDisconnectComplete;
	
	long						mTimeoutTicks;
	long						mOperationStartTicks;
	
	MacSocket_IdleWaitCallback	mIdleWaitCallback;
	void						*mUserRefPtr;
	
	OTEventCode					mExpectedCode;
	OTResult					mAsyncOperationResult;
	
	EndpointRef		 			mEndPointRef;
	TBind						*mBindRequestedAddrInfo;
	TBind						*mAssignedAddrInfo;
	TCall						*mRemoteAddrInfo;
	
	Boolean						mReadyToReadData;
	Boolean						mReadyToWriteData;
	
	Ptr							mReadBuffer;
	Ptr							mWriteBuffer;
	
	int							mLastError;
	char						mErrMessage[256];
};

typedef struct SocketStruct	SocketStruct;


static SocketStruct			sSockets[kMaxNumSockets];
static Boolean				sSocketsSetup = false;




static OSErr MyBusyWait(SocketStruct *ioSocket,Boolean returnImmediatelyOnError,OTResult *outOTResult,Boolean *inAsyncOperationCompleteFlag);

static pascal void OTNonYieldingNotifier(void *contextPtr,OTEventCode code,OTResult result,void *cookie);

static Boolean	SocketIndexIsValid(const int inSocketNum);

static void InitSocket(SocketStruct *ioSocket);

static void PrepareForAsyncOperation(SocketStruct *ioSocket,const OTEventCode inExpectedCode);

static Boolean TimeoutElapsed(const SocketStruct *inSocket);

static OSStatus NegotiateIPReuseAddrOption(EndpointRef inEndpoint,const Boolean inEnableReuseIP);



void MacSocket_GetSocketErrorInfo(const int inSocketNum,int *outSocketErrCode,char *outSocketErrString,const int inSocketErrStringMaxLength)
{
	if (outSocketErrCode != nil)
	{
		*outSocketErrCode = -1;
	}
	
	if (outSocketErrString != nil)
	{
		CopyCStrToCStr("",outSocketErrString,inSocketErrStringMaxLength);
	}
	
	
	if (SocketIndexIsValid(inSocketNum))
	{
	SocketStruct	*theSocketStruct = &(sSockets[inSocketNum]);
	
		
		if (outSocketErrCode != nil)
		{
			*outSocketErrCode = theSocketStruct->mLastError;
		}

		if (outSocketErrString != nil)
		{
			CopyCStrToCStr(theSocketStruct->mErrMessage,outSocketErrString,inSocketErrStringMaxLength);
		}
	}
}


void MacSocket_SetUserRefPtr(const int inSocketNum,void *inNewRefPtr)
{
	if (SocketIndexIsValid(inSocketNum))
	{
	SocketStruct	*theSocketStruct = &(sSockets[inSocketNum]);

		theSocketStruct->mUserRefPtr = inNewRefPtr;
	}
}



void MacSocket_GetLocalIPAndPort(const int inSocketNum,char *outIPAndPort,const int inIPAndPortLength)
{
	if (outIPAndPort != nil && SocketIndexIsValid(inSocketNum))
	{
	char			tempString[256];
	SocketStruct	*theSocketStruct = &(sSockets[inSocketNum]);
	
		
		CopyCStrToCStr("",tempString,sizeof(tempString));

		if (theSocketStruct->mAssignedAddrInfo != nil)
		{
		InetAddress		*theInetAddress = (InetAddress *) theSocketStruct->mAssignedAddrInfo->addr.buf;
		InetHost		theInetHost = theInetAddress->fHost;
			
			if (theInetHost == 0)
			{
			InetInterfaceInfo	theInetInterfaceInfo;
				
				if (::OTInetGetInterfaceInfo(&theInetInterfaceInfo,kDefaultInetInterface) == noErr)
				{
					theInetHost = theInetInterfaceInfo.fAddress;
				}
			}
		
			::OTInetHostToString(theInetHost,tempString);
			
			ConcatCStrToCStr(":",tempString,sizeof(tempString));
			ConcatLongIntToCStr(theInetAddress->fPort,tempString,sizeof(tempString));
		}
		
		CopyCStrToCStr(tempString,outIPAndPort,inIPAndPortLength);
	}
}



void MacSocket_GetRemoteIPAndPort(const int inSocketNum,char *outIPAndPort,const int inIPAndPortLength)
{
	if (outIPAndPort != nil && SocketIndexIsValid(inSocketNum))
	{
	char			tempString[256];
	SocketStruct	*theSocketStruct = &(sSockets[inSocketNum]);
	
		
		CopyCStrToCStr("",tempString,sizeof(tempString));

		if (theSocketStruct->mRemoteAddrInfo != nil)
		{
		InetAddress		*theInetAddress = (InetAddress *) theSocketStruct->mRemoteAddrInfo->addr.buf;
		InetHost		theInetHost = theInetAddress->fHost;
			
			if (theInetHost == 0)
			{
			InetInterfaceInfo	theInetInterfaceInfo;
				
				if (::OTInetGetInterfaceInfo(&theInetInterfaceInfo,kDefaultInetInterface) == noErr)
				{
					theInetHost = theInetInterfaceInfo.fAddress;
				}
			}
		
			::OTInetHostToString(theInetHost,tempString);
			
			ConcatCStrToCStr(":",tempString,sizeof(tempString));
			ConcatLongIntToCStr(theInetAddress->fPort,tempString,sizeof(tempString));
		}
		
		CopyCStrToCStr(tempString,outIPAndPort,inIPAndPortLength);
	}
}



Boolean MacSocket_RemoteEndIsClosing(const int inSocketNum)
{
Boolean		theResult = false;

	if (SocketIndexIsValid(inSocketNum))
	{
	SocketStruct	*theSocketStruct = &(sSockets[inSocketNum]);

		theResult = theSocketStruct->mReceivedTOrdRel;
	}

	return(theResult);
}



Boolean MacSocket_ListenCompleted(const int inSocketNum)
{
Boolean		theResult = false;

	if (SocketIndexIsValid(inSocketNum))
	{
	SocketStruct	*theSocketStruct = &(sSockets[inSocketNum]);

		theResult = theSocketStruct->mReceivedTPassCon;
	}

	return(theResult);
}



Boolean MacSocket_RemoteEndIsOpen(const int inSocketNum)
{
	if (SocketIndexIsValid(inSocketNum))
	{
	SocketStruct	*theSocketStruct = &(sSockets[inSocketNum]);
	
		return(theSocketStruct->mRemoteEndIsConnected);
	}
	
	else
	{
		return(false);
	}
}



Boolean MacSocket_LocalEndIsOpen(const int inSocketNum)
{
	if (SocketIndexIsValid(inSocketNum))
	{
	SocketStruct	*theSocketStruct = &(sSockets[inSocketNum]);
	
		return(theSocketStruct->mLocalEndIsConnected);
	}
	
	else
	{
		return(false);
	}
}



static Boolean TimeoutElapsed(const SocketStruct *inSocket)
{
Boolean		timeIsUp = false;

	if (inSocket != nil && inSocket->mTimeoutTicks > 0 && ::TickCount() > inSocket->mOperationStartTicks + inSocket->mTimeoutTicks)
	{
		timeIsUp = true;
	}
	
	
	return(timeIsUp);
}



static Boolean SocketIndexIsValid(const int inSocketNum)
{
	if (inSocketNum >= 0 && inSocketNum < kMaxNumSockets && sSockets[inSocketNum].mEndPointRef != kOTInvalidEndpointRef)
	{
		return(true);
	}
	
	else
	{
		return(false);
	}
}



static void InitSocket(SocketStruct *ioSocket)
{
	ioSocket->mIsInUse = false;
	
	ioSocket->mEndpointIsBound = false;
	
	ioSocket->mLocalEndIsConnected = false;
	ioSocket->mRemoteEndIsConnected = false;
	
	ioSocket->mReceivedTOpenComplete = false;
	ioSocket->mReceivedTBindComplete = false;
	ioSocket->mReceivedTConnect = false;
	ioSocket->mReceivedTListen = false;
	ioSocket->mReceivedTPassCon = false;
	ioSocket->mReceivedTDisconnect = false;
	ioSocket->mReceivedTOrdRel = false;
	ioSocket->mReceivedTDisconnectComplete = false;
	
	ioSocket->mTimeoutTicks = 30 * 60;
	ioSocket->mOperationStartTicks = -1;
	
	ioSocket->mIdleWaitCallback = nil;
	ioSocket->mUserRefPtr = nil;
	
	ioSocket->mExpectedCode = 0;
	ioSocket->mAsyncOperationResult = noErr;
	
	ioSocket->mEndPointRef = kOTInvalidEndpointRef;
	
	ioSocket->mBindRequestedAddrInfo = nil;
	ioSocket->mAssignedAddrInfo = nil;
	ioSocket->mRemoteAddrInfo = nil;
	
	ioSocket->mReadyToReadData = false;
	ioSocket->mReadyToWriteData = true;
	
	ioSocket->mReadBuffer = nil;
	ioSocket->mWriteBuffer = nil;

	ioSocket->mLastError = noErr;
	CopyCStrToCStr("",ioSocket->mErrMessage,sizeof(ioSocket->mErrMessage));
}



static void PrepareForAsyncOperation(SocketStruct *ioSocket,const OTEventCode inExpectedCode)
{
	ioSocket->mOperationStartTicks = ::TickCount();
	
	ioSocket->mAsyncOperationResult = noErr;
	
	ioSocket->mExpectedCode = inExpectedCode;
}


//	The wait function....

static OSErr MyBusyWait(SocketStruct *ioSocket,Boolean returnImmediatelyOnError,OTResult *outOTResult,Boolean *inAsyncOperationCompleteFlag)
{
OSErr 		errCode = noErr;
OTResult	theOTResult = noErr;

	
	SetErrorMessageAndBailIfNil(ioSocket,"MyBusyWait: Bad parameter, ioSocket = nil");
	SetErrorMessageAndBailIfNil(inAsyncOperationCompleteFlag,"MyBusyWait: Bad parameter, inAsyncOperationCompleteFlag = nil");
	
	for (;;) 
	{
		if (*inAsyncOperationCompleteFlag)
		{
			theOTResult = ioSocket->mAsyncOperationResult;
			
			break;
		}
		
		if (ioSocket->mIdleWaitCallback != nil)
		{
			theOTResult = (*(ioSocket->mIdleWaitCallback))(ioSocket->mUserRefPtr);
			
			if (theOTResult != noErr && returnImmediatelyOnError)
			{
				break;
			}
		}
		
		if (TimeoutElapsed(ioSocket))
		{
			theOTResult = kMacSocket_TimeoutErr;
			
			break;
		}
	}


EXITPOINT:
	
	if (outOTResult != nil)
	{
		*outOTResult = theOTResult;
	}
	
	return(errCode);
}



//	I used to do thread switching, but stopped.  It could easily be rolled back in though....

static pascal void OTNonYieldingNotifier(void *contextPtr,OTEventCode code,OTResult result,void *cookie)
{
SocketStruct *theSocketStruct = (SocketStruct *) contextPtr;
	
	if (theSocketStruct != nil)
	{
		if (theSocketStruct->mExpectedCode != 0 && code == theSocketStruct->mExpectedCode)
		{
			theSocketStruct->mAsyncOperationResult = result;
			
			theSocketStruct->mExpectedCode = 0;
		}
		
		
		switch (code) 
		{
			case T_OPENCOMPLETE:
			{
				theSocketStruct->mReceivedTOpenComplete = true;
				
				theSocketStruct->mEndPointRef = (EndpointRef) cookie;
				
				break;
			}

			
			case T_BINDCOMPLETE:
			{
				theSocketStruct->mReceivedTBindComplete = true;
				
				break;
			}
			

			case T_CONNECT:
			{
				theSocketStruct->mReceivedTConnect = true;

				theSocketStruct->mLocalEndIsConnected = true;
				
				theSocketStruct->mRemoteEndIsConnected = true;

				break;
			}
			

			case T_LISTEN:
			{
				theSocketStruct->mReceivedTListen = true;
				
				break;
			}
			

			case T_PASSCON:
			{
				theSocketStruct->mReceivedTPassCon = true;
				
				theSocketStruct->mLocalEndIsConnected = true;
				
				theSocketStruct->mRemoteEndIsConnected = true;

				break;
			}


			case T_DATA:
			{
				theSocketStruct->mReadyToReadData = true;
				
				break;
			}
			
			case T_GODATA:
			{
				theSocketStruct->mReadyToWriteData = true;
				
				break;
			}
			
			case T_DISCONNECT:
			{
				theSocketStruct->mReceivedTDisconnect = true;
				
				theSocketStruct->mRemoteEndIsConnected = false;
				
				theSocketStruct->mLocalEndIsConnected = false;
				
				::OTRcvDisconnect(theSocketStruct->mEndPointRef,nil);
				
				break;
			}

			case T_ORDREL:
			{
				theSocketStruct->mReceivedTOrdRel = true;
				
				//	We can still write data, so don't clear mRemoteEndIsConnected
				
				::OTRcvOrderlyDisconnect(theSocketStruct->mEndPointRef);
				
				break;
			}
			
			case T_DISCONNECTCOMPLETE:
			{
				theSocketStruct->mReceivedTDisconnectComplete = true;
				
				theSocketStruct->mRemoteEndIsConnected = false;
				
				theSocketStruct->mLocalEndIsConnected = false;
				
				break;
			}
		}
	}
/*
T_LISTEN OTListen
T_CONNECT OTRcvConnect
T_DATA OTRcv, OTRcvUData
T_DISCONNECT OTRcvDisconnect
T_ORDREL OTRcvOrderlyDisconnect
T_GODATA OTSnd, OTSndUData, OTLook
T_PASSCON none

T_EXDATA OTRcv
T_GOEXDATA OTSnd, OTLook
T_UDERR OTRcvUDErr
*/
}



//	Initialize the main socket data structure

OSErr MacSocket_Startup(void)
{
	if (!sSocketsSetup)
	{
		for (int i = 0;i < kMaxNumSockets;i++)
		{
			InitSocket(&(sSockets[i]));
		}

		::InitOpenTransport();
		
		sSocketsSetup = true;
	}
	
	
	return(noErr);
}



//	Cleanup before exiting

OSErr MacSocket_Shutdown(void)
{
	if (sSocketsSetup)
	{
		for (int i = 0;i < kMaxNumSockets;i++)
		{
		SocketStruct *theSocketStruct = &(sSockets[i]);
		
			if (theSocketStruct->mIsInUse)
			{
				if (theSocketStruct->mEndPointRef != kOTInvalidEndpointRef)
				{
				OTResult	theOTResult;
				
				
					//	Since we're killing the endpoint, I don't bother to send the disconnect (sorry!)

/*
					if (theSocketStruct->mLocalEndIsConnected)
					{
						//	This is an abortive action, so we do a hard disconnect instead of an OTSndOrderlyDisconnect
						
						theOTResult = ::OTSndDisconnect(theSocketStruct->mEndPointRef, nil);
						
						//	Now we have to watch for T_DISCONNECTCOMPLETE event
						
						theSocketStruct->mLocalEndIsConnected = false;
					}
*/					
					
					theOTResult = ::OTCloseProvider(theSocketStruct->mEndPointRef);
					
					
					theSocketStruct->mEndPointRef = kOTInvalidEndpointRef;
				}
				
				if (theSocketStruct->mBindRequestedAddrInfo != nil)
				{
					::OTFree((void *) theSocketStruct->mBindRequestedAddrInfo,T_BIND);
					
					theSocketStruct->mBindRequestedAddrInfo = nil;
				}
				
				if (theSocketStruct->mAssignedAddrInfo != nil)
				{
					::OTFree((void *) theSocketStruct->mAssignedAddrInfo,T_BIND);
					
					theSocketStruct->mAssignedAddrInfo = nil;
				}
				
				if (theSocketStruct->mRemoteAddrInfo != nil)
				{
					::OTFree((void *) theSocketStruct->mRemoteAddrInfo,T_CALL);
					
					theSocketStruct->mRemoteAddrInfo = nil;
				}
				
				
			}
		}
		
		::CloseOpenTransport();

		sSocketsSetup = false;
	}
	
	return(noErr);
}






//	Allocate a socket

OSErr MacSocket_socket(int *outSocketNum,const Boolean inDoThreadSwitching,const long inTimeoutTicks,MacSocket_IdleWaitCallback inIdleWaitCallback,void *inUserRefPtr)
{
//	Gotta roll support back in for threads eventually.....

#pragma unused(inDoThreadSwitching)


OSErr	errCode = noErr;

	
	SetErrorMessageAndBailIfNil(outSocketNum,"MacSocket_socket: Bad parameter, outSocketNum == nil");
	
	*outSocketNum = -1;
	
	
	//	Find an unused socket
	
	for (int i = 0;i < kMaxNumSockets;i++)
	{
		if (sSockets[i].mIsInUse == false)
		{
		OTResult		theOTResult;
		SocketStruct	*theSocketStruct = &(sSockets[i]);
		
			
			InitSocket(theSocketStruct);
			
			theSocketStruct->mIdleWaitCallback = inIdleWaitCallback;
			theSocketStruct->mUserRefPtr = inUserRefPtr;
			
			theSocketStruct->mTimeoutTicks = inTimeoutTicks;
			

			//	Set up OT endpoint
			
			PrepareForAsyncOperation(theSocketStruct,T_OPENCOMPLETE);
			
			theOTResult = ::OTAsyncOpenEndpoint(OTCreateConfiguration(kTCPName),0,nil,OTNonYieldingNotifier,(void *) theSocketStruct);
			
			SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_socket: Can't create OT endpoint, OTAsyncOpenEndpoint() = ",theOTResult);
			
			BailIfError(MyBusyWait(theSocketStruct,false,&theOTResult,&(theSocketStruct->mReceivedTOpenComplete)));
																						
			SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_socket: Can't create OT endpoint, OTAsyncOpenEndpoint() = ",theOTResult);
			
			
			*outSocketNum = i;
			
			errCode = noErr;
			
			theSocketStruct->mIsInUse = true;
			
			break;
		}
		
		else if (i == kMaxNumSockets - 1)
		{
			SetErrorMessageAndBail("MacSocket_socket: No sockets available");
		}
	}


EXITPOINT:
	
	errno = errCode;
	
	return(errCode);
}




OSErr MacSocket_listen(const int inSocketNum,const int inPortNum)
{
OSErr			errCode = noErr;
SocketStruct	*theSocketStruct = nil;


	if (!SocketIndexIsValid(inSocketNum))
	{
		SetErrorMessageAndBail("MacSocket_listen: Invalid socket number specified");
	}


	theSocketStruct = &(sSockets[inSocketNum]);


OTResult		theOTResult;
	
	
	if (theSocketStruct->mBindRequestedAddrInfo == nil)
	{
		theSocketStruct->mBindRequestedAddrInfo = (TBind *) ::OTAlloc(theSocketStruct->mEndPointRef,T_BIND,T_ADDR,&theOTResult);
																					
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_listen: Can't allocate OT T_BIND structure, OTAlloc() = ",theOTResult);
		SetErrorMessageAndBailIfNil(theSocketStruct->mBindRequestedAddrInfo,"MacSocket_listen: Can't allocate OT T_BIND structure, OTAlloc() returned nil");
	}
	
	if (theSocketStruct->mAssignedAddrInfo == nil)
	{
		theSocketStruct->mAssignedAddrInfo = (TBind *) ::OTAlloc(theSocketStruct->mEndPointRef,T_BIND,T_ADDR,&theOTResult);
																					
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_listen: Can't allocate OT T_BIND structure, OTAlloc() = ",theOTResult);
		SetErrorMessageAndBailIfNil(theSocketStruct->mAssignedAddrInfo,"MacSocket_listen: Can't allocate OT T_BIND structure, OTAlloc() returned nil");
	}
	
	if (theSocketStruct->mRemoteAddrInfo == nil)
	{
		theSocketStruct->mRemoteAddrInfo = (TCall *) ::OTAlloc(theSocketStruct->mEndPointRef,T_CALL,T_ADDR,&theOTResult);
																					
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_listen: Can't allocate OT T_CALL structure, OTAlloc() = ",theOTResult);
		SetErrorMessageAndBailIfNil(theSocketStruct->mRemoteAddrInfo,"MacSocket_listen: Can't allocate OT T_CALL structure, OTAlloc() returned nil");
	}
	

	if (!theSocketStruct->mEndpointIsBound)
	{
	InetInterfaceInfo	theInetInterfaceInfo;
		
		theOTResult = ::OTInetGetInterfaceInfo(&theInetInterfaceInfo,kDefaultInetInterface);
																					
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_listen: Can't determine OT interface info, OTInetGetInterfaceInfo() = ",theOTResult);


	InetAddress	*theInetAddress = (InetAddress *) theSocketStruct->mBindRequestedAddrInfo->addr.buf;
		
//		theInetAddress->fAddressType = AF_INET;
//		theInetAddress->fPort = inPortNum;
//		theInetAddress->fHost = theInetInterfaceInfo.fAddress;
		
		::OTInitInetAddress(theInetAddress,inPortNum,theInetInterfaceInfo.fAddress);

		theSocketStruct->mBindRequestedAddrInfo->addr.len = sizeof(InetAddress);
		
		theSocketStruct->mBindRequestedAddrInfo->qlen = 1;
		
		
		theOTResult = ::OTSetSynchronous(theSocketStruct->mEndPointRef);
																					
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_listen: Can't set OT endpoint mode, OTSetSynchronous() = ",theOTResult);
		
		theOTResult = NegotiateIPReuseAddrOption(theSocketStruct->mEndPointRef,true);
																					
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_listen: Can't set OT IP address reuse flag, NegotiateIPReuseAddrOption() = ",theOTResult);
		
		theOTResult = ::OTSetAsynchronous(theSocketStruct->mEndPointRef);
																					
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_listen: Can't set OT endpoint mode, OTSetAsynchronous() = ",theOTResult);

		
		PrepareForAsyncOperation(theSocketStruct,T_BINDCOMPLETE);
				
		theOTResult = ::OTBind(theSocketStruct->mEndPointRef,theSocketStruct->mBindRequestedAddrInfo,theSocketStruct->mAssignedAddrInfo);
																					
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_listen: Can't bind OT endpoint, OTBind() = ",theOTResult);
		
		BailIfError(MyBusyWait(theSocketStruct,false,&theOTResult,&(theSocketStruct->mReceivedTBindComplete)));
																					
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_listen: Can't bind OT endpoint, OTBind() = ",theOTResult);
		
		
		theSocketStruct->mEndpointIsBound = true;
	}


	PrepareForAsyncOperation(theSocketStruct,T_LISTEN);

	theOTResult = ::OTListen(theSocketStruct->mEndPointRef,theSocketStruct->mRemoteAddrInfo);
	
	if (theOTResult == noErr)
	{
		PrepareForAsyncOperation(theSocketStruct,T_PASSCON);
		
		theOTResult = ::OTAccept(theSocketStruct->mEndPointRef,theSocketStruct->mEndPointRef,theSocketStruct->mRemoteAddrInfo);
		
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_listen: Can't begin OT accept, OTAccept() = ",theOTResult);
		
		BailIfError(MyBusyWait(theSocketStruct,false,&theOTResult,&(theSocketStruct->mReceivedTPassCon)));
																					
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_listen: Can't accept OT connection, OTAccept() = ",theOTResult);
	}
	
	else if (theOTResult == kOTNoDataErr)
	{
		theOTResult = noErr;
	}
	
	else
	{
		SetErrorMessageAndLongIntAndBail("MacSocket_listen: Can't begin OT listen, OTListen() = ",theOTResult);
	}


	errCode = noErr;


EXITPOINT:
	
	if (theSocketStruct != nil)
	{
		theSocketStruct->mLastError = noErr;
		
		CopyCStrToCStr("",theSocketStruct->mErrMessage,sizeof(theSocketStruct->mErrMessage));

		if (errCode != noErr)
		{
			theSocketStruct->mLastError = errCode;
			
			CopyCStrToCStr(GetErrorMessage(),theSocketStruct->mErrMessage,sizeof(theSocketStruct->mErrMessage));
		}
	}
	
	errno = errCode;
	
	return(errCode);
}




OSErr MacSocket_connect(const int inSocketNum,char *inTargetAddressAndPort)
{
OSErr			errCode = noErr;
SocketStruct	*theSocketStruct = nil;


	if (!SocketIndexIsValid(inSocketNum))
	{
		SetErrorMessageAndBail("MacSocket_connect: Invalid socket number specified");
	}

	theSocketStruct = &(sSockets[inSocketNum]);

	if (theSocketStruct->mEndpointIsBound)
	{
		SetErrorMessageAndBail("MacSocket_connect: Socket previously bound");
	}

	
OTResult		theOTResult;

	theSocketStruct->mBindRequestedAddrInfo = (TBind *) ::OTAlloc(theSocketStruct->mEndPointRef,T_BIND,T_ADDR,&theOTResult);
																				
	SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_connect: Can't allocate OT T_BIND structure, OTAlloc() = ",theOTResult);
	SetErrorMessageAndBailIfNil(theSocketStruct->mBindRequestedAddrInfo,"MacSocket_connect: Can't allocate OT T_BIND structure, OTAlloc() returned nil");
	

	theSocketStruct->mAssignedAddrInfo = (TBind *) ::OTAlloc(theSocketStruct->mEndPointRef,T_BIND,T_ADDR,&theOTResult);
																				
	SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_connect: Can't allocate OT T_BIND structure, OTAlloc() = ",theOTResult);
	SetErrorMessageAndBailIfNil(theSocketStruct->mAssignedAddrInfo,"MacSocket_connect: Can't allocate OT T_BIND structure, OTAlloc() returned nil");


	theSocketStruct->mRemoteAddrInfo = (TCall *) ::OTAlloc(theSocketStruct->mEndPointRef,T_CALL,T_ADDR,&theOTResult);
																				
	SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_connect: Can't allocate OT T_CALL structure, OTAlloc() = ",theOTResult);
	SetErrorMessageAndBailIfNil(theSocketStruct->mRemoteAddrInfo,"MacSocket_connect: Can't allocate OT T_CALL structure, OTAlloc() returned nil");

	
	PrepareForAsyncOperation(theSocketStruct,T_BINDCOMPLETE);

	theOTResult = ::OTBind(theSocketStruct->mEndPointRef,nil,theSocketStruct->mAssignedAddrInfo);
																				
	SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_connect: Can't bind OT endpoint, OTBind() = ",theOTResult);
	
	BailIfError(MyBusyWait(theSocketStruct,false,&theOTResult,&(theSocketStruct->mReceivedTBindComplete)));
																				
	SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_connect: Can't bind OT endpoint, OTBind() = ",theOTResult);
	
	theSocketStruct->mEndpointIsBound = true;
	

TCall		sndCall;
DNSAddress 	hostDNSAddress;
	
	//	Set up target address
	
	sndCall.addr.buf = (UInt8 *) &hostDNSAddress;
	sndCall.addr.len = ::OTInitDNSAddress(&hostDNSAddress,inTargetAddressAndPort);
	sndCall.opt.buf = nil;
	sndCall.opt.len = 0;
	sndCall.udata.buf = nil;
	sndCall.udata.len = 0;
	sndCall.sequence = 0;
		
	//	Connect!
	
	PrepareForAsyncOperation(theSocketStruct,T_CONNECT);

	theOTResult = ::OTConnect(theSocketStruct->mEndPointRef,&sndCall,nil);
	
	if (theOTResult == kOTNoDataErr)
	{
		theOTResult = noErr;
	}
												
	SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_connect: Can't connect OT endpoint, OTConnect() = ",theOTResult);
	
	BailIfError(MyBusyWait(theSocketStruct,false,&theOTResult,&(theSocketStruct->mReceivedTConnect)));
	
	if (theOTResult == kMacSocket_TimeoutErr)
	{
		SetErrorMessageAndBail("MacSocket_connect: Can't connect OT endpoint, OTConnect() = kMacSocket_TimeoutErr");
	}
	
	else
	{
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_connect: Can't connect OT endpoint, OTConnect() = ",theOTResult);
	}

	theOTResult = ::OTRcvConnect(theSocketStruct->mEndPointRef,nil);
												
	SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_connect: Can't complete connect on OT endpoint, OTRcvConnect() = ",theOTResult);


	errCode = noErr;


#ifdef MACSOCKET_DEBUG
	printf("MacSocket_connect: connect completed\n");
#endif

EXITPOINT:
	
	if (theSocketStruct != nil)
	{
		theSocketStruct->mLastError = noErr;
		
		CopyCStrToCStr("",theSocketStruct->mErrMessage,sizeof(theSocketStruct->mErrMessage));

		if (errCode != noErr)
		{
			theSocketStruct->mLastError = errCode;
			
			CopyCStrToCStr(GetErrorMessage(),theSocketStruct->mErrMessage,sizeof(theSocketStruct->mErrMessage));
		}
	}
	
	errno = errCode;
	
	return(errCode);
}




//	Close a connection

OSErr MacSocket_close(const int inSocketNum)
{
OSErr			errCode = noErr;
SocketStruct	*theSocketStruct = nil;


	if (!SocketIndexIsValid(inSocketNum))
	{
		SetErrorMessageAndBail("MacSocket_close: Invalid socket number specified");
	}


	theSocketStruct = &(sSockets[inSocketNum]);
	
	if (theSocketStruct->mEndPointRef != kOTInvalidEndpointRef)
	{
	OTResult		theOTResult = noErr;
	
		//	Try to play nice
		
		if (theSocketStruct->mReceivedTOrdRel)
		{
			//	Already did an OTRcvOrderlyDisconnect() in the notifier
		
			if (theSocketStruct->mLocalEndIsConnected)
			{
				theOTResult = ::OTSndOrderlyDisconnect(theSocketStruct->mEndPointRef);
				
				theSocketStruct->mLocalEndIsConnected = false;
			}
		}
		
		else if (theSocketStruct->mLocalEndIsConnected)
		{
			theOTResult = ::OTSndOrderlyDisconnect(theSocketStruct->mEndPointRef);
			
			theSocketStruct->mLocalEndIsConnected = false;
			
			//	Wait for other end to hang up too!
			
//			PrepareForAsyncOperation(theSocketStruct,T_ORDREL);
//
//			errCode = MyBusyWait(theSocketStruct,false,&theOTResult,&(theSocketStruct->mReceivedTOrdRel));
		}
		
		
		if (theOTResult != noErr)
		{
			::OTCloseProvider(theSocketStruct->mEndPointRef);
		}
		
		else
		{
			theOTResult = ::OTCloseProvider(theSocketStruct->mEndPointRef);
		}

		theSocketStruct->mEndPointRef = kOTInvalidEndpointRef;
		
		errCode = theOTResult;
	}


	theSocketStruct->mIsInUse = false;

	
EXITPOINT:
	
	if (theSocketStruct != nil)
	{
		theSocketStruct->mLastError = noErr;
		
		CopyCStrToCStr("",theSocketStruct->mErrMessage,sizeof(theSocketStruct->mErrMessage));

		if (errCode != noErr)
		{
			theSocketStruct->mLastError = errCode;
			
			CopyCStrToCStr(GetErrorMessage(),theSocketStruct->mErrMessage,sizeof(theSocketStruct->mErrMessage));
		}
	}

	errno = errCode;
		
	return(errCode);
}




//	Receive some bytes

int MacSocket_recv(const int inSocketNum,void *outBuff,int outBuffLength,const Boolean inBlock)
{
OSErr			errCode = noErr;
int				totalBytesRead = 0;
SocketStruct	*theSocketStruct = nil;

	
	SetErrorMessageAndBailIfNil(outBuff,"MacSocket_recv: Bad parameter, outBuff = nil");
	
	if (outBuffLength <= 0)
	{
		SetErrorMessageAndBail("MacSocket_recv: Bad parameter, outBuffLength <= 0");
	}
	
	if (!SocketIndexIsValid(inSocketNum))
	{
		SetErrorMessageAndBail("MacSocket_recv: Invalid socket number specified");
	}

	theSocketStruct = &(sSockets[inSocketNum]);

	if (!theSocketStruct->mLocalEndIsConnected)
	{
		SetErrorMessageAndBail("MacSocket_recv: Socket not connected");
	}

	if (theSocketStruct->mReceivedTOrdRel)
	{
		totalBytesRead = 0;
		
		goto EXITPOINT;
	}

	
	PrepareForAsyncOperation(theSocketStruct,0);
	
	for (;;)
	{
	int			bytesRead;
	OTResult	theOTResult;
	
	
		theOTResult = ::OTRcv(theSocketStruct->mEndPointRef,(void *) ((unsigned long) outBuff + (unsigned long) totalBytesRead),outBuffLength - totalBytesRead,nil);
		
		if (theOTResult >= 0)
		{
			bytesRead = theOTResult;
			
#ifdef MACSOCKET_DEBUG
	printf("MacSocket_recv: read %d bytes in part\n",bytesRead);
#endif
		}
		
		else if (theOTResult == kOTNoDataErr)
		{
			bytesRead = 0;
		}
		
		else
		{
			SetErrorMessageAndLongIntAndBail("MacSocket_recv: Can't receive OT data, OTRcv() = ",theOTResult);
		}
		
		
		totalBytesRead += bytesRead;
		
		
		if (totalBytesRead <= 0)
		{
			if (theSocketStruct->mReceivedTOrdRel)
			{
				break;
			}
			
			//	This seems pretty stupid to me now.  Maybe I'll delete this blocking garbage.
			
			if (inBlock)
			{
				if (TimeoutElapsed(theSocketStruct))
				{
					SetErrorCodeAndMessageAndBail(kMacSocket_TimeoutErr,"MacSocket_recv: Receive operation timed-out");
				}
				
				if (theSocketStruct->mIdleWaitCallback != nil)
				{
					theOTResult = (*(theSocketStruct->mIdleWaitCallback))(theSocketStruct->mUserRefPtr);
					
					SetErrorMessageAndBailIfError(theOTResult,"MacSocket_recv: User cancelled operation");
				}
				
				continue;
			}
		}
		
		
		break;
	}
	
	errCode = noErr;


#ifdef MACSOCKET_DEBUG
	printf("MacSocket_recv: read %d bytes in total\n",totalBytesRead);
#endif
	
	
EXITPOINT:
	
	if (theSocketStruct != nil)
	{
		theSocketStruct->mLastError = noErr;
		
		CopyCStrToCStr("",theSocketStruct->mErrMessage,sizeof(theSocketStruct->mErrMessage));

		if (errCode != noErr)
		{
			theSocketStruct->mLastError = errCode;
			
			CopyCStrToCStr(GetErrorMessage(),theSocketStruct->mErrMessage,sizeof(theSocketStruct->mErrMessage));
		}
	}

	errno = errCode;
	
	return(totalBytesRead);
}



//	Send some bytes

int MacSocket_send(const int inSocketNum,const void *inBuff,int inBuffLength)
{
OSErr			errCode = noErr;
int				bytesSent = 0;
SocketStruct	*theSocketStruct = nil;


	SetErrorMessageAndBailIfNil(inBuff,"MacSocket_send: Bad parameter, inBuff = nil");
	
	if (inBuffLength <= 0)
	{
		SetErrorMessageAndBail("MacSocket_send: Bad parameter, inBuffLength <= 0");
	}

	if (!SocketIndexIsValid(inSocketNum))
	{
		SetErrorMessageAndBail("MacSocket_send: Invalid socket number specified");
	}
	

	theSocketStruct = &(sSockets[inSocketNum]);
	
	if (!theSocketStruct->mLocalEndIsConnected)
	{
		SetErrorMessageAndBail("MacSocket_send: Socket not connected");
	}


OTResult		theOTResult;
	

	PrepareForAsyncOperation(theSocketStruct,0);

	while (bytesSent < inBuffLength)
	{
		if (theSocketStruct->mIdleWaitCallback != nil)
		{
			theOTResult = (*(theSocketStruct->mIdleWaitCallback))(theSocketStruct->mUserRefPtr);
			
			SetErrorMessageAndBailIfError(theOTResult,"MacSocket_send: User cancelled");
		}


		theOTResult = ::OTSnd(theSocketStruct->mEndPointRef,(void *) ((unsigned long) inBuff + bytesSent),inBuffLength - bytesSent,0);
		
		if (theOTResult >= 0)
		{
			bytesSent += theOTResult;
			
			theOTResult = noErr;
			
			//	Reset timer....
			
			PrepareForAsyncOperation(theSocketStruct,0);
		}
		
		if (theOTResult == kOTFlowErr)
		{
			if (TimeoutElapsed(theSocketStruct))
			{
				SetErrorCodeAndMessageAndBail(kMacSocket_TimeoutErr,"MacSocket_send: Send timed-out")
			}

			theOTResult = noErr;
		}
													
		SetErrorMessageAndLongIntAndBailIfError(theOTResult,"MacSocket_send: Can't send OT data, OTSnd() = ",theOTResult);
	}

	
	errCode = noErr;

#ifdef MACSOCKET_DEBUG
	printf("MacSocket_send: sent %d bytes\n",bytesSent);
#endif
	
	
EXITPOINT:
	
	if (theSocketStruct != nil)
	{
		theSocketStruct->mLastError = noErr;
		
		CopyCStrToCStr("",theSocketStruct->mErrMessage,sizeof(theSocketStruct->mErrMessage));

		if (errCode != noErr)
		{
			theSocketStruct->mLastError = errCode;
			
			CopyCStrToCStr(GetErrorMessage(),theSocketStruct->mErrMessage,sizeof(theSocketStruct->mErrMessage));
		}
	}
	
	if (errCode != noErr)
	{
		::SysBeep(1);
	}
	
	errno = errCode;
	
	return(bytesSent);
}





static OSStatus NegotiateIPReuseAddrOption(EndpointRef inEndpoint,const Boolean inEnableReuseIP)
{
OSStatus	errCode;
UInt8		buf[kOTFourByteOptionSize];
TOption*	theOTOption;
TOptMgmt	theOTRequest;
TOptMgmt	theOTResult;
	

	if (!OTIsSynchronous(inEndpoint))
	{
		SetErrorMessageAndBail("NegotiateIPReuseAddrOption: Open Transport endpoint is not synchronous");
	}
	
	theOTRequest.opt.buf = buf;
	theOTRequest.opt.len = sizeof(buf);
	theOTRequest.flags = T_NEGOTIATE;

	theOTResult.opt.buf = buf;
	theOTResult.opt.maxlen = kOTFourByteOptionSize;


	theOTOption = (TOption *) buf;
	
	theOTOption->level = INET_IP;
	theOTOption->name = IP_REUSEADDR;
	theOTOption->len = kOTFourByteOptionSize;
	theOTOption->status = 0;
	*((UInt32 *) (theOTOption->value)) = inEnableReuseIP;

	errCode = ::OTOptionManagement(inEndpoint,&theOTRequest,&theOTResult);
	
	if (errCode == kOTNoError)
	{
		if (theOTOption->status != T_SUCCESS)
		{
			errCode = theOTOption->status;
		}
		
		else
		{
			errCode = kOTNoError;
		}
	}
				

EXITPOINT:
	
	errno = errCode;
	
	return(errCode);
}





//	Some rough notes....



//	OTAckSends(ep);
//	OTAckSends(ep) // enable AckSend option
//	......
//	buf = OTAllocMem( nbytes); // Allocate nbytes of memory from OT
//	OTSnd(ep, buf, nbytes, 0); // send a packet
//	......
//	NotifyProc( .... void* theParam) // Notifier Proc
//	case T_MEMORYRELEASED: // process event
//	OTFreeMem( theParam); // free up memory
//	break;



/*
struct InetInterfaceInfo
{
	InetHost		fAddress;
	InetHost		fNetmask;
	InetHost		fBroadcastAddr;
	InetHost		fDefaultGatewayAddr;
	InetHost		fDNSAddr;
	UInt16			fVersion;
	UInt16			fHWAddrLen;
	UInt8*			fHWAddr;
	UInt32			fIfMTU;
	UInt8*			fReservedPtrs[2];
	InetDomainName	fDomainName;
	UInt32			fIPSecondaryCount;
	UInt8			fReserved[252];			
};
typedef struct InetInterfaceInfo InetInterfaceInfo;



((InetAddress *) addr.buf)->fHost

struct TBind
{
	TNetbuf	addr;
	OTQLen	qlen;
};

typedef struct TBind	TBind;

struct TNetbuf
{
	size_t	maxlen;
	size_t	len;
	UInt8*	buf;
};

typedef struct TNetbuf	TNetbuf;

	
	struct InetAddress
{
		OTAddressType	fAddressType;	// always AF_INET
		InetPort		fPort;			// Port number 
		InetHost		fHost;			// Host address in net byte order
		UInt8			fUnused[8];		// Traditional unused bytes
};
typedef struct InetAddress InetAddress;
*/



/*
static pascal void Notifier(void* context, OTEventCode event, OTResult result, void* cookie)
{
EPInfo* epi = (EPInfo*) context;

	switch (event)
	{
		case T_LISTEN:
		{
			DoListenAccept();
			return;
		}
		
		case T_ACCEPTCOMPLETE:
		{
			if (result != kOTNoError)
				DBAlert1("Notifier: T_ACCEPTCOMPLETE - result %d",result);
			return;
		}
		
		case T_PASSCON:
		{
			if (result != kOTNoError)
			{
				DBAlert1("Notifier: T_PASSCON result %d", result);
				return;
			}

			OTAtomicAdd32(1, &gCntrConnections);
			OTAtomicAdd32(1, &gCntrTotalConnections);
			OTAtomicAdd32(1, &gCntrIntervalConnects);
			
			if ( OTAtomicSetBit(&epi->stateFlags, kPassconBit) != 0 )
			{
				ReadData(epi);
			}
			
			return;
		}
		
		case T_DATA:
		{
			if ( OTAtomicSetBit(&epi->stateFlags, kPassconBit) != 0 )
			{
				ReadData(epi);
			}
			
			return;
		}
		
		case T_GODATA:
		{
			SendData(epi);
			return;
		}
		
		case T_DISCONNECT:
		{
			DoRcvDisconnect(epi);
			return;
		}
		
		case T_DISCONNECTCOMPLETE:
		{
			if (result != kOTNoError)
				DBAlert1("Notifier: T_DISCONNECT_COMPLETE result %d",result);
				
			return;
		}
		
		case T_MEMORYRELEASED:
		{
			OTAtomicAdd32(-1, &epi->outstandingSends);
			return;
		}
		
		default:
		{
			DBAlert1("Notifier: unknown event <%x>", event);
			return;
		}
	}
}
*/