]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - mac/mtcpnet.c
af694d0203af4b449aaee2fd1a85982fef0d180d
[PuTTY.git] / mac / mtcpnet.c
1 /*
2  * Copyright (c) 2003 Ben Harris
3  * All rights reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person
6  * obtaining a copy of this software and associated documentation
7  * files (the "Software"), to deal in the Software without
8  * restriction, including without limitation the rights to use,
9  * copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following
12  * conditions:
13  * 
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  * 
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
21  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
22  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24  * SOFTWARE.
25  */
26 /*
27  * mtcpnet.c - MacTCP interface
28  */
29
30 #include <MacTypes.h>
31 #include <Devices.h>
32 #include <Endian.h>
33 #include <Folders.h>
34 #include <MacTCP.h>
35 #include <MixedMode.h>
36 #include <Resources.h>
37
38 #include <assert.h>
39
40 #include "putty.h"
41 #include "network.h"
42 #include "mac.h"
43
44 /*
45  * The following structures are documented as being in
46  * <AddressXlation.h>, but that isn't shipped with Universal
47  * Interfaces, and it's easier to define them here than to require
48  * people to download yet another SDK.
49  */
50
51 static OSErr OpenResolver(char *);
52 static OSErr CloseResolver(void);
53
54 enum {
55     OPENRESOLVER = 1,
56     CLOSERESOLVER,
57     STRTOADDR,
58     ADDRTOSTR,
59     ENUMCACHE,
60     ADDRTONAME,
61     HXINFO,
62     MXINFO
63 };
64
65 #define NUM_ALT_ADDRS 4
66
67 typedef struct hostInfo {
68     int rtnCode;
69     char cname[255];
70     unsigned long addr[NUM_ALT_ADDRS];
71 };
72
73 typedef CALLBACK_API(void, ResultProcPtr)(struct hostInfo *, char *);
74 typedef STACK_UPP_TYPE(ResultProcPtr) ResultUPP;
75 enum { uppResultProcInfo = kPascalStackBased
76        | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(struct hostInfo*)))
77        | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(char *)))
78 };
79 #define NewResultUPP(userRoutine)                                       \
80     (ResultUPP)NewRoutineDescriptor((ProcPtr)(userRoutine),             \
81                                     uppResultProcInfo,                  \
82                                     GetCurrentArchitecture())
83 #define DisposeResultUPP(userUPP) DisposeRoutineDescriptor(userUPP)
84
85 static OSErr StrToAddr(char *, struct hostInfo *, ResultUPP *, char *);
86
87 typedef CALLBACK_API_C(OSErr, OpenResolverProcPtr)(UInt32, char *);
88 typedef STACK_UPP_TYPE(OpenResolverProcPtr) OpenResolverUPP;
89 enum { uppOpenResolverProcInfo = kCStackBased
90        | RESULT_SIZE(SIZE_CODE(sizeof(OSErr)))
91        | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(UInt32)))
92        | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(char*)))
93 };
94 #define InvokeOpenResolverUPP(selector, fileName, userUPP)              \
95     CALL_TWO_PARAMETER_UPP((userUPP), uppOpenResolverProcInfo,          \
96                            (selector), (fileName))
97
98 typedef CALLBACK_API_C(OSErr, CloseResolverProcPtr)(UInt32);
99 typedef STACK_UPP_TYPE(CloseResolverProcPtr) CloseResolverUPP;
100 enum { uppCloseResolverProcInfo = kCStackBased
101        | RESULT_SIZE(SIZE_CODE(sizeof(OSErr)))
102        | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(UInt32)))
103 };
104 #define InvokeCloseResolverUPP(selector, userUPP)                       \
105     CALL_ONE_PARAMETER_UPP((userUPP), uppCloseResolverProcInfo, (selector))
106
107 typedef CALLBACK_API_C(OSErr, StrToAddrProcPtr)(UInt32, char *,
108                                                 struct hostInfo *, ResultUPP,
109                                                 char *);
110 typedef STACK_UPP_TYPE(StrToAddrProcPtr) StrToAddrUPP;
111 enum { uppStrToAddrProcInfo = kCStackBased
112        | RESULT_SIZE(SIZE_CODE(sizeof(OSErr)))
113        | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(UInt32)))
114        | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(char *)))
115        | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(struct hostInfo *)))
116        | STACK_ROUTINE_PARAMETER(4, SIZE_CODE(sizeof(ResultUPP)))
117        | STACK_ROUTINE_PARAMETER(5, SIZE_CODE(sizeof(char *)))
118 };
119 #define InvokeStrToAddrUPP(selector, hostName, hostInfoPtr, ResultProc, \
120                            userDataPtr, userUPP)                        \
121     CALL_FIVE_PARAMETER_UPP((userUPP), uppStrToAddrProcInfo, (selector),\
122                             (hostName), (hostInfoPtr), (ResultProc),    \
123                             (userDataPtr))
124 #define StrToAddr(hostName, hostInfoPtr, ResultProc, userDataPtr)       \
125     InvokeStrToAddrUPP(STRTOADDR, hostName, hostInfoPtr, ResultProc,    \
126                        userDataPtr, (StrToAddrUPP)*mactcp.dnr_handle)
127
128 typedef CALLBACK_API_C(OSErr, AddrToStrProcPtr)(UInt32, unsigned long, char *);
129 typedef STACK_UPP_TYPE(AddrToStrProcPtr) AddrToStrUPP;
130 enum { uppAddrToStrProcInfo = kCStackBased
131        | RESULT_SIZE(SIZE_CODE(sizeof(OSErr)))
132        | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(unsigned long)))
133        | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(char *)))
134 };
135 #define InvokeAddrToStrUPP(selector, addr, addrStr, userUPP)            \
136     CALL_THREE_PARAMETER_UPP((userUPP), uppAddrToStrProcInfo, (selector),\
137                              (addr), (addrStr))
138 #define AddrToStr(addr, addrStr)                                        \
139     InvokeAddrToStrUPP(ADDRTOSTR, addr, addrStr,                        \
140                        (AddrToStrUPP)*mactcp.dnr_handle)
141
142 /* End of AddressXlation.h bits */
143
144 struct Socket_tag {
145     struct socket_function_table *fn;
146     /* the above variable absolutely *must* be the first in this structure */
147 };
148
149 /*
150  * We used to typedef struct Socket_tag *Socket.
151  *
152  * Since we have made the networking abstraction slightly more
153  * abstract, Socket no longer means a tcp socket (it could mean
154  * an ssl socket).  So now we must use Actual_Socket when we know
155  * we are talking about a tcp socket.
156  */
157 typedef struct Socket_tag *Actual_Socket;
158
159 struct SockAddr_tag {
160     int resolved;
161     struct hostInfo hostinfo;
162     char hostname[512];
163 };
164
165 /* Global variables */
166 static struct {
167     Handle dnr_handle;
168     int initialised;
169     short refnum;
170 } mactcp;
171
172 static pascal void mactcp_lookupdone(struct hostInfo *hi, char *cookie);
173
174 /*
175  * Initialise MacTCP.
176  * This should be called once before any TCP connection is opened.
177  */
178
179 OSErr mactcp_init(void)
180 {
181     OSErr err;
182
183     /*
184      * IM:Devices describes a convoluted way of finding a spare unit
185      * number to open a driver on before calling OpenDriver.  Happily,
186      * I think the MacTCP INIT ensures that .IPP is already open (and
187      * hence has a valid unit number already) so we don't need to go
188      * through all that.
189      */
190     err = OpenDriver("\p.IPP", &mactcp.refnum);
191     if (err != noErr) return err;
192     err = OpenResolver(NULL);
193     if (err != noErr) return err;
194
195     mactcp.initialised = TRUE;
196     return noErr;
197 }
198
199 void mactcp_shutdown(void)
200 {
201
202     CloseResolver();
203     mactcp.initialised = FALSE;
204 }
205
206 static ResultUPP mactcp_lookupdone_upp;
207
208 SockAddr sk_namelookup(char *host, char **canonicalname)
209 {
210     SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
211     OSErr err;
212     volatile int done = FALSE;
213     char *realhost;
214
215     /* Clear the structure. */
216     memset(ret, 0, sizeof(struct SockAddr_tag));
217     if (mactcp_lookupdone_upp == NULL)
218         mactcp_lookupdone_upp = NewResultUPP(&mactcp_lookupdone);
219     err = StrToAddr(host, &ret->hostinfo, mactcp_lookupdone_upp,
220                     (char *)&done);
221     /*
222      * PuTTY expects DNS lookups to be synchronous (see bug
223      * "async-dns"), so we pretend they are.
224      */
225     if (err == cacheFault)
226         while (!done)
227             continue;
228     ret->resolved = TRUE;
229     
230     if (ret->hostinfo.rtnCode == noErr)
231         realhost = ret->hostinfo.cname;
232     else
233         realhost = "";
234     *canonicalname = smalloc(1+strlen(realhost));
235     strcpy(*canonicalname, realhost);
236     return ret;
237 }
238
239 static pascal void mactcp_lookupdone(struct hostInfo *hi, char *cookie)
240 {
241     volatile int *donep = (int *)cookie;
242
243     *donep = TRUE;
244 }
245
246 SockAddr sk_nonamelookup(char *host)
247 {
248     SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
249
250     ret->resolved = FALSE;
251     ret->hostinfo.rtnCode = noErr;
252     ret->hostname[0] = '\0';
253     strncat(ret->hostname, host, lenof(ret->hostname) - 1);
254     return ret;
255 }
256
257 void sk_getaddr(SockAddr addr, char *buf, int buflen)
258 {
259     char mybuf[16];
260     OSErr err;
261
262     /* XXX only return first address */
263     err = AddrToStr(addr->hostinfo.addr[0], mybuf);
264     buf[0] = '\0';
265     if (err != noErr)
266         strncat(buf, mybuf, buflen - 1);
267 }
268
269 /* I think "local" here really means "loopback" */
270
271 int sk_hostname_is_local(char *name)
272 {
273
274     return !strcmp(name, "localhost");
275 }
276
277 int sk_address_is_local(SockAddr addr)
278 {
279     int i;
280
281     if (addr->resolved)
282         for (i = 0; i < NUM_ALT_ADDRS; i++)
283             if (addr->hostinfo.addr[i] & 0xff000000 == 0x7f000000)
284                 return TRUE;
285     return FALSE;
286 }
287
288 int sk_addrtype(SockAddr addr)
289 {
290
291     if (addr->resolved)
292         return ADDRTYPE_IPV4;
293     return ADDRTYPE_NAME;
294 }
295
296 void sk_addrcopy(SockAddr addr, char *buf)
297 {
298
299     /* XXX only return first address */
300     memcpy(buf, &addr->hostinfo.addr[0], 4);
301 }
302
303 void sk_addr_free(SockAddr addr)
304 {
305
306     sfree(addr);
307 }
308
309 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
310               int nodelay, Plug plug)
311 {
312
313     fatalbox("sk_new");
314 }
315
316 /*
317  * Special error values are returned from sk_namelookup and sk_new
318  * if there's a problem. These functions extract an error message,
319  * or return NULL if there's no problem.
320  */
321 char *sk_addr_error(SockAddr addr)
322 {
323     static char buf[64];
324
325     switch (addr->hostinfo.rtnCode) {
326       case noErr:
327         return NULL;
328       case nameSyntaxErr:
329         return "Name syntax error";
330       case noNameServer:
331         return "No name server found";
332       case authNameErr:
333         return "Domain name does not exist";
334       case noAnsErr:
335         return "No answer from domain name server";
336       case dnrErr:
337         return "Domain name server returned an error";
338       case outOfMemory:
339         return "Out of memory";
340       default:
341         sprintf(buf, "Unknown DNR error %d", addr->hostinfo.rtnCode);
342         return buf;
343     }
344 }
345
346
347 /*
348  * Bits below here would usually be in dnr.c, shipped with the MacTCP
349  * SDK, but its convenient not to require that, and since we assume
350  * System 7 we can actually simplify things a lot.
351  */
352
353 static OSErr OpenResolver(char *hosts_file)
354 {
355     short vrefnum;
356     long dirid;
357     HParamBlockRec pb;
358     Str255 filename;
359     OSErr err;
360     int fd;
361     Handle dnr_handle;
362
363     if (mactcp.dnr_handle != NULL)
364         return noErr;
365
366     err = FindFolder(kOnSystemDisk, kControlPanelFolderType, FALSE, &vrefnum,
367                      &dirid);
368     if (err != noErr) return err;
369
370     /*
371      * Might be better to use PBCatSearch here, but it's not always
372      * available.
373      */
374     pb.fileParam.ioCompletion = NULL;
375     pb.fileParam.ioNamePtr = filename;
376     pb.fileParam.ioVRefNum = vrefnum;
377     pb.fileParam.ioFDirIndex = 1;
378     pb.fileParam.ioDirID = dirid;
379     fd = -1;
380
381     while (PBHGetFInfo(&pb, FALSE) == noErr) {
382         if (pb.fileParam.ioFlFndrInfo.fdType == 'cdev' &&
383             pb.fileParam.ioFlFndrInfo.fdCreator == 'ztcp') {
384             fd = HOpenResFile(vrefnum, dirid, filename, fsRdPerm);
385             if (fd == -1) continue;
386             dnr_handle = Get1IndResource('dnrp', 1);
387             if (dnr_handle != NULL)
388                 break;
389             CloseResFile(fd);
390             fd = -1;
391         }
392         pb.fileParam.ioDirID = dirid;
393         pb.fileParam.ioFDirIndex++;
394     }
395     if (fd == -1)
396         return fnfErr;
397     
398     DetachResource(dnr_handle);
399     CloseResFile(fd);
400
401     MoveHHi(dnr_handle);
402     HLock(dnr_handle);
403
404     err = InvokeOpenResolverUPP(OPENRESOLVER, hosts_file,
405                                 (OpenResolverUPP)*dnr_handle);
406     if (err != noErr) {
407         HUnlock(dnr_handle);
408         DisposeHandle(dnr_handle);
409         return err;
410     }
411
412     mactcp.dnr_handle = dnr_handle;
413     return noErr;
414 }
415
416 OSErr CloseResolver(void)
417 {
418     Handle dnr_handle = mactcp.dnr_handle;
419     OSErr err;
420
421     if (mactcp.dnr_handle == NULL)
422         return notOpenErr;
423
424     err = InvokeCloseResolverUPP(CLOSERESOLVER,
425                                  (CloseResolverUPP)*mactcp.dnr_handle);
426     if (err != noErr)
427         return err;
428
429     mactcp.dnr_handle = NULL;
430     HUnlock(dnr_handle);
431     DisposeHandle(dnr_handle);
432     return noErr;
433 }
434
435 /*
436  * Local Variables:
437  * c-file-style: "simon"
438  * End:
439  */