summaryrefslogtreecommitdiffstats
path: root/src/gui/embedded/qkbdtty_qws.cpp
blob: 2e05d2a096aa944d06d4e71e0fafb1027d2fb772 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qkbdtty_qws.h"

#if !defined(QT_NO_QWS_KEYBOARD) && !defined(QT_NO_QWS_KBD_TTY)

#include <QSocketNotifier>
#include <QStringList>

#include <qplatformdefs.h>
#include <private/qcore_unix_p.h> // overrides QT_OPEN

#include <errno.h>
#include <termios.h>

#if defined Q_OS_LINUX
#  include <linux/kd.h>
#  include <linux/vt.h> //TODO: move vt handling somewhere else (QLinuxFbScreen?)

#  include "qscreen_qws.h"
#  include "qwindowsystem_qws.h"
#  include "qapplication.h"
#  include "private/qwindowsurface_qws_p.h"
#  include "private/qwssignalhandler_p.h"

#  define VTACQSIG SIGUSR1
#  define VTRELSIG SIGUSR2
#endif


QT_BEGIN_NAMESPACE

class QWSTtyKbPrivate : public QObject
{
    Q_OBJECT
public:
    QWSTtyKbPrivate(QWSTtyKeyboardHandler *handler, const QString &device);
    ~QWSTtyKbPrivate();

private:
    void switchLed(char, bool);
    void switchConsole(int vt);

private Q_SLOTS:
    void readKeycode();
    void handleConsoleSwitch(int sig);

private:
    QWSTtyKeyboardHandler *m_handler;
    int                    m_tty_fd;
    struct termios         m_tty_attr;
    char                   m_last_keycode;
    int                    m_vt_qws;
    int                    m_orig_kbmode;
};


QWSTtyKeyboardHandler::QWSTtyKeyboardHandler(const QString &device)
    : QWSKeyboardHandler(device)
{
    d = new QWSTtyKbPrivate(this, device);
}

QWSTtyKeyboardHandler::~QWSTtyKeyboardHandler()
{
    delete d;
}

bool QWSTtyKeyboardHandler::filterKeycode(char &)
{
    return false;
}

QWSTtyKbPrivate::QWSTtyKbPrivate(QWSTtyKeyboardHandler *h, const QString &device)
    : m_handler(h), m_tty_fd(-1), m_last_keycode(0), m_vt_qws(0), m_orig_kbmode(K_XLATE)
{
    setObjectName(QLatin1String("TTY Keyboard Handler"));
#ifndef QT_NO_QWS_SIGNALHANDLER
    QWSSignalHandler::instance()->addObject(this);
#endif

    QString dev = QLatin1String("/dev/tty0");
    int repeat_delay = -1;
    int repeat_rate = -1;

    QStringList args = device.split(QLatin1Char(':'));
    foreach (const QString &arg, args) {
        if (arg.startsWith(QLatin1String("repeat-delay=")))
            repeat_delay = arg.mid(13).toInt();
        else if (arg.startsWith(QLatin1String("repeat-rate=")))
            repeat_rate = arg.mid(12).toInt();
        else if (arg.startsWith(QLatin1String("/dev/")))
            dev = arg;
    }

    m_tty_fd = QT_OPEN(dev.toLocal8Bit().constData(), O_RDWR, 0);
    if (m_tty_fd >= 0) {
        if (repeat_delay > 0 && repeat_rate > 0) {
#if defined(Q_OS_LINUX)
            struct ::kbd_repeat kbdrep = { repeat_delay, repeat_rate };
            ::ioctl(m_tty_fd, KDKBDREP, &kbdrep);
#endif
        }

        QSocketNotifier *notifier;
        notifier = new QSocketNotifier(m_tty_fd, QSocketNotifier::Read, this);
        connect(notifier, SIGNAL(activated(int)), this, SLOT(readKeycode()));

        // save tty config for restore.
        tcgetattr(m_tty_fd, &m_tty_attr);

        struct ::termios termdata;
        tcgetattr(m_tty_fd, &termdata);

#if defined(Q_OS_LINUX)
        // record the original mode so we can restore it again in the destructor.
        ::ioctl(m_tty_fd, KDGKBMODE, &m_orig_kbmode);

        // PLEASE NOTE:
        // the tty keycode interface can only report keycodes 0x01 .. 0x7f
        // KEY_MAX is however defined to 0x1ff. In practice this is sufficient
        // for a PC style keyboard though.
        // we don't support K_RAW anymore - if you need that, you have to add
        // a scan- to keycode converter yourself.
        ::ioctl(m_tty_fd, KDSKBMODE, K_MEDIUMRAW);
#endif

        // set the tty layer to pass-through
        termdata.c_iflag = (IGNPAR | IGNBRK) & (~PARMRK) & (~ISTRIP);
        termdata.c_oflag = 0;
        termdata.c_cflag = CREAD | CS8;
        termdata.c_lflag = 0;
        termdata.c_cc[VTIME]=0;
        termdata.c_cc[VMIN]=1;
        cfsetispeed(&termdata, 9600);
        cfsetospeed(&termdata, 9600);
        tcsetattr(m_tty_fd, TCSANOW, &termdata);

#if defined(Q_OS_LINUX)
        // VT switching is handled via unix signals
        connect(QApplication::instance(), SIGNAL(unixSignal(int)), this, SLOT(handleConsoleSwitch(int)));
        QApplication::instance()->watchUnixSignal(VTACQSIG, true);
        QApplication::instance()->watchUnixSignal(VTRELSIG, true);

        struct ::vt_mode vtMode;
        if (::ioctl(m_tty_fd, VT_GETMODE, &vtMode) == 0) {
            vtMode.mode = VT_PROCESS;
            vtMode.relsig = VTRELSIG;
            vtMode.acqsig = VTACQSIG;

            if (::ioctl(m_tty_fd, VT_SETMODE, &vtMode) == 0) {
                struct ::vt_stat vtStat;
                ::memset(&vtStat, 0, sizeof(vtStat));

                if (::ioctl(m_tty_fd, VT_GETSTATE, &vtStat) == 0 ) {
                    m_vt_qws = vtStat.v_active;
                }
            }
        }

        if (!m_vt_qws)
            qWarning("Could not initialize virtual console switching");
#endif
    } else {
        qWarning("Cannot open input device '%s': %s", qPrintable(dev), strerror(errno));
        return;
    }

}

QWSTtyKbPrivate::~QWSTtyKbPrivate()
{
    if (m_tty_fd >= 0) {
#if defined(Q_OS_LINUX)
        ::ioctl(m_tty_fd, KDSKBMODE, m_orig_kbmode);
#endif
        tcsetattr(m_tty_fd, TCSANOW, &m_tty_attr);
        QT_CLOSE(m_tty_fd);
    }
}



void QWSTtyKbPrivate::switchLed(char led, bool state)
{
#if defined(Q_OS_LINUX)
    char ledstate;

    ::ioctl(m_tty_fd, KDGETLED, &ledstate);
    if (state)
        ledstate |= led;
    else
        ledstate &= ~led;
    ::ioctl(m_tty_fd, KDSETLED, ledstate);
#endif
}

void QWSTtyKbPrivate::readKeycode()
{
    char buffer[32];
    int n = 0;

    forever {
        n = QT_READ(m_tty_fd, buffer + n, 32 - n);

        if (n == 0) {
            qWarning("Got EOF from the input device.");
            return;
        } else if (n < 0 && (errno != EINTR && errno != EAGAIN)) {
            qWarning("Could not read from input device: %s", strerror(errno));
            return;
        } else {
            break;
        }
    }

    for (int i = 0; i < n; ++i) {
        if (m_handler->filterKeycode(buffer[i]))
            continue;

        QWSKeyboardHandler::KeycodeAction ka;
        ka = m_handler->processKeycode(buffer[i] & 0x7f, (buffer[i] & 0x80) == 0x00, buffer[i] == m_last_keycode);
        m_last_keycode = buffer[i];

        switch (ka) {
        case QWSKeyboardHandler::CapsLockOn:
        case QWSKeyboardHandler::CapsLockOff:
            switchLed(LED_CAP, ka == QWSKeyboardHandler::CapsLockOn);
            break;

        case QWSKeyboardHandler::NumLockOn:
        case QWSKeyboardHandler::NumLockOff:
            switchLed(LED_NUM, ka == QWSKeyboardHandler::NumLockOn);
            break;

        case QWSKeyboardHandler::ScrollLockOn:
        case QWSKeyboardHandler::ScrollLockOff:
            switchLed(LED_SCR, ka == QWSKeyboardHandler::ScrollLockOn);
            break;

        case QWSKeyboardHandler::PreviousConsole:
            switchConsole(qBound(1, m_vt_qws - 1, 10));
            break;

        case QWSKeyboardHandler::NextConsole:
            switchConsole(qBound(1, m_vt_qws + 1, 10));
            break;

        default:
            if (ka >= QWSKeyboardHandler::SwitchConsoleFirst &&
                ka <= QWSKeyboardHandler::SwitchConsoleLast) {
                switchConsole(1 + (ka & QWSKeyboardHandler::SwitchConsoleMask));
            }
            //ignore reboot
            break;
        }
    }
}


void QWSTtyKbPrivate::switchConsole(int vt)
{
#if defined(Q_OS_LINUX)
    if (m_vt_qws && vt && (m_tty_fd >= 0 ))
        ::ioctl(m_tty_fd, VT_ACTIVATE, vt);
#endif
}

void QWSTtyKbPrivate::handleConsoleSwitch(int sig)
{
#if defined(Q_OS_LINUX)
    // received a notification from the kernel that the current VT is
    // changing: either enable or disable QWS painting accordingly.

    if (sig == VTACQSIG) {
        if (::ioctl(m_tty_fd, VT_RELDISP, VT_ACKACQ) == 0) {
            qwsServer->enablePainting(true);
            qt_screen->restore();
            qwsServer->resumeMouse();
            qwsServer->refresh();
        }
    } else if (sig == VTRELSIG) {
        qwsServer->enablePainting(false);

        // Check for reserved surfaces which might still do painting
        bool allWindowsHidden = true;
        const QList<QWSWindow*> windows = QWSServer::instance()->clientWindows();
        for (int i = 0; i < windows.size(); ++i) {
            const QWSWindow *w = windows.at(i);
            QWSWindowSurface *s = w->windowSurface();
            if (s && s->isRegionReserved() && !w->allocatedRegion().isEmpty()) {
                allWindowsHidden = false;
                break;
            }
        }

        if (!allWindowsHidden) {
            ::ioctl(m_tty_fd, VT_RELDISP, 0); // abort console switch
            qwsServer->enablePainting(true);
        } else if (::ioctl(m_tty_fd, VT_RELDISP, 1) == 0) {
            qt_screen->save();
            qwsServer->suspendMouse();
        } else {
            qwsServer->enablePainting(true);
        }
    }
#endif
}

QT_END_NAMESPACE

#include "qkbdtty_qws.moc"

#endif // QT_NO_QWS_KEYBOARD || QT_NO_QWS_KBD_TTY
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
/* 
 * tclMacSock.c
 *
 *	Channel drivers for Macintosh sockets.
 *
 * Copyright (c) 1996-1997 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: tclMacSock.c,v 1.14 2002/04/08 09:03:17 das Exp $
 */

#include "tclInt.h"
#include "tclPort.h"
#include "tclMacInt.h"
#include <AddressXlation.h>
#include <Aliases.h>
#undef Status
#include <Devices.h>
#include <Errors.h>
#include <Events.h>
#include <Files.h>
#include <Gestalt.h>
#include <MacTCP.h>
#include <Processes.h>
#include <Strings.h>

/*
 * The following variable is used to tell whether this module has been
 * initialized.
 */

static int initialized = 0;

/*
 * If debugging is on we may drop into the debugger to handle certain cases
 * that are not supposed to happen.  Otherwise, we change ignore the error
 * and most code should handle such errors ok.
 */

#ifndef TCL_DEBUG
    #define Debugger()
#endif

/*
 * The preferred buffer size for Macintosh channels.
 */

#define CHANNEL_BUF_SIZE	8192

/*
 * Port information structure.  Used to match service names
 * to a Tcp/Ip port number.
 */

typedef struct {
    char *name;			/* Name of service. */
    int port;			/* Port number. */
} PortInfo;

/*
 * This structure describes per-instance state of a tcp based channel.
 */

typedef struct TcpState {
    TCPiopb pb;			   /* Parameter block used by this stream. 
				    * This must be in the first position. */
    ProcessSerialNumber	psn;	   /* PSN used to wake up process. */
    StreamPtr tcpStream;	   /* Macintosh tcp stream pointer. */
    int port;			   /* The port we are connected to. */
    int flags;			   /* Bit field comprised of the flags
				    * described below.  */
    int checkMask;		   /* OR'ed combination of TCL_READABLE and
				    * TCL_WRITABLE as set by an asynchronous
				    * event handler. */
    int watchMask;		   /* OR'ed combination of TCL_READABLE and
				    * TCL_WRITABLE as set by TcpWatch. */
    Tcl_TcpAcceptProc *acceptProc; /* Proc to call on accept. */
    ClientData acceptProcData;	   /* The data for the accept proc. */
    wdsEntry dataSegment[2];       /* List of buffers to be written async. */
    rdsEntry rdsarray[5+1];	   /* Array used when cleaning out recieve 
				    * buffers on a closing socket. */
    Tcl_Channel channel;	   /* Channel associated with this socket. */
    int writeBufferSize;           /* Size of buffer to hold data for
                                    *  asynchronous writes. */
    void *writeBuffer;             /* Buffer for async write data. */
    struct TcpState *nextPtr;	   /* The next socket on the global socket
				    * list. */
} TcpState;

/*
 * This structure is used by domain name resolver callback.
 */

typedef struct DNRState {
    struct hostInfo hostInfo;	/* Data structure used by DNR functions. */
    int done;			/* Flag to determine when we are done. */
    ProcessSerialNumber psn;	/* Process to wake up when we are done. */
} DNRState;

/*
 * The following macros may be used to set the flags field of
 * a TcpState structure.
 */

#define TCP_ASYNC_SOCKET	(1<<0)  /* The socket is in async mode. */
#define TCP_ASYNC_CONNECT	(1<<1)  /* The socket is trying to connect. */
#define TCP_CONNECTED		(1<<2)  /* The socket is connected. */
#define TCP_PENDING		(1<<3)	/* A SocketEvent is on the queue. */
#define TCP_LISTENING 		(1<<4)  /* This socket is listening for
					 * a connection. */
#define TCP_LISTEN_CONNECT 	(1<<5)  /* Someone has connect to the
					 * listening port. */
#define TCP_REMOTE_CLOSED 	(1<<6)  /* The remote side has closed
					 * the connection. */
#define TCP_RELEASE	 	(1<<7)  /* The socket may now be released. */
#define TCP_WRITING		(1<<8)  /* A background write is in progress. */
#define TCP_SERVER_ZOMBIE	(1<<9)  /* The server can no longer accept connects. */

/*
 * The following structure is what is added to the Tcl event queue when
 * a socket event occurs.
 */

typedef struct SocketEvent {
    Tcl_Event header;		/* Information that is standard for
				 * all events. */
    TcpState *statePtr;		/* Socket descriptor that is ready. */
    StreamPtr tcpStream;	/* Low level Macintosh stream. */
} SocketEvent;

/*
 * Static routines for this file:
 */

static pascal void	CleanUpExitProc _ANSI_ARGS_((void));
static void		ClearZombieSockets _ANSI_ARGS_((void));
static void		CloseCompletionRoutine _ANSI_ARGS_((TCPiopb *pb));
static TcpState *	CreateSocket _ANSI_ARGS_((Tcl_Interp *interp,
			    int port, CONST char *host, CONST char *myAddr,
			    int myPort, int server, int async));
static pascal void	DNRCompletionRoutine _ANSI_ARGS_((
			    struct hostInfo *hostinfoPtr,
			    DNRState *dnrStatePtr));
static void		FreeSocketInfo _ANSI_ARGS_((TcpState *statePtr));
static long		GetBufferSize _ANSI_ARGS_((void));
static OSErr		GetHostFromString _ANSI_ARGS_((CONST char *name,
			    ip_addr *address));
static OSErr		GetLocalAddress _ANSI_ARGS_((unsigned long *addr));
static void		IOCompletionRoutine _ANSI_ARGS_((TCPiopb *pb));
static void		InitMacTCPParamBlock _ANSI_ARGS_((TCPiopb *pBlock,
			    int csCode));
static void		InitSockets _ANSI_ARGS_((void));
static TcpState *	NewSocketInfo _ANSI_ARGS_((StreamPtr stream));
static OSErr		ResolveAddress _ANSI_ARGS_((ip_addr tcpAddress,
			    Tcl_DString *dsPtr));
static void		SocketCheckProc _ANSI_ARGS_((ClientData clientData,
			    int flags));
static int		SocketEventProc _ANSI_ARGS_((Tcl_Event *evPtr,
			    int flags));
static void		SocketExitHandler _ANSI_ARGS_((ClientData clientData));
static void		SocketFreeProc _ANSI_ARGS_((ClientData clientData));
static int		SocketReady _ANSI_ARGS_((TcpState *statePtr));
static void		SocketSetupProc _ANSI_ARGS_((ClientData clientData,
			    int flags));
static void		TcpAccept _ANSI_ARGS_((TcpState *statePtr));
static int		TcpBlockMode _ANSI_ARGS_((ClientData instanceData, int mode));
static int		TcpClose _ANSI_ARGS_((ClientData instanceData,
			    Tcl_Interp *interp));
static int		TcpGetHandle _ANSI_ARGS_((ClientData instanceData,
		            int direction, ClientData *handlePtr));
static int		TcpGetOptionProc _ANSI_ARGS_((ClientData instanceData,
                            Tcl_Interp *interp, CONST char *optionName,
			    Tcl_DString *dsPtr));
static int		TcpInput _ANSI_ARGS_((ClientData instanceData,
			    char *buf, int toRead, int *errorCodePtr));
static int		TcpOutput _ANSI_ARGS_((ClientData instanceData,
			    CONST char *buf, int toWrite, int *errorCodePtr));
static void		TcpWatch _ANSI_ARGS_((ClientData instanceData,
		            int mask));
static int		WaitForSocketEvent _ANSI_ARGS_((TcpState *infoPtr,
		            int mask, int *errorCodePtr));

pascal void NotifyRoutine (
    StreamPtr tcpStream,
    unsigned short eventCode,
    Ptr userDataPtr,
    unsigned short terminReason,
    struct ICMPReport *icmpMsg);
    
/*
 * This structure describes the channel type structure for TCP socket
 * based IO:
 */

static Tcl_ChannelType tcpChannelType = {
    "tcp",			/* Type name. */
    (Tcl_ChannelTypeVersion)TcpBlockMode,		/* Set blocking or
                                 * non-blocking mode.*/
    TcpClose,			/* Close proc. */
    TcpInput,			/* Input proc. */
    TcpOutput,			/* Output proc. */
    NULL,			/* Seek proc. */
    NULL,			/* Set option proc. */
    TcpGetOptionProc,		/* Get option proc. */
    TcpWatch,			/* Initialize notifier. */
    TcpGetHandle		/* Get handles out of channel. */
};

/*
 * Universal Procedure Pointers (UPP) for various callback
 * routines used by MacTcp code.
 */

ResultUPP resultUPP = NULL;
TCPIOCompletionUPP completeUPP = NULL;
TCPIOCompletionUPP closeUPP = NULL;
TCPNotifyUPP notifyUPP = NULL;

/*
 * Built-in commands, and the procedures associated with them:
 */

static PortInfo portServices[] = {
    {"echo",		7},
    {"discard",		9},
    {"systat",		11},
    {"daytime",		13},
    {"netstat",		15},
    {"chargen",		19},
    {"ftp-data",	20},
    {"ftp",		21},
    {"telnet",		23},
    {"telneto",		24},
    {"smtp",		25},
    {"time",		37},
    {"whois",		43},
    {"domain",		53},
    {"gopher",		70},
    {"finger",		79},
    {"hostnames",	101},
    {"sunrpc",		111},
    {"nntp",		119},
    {"exec",		512},
    {"login",		513},
    {"shell",		514},
    {"printer",		515},
    {"courier",		530},
    {"uucp",		540},
    {NULL,		0},
};

typedef struct ThreadSpecificData {
    /*
     * Every open socket has an entry on the following list.
     */
    
    TcpState *socketList;
} ThreadSpecificData;

static Tcl_ThreadDataKey dataKey;

/*
 * Globals for holding information about OS support for sockets.
 */

static int socketsTestInited = false;
static int hasSockets = false;
static short driverRefNum = 0;
static int socketNumber = 0;
static int socketBufferSize = CHANNEL_BUF_SIZE;
static ProcessSerialNumber applicationPSN;

/*
 *----------------------------------------------------------------------
 *
 * InitSockets --
 *
 *	Load the MacTCP driver and open the name resolver.  We also
 *	create several UPP's used by our code.  Lastly, we install
 *	a patch to ExitToShell to clean up socket connections if
 *	we are about to exit.
 *
 * Results:
 *	1 if successful, 0 on failure.
 *
 * Side effects:
 *	Creates a new event source, loads the MacTCP driver,
 *	registers an exit to shell callback.
 *
 *----------------------------------------------------------------------
 */

#define gestaltMacTCPVersion 'mtcp'
static void
InitSockets()
{
    ParamBlockRec pb; 
    OSErr err;
    long response;
    ThreadSpecificData *tsdPtr;
    
    if (! initialized) {
	/*
	 * Do process wide initialization.
	 */

	initialized = 1;
	    
	if (Gestalt(gestaltMacTCPVersion, &response) == noErr) {
	    hasSockets = true;
	} else {
	    hasSockets = false;
	}
    
	if (!hasSockets) {
	    return;
	}
    
	/*
	 * Load MacTcp driver and name server resolver.
	 */
	    
		    
	pb.ioParam.ioCompletion = 0L; 
	pb.ioParam.ioNamePtr = "\p.IPP"; 
	pb.ioParam.ioPermssn = fsCurPerm; 
	err = PBOpenSync(&pb); 
	if (err != noErr) {
	    hasSockets = 0;
	    return;
	}
	driverRefNum = pb.ioParam.ioRefNum; 
	    
	socketBufferSize = GetBufferSize();
	err = OpenResolver(NULL);
	if (err != noErr) {
	    hasSockets = 0;
	    return;
	}
    
	GetCurrentProcess(&applicationPSN);
	/*
	 * Create UPP's for various callback routines.
	 */
    
	resultUPP = NewResultProc(DNRCompletionRoutine);
	completeUPP = NewTCPIOCompletionProc(IOCompletionRoutine);
	closeUPP = NewTCPIOCompletionProc(CloseCompletionRoutine);
	notifyUPP = NewTCPNotifyProc(NotifyRoutine);
    
	/*
	 * Install an ExitToShell patch.  We use this patch instead
	 * of the Tcl exit mechanism because we need to ensure that
	 * these routines are cleaned up even if we crash or are forced
	 * to quit.  There are some circumstances when the Tcl exit
	 * handlers may not fire.
	 */
    
	TclMacInstallExitToShellPatch(CleanUpExitProc);
    }

    /*
     * Do per-thread initialization.
     */

    tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
    if (tsdPtr == NULL) {
	tsdPtr->socketList = NULL;
	Tcl_CreateEventSource(SocketSetupProc, SocketCheckProc, NULL);
	Tcl_CreateThreadExitHandler(SocketExitHandler, (ClientData) NULL);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * SocketExitHandler --
 *
 *	Callback invoked during exit clean up to deinitialize the
 *	socket module.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
SocketExitHandler(
    ClientData clientData)              /* Not used. */
{
    if (hasSockets) {
	Tcl_DeleteEventSource(SocketSetupProc, SocketCheckProc, NULL);
	/* CleanUpExitProc();
	TclMacDeleteExitToShellPatch(CleanUpExitProc); */
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TclpHasSockets --
 *
 *	This function determines whether sockets are available on the
 *	current system and returns an error in interp if they are not.
 *	Note that interp may be NULL.
 *
 * Results:
 *	Returns TCL_OK if the system supports sockets, or TCL_ERROR with
 *	an error in interp.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TclpHasSockets(
    Tcl_Interp *interp)		/* Interp for error messages. */
{
    InitSockets();

    if (hasSockets) {
	return TCL_OK;
    }
    if (interp != NULL) {
	Tcl_AppendResult(interp, "sockets are not available on this system",
		NULL);
    }
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * SocketSetupProc --
 *
 *	This procedure is invoked before Tcl_DoOneEvent blocks waiting
 *	for an event.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Adjusts the block time if needed.
 *
 *----------------------------------------------------------------------
 */

static void
SocketSetupProc(
    ClientData data,		/* Not used. */
    int flags)			/* Event flags as passed to Tcl_DoOneEvent. */
{
    TcpState *statePtr;
    Tcl_Time blockTime = { 0, 0 };
    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);

    if (!(flags & TCL_FILE_EVENTS)) {
	return;
    }
    
    /*
     * Check to see if there is a ready socket.  If so, poll.
     */

    for (statePtr = tsdPtr->socketList; statePtr != NULL;
	    statePtr = statePtr->nextPtr) {
	if (statePtr->flags & TCP_RELEASE) {
	    continue;
	}
	if (SocketReady(statePtr)) {
	    Tcl_SetMaxBlockTime(&blockTime);
	    break;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * SocketCheckProc --
 *
 *	This procedure is called by Tcl_DoOneEvent to check the socket
 *	event source for events. 
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May queue an event.
 *
 *----------------------------------------------------------------------
 */

static void
SocketCheckProc(
    ClientData data,		/* Not used. */
    int flags)			/* Event flags as passed to Tcl_DoOneEvent. */
{
    TcpState *statePtr;
    SocketEvent *evPtr;
    TcpState dummyState;
    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);

    if (!(flags & TCL_FILE_EVENTS)) {
	return;
    }
    
    /*
     * Queue events for any ready sockets that don't already have events
     * queued (caused by persistent states that won't generate WinSock
     * events).
     */

    for (statePtr = tsdPtr->socketList; statePtr != NULL;
	    statePtr = statePtr->nextPtr) {
	/*
	 * Check to see if this socket is dead and needs to be cleaned
	 * up.  We use a dummy statePtr whose only valid field is the
	 * nextPtr to allow the loop to continue even if the element
	 * is deleted.
	 */

	if (statePtr->flags & TCP_RELEASE) {
	    if (!(statePtr->flags & TCP_PENDING)) {
		dummyState.nextPtr = statePtr->nextPtr;
		SocketFreeProc(statePtr);
		statePtr = &dummyState;
	    }
	    continue;
	}

	if (!(statePtr->flags & TCP_PENDING) && SocketReady(statePtr)) {
	    statePtr->flags |= TCP_PENDING;
	    evPtr = (SocketEvent *) ckalloc(sizeof(SocketEvent));
	    evPtr->header.proc = SocketEventProc;
	    evPtr->statePtr = statePtr;
	    evPtr->tcpStream = statePtr->tcpStream;
	    Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * SocketReady --
 *
 *	This function checks the current state of a socket to see
 *	if any interesting conditions are present.
 *
 * Results:
 *	Returns 1 if an event that someone is watching is present, else
 *	returns 0.
 *
 * Side effects:
 *	Updates the checkMask for the socket to reflect any newly
 *	detected events.
 *
 *----------------------------------------------------------------------
 */

static int
SocketReady(
    TcpState *statePtr)
{
    TCPiopb statusPB;
    int foundSomething = 0;
    int didStatus = 0;
    int amount;
    OSErr err;

    if (statePtr->flags & TCP_LISTEN_CONNECT) {
	foundSomething = 1;
	statePtr->checkMask |= TCL_READABLE;
    }
    if (statePtr->watchMask & TCL_READABLE) {
	if (statePtr->checkMask & TCL_READABLE) {
	    foundSomething = 1;
	} else if (statePtr->flags & TCP_CONNECTED) {
	    statusPB.ioCRefNum = driverRefNum;
	    statusPB.tcpStream = statePtr->tcpStream;
	    statusPB.csCode = TCPStatus;
	    err = PBControlSync((ParmBlkPtr) &statusPB);
	    didStatus = 1;

	    /*
	     * We make the fchannel readable if 1) we get an error,
	     * 2) there is more data available, or 3) we detect
	     * that a close from the remote connection has arrived.
	     */

	    if ((err != noErr) ||
		    (statusPB.csParam.status.amtUnreadData > 0) ||
		    (statusPB.csParam.status.connectionState == 14)) {
		statePtr->checkMask |= TCL_READABLE;
		foundSomething = 1;
	    }
	}
    }
    if (statePtr->watchMask & TCL_WRITABLE) {
	if (statePtr->checkMask & TCL_WRITABLE) {
	    foundSomething = 1;
	} else if (statePtr->flags & TCP_CONNECTED) {
	    if (!didStatus) {
		statusPB.ioCRefNum = driverRefNum;
		statusPB.tcpStream = statePtr->tcpStream;
		statusPB.csCode = TCPStatus;
		err = PBControlSync((ParmBlkPtr) &statusPB);
	    }

	    /*
	     * If there is an error or there if there is room to
	     * send more data we make the channel writeable.
	     */

	    amount = statusPB.csParam.status.sendWindow - 
		statusPB.csParam.status.amtUnackedData;
	    if ((err != noErr) || (amount > 0)) {
		statePtr->checkMask |= TCL_WRITABLE;
		foundSomething = 1;
	    }
	}
    }
    return foundSomething;
}

/*
 *----------------------------------------------------------------------
 *
 * InitMacTCPParamBlock--
 *
 *	Initialize a MacTCP parameter block.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Initializes the parameter block.
 *
 *----------------------------------------------------------------------
 */

static void
InitMacTCPParamBlock(
    TCPiopb *pBlock,		/* Tcp parmeter block. */
    int csCode)			/* Tcp operation code. */
{
    memset(pBlock, 0, sizeof(TCPiopb));
    pBlock->ioResult = 1;
    pBlock->ioCRefNum = driverRefNum;
    pBlock->csCode = (short) csCode;
}

/*
 *----------------------------------------------------------------------
 *
 * TcpBlockMode --
 *
 *	Set blocking or non-blocking mode on channel.
 *
 * Results:
 *	0 if successful, errno when failed.
 *
 * Side effects:
 *	Sets the device into blocking or non-blocking mode.
 *
 *----------------------------------------------------------------------
 */

static int
TcpBlockMode(
    ClientData instanceData, 		/* Channel state. */
    int mode)				/* The mode to set. */
{
    TcpState *statePtr = (TcpState *) instanceData;
    
    if (mode == TCL_MODE_BLOCKING) {
	statePtr->flags &= ~TCP_ASYNC_SOCKET;
    } else {
	statePtr->flags |= TCP_ASYNC_SOCKET;
    }
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * TcpClose --
 *
 *	Close the socket.
 *
 * Results:
 *	0 if successful, the value of errno if failed.
 *
 * Side effects:
 *	Closes the socket.
 *
 *----------------------------------------------------------------------
 */

static int
TcpClose(
    ClientData instanceData,		/* The socket to close. */
    Tcl_Interp *interp)			/* Interp for error messages. */
{
    TcpState *statePtr = (TcpState *) instanceData;
    StreamPtr tcpStream;
    TCPiopb closePB;
    OSErr err;

    tcpStream = statePtr->tcpStream;
    statePtr->flags &= ~TCP_CONNECTED;
    
    /*
     * If this is a server socket we can't use the statePtr
     * param block because it is in use.  However, we can 
     * close syncronously.
     */

    if ((statePtr->flags & TCP_LISTENING) ||
	    (statePtr->flags & TCP_LISTEN_CONNECT)) {
	InitMacTCPParamBlock(&closePB, TCPClose);
    	closePB.tcpStream = tcpStream;
    	closePB.ioCompletion = NULL; 
	closePB.csParam.close.ulpTimeoutValue = 60 /* seconds */;
	closePB.csParam.close.ulpTimeoutAction = 1 /* 1:abort 0:report */;
	closePB.csParam.close.validityFlags = timeoutValue | timeoutAction;
    	err = PBControlSync((ParmBlkPtr) &closePB);
    	if (err != noErr) {
    	    Debugger();
    	    goto afterRelease;
            /* panic("error closing server socket"); */
    	}
	statePtr->flags |= TCP_RELEASE;

	/*
	 * Server sockets are closed sync.  Therefor, we know it is OK to
	 * release the socket now.
	 */

	InitMacTCPParamBlock(&statePtr->pb, TCPRelease);
	statePtr->pb.tcpStream = statePtr->tcpStream;
	err = PBControlSync((ParmBlkPtr) &statePtr->pb);
	if (err != noErr) {
            panic("error releasing server socket");
	}

	/*
	 * Free the buffer space used by the socket and the 
	 * actual socket state data structure.
	 */
      afterRelease:
        
        /*
         * Have to check whether the pointer is NULL, since we could get here
         * on a failed socket open, and then the rcvBuff would never have been
         * allocated.
         */
         
        if (err == noErr) {
	    ckfree((char *) statePtr->pb.csParam.create.rcvBuff);
	}
	FreeSocketInfo(statePtr);
	return 0;
    }

    /*
     * If this socket is in the midddle on async connect we can just
     * abort the connect and release the stream right now.
     */
 
    if (statePtr->flags & TCP_ASYNC_CONNECT) {
	InitMacTCPParamBlock(&closePB, TCPClose);
    	closePB.tcpStream = tcpStream;
    	closePB.ioCompletion = NULL; 
    	err = PBControlSync((ParmBlkPtr) &closePB);
    	if (err == noErr) {
	    statePtr->flags |= TCP_RELEASE;

	    InitMacTCPParamBlock(&closePB, TCPRelease);
    	    closePB.tcpStream = tcpStream;
    	    closePB.ioCompletion = NULL; 

	    err = PBControlSync((ParmBlkPtr) &closePB);
	}

	/*
	 * Free the buffer space used by the socket and the 
	 * actual socket state data structure.  However, if the
	 * RELEASE returns an error, then the rcvBuff is usually
	 * bad, so we can't release it.  I think this means we will
	 * leak the buffer, so in the future, we may want to track the
	 * buffers separately, and nuke them on our own (or just not
	 * use MacTCP!).
	 */

        if (err == noErr) {
	    ckfree((char *) closePB.csParam.create.rcvBuff);
	}
	
	FreeSocketInfo(statePtr);
	return err;
    }

    /*
     * Client sockets:
     * If a background write is in progress, don't close
     * the socket yet.  The completion routine for the 
     * write will take care of it.
     */
    
    if (!(statePtr->flags & TCP_WRITING)) {
	InitMacTCPParamBlock(&statePtr->pb, TCPClose);
    	statePtr->pb.tcpStream = tcpStream;
    	statePtr->pb.ioCompletion = closeUPP; 
    	statePtr->pb.csParam.close.userDataPtr = (Ptr) statePtr;
    	err = PBControlAsync((ParmBlkPtr) &statePtr->pb);
    	if (err != noErr) {
	    Debugger();
	    statePtr->flags |= TCP_RELEASE;
            /* return 0; */
    	}
    }

    SocketFreeProc(instanceData);
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * CloseCompletionRoutine --
 *
 *	Handles the close protocol for a Tcp socket.  This will do
 *	a series of calls to release all data currently buffered for
 *	the socket.  This is important to do to as it allows the remote
 *	connection to recieve and issue it's own close on the socket.
 *	Note that this function is running at interupt time and can't
 *	allocate memory or do much else except set state.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The buffers for the socket are flushed.
 *
 *----------------------------------------------------------------------
 */

static void
CloseCompletionRoutine(
    TCPiopb *pbPtr)		/* Tcp parameter block. */
{
    TcpState *statePtr;
    OSErr err;
    
    if (pbPtr->csCode == TCPClose) {
	statePtr = (TcpState *) (pbPtr->csParam.close.userDataPtr);
    } else {
	statePtr = (TcpState *) (pbPtr->csParam.receive.userDataPtr);
    }

    /*
     * It's very bad if the statePtr is nNULL - we should probably panic...
     */

    if (statePtr == NULL) {
	Debugger();
	return;
    }
    
    WakeUpProcess(&statePtr->psn);

    /*
     * If there is an error we assume the remote side has already
     * close.  We are done closing as soon as we decide that the
     * remote connection has closed.
     */
    
    if (pbPtr->ioResult != noErr) {
	statePtr->flags |= TCP_RELEASE;
	return;
    }
    if (statePtr->flags & TCP_REMOTE_CLOSED) {
	statePtr->flags |= TCP_RELEASE;
	return;
    }
    
    /*
     * If we just did a recieve we need to return the buffers.
     * Otherwise, attempt to recieve more data until we recieve an
     * error (usually because we have no more data).
     */

    if (statePtr->pb.csCode == TCPNoCopyRcv) {
	InitMacTCPParamBlock(&statePtr->pb, TCPRcvBfrReturn);
    	statePtr->pb.tcpStream = statePtr->tcpStream;
	statePtr->pb.ioCompletion = closeUPP; 
	statePtr->pb.csParam.receive.rdsPtr = (Ptr) statePtr->rdsarray;
    	statePtr->pb.csParam.receive.userDataPtr = (Ptr) statePtr;
	err = PBControlAsync((ParmBlkPtr) &statePtr->pb);
    } else {
	InitMacTCPParamBlock(&statePtr->pb, TCPNoCopyRcv);
    	statePtr->pb.tcpStream = statePtr->tcpStream;
	statePtr->pb.ioCompletion = closeUPP; 
	statePtr->pb.csParam.receive.commandTimeoutValue = 1;
	statePtr->pb.csParam.receive.rdsPtr = (Ptr) statePtr->rdsarray;
	statePtr->pb.csParam.receive.rdsLength = 5;
    	statePtr->pb.csParam.receive.userDataPtr = (Ptr) statePtr;
	err = PBControlAsync((ParmBlkPtr) &statePtr->pb);
    }

    if (err != noErr) {
	statePtr->flags |= TCP_RELEASE;
    }
}
/*
 *----------------------------------------------------------------------
 *
 * SocketFreeProc --
 *
 *      This callback is invoked in order to delete
 *      the notifier data associated with a file handle.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Removes the SocketInfo from the global socket list.
 *
 *----------------------------------------------------------------------
 */

static void
SocketFreeProc(
    ClientData clientData)      /* Channel state. */
{
    TcpState *statePtr = (TcpState *) clientData;
    OSErr err;
    TCPiopb statusPB;

    /*
     * Get the status of this connection.  We need to do a
     * few tests to see if it's OK to release the stream now.
     */

    if (!(statePtr->flags & TCP_RELEASE)) {
	return;
    }
    statusPB.ioCRefNum = driverRefNum;
    statusPB.tcpStream = statePtr->tcpStream;
    statusPB.csCode = TCPStatus;
    err = PBControlSync((ParmBlkPtr) &statusPB);
    if ((statusPB.csParam.status.connectionState == 0) ||
	(statusPB.csParam.status.connectionState == 2)) {
	/*
	 * If the conection state is 0 then this was a client
	 * connection and it's closed.  If it is 2 then this a
	 * server client and we may release it.  If it isn't
	 * one of those values then we return and we'll try to
	 * clean up later.
	 */

    } else {
	return;
    }
    
    /*
     * The Close request is made async.  We know it's
     * OK to release the socket when the TCP_RELEASE flag
     * gets set.
     */

    InitMacTCPParamBlock(&statePtr->pb, TCPRelease);
    statePtr->pb.tcpStream = statePtr->tcpStream;
    err = PBControlSync((ParmBlkPtr) &statePtr->pb);
    if (err != noErr) {
        Debugger(); /* Ignoreing leaves stranded stream.  Is there an
		       alternative?  */
    }

    /*
     * Free the buffer space used by the socket and the 
     * actual socket state data structure.
     */

    ckfree((char *) statePtr->pb.csParam.create.rcvBuff);
    FreeSocketInfo(statePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TcpInput --
 *
 *	Reads input from the IO channel into the buffer given. Returns
 *	count of how many bytes were actually read, and an error 
 *	indication.
 *
 * Results:
 *	A count of how many bytes were read is returned.  A value of -1
 *	implies an error occured.  A value of zero means we have reached
 *	the end of data (EOF).
 *
 * Side effects:
 *	Reads input from the actual channel.
 *
 *----------------------------------------------------------------------
 */

int
TcpInput(
    ClientData instanceData,		/* Channel state. */
    char *buf, 				/* Where to store data read. */
    int bufSize, 			/* How much space is available
                                         * in the buffer? */
    int *errorCodePtr)			/* Where to store error code. */
{
    TcpState *statePtr = (TcpState *) instanceData;
    StreamPtr tcpStream;
    OSErr err;
    TCPiopb statusPB;
    int toRead, dataAvail;

    *errorCodePtr = 0;
    errno = 0;
    tcpStream = statePtr->tcpStream;

    if (bufSize == 0) {
        return 0;
    }
    toRead = bufSize;

    /*
     * First check to see if EOF was already detected, to prevent
     * calling the socket stack after the first time EOF is detected.
     */

    if (statePtr->flags & TCP_REMOTE_CLOSED) {
	return 0;
    }

    /*
     * If an asynchronous connect is in progress, attempt to wait for it
     * to complete before reading.
     */
    
    if ((statePtr->flags & TCP_ASYNC_CONNECT)
	    && ! WaitForSocketEvent(statePtr, TCL_READABLE, errorCodePtr)) {
	return -1;
    }

    /*
     * No EOF, and it is connected, so try to read more from the socket.
     * If the socket is blocking, we keep trying until there is data
     * available or the socket is closed.
     */

    while (1) {

	statusPB.ioCRefNum = driverRefNum;
	statusPB.tcpStream = tcpStream;
	statusPB.csCode = TCPStatus;
	err = PBControlSync((ParmBlkPtr) &statusPB);
	if (err != noErr) {
	    Debugger();
	    statePtr->flags |= TCP_REMOTE_CLOSED;
	    return 0;	/* EOF */
	}
	dataAvail = statusPB.csParam.status.amtUnreadData;
	if (dataAvail < bufSize) {
	    toRead = dataAvail;
	} else {
	    toRead = bufSize;
	}
	if (toRead != 0) {
	    /*
	     * Try to read the data.
	     */
	    
	    InitMacTCPParamBlock(&statusPB, TCPRcv);
	    statusPB.tcpStream = tcpStream;
	    statusPB.csParam.receive.rcvBuff = buf;
	    statusPB.csParam.receive.rcvBuffLen = toRead;
	    err = PBControlSync((ParmBlkPtr) &statusPB);

	    statePtr->checkMask &= ~TCL_READABLE;
	    switch (err) {
		case noErr:
		    /*
		     * The channel remains readable only if this read succeds
		     * and we had more data then the size of the buffer we were
		     * trying to fill.  Use the info from the call to status to
		     * determine this.
		     */

		    if (dataAvail > bufSize) {
			statePtr->checkMask |= TCL_READABLE;
		    }
		    return statusPB.csParam.receive.rcvBuffLen;
		case connectionClosing:
		    *errorCodePtr = errno = ESHUTDOWN;
		    statePtr->flags |= TCP_REMOTE_CLOSED;
		    return 0;
		case connectionDoesntExist:
		case connectionTerminated:
		    *errorCodePtr = errno = ENOTCONN;
		    statePtr->flags |= TCP_REMOTE_CLOSED;
		    return 0;
		case invalidStreamPtr:
		default:
		    *errorCodePtr = EINVAL;
		    return -1;
	    }
	}

	/*
	 * No data is available, so check the connection state to
	 * see why this is the case.  
	 */

	if (statusPB.csParam.status.connectionState == 14) {
	    statePtr->flags |= TCP_REMOTE_CLOSED;
	    return 0;
	}
	if (statusPB.csParam.status.connectionState != 8) {
	    Debugger();
	}
	statePtr->checkMask &= ~TCL_READABLE;
	if (statePtr->flags & TCP_ASYNC_SOCKET) {
	    *errorCodePtr = EWOULDBLOCK;
	    return -1;
	}

	/*
	 * In the blocking case, wait until the file becomes readable
	 * or closed and try again.
	 */

	if (!WaitForSocketEvent(statePtr, TCL_READABLE, errorCodePtr)) {
	    return -1;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TcpGetHandle --
 *
 *	Called from Tcl_GetChannelHandle to retrieve handles from inside
 *	a file based channel.
 *
 * Results:
 *	The appropriate handle or NULL if not present. 
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
TcpGetHandle(
    ClientData instanceData,		/* The file state. */
    int direction,			/* Which handle to retrieve? */
    ClientData *handlePtr)
{
    TcpState *statePtr = (TcpState *) instanceData;

    *handlePtr = (ClientData) statePtr->tcpStream;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TcpOutput--
 *
 *	Writes the given output on the IO channel. Returns count of how
 *	many characters were actually written, and an error indication.
 *
 * Results:
 *	A count of how many characters were written is returned and an
 *	error indication is returned in an output argument.
 *
 * Side effects:
 *	Writes output on the actual channel.
 *
 *----------------------------------------------------------------------
 */

static int
TcpOutput(
    ClientData instanceData, 		/* Channel state. */
    CONST char *buf,			/* The data buffer. */
    int toWrite, 			/* How many bytes to write? */
    int *errorCodePtr)			/* Where to store error code. */
{
    TcpState *statePtr = (TcpState *) instanceData;
    StreamPtr tcpStream;
    OSErr err;
    int amount;
    TCPiopb statusPB;

    *errorCodePtr = 0;
    tcpStream = statePtr->tcpStream;

    /*
     * If an asynchronous connect is in progress, attempt to wait for it
     * to complete before writing.
     */
    
    if ((statePtr->flags & TCP_ASYNC_CONNECT)
	    && ! WaitForSocketEvent(statePtr, TCL_WRITABLE, errorCodePtr)) {
	return -1;
    }

    /*
     * Loop until we have written some data, or an error occurs.
     */

    while (1) {
	statusPB.ioCRefNum = driverRefNum;
	statusPB.tcpStream = tcpStream;
	statusPB.csCode = TCPStatus;
	err = PBControlSync((ParmBlkPtr) &statusPB);
	if ((err == connectionDoesntExist) || ((err == noErr) && 
		(statusPB.csParam.status.connectionState == 14))) {
	    /*
	     * The remote connection is gone away.  Report an error
	     * and don't write anything.
	     */

	    *errorCodePtr = errno = EPIPE;
	    return -1;
	} else if (err != noErr) {
	    return -1;
	}
	amount = statusPB.csParam.status.sendWindow
	    - statusPB.csParam.status.amtUnackedData;

	/*
	 * Attempt to write the data to the socket if a background
	 * write isn't in progress and there is room in the output buffers.
	 */

	if (!(statePtr->flags & TCP_WRITING) && amount > 0) {
	    if (toWrite < amount) {
		amount = toWrite;
	    }

            /* We need to copy the data, otherwise the caller may overwrite
             * the buffer in the middle of our asynchronous call
             */
             
            if (amount > statePtr->writeBufferSize) {
                /* 
                 * need to grow write buffer 
                 */
                 
                if (statePtr->writeBuffer != (void *) NULL) {
                    ckfree(statePtr->writeBuffer);
                }
                statePtr->writeBuffer = (void *) ckalloc(amount);
                statePtr->writeBufferSize = amount;
            }
            memcpy(statePtr->writeBuffer, buf, amount);
            statePtr->dataSegment[0].ptr = statePtr->writeBuffer;

	    statePtr->dataSegment[0].length = amount;
	    statePtr->dataSegment[1].length = 0;
	    InitMacTCPParamBlock(&statePtr->pb, TCPSend);
	    statePtr->pb.ioCompletion = completeUPP;
	    statePtr->pb.tcpStream = tcpStream;
	    statePtr->pb.csParam.send.wdsPtr = (Ptr) statePtr->dataSegment;
	    statePtr->pb.csParam.send.pushFlag = 1;
	    statePtr->pb.csParam.send.userDataPtr = (Ptr) statePtr;
	    statePtr->flags |= TCP_WRITING;
	    err = PBControlAsync((ParmBlkPtr) &(statePtr->pb));
	    switch (err) {
		case noErr:
		    return amount;
		case connectionClosing:
		    *errorCodePtr = errno = ESHUTDOWN;
		    statePtr->flags |= TCP_REMOTE_CLOSED;
		    return -1;
		case connectionDoesntExist:
		case connectionTerminated:
		    *errorCodePtr = errno = ENOTCONN;
		    statePtr->flags |= TCP_REMOTE_CLOSED;
		    return -1;
		case invalidStreamPtr:
		default:
		    return -1;
	    }

	}

	/*
	 * The socket wasn't writable.  In the non-blocking case, return
	 * immediately, otherwise wait  until the file becomes writable
	 * or closed and try again.
	 */

	if (statePtr->flags & TCP_ASYNC_SOCKET) {
	    statePtr->checkMask &= ~TCL_WRITABLE;
	    *errorCodePtr = EWOULDBLOCK;
	    return -1;
	} else if (!WaitForSocketEvent(statePtr, TCL_WRITABLE, errorCodePtr)) {
	    return -1;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TcpGetOptionProc --
 *
 *	Computes an option value for a TCP socket based channel, or a
 *	list of all options and their values.
 *
 *	Note: This code is based on code contributed by John Haxby.
 *
 * Results:
 *	A standard Tcl result. The value of the specified option or a
 *	list of all options and	their values is returned in the
 *	supplied DString.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
TcpGetOptionProc(
    ClientData instanceData, 		/* Socket state. */
    Tcl_Interp *interp,                 /* For error reporting - can be NULL.*/
    CONST char *optionName, 		/* Name of the option to
                                         * retrieve the value for, or
                                         * NULL to get all options and
                                         * their values. */
    Tcl_DString *dsPtr)			/* Where to store the computed
                                         * value; initialized by caller. */
{
    TcpState *statePtr = (TcpState *) instanceData;
    int doPeerName = false, doSockName = false, doError = false, doAll = false;
    ip_addr tcpAddress;
    char buffer[128];
    OSErr err;
    Tcl_DString dString;
    TCPiopb statusPB;
    int errorCode;
    size_t len = 0;

    /*
     * If an asynchronous connect is in progress, attempt to wait for it
     * to complete before accessing the socket state.
     */
    
    if ((statePtr->flags & TCP_ASYNC_CONNECT)
	    && ! WaitForSocketEvent(statePtr, TCL_WRITABLE, &errorCode)) {
	if (interp) {
	    /*
	     * fix the error message.
	     */

	    Tcl_AppendResult(interp, "connect is in progress and can't wait",
	    		NULL);
	}
	return TCL_ERROR;
    }
            
    /*
     * Determine which options we need to do.  Do all of them
     * if optionName is NULL.
     */

    if (optionName == (CONST char *) NULL || optionName[0] == '\0') {
        doAll = true;
    } else {
	len = strlen(optionName);
	if (!strncmp(optionName, "-peername", len)) {
	    doPeerName = true;
	} else if (!strncmp(optionName, "-sockname", len)) {
	    doSockName = true;
	} else if (!strncmp(optionName, "-error", len)) {
	    /* SF Bug #483575 */
	    doError = true;
	} else {
	    return Tcl_BadChannelOption(interp, optionName, 
		        "error peername sockname");
	}
    }

    /*
     * SF Bug #483575
     *
     * Return error information. Currently we ignore
     * this option. IOW, we always return the empty
     * string, signaling 'no error'.
     *
     * FIXME: Get a mac/socket expert to write a correct
     * FIXME: implementation.
     */

    if (doAll || doError) {
	if (doAll) {
	    Tcl_DStringAppendElement(dsPtr, "-error");
	    Tcl_DStringAppendElement(dsPtr, "");
	} else {
	    Tcl_DStringAppend (dsPtr, "", -1);
	    return TCL_OK;
	}
    }

    /*
     * Get status on the stream.  Make sure to use a new pb struct because
     * the struct in the statePtr may be part of an asyncronous call.
     */

    statusPB.ioCRefNum = driverRefNum;
    statusPB.tcpStream = statePtr->tcpStream;
    statusPB.csCode = TCPStatus;
    err = PBControlSync((ParmBlkPtr) &statusPB);
    if ((err == connectionDoesntExist) ||
	((err == noErr) && (statusPB.csParam.status.connectionState == 14))) {
	/*
	 * The socket was probably closed on the other side of the connection.
	 */

	if (interp) {
	    Tcl_AppendResult(interp, "can't access socket info: ",
			     "connection reset by peer", NULL);
	}
	return TCL_ERROR;
    } else if (err != noErr) {
	if (interp) { 
	    Tcl_AppendResult(interp, "unknown socket error", NULL);
	}
	Debugger();
	return TCL_ERROR;
    }


    /*
     * Get the sockname for the socket.
     */

    Tcl_DStringInit(&dString);
    if (doAll || doSockName) {
	if (doAll) {
	    Tcl_DStringAppendElement(dsPtr, "-sockname");
	    Tcl_DStringStartSublist(dsPtr);
	}
	tcpAddress = statusPB.csParam.status.localHost;
	sprintf(buffer, "%d.%d.%d.%d", tcpAddress>>24,
		tcpAddress>>16 & 0xff, tcpAddress>>8 & 0xff,
		tcpAddress & 0xff);
	Tcl_DStringAppendElement(dsPtr, buffer);
	if (ResolveAddress(tcpAddress, &dString) == noErr) {
	    Tcl_DStringAppendElement(dsPtr, dString.string);
	} else {
	    Tcl_DStringAppendElement(dsPtr, "<unknown>");
	}
	sprintf(buffer, "%d", statusPB.csParam.status.localPort);
	Tcl_DStringAppendElement(dsPtr, buffer);
	if (doAll) {
	    Tcl_DStringEndSublist(dsPtr);
	}
    }

    /*
     * Get the peername for the socket.
     */

    if ((doAll || doPeerName) && (statePtr->flags & TCP_CONNECTED)) {
	if (doAll) {
	    Tcl_DStringAppendElement(dsPtr, "-peername");
	    Tcl_DStringStartSublist(dsPtr);
	}
	tcpAddress = statusPB.csParam.status.remoteHost;
	sprintf(buffer, "%d.%d.%d.%d", tcpAddress>>24,
		tcpAddress>>16 & 0xff, tcpAddress>>8 & 0xff,
		tcpAddress & 0xff);
	Tcl_DStringAppendElement(dsPtr, buffer);
	Tcl_DStringSetLength(&dString, 0);
	if (ResolveAddress(tcpAddress, &dString) == noErr) {
	    Tcl_DStringAppendElement(dsPtr, dString.string);
	} else {
	    Tcl_DStringAppendElement(dsPtr, "<unknown>");
	}
	sprintf(buffer, "%d", statusPB.csParam.status.remotePort);
	Tcl_DStringAppendElement(dsPtr, buffer);
	if (doAll) {
	    Tcl_DStringEndSublist(dsPtr);
	}
    }

    Tcl_DStringFree(&dString);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TcpWatch --
 *
 *	Initialize the notifier to watch this channel.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Sets the watchMask for the channel.
 *
 *----------------------------------------------------------------------
 */

static void
TcpWatch(instanceData, mask)
    ClientData instanceData;		/* The file state. */
    int mask;				/* Events of interest; an OR-ed
                                         * combination of TCL_READABLE,
                                         * TCL_WRITABLE and TCL_EXCEPTION. */
{
    TcpState *statePtr = (TcpState *) instanceData;

    statePtr->watchMask = mask;
}

/*
 *----------------------------------------------------------------------
 *
 * NewSocketInfo --
 *
 *	This function allocates and initializes a new SocketInfo
 *	structure.
 *
 * Results:
 *	Returns a newly allocated SocketInfo.
 *
 * Side effects:
 *	Adds the socket to the global socket list, allocates memory.
 *
 *----------------------------------------------------------------------
 */

static TcpState *
NewSocketInfo(
    StreamPtr tcpStream)
{
    TcpState *statePtr;
    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);

    statePtr = (TcpState *) ckalloc((unsigned) sizeof(TcpState));
    statePtr->tcpStream = tcpStream;
    statePtr->psn = applicationPSN;
    statePtr->flags = 0;
    statePtr->checkMask = 0;
    statePtr->watchMask = 0;
    statePtr->acceptProc = (Tcl_TcpAcceptProc *) NULL;
    statePtr->acceptProcData = (ClientData) NULL;
    statePtr->writeBuffer = (void *) NULL;
    statePtr->writeBufferSize = 0;
    statePtr->nextPtr = tsdPtr->socketList;
    tsdPtr->socketList = statePtr;
    return statePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * FreeSocketInfo --
 *
 *	This function deallocates a SocketInfo structure that is no
 *	longer needed.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Removes the socket from the global socket list, frees memory.
 *
 *----------------------------------------------------------------------
 */

static void
FreeSocketInfo(
    TcpState *statePtr)		/* The state pointer to free. */
{
    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);

    if (statePtr == tsdPtr->socketList) {
	tsdPtr->socketList = statePtr->nextPtr;
    } else {
	TcpState *p;
	for (p = tsdPtr->socketList; p != NULL; p = p->nextPtr) {
	    if (p->nextPtr == statePtr) {
		p->nextPtr = statePtr->nextPtr;
		break;
	    }
	}
    }
    
    if (statePtr->writeBuffer != (void *) NULL) {
        ckfree(statePtr->writeBuffer);
    }
    
    ckfree((char *) statePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_MakeTcpClientChannel --
 *
 *	Creates a Tcl_Channel from an existing client TCP socket.
 *
 * Results:
 *	The Tcl_Channel wrapped around the preexisting TCP socket.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_MakeTcpClientChannel(
    ClientData sock)	/* The socket to wrap up into a channel. */
{
    TcpState *statePtr;
    char channelName[20];

    if (TclpHasSockets(NULL) != TCL_OK) {
	return NULL;
    }
	
    statePtr = NewSocketInfo((StreamPtr) sock);
    /* TODO: do we need to set the port??? */
    
    sprintf(channelName, "sock%d", socketNumber++);
    
    statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
            (ClientData) statePtr, (TCL_READABLE | TCL_WRITABLE));
    Tcl_SetChannelBufferSize(statePtr->channel, socketBufferSize);
    Tcl_SetChannelOption(NULL, statePtr->channel, "-translation", "auto crlf");
    return statePtr->channel;
}

/*
 *----------------------------------------------------------------------
 *
 * CreateSocket --
 *
 *	This function opens a new socket and initializes the
 *	SocketInfo structure.
 *
 * Results:
 *	Returns a new SocketInfo, or NULL with an error in interp.
 *
 * Side effects:
 *	Adds a new socket to the socketList.
 *
 *----------------------------------------------------------------------
 */

static TcpState *
CreateSocket(
    Tcl_Interp *interp,		/* For error reporting; can be NULL. */
    int port,			/* Port number to open. */
    CONST char *host,		/* Name of host on which to open port. */
    CONST char *myaddr,		/* Optional client-side address */
    int myport,			/* Optional client-side port */
    int server,			/* 1 if socket should be a server socket,
				 * else 0 for a client socket. */
    int async)			/* 1 create async, 0 do sync. */
{
    ip_addr macAddr;
    OSErr err;
    TCPiopb pb;
    StreamPtr tcpStream;
    TcpState *statePtr;
    char * buffer;
    
    /*
     * Figure out the ip address from the host string.
     */

    if (host == NULL) {
	err = GetLocalAddress(&macAddr);
    } else {
	err = GetHostFromString(host, &macAddr);
    }
    if (err != noErr) {
	Tcl_SetErrno(EHOSTUNREACH);
	if (interp != (Tcl_Interp *) NULL) {
	    Tcl_AppendResult(interp, "couldn't open socket: ",
                        Tcl_PosixError(interp), (char *) NULL);
	}
	return (TcpState *) NULL;
    }
    
    /*
     * Create a MacTCP stream and create the state used for socket
     * transactions from here on out.
     */

    ClearZombieSockets();
    buffer = ckalloc(socketBufferSize);
    InitMacTCPParamBlock(&pb, TCPCreate);
    pb.csParam.create.rcvBuff = buffer;
    pb.csParam.create.rcvBuffLen = socketBufferSize;
    pb.csParam.create.notifyProc = nil /* notifyUPP */;
    err = PBControlSync((ParmBlkPtr) &pb);
    if (err != noErr) {
        Tcl_SetErrno(0); /* TODO: set to ENOSR - maybe?*/
        if (interp != (Tcl_Interp *) NULL) {
	    Tcl_AppendResult(interp, "couldn't open socket: ",
		Tcl_PosixError(interp), (char *) NULL);
        }
	return (TcpState *) NULL;
    }

    tcpStream = pb.tcpStream;
    statePtr = NewSocketInfo(tcpStream);
    statePtr->port = port;
    
    if (server) {
        /* 
         * Set up server connection.
         */

	InitMacTCPParamBlock(&statePtr->pb, TCPPassiveOpen);
	statePtr->pb.tcpStream = tcpStream;
	statePtr->pb.csParam.open.localPort = statePtr->port;
	statePtr->pb.ioCompletion = completeUPP; 
	statePtr->pb.csParam.open.userDataPtr = (Ptr) statePtr;
	statePtr->pb.csParam.open.ulpTimeoutValue = 100;
	statePtr->pb.csParam.open.ulpTimeoutAction 	= 1 /* 1:abort 0:report */;
	statePtr->pb.csParam.open.commandTimeoutValue	= 0 /* infinity */;

	statePtr->flags |= TCP_LISTENING;
	err = PBControlAsync((ParmBlkPtr) &(statePtr->pb));

	/*
	 * If this is a server on port 0 then we need to wait until
	 * the dynamic port allocation is made by the MacTcp driver.
	 */

	if (statePtr->port == 0) {
	    EventRecord dummy;

	    while (statePtr->pb.csParam.open.localPort == 0) {
		WaitNextEvent(0, &dummy, 1, NULL);
		if (statePtr->pb.ioResult != 0) {
		    break;
		}
	    }
	    statePtr->port = statePtr->pb.csParam.open.localPort;
	}
	Tcl_SetErrno(EINPROGRESS);
    } else {
	/*
	 * Attempt to connect. The connect may fail at present with an
	 * EINPROGRESS but at a later time it will complete. The caller
	 * will set up a file handler on the socket if she is interested in
	 * being informed when the connect completes.
	 */

	InitMacTCPParamBlock(&statePtr->pb, TCPActiveOpen);
	
	statePtr->pb.tcpStream = tcpStream;
	statePtr->pb.csParam.open.remoteHost = macAddr;
	statePtr->pb.csParam.open.remotePort = port;
	statePtr->pb.csParam.open.localHost = 0;
	statePtr->pb.csParam.open.localPort = myport;
	statePtr->pb.csParam.open.userDataPtr = (Ptr) statePtr;	
	statePtr->pb.csParam.open.validityFlags 	= timeoutValue | timeoutAction;
	statePtr->pb.csParam.open.ulpTimeoutValue 	= 60 /* seconds */;
	statePtr->pb.csParam.open.ulpTimeoutAction 	= 1 /* 1:abort 0:report */;
	statePtr->pb.csParam.open.commandTimeoutValue   = 0;

	statePtr->pb.ioCompletion = completeUPP;
	if (async) {
	    statePtr->flags |= TCP_ASYNC_CONNECT;
	    err = PBControlAsync((ParmBlkPtr) &(statePtr->pb));
	    Tcl_SetErrno(EINPROGRESS);
	} else {
	    err = PBControlSync((ParmBlkPtr) &(statePtr->pb));
	}
    }
    
    switch (err) {
	case noErr:
	    if (!async) {
		statePtr->flags |= TCP_CONNECTED;
	    }
	    return statePtr;
	case duplicateSocket:
	    Tcl_SetErrno(EADDRINUSE);
	    break;
	case openFailed:
	case connectionTerminated:
	    Tcl_SetErrno(ECONNREFUSED);
	    break;
	case invalidStreamPtr:
	case connectionExists:
	default:
	    /*
	     * These cases should never occur.  However, we will fail
	     * gracefully and hope Tcl can resume.  The alternative is to panic
	     * which is probably a bit drastic.
	     */

	    Debugger();
	    Tcl_SetErrno(err);
    }

    /*
     * We had error during the connection.  Release the stream
     * and file handle.  Also report to the interp.
     */

    pb.ioCRefNum = driverRefNum;
    pb.csCode = TCPRelease;
    pb.tcpStream = tcpStream;
    pb.ioCompletion = NULL; 
    err = PBControlSync((ParmBlkPtr) &pb);

    if (interp != (Tcl_Interp *) NULL) {
	Tcl_AppendResult(interp, "couldn't open socket: ",
	    Tcl_PosixError(interp), (char *) NULL);
    }

    ckfree(buffer);
    FreeSocketInfo(statePtr);
    return (TcpState *) NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_OpenTcpClient --
 *
 *	Opens a TCP client socket and creates a channel around it.
 *
 * Results:
 *	The channel or NULL if failed. On failure, the routine also
 *	sets the output argument errorCodePtr to the error code.
 *
 * Side effects:
 *	Opens a client socket and creates a new channel.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_OpenTcpClient(
    Tcl_Interp *interp, 		/* For error reporting; can be NULL. */
    int port, 				/* Port number to open. */
    CONST char *host, 			/* Host on which to open port. */
    CONST char *myaddr,			/* Client-side address */
    int myport, 			/* Client-side port */
    int async)				/* If nonzero, attempt to do an
                                         * asynchronous connect. Otherwise
                                         * we do a blocking connect. 
                                         * - currently ignored */
{
    TcpState *statePtr;
    char channelName[20];

    if (TclpHasSockets(interp) != TCL_OK) {
	return NULL;
    }
	
    /*
     * Create a new client socket and wrap it in a channel.
     */

    statePtr = CreateSocket(interp, port, host, myaddr, myport, 0, async);
    if (statePtr == NULL) {
	return NULL;
    }
    
    sprintf(channelName, "sock%d", socketNumber++);

    statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
            (ClientData) statePtr, (TCL_READABLE | TCL_WRITABLE));
    Tcl_SetChannelBufferSize(statePtr->channel, socketBufferSize);
    Tcl_SetChannelOption(NULL, statePtr->channel, "-translation", "auto crlf");
    return statePtr->channel;
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_OpenTcpServer --
 *
 *	Opens a TCP server socket and creates a channel around it.
 *
 * Results:
 *	The channel or NULL if failed.
 *
 * Side effects:
 *	Opens a server socket and creates a new channel.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_OpenTcpServer(
    Tcl_Interp *interp,			/* For error reporting - may be
                                         * NULL. */
    int port,				/* Port number to open. */
    CONST char *host,			/* Name of local host. */
    Tcl_TcpAcceptProc *acceptProc,	/* Callback for accepting connections
                                         * from new clients. */
    ClientData acceptProcData)		/* Data for the callback. */
{
    TcpState *statePtr;
    char channelName[20];

    if (TclpHasSockets(interp) != TCL_OK) {
	return NULL;
    }

    /*
     * Create a new client socket and wrap it in a channel.
     */

    statePtr = CreateSocket(interp, port, host, NULL, 0, 1, 1);
    if (statePtr == NULL) {
	return NULL;
    }

    statePtr->acceptProc = acceptProc;
    statePtr->acceptProcData = acceptProcData;

    sprintf(channelName, "sock%d", socketNumber++);

    statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
            (ClientData) statePtr, 0);
    Tcl_SetChannelBufferSize(statePtr->channel, socketBufferSize);
    Tcl_SetChannelOption(NULL, statePtr->channel, "-translation", "auto crlf");
    return statePtr->channel;
}

/*
 *----------------------------------------------------------------------
 *
 * SocketEventProc --
 *
 *	This procedure is called by Tcl_ServiceEvent when a socket event
 *	reaches the front of the event queue.  This procedure is
 *	responsible for notifying the generic channel code.
 *
 * Results:
 *	Returns 1 if the event was handled, meaning it should be removed
 *	from the queue.  Returns 0 if the event was not handled, meaning
 *	it should stay on the queue.  The only time the event isn't
 *	handled is if the TCL_FILE_EVENTS flag bit isn't set.
 *
 * Side effects:
 *	Whatever the channel callback procedures do.
 *
 *----------------------------------------------------------------------
 */

static int
SocketEventProc(
    Tcl_Event *evPtr,		/* Event to service. */
    int flags)			/* Flags that indicate what events to
				 * handle, such as TCL_FILE_EVENTS. */
{
    TcpState *statePtr;
    SocketEvent *eventPtr = (SocketEvent *) evPtr;
    int mask = 0;
    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);

    if (!(flags & TCL_FILE_EVENTS)) {
	return 0;
    }

    /*
     * Find the specified socket on the socket list.
     */

    for (statePtr = tsdPtr->socketList; statePtr != NULL;
	    statePtr = statePtr->nextPtr) {
	if ((statePtr == eventPtr->statePtr) && 
		(statePtr->tcpStream == eventPtr->tcpStream)) {
	    break;
	}
    }

    /*
     * Discard events that have gone stale.
     */

    if (!statePtr) {
	return 1;
    }
    statePtr->flags &= ~(TCP_PENDING);
    if (statePtr->flags & TCP_RELEASE) {
	SocketFreeProc(statePtr);
	return 1;
    }


    /*
     * Handle connection requests directly.
     */

    if (statePtr->flags & TCP_LISTEN_CONNECT) {
	if (statePtr->checkMask & TCL_READABLE) {
	    TcpAccept(statePtr);
	}
	return 1;
    }

    /*
     * Mask off unwanted events then notify the channel.
     */

    mask = statePtr->checkMask & statePtr->watchMask;
    if (mask) {
	Tcl_NotifyChannel(statePtr->channel, mask);
    }
    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * WaitForSocketEvent --
 *
 *	Waits until one of the specified events occurs on a socket.
 *
 * Results:
 *	Returns 1 on success or 0 on failure, with an error code in
 *	errorCodePtr.
 *
 * Side effects:
 *	Processes socket events off the system queue.
 *
 *----------------------------------------------------------------------
 */

static int
WaitForSocketEvent(
    TcpState *statePtr,		/* Information about this socket. */
    int mask,			/* Events to look for. */
    int *errorCodePtr)		/* Where to store errors? */
{
    OSErr err;
    TCPiopb statusPB;
    EventRecord dummy;

    /*
     * Loop until we get the specified condition, unless the socket is
     * asynchronous.
     */
    
    do {
	statusPB.ioCRefNum = driverRefNum;
	statusPB.tcpStream = statePtr->tcpStream;
	statusPB.csCode = TCPStatus;
	err = PBControlSync((ParmBlkPtr) &statusPB);
	if (err != noErr) {
            /*
             * I am not sure why it is right to return 1 - indicating success
             * for synchronous sockets when an attempt to get status on the
             * driver yeilds an error.   But it is CERTAINLY wrong for async
             * sockect which have not yet connected.
             */
             
	    if (statePtr->flags & TCP_ASYNC_CONNECT) {
	        *errorCodePtr = EWOULDBLOCK;
	        return 0;
	    } else {
	        statePtr->checkMask |= (TCL_READABLE | TCL_WRITABLE);
	        return 1;
	    }
	}
	statePtr->checkMask = 0;
	
	/*
	 * The "6" below is the "connection being established" flag.  I couldn't
	 * find a define for this in MacTCP.h, but that's what the programmer's
	 * guide says.
	 */
	 
	if ((statusPB.csParam.status.connectionState != 0)
	        && (statusPB.csParam.status.connectionState != 4)
	        && (statusPB.csParam.status.connectionState != 6)) {
	    if (statusPB.csParam.status.amtUnreadData > 0) {
	        statePtr->checkMask |= TCL_READABLE;
	    }
	    if (!(statePtr->flags & TCP_WRITING)
		    && (statusPB.csParam.status.sendWindow - 
			    statusPB.csParam.status.amtUnackedData) > 0) {
	        statePtr->flags &= ~(TCP_ASYNC_CONNECT);
	        statePtr->checkMask |= TCL_WRITABLE;
	    }
	    if (mask & statePtr->checkMask) {
	        return 1;
	    }
        } else {
            break;
        }
        
	/*
	 * Call the system to let other applications run while we
	 * are waiting for this event to occur.
	 */
	
	WaitNextEvent(0, &dummy, 1, NULL);
    } while (!(statePtr->flags & TCP_ASYNC_SOCKET));
    *errorCodePtr = EWOULDBLOCK;
    return 0;
} 

/*
 *----------------------------------------------------------------------
 *
 * TcpAccept --
 *	Accept a TCP socket connection.  This is called by the event 
 *	loop, and it in turns calls any registered callbacks for this
 *	channel.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Evals the Tcl script associated with the server socket.
 *
 *----------------------------------------------------------------------
 */

static void
TcpAccept(
    TcpState *statePtr)
{
    TcpState *newStatePtr;
    StreamPtr tcpStream;
    char remoteHostname[255];
    OSErr err;
    ip_addr remoteAddress;
    long remotePort;
    char channelName[20];
    
    statePtr->flags &= ~TCP_LISTEN_CONNECT;
    statePtr->checkMask &= ~TCL_READABLE;

    /*
     * Transfer sever stream to new connection.
     */

    tcpStream = statePtr->tcpStream;
    newStatePtr = NewSocketInfo(tcpStream);
    newStatePtr->tcpStream = tcpStream;
    sprintf(channelName, "sock%d", socketNumber++);


    newStatePtr->flags |= TCP_CONNECTED;
    newStatePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
            (ClientData) newStatePtr, (TCL_READABLE | TCL_WRITABLE));
    Tcl_SetChannelBufferSize(newStatePtr->channel, socketBufferSize);
    Tcl_SetChannelOption(NULL, newStatePtr->channel, "-translation",
	    "auto crlf");

    remoteAddress = statePtr->pb.csParam.open.remoteHost;
    remotePort = statePtr->pb.csParam.open.remotePort;

    /*
     * Reopen passive connect.  Make new tcpStream the server.
     */

    ClearZombieSockets();
    InitMacTCPParamBlock(&statePtr->pb, TCPCreate);
    statePtr->pb.csParam.create.rcvBuff = ckalloc(socketBufferSize);
    statePtr->pb.csParam.create.rcvBuffLen = socketBufferSize;
    err = PBControlSync((ParmBlkPtr) &statePtr->pb);
    if (err != noErr) {
	/* 
	 * Hmmm...  We can't reopen the server.  We'll go ahead
	 * an continue - but we are kind of broken now...
	 */
	 Debugger();
	 statePtr->tcpStream = -1;
	 statePtr->flags |= TCP_SERVER_ZOMBIE;
    }

    tcpStream = statePtr->tcpStream = statePtr->pb.tcpStream;
    
    InitMacTCPParamBlock(&statePtr->pb, TCPPassiveOpen);
    statePtr->pb.tcpStream = tcpStream;
    statePtr->pb.csParam.open.localHost = 0;
    statePtr->pb.csParam.open.localPort = statePtr->port;
    statePtr->pb.ioCompletion = completeUPP; 
    statePtr->pb.csParam.open.userDataPtr = (Ptr) statePtr;
    statePtr->flags |= TCP_LISTENING;
    err = PBControlAsync((ParmBlkPtr) &(statePtr->pb));
    /*
     * TODO: deal with case where we can't recreate server socket...
     */

    /*
     * Finally we run the accept procedure.  We must do this last to make
     * sure we are in a nice clean state.  This Tcl code can do anything
     * including closing the server or client sockets we've just delt with.
     */

    if (statePtr->acceptProc != NULL) {
	sprintf(remoteHostname, "%d.%d.%d.%d", remoteAddress>>24,
		remoteAddress>>16 & 0xff, remoteAddress>>8 & 0xff,
		remoteAddress & 0xff);
		
	(statePtr->acceptProc)(statePtr->acceptProcData, newStatePtr->channel, 
	    remoteHostname, remotePort);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetHostName --
 *
 *	Returns the name of the local host.
 *
 * Results:
 *	A string containing the network name for this machine, or
 *	an empty string if we can't figure out the name.  The caller 
 *	must not modify or free this string.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

CONST char *
Tcl_GetHostName()
{
    static int  hostnameInited = 0;
    static char hostname[255];
    ip_addr ourAddress;
    Tcl_DString dString;
    OSErr err;
    
    if (hostnameInited) {
        return hostname;
    }
    
    if (TclpHasSockets(NULL) == TCL_OK) {
	err = GetLocalAddress(&ourAddress);
	if (err == noErr) {
	    /*
	     * Search for the doman name and return it if found.  Otherwise, 
	     * just print the IP number to a string and return that.
	     */

	    Tcl_DStringInit(&dString);
	    err = ResolveAddress(ourAddress, &dString);
	    if (err == noErr) {
		strcpy(hostname, dString.string);
	    } else {
		sprintf(hostname, "%d.%d.%d.%d", ourAddress>>24, ourAddress>>16 & 0xff,
		    ourAddress>>8 & 0xff, ourAddress & 0xff);
	    }
	    Tcl_DStringFree(&dString);
	    
	    hostnameInited = 1;
	    return hostname;
	}
    }

    hostname[0] = '\0';
    hostnameInited = 1;
    return hostname;
}

/*
 *----------------------------------------------------------------------
 *
 * ResolveAddress --
 *
 *	This function is used to resolve an ip address to it's full 
 *	domain name address.
 *
 * Results:
 *	An os err value.
 *
 * Side effects:
 *	Treats client data as int we set to true.
 *
 *----------------------------------------------------------------------
 */

static OSErr 
ResolveAddress(
    ip_addr tcpAddress, 	/* Address to resolve. */
    Tcl_DString *dsPtr)		/* Returned address in string. */
{
    int i;
    EventRecord dummy;
    DNRState dnrState;
    OSErr err;

    /*
     * Call AddrToName to resolve our ip address to our domain name.
     * The call is async, so we must wait for a callback to tell us
     * when to continue.
     */

     for (i = 0; i < NUM_ALT_ADDRS; i++) {
	dnrState.hostInfo.addr[i] = 0;
     }
    dnrState.done = 0;
    GetCurrentProcess(&(dnrState.psn));
    err = AddrToName(tcpAddress, &dnrState.hostInfo, resultUPP, (Ptr) &dnrState);
    if (err == cacheFault) {
	while (!dnrState.done) {
	    WaitNextEvent(0, &dummy, 1, NULL);
	}
    }
    
    /*
     * If there is no error in finding the domain name we set the
     * result into the dynamic string.  We also work around a bug in
     * MacTcp where an extranious '.' may be found at the end of the name.
     */

    if (dnrState.hostInfo.rtnCode == noErr) {
	i = strlen(dnrState.hostInfo.cname) - 1;
	if (dnrState.hostInfo.cname[i] == '.') {
	    dnrState.hostInfo.cname[i] = '\0';
	}
	Tcl_DStringAppend(dsPtr, dnrState.hostInfo.cname, -1);
    }
    
    return dnrState.hostInfo.rtnCode;
}

/*
 *----------------------------------------------------------------------
 *
 * DNRCompletionRoutine --
 *
 *	This function is called when the Domain Name Server is done
 *	seviceing our request.  It just sets a flag that we can poll
 *	in functions like Tcl_GetHostName to let them know to continue.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Treats client data as int we set to true.
 *
 *----------------------------------------------------------------------
 */

static pascal void 
DNRCompletionRoutine(
    struct hostInfo *hostinfoPtr, 	/* Host infor struct. */
    DNRState *dnrStatePtr)		/* Completetion state. */
{
    dnrStatePtr->done = true;
    WakeUpProcess(&(dnrStatePtr->psn));
}

/*
 *----------------------------------------------------------------------
 *
 * CleanUpExitProc --
 *
 *	This procedure is invoked as an exit handler when ExitToShell
 *	is called.  It aborts any lingering socket connections.  This 
 *	must be called or the Mac OS will more than likely crash.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static pascal void
CleanUpExitProc()
{
    TCPiopb exitPB;
    TcpState *statePtr;
    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);

    while (tsdPtr->socketList != NULL) {
	statePtr = tsdPtr->socketList;
	tsdPtr->socketList = statePtr->nextPtr;

	/*
	 * Close and Release the connection.
	 */

	exitPB.ioCRefNum = driverRefNum;
	exitPB.csCode = TCPClose;
	exitPB.tcpStream = statePtr->tcpStream;
	exitPB.csParam.close.ulpTimeoutValue = 60 /* seconds */;
	exitPB.csParam.close.ulpTimeoutAction = 1 /* 1:abort 0:report */;
	exitPB.csParam.close.validityFlags = timeoutValue | timeoutAction;
	exitPB.ioCompletion = NULL; 
	PBControlSync((ParmBlkPtr) &exitPB);

	exitPB.ioCRefNum = driverRefNum;
	exitPB.csCode = TCPRelease;
	exitPB.tcpStream = statePtr->tcpStream;
	exitPB.ioCompletion = NULL; 
	PBControlSync((ParmBlkPtr) &exitPB);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetHostFromString --
 *
 *	Looks up the passed in domain name in the domain resolver.  It
 *	can accept strings of two types: 1) the ip number in string
 *	format, or 2) the domain name.
 *
 * Results:
 *	We return a ip address or 0 if there was an error or the 
 *	domain does not exist.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static OSErr
GetHostFromString(
    CONST char *name, 		/* Host in string form. */
    ip_addr *address)		/* Returned IP address. */
{
    OSErr err;
    int i;
    EventRecord dummy;
    DNRState dnrState;
	
    if (TclpHasSockets(NULL) != TCL_OK) {
	return 0;
    }

    /*
     * Call StrToAddr to get the ip number for the passed in domain
     * name.  The call is async, so we must wait for a callback to 
     * tell us when to continue.
     */

    for (i = 0; i < NUM_ALT_ADDRS; i++) {
	dnrState.hostInfo.addr[i] = 0;
    }
    dnrState.done = 0;
    GetCurrentProcess(&(dnrState.psn));
    err = StrToAddr((char*)name, &dnrState.hostInfo, resultUPP, (Ptr) &dnrState);
    if (err == cacheFault) {
	while (!dnrState.done) {
	    WaitNextEvent(0, &dummy, 1, NULL);
	}
    }
    
    /*
     * For some reason MacTcp may return a cachFault a second time via
     * the hostinfo block.  This seems to be a bug in MacTcp.  In this case 
     * we run StrToAddr again - which seems to then work just fine.
     */

    if (dnrState.hostInfo.rtnCode == cacheFault) {
	dnrState.done = 0;
	err = StrToAddr((char*)name, &dnrState.hostInfo, resultUPP, (Ptr) &dnrState);
	if (err == cacheFault) {
	    while (!dnrState.done) {
		WaitNextEvent(0, &dummy, 1, NULL);
	    }
	}
    }

    if (dnrState.hostInfo.rtnCode == noErr) {
	*address = dnrState.hostInfo.addr[0];
    }
    
    return dnrState.hostInfo.rtnCode;
}

/*
 *----------------------------------------------------------------------
 *
 * IOCompletionRoutine --
 *
 *	This function is called when an asynchronous socket operation
 *	completes.  Since this routine runs as an interrupt handler, 
 *	it will simply set state to tell the notifier that this socket
 *	is now ready for action.  Note that this function is running at
 *	interupt time and can't allocate memory or do much else except 
 *      set state.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Sets some state in the socket state.  May also wake the process
 *	if we are not currently running.
 *
 *----------------------------------------------------------------------
 */

static void
IOCompletionRoutine(
    TCPiopb *pbPtr)		/* Tcp parameter block. */
{
    TcpState *statePtr;
    
    if (pbPtr->csCode == TCPSend) {
    	statePtr = (TcpState *) pbPtr->csParam.send.userDataPtr;
    } else {
	statePtr = (TcpState *) pbPtr->csParam.open.userDataPtr;
    }
    
    /*
     * Always wake the process in case it's in WaitNextEvent.
     * If an error has a occured - just return.  We will deal
     * with the problem later.
     */

    WakeUpProcess(&statePtr->psn);
    if (pbPtr->ioResult != noErr) {
	return;
    }
    
    if (statePtr->flags & TCP_ASYNC_CONNECT) {
	statePtr->flags &= ~TCP_ASYNC_CONNECT;
	statePtr->flags |= TCP_CONNECTED;
	statePtr->checkMask |= TCL_READABLE & TCL_WRITABLE;
    } else if (statePtr->flags & TCP_LISTENING) {
	if (statePtr->port == 0) {
	    Debugger();
	}
	statePtr->flags &= ~TCP_LISTENING;
	statePtr->flags |= TCP_LISTEN_CONNECT;
	statePtr->checkMask |= TCL_READABLE;
    } else if (statePtr->flags & TCP_WRITING) {
	statePtr->flags &= ~TCP_WRITING;
	statePtr->checkMask |= TCL_WRITABLE;
	if (!(statePtr->flags & TCP_CONNECTED)) {
	    InitMacTCPParamBlock(&statePtr->pb, TCPClose);
    	    statePtr->pb.tcpStream = statePtr->tcpStream;
    	    statePtr->pb.ioCompletion = closeUPP; 
    	    statePtr->pb.csParam.close.userDataPtr = (Ptr) statePtr;
    	    if (PBControlAsync((ParmBlkPtr) &statePtr->pb) != noErr) {
	        statePtr->flags |= TCP_RELEASE;
    	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetLocalAddress --
 *
 *	Get the IP address for this machine.  The result is cached so
 *	the result is returned quickly after the first call.
 *
 * Results:
 *	Macintosh error code.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static OSErr 
GetLocalAddress(
    unsigned long *addr)	/* Returns host IP address. */
{
    struct GetAddrParamBlock pBlock;
    OSErr err = noErr;
    static unsigned long localAddress = 0;

    if (localAddress == 0) {
	memset(&pBlock, 0, sizeof(pBlock));
	pBlock.ioResult = 1;
	pBlock.csCode = ipctlGetAddr;
	pBlock.ioCRefNum = driverRefNum;
	err = PBControlSync((ParmBlkPtr) &pBlock);

	if (err != noErr) {
	    return err;
	}
	localAddress = pBlock.ourAddress;
    }
    
    *addr = localAddress;
    return noErr;
}

/*
 *----------------------------------------------------------------------
 *
 * GetBufferSize --
 *
 *	Get the appropiate buffer size for our machine & network.  This
 *	value will be used by the rest of Tcl & the MacTcp driver for
 *	the size of its buffers.  If out method for determining the
 *	optimal buffer size fails for any reason - we return a 
 *	reasonable default.
 *
 * Results:
 *	Size of optimal buffer in bytes.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static long 
GetBufferSize()
{
    UDPiopb iopb;
    OSErr err = noErr;
    long bufferSize;
	
    memset(&iopb, 0, sizeof(iopb));
    err = GetLocalAddress(&iopb.csParam.mtu.remoteHost);
    if (err != noErr) {
	return CHANNEL_BUF_SIZE;
    }
    iopb.ioCRefNum = driverRefNum;
    iopb.csCode = UDPMaxMTUSize;
    err = PBControlSync((ParmBlkPtr)&iopb);
    if (err != noErr) {
	return CHANNEL_BUF_SIZE;
    }
    bufferSize = (iopb.csParam.mtu.mtuSize * 4) + 1024;
    if (bufferSize < CHANNEL_BUF_SIZE) {
	bufferSize = CHANNEL_BUF_SIZE;
    }
    return bufferSize;
}

/*
 *----------------------------------------------------------------------
 *
 * TclSockGetPort --
 *
 *	Maps from a string, which could be a service name, to a port.
 *	Used by socket creation code to get port numbers and resolve
 *	registered service names to port numbers.
 *
 * Results:
 *	A standard Tcl result.  On success, the port number is
 *	returned in portPtr. On failure, an error message is left in
 *	the interp's result.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TclSockGetPort(
    Tcl_Interp *interp, 	/* Interp for error messages. */
    char *string, 		/* Integer or service name */
    char *proto, 		/* "tcp" or "udp", typically - 
    				 * ignored on Mac - assumed to be tcp */
    int *portPtr)		/* Return port number */
{
    PortInfo *portInfoPtr = NULL;
    
    if (Tcl_GetInt(interp, string, portPtr) == TCL_OK) {
	if (*portPtr > 0xFFFF) {
	    Tcl_AppendResult(interp, "couldn't open socket: port number too high",
                (char *) NULL);
	    return TCL_ERROR;
	}
	if (*portPtr < 0) {
	    Tcl_AppendResult(interp, "couldn't open socket: negative port number",
                (char *) NULL);
	    return TCL_ERROR;
	}
	return TCL_OK;
    }
    for (portInfoPtr = portServices; portInfoPtr->name != NULL; portInfoPtr++) {
	if (!strcmp(portInfoPtr->name, string)) {
	    break;
	}
    }
    if (portInfoPtr != NULL && portInfoPtr->name != NULL) {
	*portPtr = portInfoPtr->port;
	Tcl_ResetResult(interp);
	return TCL_OK;
    }
    
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * ClearZombieSockets --
 *
 *	This procedure looks through the socket list and removes the
 *	first stream it finds that is ready for release. This procedure 
 *	should be called before we ever try to create new Tcp streams
 *	to ensure we can least allocate one stream.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Tcp streams may be released.
 *
 *----------------------------------------------------------------------
 */

static void
ClearZombieSockets()
{
    TcpState *statePtr;
    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);

    for (statePtr = tsdPtr->socketList; statePtr != NULL;
	    statePtr = statePtr->nextPtr) {
	if (statePtr->flags & TCP_RELEASE) {
	    SocketFreeProc(statePtr);
	    return;
	}
    }
}


/*
 *----------------------------------------------------------------------
 *
 * NotifyRoutine --
 *
 *	This routine does nothing currently, and is not being used.  But
 *      it is useful if you want to experiment with what MacTCP thinks that
 *      it is doing...
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
pascal void NotifyRoutine (
    StreamPtr tcpStream,
    unsigned short eventCode,
    Ptr userDataPtr,
    unsigned short terminReason,
    struct ICMPReport *icmpMsg)
{
    StreamPtr localTcpStream;
    unsigned short localEventCode;
    unsigned short localTerminReason;
    struct ICMPReport localIcmpMsg;

    localTcpStream = tcpStream;
    localEventCode = eventCode;
    localTerminReason = terminReason;
    localIcmpMsg = *icmpMsg;
        
}