aboutsummaryrefslogtreecommitdiff
path: root/openssl/trunk/crypto/dsa/dsa.h
diff options
context:
space:
mode:
Diffstat (limited to 'openssl/trunk/crypto/dsa/dsa.h')
-rw-r--r--openssl/trunk/crypto/dsa/dsa.h279
1 files changed, 279 insertions, 0 deletions
diff --git a/openssl/trunk/crypto/dsa/dsa.h b/openssl/trunk/crypto/dsa/dsa.h
new file mode 100644
index 00000000..b12db98b
--- /dev/null
+++ b/openssl/trunk/crypto/dsa/dsa.h
@@ -0,0 +1,279 @@
+/* crypto/dsa/dsa.h */
+/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
+ * All rights reserved.
+ *
+ * This package is an SSL implementation written
+ * by Eric Young (eay@cryptsoft.com).
+ * The implementation was written so as to conform with Netscapes SSL.
+ *
+ * This library is free for commercial and non-commercial use as long as
+ * the following conditions are aheared to. The following conditions
+ * apply to all code found in this distribution, be it the RC4, RSA,
+ * lhash, DES, etc., code; not just the SSL code. The SSL documentation
+ * included with this distribution is covered by the same copyright terms
+ * except that the holder is Tim Hudson (tjh@cryptsoft.com).
+ *
+ * Copyright remains Eric Young's, and as such any Copyright notices in
+ * the code are not to be removed.
+ * If this package is used in a product, Eric Young should be given attribution
+ * as the author of the parts of the library used.
+ * This can be in the form of a textual message at program startup or
+ * in documentation (online or textual) provided with the package.
+ *
+ * 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 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 acknowledgement:
+ * "This product includes cryptographic software written by
+ * Eric Young (eay@cryptsoft.com)"
+ * The word 'cryptographic' can be left out if the rouines from the library
+ * being used are not cryptographic related :-).
+ * 4. If you include any Windows specific code (or a derivative thereof) from
+ * the apps directory (application code) you must include an acknowledgement:
+ * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
+ * ANY EXPRESS 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 AUTHOR OR 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.
+ *
+ * The licence and distribution terms for any publically available version or
+ * derivative of this code cannot be changed. i.e. this code cannot simply be
+ * copied and put under another distribution licence
+ * [including the GNU Public Licence.]
+ */
+
+/*
+ * The DSS routines are based on patches supplied by
+ * Steven Schoch <schoch@sheba.arc.nasa.gov>. He basically did the
+ * work and I have just tweaked them a little to fit into my
+ * stylistic vision for SSLeay :-) */
+
+#ifndef HEADER_DSA_H
+#define HEADER_DSA_H
+
+#include <openssl/e_os2.h>
+
+#ifdef OPENSSL_NO_DSA
+#error DSA is disabled.
+#endif
+
+#ifndef OPENSSL_NO_BIO
+#include <openssl/bio.h>
+#endif
+#include <openssl/crypto.h>
+#include <openssl/ossl_typ.h>
+
+#ifndef OPENSSL_NO_DEPRECATED
+#include <openssl/bn.h>
+#ifndef OPENSSL_NO_DH
+# include <openssl/dh.h>
+#endif
+#endif
+
+#define DSA_FLAG_CACHE_MONT_P 0x01
+#define DSA_FLAG_NO_EXP_CONSTTIME 0x02 /* new with 0.9.7h; the built-in DSA
+ * implementation now uses constant time
+ * modular exponentiation for secret exponents
+ * by default. This flag causes the
+ * faster variable sliding window method to
+ * be used for all exponents.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Already defined in ossl_typ.h */
+/* typedef struct dsa_st DSA; */
+/* typedef struct dsa_method DSA_METHOD; */
+
+typedef struct DSA_SIG_st
+ {
+ BIGNUM *r;
+ BIGNUM *s;
+ } DSA_SIG;
+
+struct dsa_method
+ {
+ const char *name;
+ DSA_SIG * (*dsa_do_sign)(const unsigned char *dgst, int dlen, DSA *dsa);
+ int (*dsa_sign_setup)(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
+ BIGNUM **rp);
+ int (*dsa_do_verify)(const unsigned char *dgst, int dgst_len,
+ DSA_SIG *sig, DSA *dsa);
+ int (*dsa_mod_exp)(DSA *dsa, BIGNUM *rr, BIGNUM *a1, BIGNUM *p1,
+ BIGNUM *a2, BIGNUM *p2, BIGNUM *m, BN_CTX *ctx,
+ BN_MONT_CTX *in_mont);
+ int (*bn_mod_exp)(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p,
+ const BIGNUM *m, BN_CTX *ctx,
+ BN_MONT_CTX *m_ctx); /* Can be null */
+ int (*init)(DSA *dsa);
+ int (*finish)(DSA *dsa);
+ int flags;
+ char *app_data;
+ /* If this is non-NULL, it is used to generate DSA parameters */
+ int (*dsa_paramgen)(DSA *dsa, int bits,
+ unsigned char *seed, int seed_len,
+ int *counter_ret, unsigned long *h_ret,
+ BN_GENCB *cb);
+ /* If this is non-NULL, it is used to generate DSA keys */
+ int (*dsa_keygen)(DSA *dsa);
+ };
+
+struct dsa_st
+ {
+ /* This first variable is used to pick up errors where
+ * a DSA is passed instead of of a EVP_PKEY */
+ int pad;
+ long version;
+ int write_params;
+ BIGNUM *p;
+ BIGNUM *q; /* == 20 */
+ BIGNUM *g;
+
+ BIGNUM *pub_key; /* y public key */
+ BIGNUM *priv_key; /* x private key */
+
+ BIGNUM *kinv; /* Signing pre-calc */
+ BIGNUM *r; /* Signing pre-calc */
+
+ int flags;
+ /* Normally used to cache montgomery values */
+ BN_MONT_CTX *method_mont_p;
+ int references;
+ CRYPTO_EX_DATA ex_data;
+ const DSA_METHOD *meth;
+ /* functional reference if 'meth' is ENGINE-provided */
+ ENGINE *engine;
+ };
+
+#define DSAparams_dup(x) ASN1_dup_of_const(DSA,i2d_DSAparams,d2i_DSAparams,x)
+#define d2i_DSAparams_fp(fp,x) (DSA *)ASN1_d2i_fp((char *(*)())DSA_new, \
+ (char *(*)())d2i_DSAparams,(fp),(unsigned char **)(x))
+#define i2d_DSAparams_fp(fp,x) ASN1_i2d_fp(i2d_DSAparams,(fp), \
+ (unsigned char *)(x))
+#define d2i_DSAparams_bio(bp,x) ASN1_d2i_bio_of(DSA,DSA_new,d2i_DSAparams,bp,x)
+#define i2d_DSAparams_bio(bp,x) ASN1_i2d_bio_of_const(DSA,i2d_DSAparams,bp,x)
+
+
+DSA_SIG * DSA_SIG_new(void);
+void DSA_SIG_free(DSA_SIG *a);
+int i2d_DSA_SIG(const DSA_SIG *a, unsigned char **pp);
+DSA_SIG * d2i_DSA_SIG(DSA_SIG **v, const unsigned char **pp, long length);
+
+DSA_SIG * DSA_do_sign(const unsigned char *dgst,int dlen,DSA *dsa);
+int DSA_do_verify(const unsigned char *dgst,int dgst_len,
+ DSA_SIG *sig,DSA *dsa);
+
+const DSA_METHOD *DSA_OpenSSL(void);
+
+void DSA_set_default_method(const DSA_METHOD *);
+const DSA_METHOD *DSA_get_default_method(void);
+int DSA_set_method(DSA *dsa, const DSA_METHOD *);
+
+DSA * DSA_new(void);
+DSA * DSA_new_method(ENGINE *engine);
+void DSA_free (DSA *r);
+/* "up" the DSA object's reference count */
+int DSA_up_ref(DSA *r);
+int DSA_size(const DSA *);
+ /* next 4 return -1 on error */
+int DSA_sign_setup( DSA *dsa,BN_CTX *ctx_in,BIGNUM **kinvp,BIGNUM **rp);
+int DSA_sign(int type,const unsigned char *dgst,int dlen,
+ unsigned char *sig, unsigned int *siglen, DSA *dsa);
+int DSA_verify(int type,const unsigned char *dgst,int dgst_len,
+ const unsigned char *sigbuf, int siglen, DSA *dsa);
+int DSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
+ CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func);
+int DSA_set_ex_data(DSA *d, int idx, void *arg);
+void *DSA_get_ex_data(DSA *d, int idx);
+
+DSA * d2i_DSAPublicKey(DSA **a, const unsigned char **pp, long length);
+DSA * d2i_DSAPrivateKey(DSA **a, const unsigned char **pp, long length);
+DSA * d2i_DSAparams(DSA **a, const unsigned char **pp, long length);
+
+/* Deprecated version */
+#ifndef OPENSSL_NO_DEPRECATED
+DSA * DSA_generate_parameters(int bits,
+ unsigned char *seed,int seed_len,
+ int *counter_ret, unsigned long *h_ret,void
+ (*callback)(int, int, void *),void *cb_arg);
+#endif /* !defined(OPENSSL_NO_DEPRECATED) */
+
+/* New version */
+int DSA_generate_parameters_ex(DSA *dsa, int bits,
+ unsigned char *seed,int seed_len,
+ int *counter_ret, unsigned long *h_ret, BN_GENCB *cb);
+
+int DSA_generate_key(DSA *a);
+int i2d_DSAPublicKey(const DSA *a, unsigned char **pp);
+int i2d_DSAPrivateKey(const DSA *a, unsigned char **pp);
+int i2d_DSAparams(const DSA *a,unsigned char **pp);
+
+#ifndef OPENSSL_NO_BIO
+int DSAparams_print(BIO *bp, const DSA *x);
+int DSA_print(BIO *bp, const DSA *x, int off);
+#endif
+#ifndef OPENSSL_NO_FP_API
+int DSAparams_print_fp(FILE *fp, const DSA *x);
+int DSA_print_fp(FILE *bp, const DSA *x, int off);
+#endif
+
+#define DSS_prime_checks 50
+/* Primality test according to FIPS PUB 186[-1], Appendix 2.1:
+ * 50 rounds of Rabin-Miller */
+#define DSA_is_prime(n, callback, cb_arg) \
+ BN_is_prime(n, DSS_prime_checks, callback, NULL, cb_arg)
+
+#ifndef OPENSSL_NO_DH
+/* Convert DSA structure (key or just parameters) into DH structure
+ * (be careful to avoid small subgroup attacks when using this!) */
+DH *DSA_dup_DH(const DSA *r);
+#endif
+
+/* BEGIN ERROR CODES */
+/* The following lines are auto generated by the script mkerr.pl. Any changes
+ * made after this point may be overwritten when the script is next run.
+ */
+void ERR_load_DSA_strings(void);
+
+/* Error codes for the DSA functions. */
+
+/* Function codes. */
+#define DSA_F_D2I_DSA_SIG 110
+#define DSA_F_DSAPARAMS_PRINT 100
+#define DSA_F_DSAPARAMS_PRINT_FP 101
+#define DSA_F_DSA_DO_SIGN 112
+#define DSA_F_DSA_DO_VERIFY 113
+#define DSA_F_DSA_NEW_METHOD 103
+#define DSA_F_DSA_PRINT 104
+#define DSA_F_DSA_PRINT_FP 105
+#define DSA_F_DSA_SIGN 106
+#define DSA_F_DSA_SIGN_SETUP 107
+#define DSA_F_DSA_SIG_NEW 109
+#define DSA_F_DSA_VERIFY 108
+#define DSA_F_I2D_DSA_SIG 111
+#define DSA_F_SIG_CB 114
+
+/* Reason codes. */
+#define DSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE 100
+#define DSA_R_MISSING_PARAMETERS 101
+
+#ifdef __cplusplus
+}
+#endif
+#endif
a id='n579' href='#n579'>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
/*
 *	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;
		}
	}
}
*/