]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - mactcp.c
Removing one bug, and hunting another
[PuTTY.git] / mactcp.c
1 /* $Id: mactcp.c,v 1.1.2.1 1999/08/02 08:06:32 ben Exp $ */
2 /*
3  * Copyright (c) 1999 Ben Harris
4  * All rights reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person
7  * obtaining a copy of this software and associated documentation
8  * files (the "Software"), to deal in the Software without
9  * restriction, including without limitation the rights to use,
10  * copy, modify, merge, publish, distribute, sublicense, and/or
11  * sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following
13  * conditions:
14  * 
15  * The above copyright notice and this permission notice shall be
16  * included in all copies or substantial portions of the Software.
17  * 
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
22  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
23  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25  * SOFTWARE.
26  */
27 /*
28  * macnet.c -- PuTTY-to-MacTCP glue
29  */
30
31 #include <MacTypes.h>
32 #include <AddressXlation.h>
33 #include <Devices.h>
34 #include <MacTCP.h>
35 #include <MixedMode.h>
36 #include <OSUtils.h>
37 #include <Processes.h>
38
39 #include <assert.h>
40 #include <stdlib.h>
41 #include <string.h>
42
43 #include "putty.h"
44
45 /*
46  * The theory behind this stuff:
47  *
48  * net_recv attempts to deliver any incoming data waiting on the
49  * queue.  Since MacTCP maintains a buffer for incoming data, there's
50  * no need for us to run asynchronous TCPRcvs, and we just do a
51  * synchronous one if we detect some data waiting.  Since TCPRcv can't
52  * be given a timeout of zero, we use TCPStatus to work out if there's
53  * anything waiting first.
54  *
55  * Sending data is trickier.  TCPSend reserves the right to block
56  * until everything we've sent is ACKed, which means we have to use it
57  * asynchronously.  In order to make life easier for backends, and to
58  * save a proliferation of circular buffers, we guarantee to take data
59  * off the hands of the backend as soon as it gives it to us.  This is
60  * reasonable because currently there's no way for the backend to say
61  * it can't take data, and once it's got them, it may as well give
62  * them to us.
63  * 
64  * Anyway, in order to avoid a fixed-size buffer overflowing, the send
65  * buffer is kept as a queue of blocks.  When net_send is called, we
66  * malloc a new block and stick it on the queue.  If the queue was
67  * empty, we kick off a new asynchronous TCPSend to handle our block.
68  *
69  */
70
71 typedef struct Socket {
72     TCPiopb iopb; /* current MacTCP operation */
73     TCPiopb spareiopb; /* for closing etc */
74     hostInfo hostinfo;
75     int port;
76     ProcessSerialNumber psn;
77     Session *s;
78 #if TARGET_CPU_68K && !TARGET_RT_CFM
79     long a5;
80 #endif
81     QHdr sendq; /* Blocks waiting to be sent */
82 } Socket;
83
84 typedef struct {
85     QElem qelem;
86     int flags;
87     wdsEntry wds;
88     short wdsterm;
89 } Send_Buffer;
90
91 /*
92  * Yes, I know the struct QElem has a short[1] to represent the user
93  * data.  I'm ignoring it because it makes my code prettier and
94  * improves the alignment.
95  */
96
97 typedef struct {
98     QElem qelem;
99     Socket *sock;
100     Net_Event_Type type;
101 } NetEvent;
102
103 #define TCPBUF_SIZE 8192
104
105 static QHdr macnet_eventq;
106 static QHdr macnet_freeq;
107
108 static short mtcp_refnum;
109 static int mtcp_initted = FALSE;
110
111 static OSErr macnet_init(void);
112 static pascal void macnet_resolved(hostInfo *, char *);
113 static void macnet_completed_open(TCPiopb*);
114 static void macnet_completed_send(TCPiopb*);
115 static void macnet_sent(Socket *);
116 static void macnet_startsend(Socket *);
117 static void macnet_completed_close(TCPiopb*);
118 static pascal void macnet_asr(StreamPtr, unsigned short, Ptr, unsigned short,
119                               ICMPReport *);
120 static void macnet_sendevent(Socket *, Net_Event_Type);
121
122 #if TARGET_RT_MAC_CFM
123 static RoutineDescriptor macnet_resolved_upp =
124     BUILD_ROUTINE_DESCRIPTOR(uppResultProcInfo, (ProcPtr)macnet_resolved);
125 static RoutineDescriptor macnet_completed_open_upp =
126     BUILD_ROUTINE_DESCRIPTOR(uppTCPIOCompletionProcInfo,
127                              (ProcPtr)macnet_completed_open);
128 static RoutineDescriptor macnet_complete_send_upp =
129     BUILD_ROUTINE_DESCRIPTOR(uppTCPIOCompletionProcInfo,
130                              (ProcPtr)macnet_completed_send);
131 static RoutineDescriptor macnet_completed_close_upp =
132     BUILD_ROUTINE_DESCRIPTOR(uppTCPIOCompletionProcInfo,
133                              (ProcPtr)macnet_completed_close);
134 static RoutineDescriptor macnet_asr_upp =
135     BUILD_ROUTINE_DESCRIPTOR(uppTCPNotifyProcInfo, (ProcPtr)macnet_asr);
136 #else
137 /* These handle A5 switching to thwart the optimiser. */
138 static pascal void macnet_resolved_upp(hostInfo *, char *);
139 static void macnet_completed_open_upp(TCPiopb *);
140 static void macnet_completed_send_upp(TCPiopb *);
141 static void macnet_completed_close_upp(TCPiopb *);
142 /* ASRs apparently get their A5 world set up for them. */
143 #define macnet_asr_upp macnet_asr
144 #endif
145
146 /*
147  * Number of outstanding network events allowed. 
148  */
149 #define NUM_EVENTS 16
150
151 /*
152  * Initialise networking.  Set mtcp_initted if it goes OK.
153  */
154 static OSErr macnet_init(void) {
155     OSErr err;
156     NetEvent *eventblock;
157     int i;
158
159     /*
160      * FIXME: This is hideously broken, in that we're meant to faff
161      * with unit numbers and stuff, and we blatantly don't.
162      * On the other hand, neither does NCSA Telnet.  Hmm.
163      */
164     err = opendriver(".IPP", &mtcp_refnum);
165     if (err != noErr)
166         return err;
167     err = OpenResolver(NULL);
168     if (err != noErr)
169         return err;
170     /* Set up the event queues, and fill the free queue with events */
171     macnet_eventq.qFlags = 0;
172     macnet_eventq.qHead = macnet_eventq.qTail = NULL;
173     macnet_freeq.qFlags = 0;
174     macnet_freeq.qHead = macnet_eventq.qTail = NULL;
175     eventblock = smalloc(NUM_EVENTS * sizeof(*eventblock));
176     for (i = 0; i < NUM_EVENTS; i++)
177         Enqueue(&eventblock[i].qelem, &macnet_freeq);
178     mtcp_initted = TRUE;
179     return 0;
180 }
181
182 Socket *net_open(Session *s, char *host, int port) {
183     ip_addr a;
184     OSErr err = noErr;
185     Socket *sock;
186     void *tcpbuf;
187
188     /*
189      * First, get hold of all the memory we'll need (a lot of the
190      * later stuff happens at interrupt time)
191      */
192     sock = smalloc(sizeof(*sock));
193     memset(sock, 0, sizeof(*sock));
194     tcpbuf = smalloc(TCPBUF_SIZE);
195
196     /* Make a note of anything we don't want to forget */
197     sock->port = port;
198     GetCurrentProcess(&sock->psn);
199 #if TARGET_CPU_68K && !TARGET_RT_CFM
200     sock->a5 = SetCurrentA5();
201 #endif
202
203     /* Get MacTCP running if it's not already */
204     if (!mtcp_initted)
205         if ((err = macnet_init()) != noErr)
206             fatalbox("Couldn't init network (%d)", err);
207
208     /* Get ourselves a TCP stream to play with */
209     sock->iopb.ioCRefNum = mtcp_refnum;
210     sock->iopb.ioCompletion = NULL;
211     sock->iopb.csCode = TCPCreate;
212     sock->iopb.csParam.create.rcvBuff = tcpbuf;
213     sock->iopb.csParam.create.rcvBuffLen = TCPBUF_SIZE;
214     sock->iopb.csParam.create.notifyProc = macnet_asr_upp;
215     sock->iopb.csParam.create.userDataPtr = (Ptr)sock;
216     /* This could be done asynchronously, but I doubt it'll take long. */
217     err = PBControlSync((ParmBlkPtr)&sock->iopb);
218     if (err != noErr)
219         fatalbox("TCP stream create failed (%d)", err);
220
221     err = StrToAddr(host, &sock->hostinfo, &macnet_resolved_upp, (char *)sock);
222     /*
223      * A cache fault indicates that the DNR will call us back when
224      * it's found the host for us.
225      */
226     if (err != cacheFault)
227         macnet_resolved(&sock->hostinfo, (char *)sock);
228     return sock;
229 }
230
231 #if TARGET_CPU_68K && !TARGET_RT_CFM
232 static pascal void macnet_resolved_upp(hostInfo *hi, char *cookie) {
233     Socket *sock = (Socket *)cookie;
234     long olda5;
235
236     olda5 = SetA5(sock->a5);
237     macnet_resolved(hi, cookie);
238     SetA5(olda5);
239 }
240 #endif
241
242 static pascal void macnet_resolved(hostInfo *hi, char *cookie) {
243     Socket *sock = (Socket *)cookie;
244     OSErr err;
245
246     /*
247      * We've resolved a name, so now we'd like to connect to it (or
248      * report an error).
249      */
250     switch (sock->hostinfo.rtnCode) {
251       case noErr:
252         /* Open a connection */
253         sock->iopb.ioCompletion = macnet_completed_open_upp;
254         sock->iopb.csCode = TCPActiveOpen;
255         memset(&sock->iopb.csParam, 0, sizeof(sock->iopb.csParam));
256         sock->iopb.csParam.open.validityFlags = typeOfService;
257         sock->iopb.csParam.open.remoteHost = sock->hostinfo.addr[0]; /*XXX*/
258         sock->iopb.csParam.open.remotePort = sock->port;
259         sock->iopb.csParam.open.tosFlags = lowDelay;
260         sock->iopb.csParam.open.userDataPtr = (char *)sock;
261         err = PBControlAsync((ParmBlkPtr)&sock->iopb);
262         if (err != noErr)
263             macnet_sendevent(sock, NE_NOOPEN);
264         break;
265       default: /* Something went wrong */
266         macnet_sendevent(sock, NE_NOHOST);
267         break;
268     }
269 }
270
271 #if TARGET_CPU_68K && !TARGET_RT_CFM
272 static void macnet_completed_open_upp(TCPiopb *iopb) {
273     Socket *sock = (Socket *)iopb->csParam.open.userDataPtr;
274     long olda5;
275
276     olda5 = SetA5(sock->a5);
277     macnet_completed_open(iopb);
278     SetA5(olda5);
279 }
280 #endif
281
282 static void macnet_completed_open(TCPiopb *iopb) {
283     Socket *sock = (Socket *)iopb->csParam.open.userDataPtr;
284
285     switch (iopb->ioResult) {
286       case noErr:
287         macnet_sendevent(sock, NE_OPEN);
288         break;
289       default:
290         macnet_sendevent(sock, NE_NOOPEN);
291         break;
292     }
293 }
294
295 static pascal void macnet_asr(StreamPtr tcpstream, unsigned short eventcode,
296                               Ptr cookie, unsigned short terminreason,
297                               ICMPReport *icmpmsg) {
298     Socket *sock = (Socket *)cookie;
299
300     switch (eventcode) {
301       case TCPClosing:
302         macnet_sendevent(sock, NE_CLOSING);
303         break;
304       case TCPULPTimeout:
305         macnet_sendevent(sock, NE_TIMEOUT);
306         break;
307       case TCPTerminate:
308         switch (terminreason) {
309           case TCPRemoteAbort:
310             macnet_sendevent(sock, NE_ABORT);
311             break;
312           default:
313             macnet_sendevent(sock, NE_DIED);
314             break;
315         }
316         break;
317       case TCPDataArrival:
318         macnet_sendevent(sock, NE_DATA);
319         break;
320       case TCPUrgent:
321         macnet_sendevent(sock, NE_URGENT);
322         break;
323       case TCPICMPReceived:
324         switch (icmpmsg->reportType) {
325           case portUnreach:
326             macnet_sendevent(sock, NE_REFUSED);
327             break;
328         }
329         break;
330     }
331 }
332
333 /*
334  * Send a block of data.
335  */
336
337 int net_send(Socket *sock, void *buf, int buflen, int flags) {
338     OSErr err;
339     Send_Buffer *buff;
340
341     buff = smalloc(sizeof(Send_Buffer) + buflen);
342     buff->flags = flags;
343     buff->wds.length = buflen;
344     buff->wds.ptr = (Ptr)&buff[1]; /* after the end of the struct */
345     buff->wdsterm = 0;
346     memcpy(&buff[1], buf, buflen);
347     Enqueue(&buff->qelem, &sock->sendq);
348     /* Kick off the transmit if the queue was empty */
349     if (sock->sendq.qHead == &buff->qelem)
350         macnet_startsend(sock);
351 }
352
353 /*
354  * This is called once every time round the event loop to check for
355  * network events and handle them.
356  */
357 void macnet_eventcheck() {
358     NetEvent *ne;
359
360     if (!mtcp_initted)
361         return;
362     ne = (NetEvent *)macnet_eventq.qHead;
363     if (ne == NULL)
364         return;
365     Dequeue(&ne->qelem, &macnet_eventq);
366     switch (ne->type) {
367       case NE_SENT:
368         macnet_sent(ne->sock);
369         break;
370       default:
371         (ne->sock->s->back->msg)(ne->sock->s, ne->sock, ne->type);
372         break;
373     }
374     Enqueue(&ne->qelem, &macnet_freeq);
375 }
376
377 /*
378  * The block at the head of the send queue has finished sending, so we
379  * can free it.  Kick off the next transmission if there is one.
380  */
381 static void macnet_sent(Socket *sock) {
382     Send_Buffer *buff;
383
384     assert(sock->sendq.qHead != NULL);
385     buff = (Send_Buffer *)sock->sendq.qHead;
386     Dequeue(&buff->qelem, &sock->sendq);
387     sfree(buff);
388     if (sock->sendq.qHead != NULL)
389         macnet_startsend(sock);
390 }
391
392 /*
393  * There's a block on the head of the send queue which needs to be
394  * sent.
395  */
396
397 static void macnet_startsend(Socket *sock) {
398     Send_Buffer *buff;
399     OSErr err;
400
401     buff = (Send_Buffer *)sock->sendq.qHead;
402     sock->iopb.ioCompletion = macnet_completed_send_upp;
403     sock->iopb.csCode = TCPSend;
404     memset(&sock->iopb.csParam, 0, sizeof(sock->iopb.csParam));
405     sock->iopb.csParam.send.validityFlags = 0;
406     sock->iopb.csParam.send.pushFlag = buff->flags & SEND_PUSH ? true : false;
407     sock->iopb.csParam.send.urgentFlag = buff->flags & SEND_URG ? true : false;
408     sock->iopb.csParam.send.wdsPtr = (Ptr)&buff->wds;
409     sock->iopb.csParam.send.userDataPtr = (char *)sock;
410     err = PBControlAsync((ParmBlkPtr)&sock->iopb);
411 }
412
413 #if TARGET_CPU_68K && !TARGET_RT_CFM
414 static void macnet_completed_send_upp(TCPiopb *iopb) {
415     Socket *sock = (Socket *)iopb->csParam.send.userDataPtr;
416     long olda5;
417
418     olda5 = SetA5(sock->a5);
419     macnet_completed_send(iopb);
420     SetA5(olda5);
421 }
422 #endif
423
424 static void macnet_completed_send(TCPiopb *iopb) {
425     Socket *sock = (Socket *)iopb->csParam.send.userDataPtr;
426
427     switch (iopb->ioResult) {
428       case noErr:
429         macnet_sendevent(sock, NE_SENT);
430         break;
431       case connectionClosing:
432       case connectionTerminated:
433         /* We'll get an ASR, so ignore it here. */
434         break;
435       default:
436         macnet_sendevent(sock, NE_DIED);
437         break;
438     }
439 }
440
441
442 int net_recv(Socket *sock, void *buf, int buflen, int flags) {
443     TCPiopb iopb;
444     OSErr err;
445     int avail, want, got;
446
447     memcpy(&iopb, &sock->iopb, sizeof(TCPiopb));
448     /* Work out if there's anything to recieve (we don't want to block)  */
449     iopb.ioCompletion = NULL;
450     iopb.csCode = TCPStatus;
451     memset(&sock->iopb.csParam, 0, sizeof(sock->iopb.csParam));
452     err = PBControlSync((ParmBlkPtr)&iopb);
453     if (err != noErr)
454         return 0; /* macnet_asr should catch it anyway */
455     avail = iopb.csParam.status.amtUnreadData;
456     if (avail == 0)
457         return 0;
458     want = avail < buflen ? avail : buflen;
459     iopb.ioCompletion = NULL;
460     iopb.csCode = TCPRcv;
461     memset(&sock->iopb.csParam, 0, sizeof(sock->iopb.csParam));
462     iopb.csParam.receive.rcvBuff = buf;
463     iopb.csParam.receive.rcvBuffLen = want;
464     err = PBControlSync((ParmBlkPtr)&iopb);
465     if (err != noErr)
466         return 0;
467     return iopb.csParam.receive.rcvBuffLen;
468 }
469         
470
471 void net_close(Socket *sock) {
472     OSErr err;
473
474     /*
475      * This might get called in the middle of processing another
476      * request on the socket, so we have a spare parameter block for
477      * this purpose (allocating one dynamically would mean having to
478      * free it, which we can't do at interrupt time).
479      */
480     memcpy(&sock->spareiopb, &sock->iopb, sizeof(TCPiopb));
481     memset(&sock->spareiopb.csParam, 0, sizeof(sock->spareiopb.csParam));
482     sock->spareiopb.ioCompletion = macnet_completed_close_upp;
483     sock->spareiopb.csCode = TCPClose;
484     sock->spareiopb.csParam.close.validityFlags = 0;
485     sock->spareiopb.csParam.close.userDataPtr = (char *)sock;
486     err = PBControlAsync((ParmBlkPtr)&sock->spareiopb);
487     switch (err) {
488       case noErr:
489       case connectionClosing:
490       case connectionTerminated: /* We'll get an ASR */
491         break;
492       default:
493         macnet_sendevent(sock, NE_DIED);
494         break;
495     }
496 }
497
498 #if TARGET_CPU_68K && !TARGET_RT_CFM
499 static void macnet_completed_close_upp(TCPiopb* iopb) {
500     Socket *sock = (Socket *)iopb->csParam.close.userDataPtr;
501     long olda5;
502
503     olda5 = SetA5(sock->a5);
504     macnet_completed_close(iopb);
505     SetA5(olda5);
506 }
507 #endif
508
509 static void macnet_completed_close(TCPiopb* iopb) {
510     Socket *sock = (Socket *)iopb->csParam.close.userDataPtr;
511
512     switch (iopb->ioResult) {
513       case noErr:
514         macnet_sendevent(sock, NE_CLOSED);
515         break;
516       case connectionClosing:
517       case connectionTerminated:
518         break;
519       default:
520         macnet_sendevent(sock, NE_DIED);
521         break;
522     }
523 }
524
525 /*
526  * Free all the data structures associated with a socket and tear down
527  * any connection through it.
528  */
529 void net_destroy(Socket *sock) {
530     TCPiopb iopb;
531     OSErr err;
532
533     /*
534      * Yes, we need _another_ iopb, as there may be a send _and_ a
535      * close outstanding.  Luckily, destroying a socket is
536      * synchronous, so we can allocate this one dynamically.
537      */
538     memcpy(&iopb, &sock->iopb, sizeof(TCPiopb));
539     iopb.ioCompletion = NULL;
540     iopb.csCode = TCPRelease;
541     memset(&iopb.csParam, 0, sizeof(iopb.csParam));
542     err = PBControlSync((ParmBlkPtr)&iopb);
543     sfree(iopb.csParam.create.rcvBuff);
544     sfree(sock);
545 }
546
547 static void macnet_sendevent(Socket *sock, Net_Event_Type type) {
548     NetEvent *ne;
549
550     ne = (NetEvent *)macnet_freeq.qHead;
551     if (ne == NULL) return; /* It's a disaster, but how do we tell anyone? */
552     Dequeue(&ne->qelem, &macnet_freeq);
553     ne->sock = sock;
554     ne->type = type;
555     Enqueue(&ne->qelem, &macnet_eventq);
556     WakeUpProcess(&sock->psn);
557 }
558
559 /*
560  * Local Variables:
561  * c-file-style: "simon"
562  * End:
563  */