imapext-2007

view src/osdep/unix/tcp_unix.c @ 4:d741b3ecc917

imapext-2007f
author HIROSE Yuuji <yuuji@gentei.org>
date Thu, 30 Oct 2014 00:03:05 +0900
parents 2366b362676d
children
line source
1 /* ========================================================================
2 * Copyright 1988-2008 University of Washington
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *
11 * ========================================================================
12 */
14 /*
15 * Program: UNIX TCP/IP routines
16 *
17 * Author: Mark Crispin
18 * Networks and Distributed Computing
19 * Computing & Communications
20 * University of Washington
21 * Administration Building, AG-44
22 * Seattle, WA 98195
23 * Internet: MRC@CAC.Washington.EDU
24 *
25 * Date: 1 August 1988
26 * Last Edited: 13 January 2008
27 */
29 #include "ip_unix.c"
31 #undef write /* don't use redefined write() */
33 static tcptimeout_t tmoh = NIL; /* TCP timeout handler routine */
34 static long ttmo_open = 0; /* TCP timeouts, in seconds */
35 static long ttmo_read = 0;
36 static long ttmo_write = 0;
37 static long rshtimeout = 15; /* rsh timeout */
38 static char *rshcommand = NIL; /* rsh command */
39 static char *rshpath = NIL; /* rsh path */
40 static long sshtimeout = 15; /* ssh timeout */
41 static char *sshcommand = NIL; /* ssh command */
42 static char *sshpath = NIL; /* ssh path */
43 static long allowreversedns = T;/* allow reverse DNS lookup */
44 static long tcpdebug = NIL; /* extra TCP debugging telemetry */
45 static char *myClientAddr = NIL;/* client IP address */
46 static char *myClientHost = NIL;/* client DNS name */
47 static long myClientPort = -1; /* client port number */
48 static char *myServerAddr = NIL;/* server IP address */
49 static char *myServerHost = NIL;/* server DNS name */
50 static long myServerPort = -1; /* server port number */
52 extern long maxposint; /* get this from write.c */
54 /* Local function prototypes */
56 int tcp_socket_open (int family,void *adr,size_t adrlen,unsigned short port,
57 char *tmp,int *ctr,char *hst);
58 static char *tcp_getline_work (TCPSTREAM *stream,unsigned long *size,
59 long *contd);
60 long tcp_abort (TCPSTREAM *stream);
61 char *tcp_name (struct sockaddr *sadr,long flag);
62 char *tcp_name_valid (char *s);
64 /* TCP/IP manipulate parameters
65 * Accepts: function code
66 * function-dependent value
67 * Returns: function-dependent return value
68 */
70 void *tcp_parameters (long function,void *value)
71 {
72 void *ret = NIL;
73 switch ((int) function) {
74 case SET_TIMEOUT:
75 tmoh = (tcptimeout_t) value;
76 case GET_TIMEOUT:
77 ret = (void *) tmoh;
78 break;
79 case SET_OPENTIMEOUT:
80 ttmo_open = (long) value;
81 case GET_OPENTIMEOUT:
82 ret = (void *) ttmo_open;
83 break;
84 case SET_READTIMEOUT:
85 ttmo_read = (long) value;
86 case GET_READTIMEOUT:
87 ret = (void *) ttmo_read;
88 break;
89 case SET_WRITETIMEOUT:
90 ttmo_write = (long) value;
91 case GET_WRITETIMEOUT:
92 ret = (void *) ttmo_write;
93 break;
94 case SET_ALLOWREVERSEDNS:
95 allowreversedns = (long) value;
96 case GET_ALLOWREVERSEDNS:
97 ret = (void *) allowreversedns;
98 break;
99 case SET_TCPDEBUG:
100 tcpdebug = (long) value;
101 case GET_TCPDEBUG:
102 ret = (void *) tcpdebug;
103 break;
105 case SET_RSHTIMEOUT:
106 rshtimeout = (long) value;
107 case GET_RSHTIMEOUT:
108 ret = (void *) rshtimeout;
109 break;
110 case SET_RSHCOMMAND:
111 if (rshcommand) fs_give ((void **) &rshcommand);
112 rshcommand = cpystr ((char *) value);
113 case GET_RSHCOMMAND:
114 ret = (void *) rshcommand;
115 break;
116 case SET_RSHPATH:
117 if (rshpath) fs_give ((void **) &rshpath);
118 rshpath = cpystr ((char *) value);
119 case GET_RSHPATH:
120 ret = (void *) rshpath;
121 break;
122 case SET_SSHTIMEOUT:
123 sshtimeout = (long) value;
124 case GET_SSHTIMEOUT:
125 ret = (void *) sshtimeout;
126 break;
127 case SET_SSHCOMMAND:
128 if (sshcommand) fs_give ((void **) &sshcommand);
129 sshcommand = cpystr ((char *) value);
130 case GET_SSHCOMMAND:
131 ret = (void *) sshcommand;
132 break;
133 case SET_SSHPATH:
134 if (sshpath) fs_give ((void **) &sshpath);
135 sshpath = cpystr ((char *) value);
136 case GET_SSHPATH:
137 ret = (void *) sshpath;
138 break;
139 }
140 return ret;
141 }
143 /* TCP/IP open
144 * Accepts: host name
145 * contact service name
146 * contact port number and optional silent flag
147 * Returns: TCP/IP stream if success else NIL
148 */
150 TCPSTREAM *tcp_open (char *host,char *service,unsigned long port)
151 {
152 TCPSTREAM *stream = NIL;
153 int family;
154 int sock = -1;
155 int ctr = 0;
156 int silent = (port & NET_SILENT) ? T : NIL;
157 int *ctrp = (port & NET_NOOPENTIMEOUT) ? NIL : &ctr;
158 char *s,*hostname,tmp[MAILTMPLEN];
159 void *adr;
160 size_t adrlen;
161 struct servent *sv = NIL;
162 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
163 void *data,*next;
164 port &= 0xffff; /* erase flags */
165 /* lookup service */
166 if (service && (sv = getservbyname (service,"tcp")))
167 port = ntohs (sv->s_port);
168 /* The domain literal form is used (rather than simply the dotted decimal
169 as with other Unix programs) because it has to be a valid "host name"
170 in mailsystem terminology. */
171 /* look like domain literal? */
172 if (host[0] == '[' && host[(strlen (host))-1] == ']') {
173 strcpy (tmp,host+1); /* yes, copy number part */
174 tmp[(strlen (tmp))-1] = '\0';
175 if (adr = ip_stringtoaddr (tmp,&adrlen,&family)) {
176 (*bn) (BLOCK_TCPOPEN,NIL);
177 /* get an open socket for this system */
178 sock = tcp_socket_open (family,adr,adrlen,port,tmp,ctrp,hostname = host);
179 (*bn) (BLOCK_NONE,NIL);
180 fs_give ((void **) &adr);
181 }
182 else sprintf (tmp,"Bad format domain-literal: %.80s",host);
183 }
185 else { /* lookup host name */
186 if (tcpdebug) {
187 sprintf (tmp,"DNS resolution %.80s",host);
188 mm_log (tmp,TCPDEBUG);
189 }
190 (*bn) (BLOCK_DNSLOOKUP,NIL);/* quell alarms */
191 data = (*bn) (BLOCK_SENSITIVE,NIL);
192 if (!(s = ip_nametoaddr (host,&adrlen,&family,&hostname,&next)))
193 sprintf (tmp,"No such host as %.80s",host);
194 (*bn) (BLOCK_NONSENSITIVE,data);
195 (*bn) (BLOCK_NONE,NIL);
196 if (s) { /* DNS resolution won? */
197 if (tcpdebug) mm_log ("DNS resolution done",TCPDEBUG);
198 do {
199 (*bn) (BLOCK_TCPOPEN,NIL);
200 if (((sock = tcp_socket_open (family,s,adrlen,port,tmp,ctrp,
201 hostname)) < 0) &&
202 (s = ip_nametoaddr (NIL,&adrlen,&family,&hostname,&next)) &&
203 !silent) mm_log (tmp,WARN);
204 (*bn) (BLOCK_NONE,NIL);
205 } while ((sock < 0) && s);/* repeat until success or no more addreses */
206 }
207 }
208 if (sock >= 0) { /* won */
209 stream = (TCPSTREAM *) memset (fs_get (sizeof (TCPSTREAM)),0,
210 sizeof (TCPSTREAM));
211 stream->port = port; /* port number */
212 /* init sockets */
213 stream->tcpsi = stream->tcpso = sock;
214 /* stash in the snuck-in byte */
215 if (stream->ictr = ctr) *(stream->iptr = stream->ibuf) = tmp[0];
216 /* copy official host name */
217 stream->host = cpystr (hostname);
218 if (tcpdebug) mm_log ("Stream open and ready for read",TCPDEBUG);
219 }
220 else if (!silent) mm_log (tmp,ERROR);
221 return stream; /* return success */
222 }
224 /* Open a TCP socket
225 * Accepts: protocol family
226 * address to connect to
227 * address length
228 * port
229 * scratch buffer
230 * pointer to "first byte read in" storage or NIL
231 * host name for error message
232 * Returns: socket if success, else -1 with error string in scratch buffer
233 */
235 int tcp_socket_open (int family,void *adr,size_t adrlen,unsigned short port,
236 char *tmp,int *ctr,char *hst)
237 {
238 int i,ti,sock,flgs;
239 size_t len;
240 time_t now;
241 struct protoent *pt = getprotobyname ("tcp");
242 fd_set rfds,wfds,efds;
243 struct timeval tmo;
244 struct sockaddr *sadr = ip_sockaddr (family,adr,adrlen,port,&len);
245 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
246 /* fetid Solaris */
247 void *data = (*bn) (BLOCK_SENSITIVE,NIL);
248 sprintf (tmp,"Trying IP address [%s]",ip_sockaddrtostring (sadr));
249 mm_log (tmp,NIL);
250 /* make a socket */
251 if ((sock = socket (sadr->sa_family,SOCK_STREAM,pt ? pt->p_proto : 0)) < 0) {
252 sprintf (tmp,"Unable to create TCP socket: %s",strerror (errno));
253 (*bn) (BLOCK_NONSENSITIVE,data);
254 }
255 else if (sock >= FD_SETSIZE) {/* unselectable sockets are useless */
256 sprintf (tmp,"Unable to create selectable TCP socket (%d >= %d)",
257 sock,FD_SETSIZE);
258 (*bn) (BLOCK_NONSENSITIVE,data);
259 close (sock);
260 sock = -1;
261 errno = EMFILE;
262 }
264 else { /* get current socket flags */
265 flgs = fcntl (sock,F_GETFL,0);
266 /* set non-blocking if want open timeout */
267 if (ctr) fcntl (sock,F_SETFL,flgs | FNDELAY);
268 /* open connection */
269 while ((i = connect (sock,sadr,len)) < 0 && (errno == EINTR));
270 (*bn) (BLOCK_NONSENSITIVE,data);
271 if (i < 0) switch (errno) { /* failed? */
272 case EAGAIN: /* DG brain damage */
273 case EINPROGRESS: /* what we expect to happen */
274 case EALREADY: /* or another form of it */
275 case EISCONN: /* restart after interrupt? */
276 case EADDRINUSE: /* restart after interrupt? */
277 break; /* well, not really, it was interrupted */
278 default:
279 sprintf (tmp,"Can't connect to %.80s,%u: %s",hst,(unsigned int) port,
280 strerror (errno));
281 close (sock); /* flush socket */
282 sock = -1;
283 }
284 if ((sock >= 0) && ctr) { /* want open timeout? */
285 now = time (0); /* open timeout */
286 ti = ttmo_open ? now + ttmo_open : 0;
287 tmo.tv_usec = 0;
288 FD_ZERO (&rfds); /* initialize selection vector */
289 FD_ZERO (&wfds); /* initialize selection vector */
290 FD_ZERO (&efds); /* handle errors too */
291 FD_SET (sock,&rfds); /* block for error or readable or writable */
292 FD_SET (sock,&wfds);
293 FD_SET (sock,&efds);
294 do { /* block under timeout */
295 tmo.tv_sec = ti ? ti - now : 0;
296 i = select (sock+1,&rfds,&wfds,&efds,ti ? &tmo : NIL);
297 now = time (0); /* fake timeout if interrupt & time expired */
298 if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
299 } while ((i < 0) && (errno == EINTR));
300 if (i > 0) { /* success, make sure really connected */
301 /* restore blocking status */
302 fcntl (sock,F_SETFL,flgs);
303 /* This used to be a zero-byte read(), but that crashes Solaris */
304 /* get socket status */
305 if(FD_ISSET(sock, &rfds)) while (((i = *ctr = read (sock,tmp,1)) < 0) && (errno == EINTR));
306 }
307 if (i <= 0) { /* timeout or error? */
308 i = i ? errno : ETIMEDOUT;/* determine error code */
309 close (sock); /* flush socket */
310 sock = -1;
311 errno = i; /* return error code */
312 sprintf (tmp,"Connection failed to %.80s,%lu: %s",hst,
313 (unsigned long) port,strerror (errno));
314 }
315 }
316 }
317 fs_give ((void **) &sadr);
318 return sock; /* return the socket */
319 }
321 /* TCP/IP authenticated open
322 * Accepts: host name
323 * service name
324 * returned user name buffer
325 * Returns: TCP/IP stream if success else NIL
326 */
328 #define MAXARGV 20
330 TCPSTREAM *tcp_aopen (NETMBX *mb,char *service,char *usrbuf)
331 {
332 TCPSTREAM *stream = NIL;
333 void *adr;
334 char host[MAILTMPLEN],tmp[MAILTMPLEN],*path,*argv[MAXARGV+1],*r;
335 int i,ti,pipei[2],pipeo[2];
336 size_t len;
337 time_t now;
338 struct timeval tmo;
339 fd_set fds,efds;
340 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
341 #ifdef SSHPATH /* ssh path defined yet? */
342 if (!sshpath) sshpath = cpystr (SSHPATH);
343 #endif
344 #ifdef RSHPATH /* rsh path defined yet? */
345 if (!rshpath) rshpath = cpystr (RSHPATH);
346 #endif
347 if (*service == '*') { /* want ssh? */
348 /* return immediately if ssh disabled */
349 if (!(sshpath && (ti = sshtimeout))) return NIL;
350 /* ssh command prototype defined yet? */
351 if (!sshcommand) sshcommand = cpystr ("%s %s -l %s exec /etc/r%sd");
352 }
353 /* want rsh? */
354 else if (rshpath && (ti = rshtimeout)) {
355 /* rsh command prototype defined yet? */
356 if (!rshcommand) rshcommand = cpystr ("%s %s -l %s exec /etc/r%sd");
357 }
358 else return NIL; /* rsh disabled */
359 /* look like domain literal? */
360 if (mb->host[0] == '[' && mb->host[i = (strlen (mb->host))-1] == ']') {
361 strcpy (host,mb->host+1); /* yes, copy without brackets */
362 host[i-1] = '\0';
363 /* validate domain literal */
364 if (adr = ip_stringtoaddr (host,&len,&i)) fs_give ((void **) &adr);
365 else {
366 sprintf (tmp,"Bad format domain-literal: %.80s",host);
367 mm_log (tmp,ERROR);
368 return NIL;
369 }
370 }
371 else strcpy (host,tcp_canonical (mb->host));
373 if (*service == '*') /* build ssh command */
374 sprintf (tmp,sshcommand,sshpath,host,
375 mb->user[0] ? mb->user : myusername (),service + 1);
376 else sprintf (tmp,rshcommand,rshpath,host,
377 mb->user[0] ? mb->user : myusername (),service);
378 if (tcpdebug) {
379 char msg[MAILTMPLEN];
380 sprintf (msg,"Trying %.100s",tmp);
381 mm_log (msg,TCPDEBUG);
382 }
383 /* parse command into argv */
384 for (i = 1,path = argv[0] = strtok_r (tmp," ",&r);
385 (i < MAXARGV) && (argv[i] = strtok_r (NIL," ",&r)); i++);
386 argv[i] = NIL; /* make sure argv tied off */
387 /* make command pipes */
388 if (pipe (pipei) < 0) return NIL;
389 if ((pipei[0] >= FD_SETSIZE) || (pipei[1] >= FD_SETSIZE) ||
390 (pipe (pipeo) < 0)) {
391 close (pipei[0]); close (pipei[1]);
392 return NIL;
393 }
394 (*bn) (BLOCK_TCPOPEN,NIL); /* quell alarm up here for NeXT */
395 if ((pipeo[0] >= FD_SETSIZE) || (pipeo[1] >= FD_SETSIZE) ||
396 ((i = fork ()) < 0)) { /* make inferior process */
397 close (pipei[0]); close (pipei[1]);
398 close (pipeo[0]); close (pipeo[1]);
399 (*bn) (BLOCK_NONE,NIL);
400 return NIL;
401 }
402 if (!i) { /* if child */
403 alarm (0); /* never have alarms in children */
404 if (!fork ()) { /* make grandchild so it's inherited by init */
405 int cf; /* don't alter parent vars in case vfork() */
406 int maxfd = max (20,max (max(pipei[0],pipei[1]),max(pipeo[0],pipeo[1])));
407 dup2 (pipei[1],1); /* parent's input is my output */
408 dup2 (pipei[1],2); /* parent's input is my error output too */
409 dup2 (pipeo[0],0); /* parent's output is my input */
410 /* close all unnecessary descriptors */
411 for (cf = 3; cf <= maxfd; cf++) close (cf);
412 setpgrp (0,getpid ()); /* be our own process group */
413 _exit (execv (path,argv));/* now run it */
414 }
415 _exit (1); /* child is done */
416 }
417 grim_pid_reap (i,NIL); /* reap child; grandchild now owned by init */
418 close (pipei[1]); /* close child's side of the pipes */
419 close (pipeo[0]);
421 /* create TCP/IP stream */
422 stream = (TCPSTREAM *) memset (fs_get (sizeof (TCPSTREAM)),0,
423 sizeof (TCPSTREAM));
424 /* copy remote host name from argument */
425 stream->remotehost = cpystr (stream->host = cpystr (host));
426 stream->tcpsi = pipei[0]; /* init sockets */
427 stream->tcpso = pipeo[1];
428 stream->ictr = 0; /* init input counter */
429 stream->port = 0xffffffff; /* no port number */
430 ti += now = time (0); /* open timeout */
431 tmo.tv_usec = 0; /* initialize usec timeout */
432 FD_ZERO (&fds); /* initialize selection vector */
433 FD_ZERO (&efds); /* handle errors too */
434 FD_SET (stream->tcpsi,&fds); /* set bit in selection vector */
435 FD_SET (stream->tcpsi,&efds); /* set bit in error selection vector */
436 FD_SET (stream->tcpso,&efds); /* set bit in error selection vector */
437 do { /* block under timeout */
438 tmo.tv_sec = ti - now;
439 i = select (max (stream->tcpsi,stream->tcpso)+1,&fds,NIL,&efds,&tmo);
440 now = time (0); /* fake timeout if interrupt & time expired */
441 if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
442 } while ((i < 0) && (errno == EINTR));
443 if (i <= 0) { /* timeout or error? */
444 sprintf (tmp,i ? "error in %s to IMAP server" :
445 "%s to IMAP server timed out",(*service == '*') ? "ssh" : "rsh");
446 mm_log (tmp,WARN);
447 tcp_close (stream); /* punt stream */
448 stream = NIL;
449 }
450 (*bn) (BLOCK_NONE,NIL);
451 /* return user name */
452 strcpy (usrbuf,mb->user[0] ? mb->user : myusername ());
453 return stream; /* return success */
454 }
456 /* TCP receive line
457 * Accepts: TCP stream
458 * Returns: text line string or NIL if failure
459 */
461 char *tcp_getline (TCPSTREAM *stream)
462 {
463 unsigned long n,contd;
464 char *ret = tcp_getline_work (stream,&n,&contd);
465 if (ret && contd) { /* got a line needing continuation? */
466 STRINGLIST *stl = mail_newstringlist ();
467 STRINGLIST *stc = stl;
468 do { /* collect additional lines */
469 stc->text.data = (unsigned char *) ret;
470 stc->text.size = n;
471 stc = stc->next = mail_newstringlist ();
472 ret = tcp_getline_work (stream,&n,&contd);
473 } while (ret && contd);
474 if (ret) { /* stash final part of line on list */
475 stc->text.data = (unsigned char *) ret;
476 stc->text.size = n;
477 /* determine how large a buffer we need */
478 for (n = 0, stc = stl; stc; stc = stc->next) n += stc->text.size;
479 ret = fs_get (n + 1); /* copy parts into buffer */
480 for (n = 0, stc = stl; stc; n += stc->text.size, stc = stc->next)
481 memcpy (ret + n,stc->text.data,stc->text.size);
482 ret[n] = '\0';
483 }
484 mail_free_stringlist (&stl);/* either way, done with list */
485 }
486 return ret;
487 }
489 /* TCP receive line or partial line
490 * Accepts: TCP stream
491 * pointer to return size
492 * pointer to return continuation flag
493 * Returns: text line string, size and continuation flag, or NIL if failure
494 */
496 static char *tcp_getline_work (TCPSTREAM *stream,unsigned long *size,
497 long *contd)
498 {
499 unsigned long n;
500 char *s,*ret,c,d;
501 *contd = NIL; /* assume no continuation */
502 /* make sure have data */
503 if (!tcp_getdata (stream)) return NIL;
504 for (s = stream->iptr, n = 0, c = '\0'; stream->ictr--; n++, c = d) {
505 d = *stream->iptr++; /* slurp another character */
506 if ((c == '\015') && (d == '\012')) {
507 ret = (char *) fs_get (n--);
508 memcpy (ret,s,*size = n); /* copy into a free storage string */
509 ret[n] = '\0'; /* tie off string with null */
510 return ret;
511 }
512 }
513 /* copy partial string from buffer */
514 memcpy ((ret = (char *) fs_get (n)),s,*size = n);
515 /* get more data from the net */
516 if (!tcp_getdata (stream)) fs_give ((void **) &ret);
517 /* special case of newline broken by buffer */
518 else if ((c == '\015') && (*stream->iptr == '\012')) {
519 stream->iptr++; /* eat the line feed */
520 stream->ictr--;
521 ret[*size = --n] = '\0'; /* tie off string with null */
522 }
523 else *contd = LONGT; /* continuation needed */
524 return ret;
525 }
527 /* TCP/IP receive buffer
528 * Accepts: TCP/IP stream
529 * size in bytes
530 * buffer to read into
531 * Returns: T if success, NIL otherwise
532 */
534 long tcp_getbuffer (TCPSTREAM *stream,unsigned long size,char *s)
535 {
536 unsigned long n;
537 /* make sure socket still alive */
538 if (stream->tcpsi < 0) return NIL;
539 /* can transfer bytes from buffer? */
540 if (n = min (size,stream->ictr)) {
541 memcpy (s,stream->iptr,n); /* yes, slurp as much as we can from it */
542 s += n; /* update pointer */
543 stream->iptr +=n;
544 size -= n; /* update # of bytes to do */
545 stream->ictr -=n;
546 }
547 if (size) {
548 int i;
549 fd_set fds,efds;
550 struct timeval tmo;
551 time_t t = time (0);
552 blocknotify_t bn=(blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
553 (*bn) (BLOCK_TCPREAD,NIL);
554 while (size > 0) { /* until request satisfied */
555 time_t tl = time (0);
556 time_t now = tl;
557 time_t ti = ttmo_read ? now + ttmo_read : 0;
558 if (tcpdebug) mm_log ("Reading TCP buffer",TCPDEBUG);
559 tmo.tv_usec = 0;
560 FD_ZERO (&fds); /* initialize selection vector */
561 FD_ZERO (&efds); /* handle errors too */
562 /* set bit in selection vectors */
563 FD_SET (stream->tcpsi,&fds);
564 FD_SET (stream->tcpsi,&efds);
565 errno = NIL; /* initially no error */
566 do { /* block under timeout */
567 tmo.tv_sec = ti ? ti - now : 0;
568 i = select (stream->tcpsi+1,&fds,NIL,&efds,ti ? &tmo : NIL);
569 now = time (0); /* fake timeout if interrupt & time expired */
570 if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
571 } while ((i < 0) && (errno == EINTR));
572 if (i) { /* non-timeout result from select? */
573 if (i > 0) /* read what we can */
574 while (((i = read (stream->tcpsi,s,(int) min (maxposint,size))) < 0)
575 && (errno == EINTR));
576 if (i <= 0) { /* error seen? */
577 if (tcpdebug) {
578 char tmp[MAILTMPLEN];
579 if (i) sprintf (s = tmp,"TCP buffer read I/O error %d",errno);
580 else s = "TCP buffer read end of file";
581 mm_log (s,TCPDEBUG);
582 }
583 return tcp_abort (stream);
584 }
585 s += i; /* success, point at new place to write */
586 size -= i; /* reduce byte count */
587 if (tcpdebug) mm_log ("Successfully read TCP buffer",TCPDEBUG);
588 }
589 /* timeout, punt unless told not to */
590 else if (!tmoh || !(*tmoh) (now - t,now - tl)) {
591 if (tcpdebug) mm_log ("TCP buffer read timeout",TCPDEBUG);
592 return tcp_abort (stream);
593 }
594 }
595 (*bn) (BLOCK_NONE,NIL);
596 }
597 *s = '\0'; /* tie off string */
598 return LONGT;
599 }
601 /* TCP/IP receive data
602 * Accepts: TCP/IP stream
603 * Returns: T if success, NIL otherwise
604 */
606 long tcp_getdata (TCPSTREAM *stream)
607 {
608 int i;
609 fd_set fds,efds;
610 struct timeval tmo;
611 time_t t = time (0);
612 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
613 if (stream->tcpsi < 0) return NIL;
614 (*bn) (BLOCK_TCPREAD,NIL);
615 while (stream->ictr < 1) { /* if nothing in the buffer */
616 time_t tl = time (0); /* start of request */
617 time_t now = tl;
618 time_t ti = ttmo_read ? now + ttmo_read : 0;
619 if (tcpdebug) mm_log ("Reading TCP data",TCPDEBUG);
620 tmo.tv_usec = 0;
621 FD_ZERO (&fds); /* initialize selection vector */
622 FD_ZERO (&efds); /* handle errors too */
623 FD_SET (stream->tcpsi,&fds);/* set bit in selection vectors */
624 FD_SET (stream->tcpsi,&efds);
625 errno = NIL; /* initially no error */
626 do { /* block under timeout */
627 tmo.tv_sec = ti ? ti - now : 0;
628 i = select (stream->tcpsi+1,&fds,NIL,&efds,ti ? &tmo : NIL);
629 now = time (0); /* fake timeout if interrupt & time expired */
630 if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
631 } while ((i < 0) && (errno == EINTR));
632 if (i) { /* non-timeout result from select? */
633 /* read what we can */
634 if (i > 0) while (((i = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 0) &&
635 (errno == EINTR));
636 if (i <= 0) { /* error seen? */
637 if (tcpdebug) {
638 char *s,tmp[MAILTMPLEN];
639 if (i) sprintf (s = tmp,"TCP data read I/O error %d",errno);
640 else s = "TCP data read end of file";
641 mm_log (s,TCPDEBUG);
642 }
643 return tcp_abort (stream);
644 }
645 stream->ictr = i; /* success, set new count and pointer */
646 stream->iptr = stream->ibuf;
647 if (tcpdebug) mm_log ("Successfully read TCP data",TCPDEBUG);
648 }
649 /* timeout, punt unless told not to */
650 else if (!tmoh || !(*tmoh) (now - t,now - tl)) {
651 if (tcpdebug) mm_log ("TCP data read timeout",TCPDEBUG);
652 return tcp_abort (stream);/* error or timeout no-continue */
653 }
654 }
655 (*bn) (BLOCK_NONE,NIL);
656 return T;
657 }
659 /* TCP/IP send string as record
660 * Accepts: TCP/IP stream
661 * string pointer
662 * Returns: T if success else NIL
663 */
665 long tcp_soutr (TCPSTREAM *stream,char *string)
666 {
667 return tcp_sout (stream,string,(unsigned long) strlen (string));
668 }
671 /* TCP/IP send string
672 * Accepts: TCP/IP stream
673 * string pointer
674 * byte count
675 * Returns: T if success else NIL
676 */
678 long tcp_sout (TCPSTREAM *stream,char *string,unsigned long size)
679 {
680 int i;
681 fd_set fds,efds;
682 struct timeval tmo;
683 time_t t = time (0);
684 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
685 if (stream->tcpso < 0) return NIL;
686 (*bn) (BLOCK_TCPWRITE,NIL);
687 while (size > 0) { /* until request satisfied */
688 time_t tl = time (0); /* start of request */
689 time_t now = tl;
690 time_t ti = ttmo_write ? now + ttmo_write : 0;
691 if (tcpdebug) mm_log ("Writing to TCP",TCPDEBUG);
692 tmo.tv_usec = 0;
693 FD_ZERO (&fds); /* initialize selection vector */
694 FD_ZERO (&efds); /* handle errors too */
695 FD_SET (stream->tcpso,&fds);/* set bit in selection vector */
696 FD_SET(stream->tcpso,&efds);/* set bit in error selection vector */
697 errno = NIL; /* block and write */
698 do { /* block under timeout */
699 tmo.tv_sec = ti ? ti - now : 0;
700 i = select (stream->tcpso+1,NIL,&fds,&efds,ti ? &tmo : NIL);
701 now = time (0); /* fake timeout if interrupt & time expired */
702 if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
703 } while ((i < 0) && (errno == EINTR));
704 if (i) { /* non-timeout result from select? */
705 /* write what we can */
706 if (i > 0) while (((i = write (stream->tcpso,string,size)) < 0) &&
707 (errno == EINTR));
708 if (i <= 0) { /* error seen? */
709 if (tcpdebug) {
710 char tmp[MAILTMPLEN];
711 sprintf (tmp,"TCP write I/O error %d",errno);
712 mm_log (tmp,TCPDEBUG);
713 }
714 return tcp_abort (stream);
715 }
716 string += i; /* how much we sent */
717 size -= i; /* count this size */
718 if (tcpdebug) mm_log ("successfully wrote to TCP",TCPDEBUG);
719 }
720 /* timeout, punt unless told not to */
721 else if (!tmoh || !(*tmoh) (now - t,now - tl)) {
722 if (tcpdebug) mm_log ("TCP write timeout",TCPDEBUG);
723 return tcp_abort (stream);
724 }
725 }
726 (*bn) (BLOCK_NONE,NIL);
727 return T; /* all done */
728 }
730 /* TCP/IP close
731 * Accepts: TCP/IP stream
732 */
734 void tcp_close (TCPSTREAM *stream)
735 {
736 tcp_abort (stream); /* nuke the stream */
737 /* flush host names */
738 if (stream->host) fs_give ((void **) &stream->host);
739 if (stream->remotehost) fs_give ((void **) &stream->remotehost);
740 if (stream->localhost) fs_give ((void **) &stream->localhost);
741 fs_give ((void **) &stream); /* flush the stream */
742 }
745 /* TCP/IP abort stream
746 * Accepts: TCP/IP stream
747 * Returns: NIL always
748 */
750 long tcp_abort (TCPSTREAM *stream)
751 {
752 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
753 if (stream->tcpsi >= 0) { /* no-op if no socket */
754 (*bn) (BLOCK_TCPCLOSE,NIL);
755 close (stream->tcpsi); /* nuke the socket */
756 if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
757 stream->tcpsi = stream->tcpso = -1;
758 }
759 (*bn) (BLOCK_NONE,NIL);
760 return NIL;
761 }
763 /* TCP/IP get host name
764 * Accepts: TCP/IP stream
765 * Returns: host name for this stream
766 */
768 char *tcp_host (TCPSTREAM *stream)
769 {
770 return stream->host; /* use tcp_remotehost() if want guarantees */
771 }
774 /* TCP/IP get remote host name
775 * Accepts: TCP/IP stream
776 * Returns: host name for this stream
777 */
779 char *tcp_remotehost (TCPSTREAM *stream)
780 {
781 if (!stream->remotehost) {
782 size_t sadrlen;
783 struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
784 stream->remotehost = /* get socket's peer name */
785 getpeername (stream->tcpsi,sadr,(void *) &sadrlen) ?
786 cpystr (stream->host) : tcp_name (sadr,NIL);
787 fs_give ((void **) &sadr);
788 }
789 return stream->remotehost;
790 }
793 /* TCP/IP return port for this stream
794 * Accepts: TCP/IP stream
795 * Returns: port number for this stream
796 */
798 unsigned long tcp_port (TCPSTREAM *stream)
799 {
800 return stream->port; /* return port number */
801 }
804 /* TCP/IP get local host name
805 * Accepts: TCP/IP stream
806 * Returns: local host name
807 */
809 char *tcp_localhost (TCPSTREAM *stream)
810 {
811 if (!stream->localhost) {
812 size_t sadrlen;
813 struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
814 stream->localhost = /* get socket's name */
815 ((stream->port & 0xffff000) ||
816 getsockname (stream->tcpsi,sadr,(void *) &sadrlen)) ?
817 cpystr (mylocalhost ()) : tcp_name (sadr,NIL);
818 fs_give ((void **) &sadr);
819 }
820 return stream->localhost; /* return local host name */
821 }
823 /* Get $TCPREMOTEHOST || $TCPREMOTEHOST
824 * If invoked via tcpserver or couriertcpd, consult $TCPREMOTEHOST
825 * or $TCPREMOTEIP
826 */
827 char* gettcpremoteip()
828 {
829 if (getenv("TCPREMOTEHOST") && strcmp("0", getenv("TCPREMOTEHOST"))) {
830 return getenv("TCPREMOTEHOST");
831 } else if (getenv("TCPREMOTEIP")) {
832 return getenv("TCPREMOTEIP");
833 }
834 return "NON-IPv4";
835 }
837 /* TCP/IP get client host address (server calls only)
838 * Returns: client host address
839 */
841 char *tcp_clientaddr ()
842 {
843 if (!myClientAddr) {
844 size_t sadrlen;
845 struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
846 if (getpeername (0,sadr,(void *) &sadrlen))
847 myClientAddr = cpystr ("UNKNOWN");
848 else { /* get stdin's peer name */
849 myClientAddr = cpystr (ip_sockaddrtostring (sadr));
850 if (myClientPort < 0) myClientPort = ip_sockaddrtoport (sadr);
851 }
852 fs_give ((void **) &sadr);
853 }
854 return myClientAddr;
855 }
858 /* TCP/IP get client host name (server calls only)
859 * Returns: client host name
860 */
862 char *tcp_clienthost ()
863 {
864 if (!myClientHost) {
865 size_t sadrlen;
866 struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
867 #ifdef INET6
868 if (getenv("TCPREMOTEIP")) {
869 myClientHost =
870 cpystr((getenv("TCPREMOTEHOST")
871 && strcasecmp("UNKNOWN", getenv("TCPREMOTEHOST")))
872 ? getenv("TCPREMOTEHOST")
873 : getenv("TCPREMOTEIP"));
874 } else
875 #endif
876 if (getpeername (0,sadr,(void *) &sadrlen)) {
877 char *s,*t,*v,tmp[MAILTMPLEN];
878 if ((s = getenv (t = "SSH_CLIENT")) ||
879 (s = getenv (t = "KRB5REMOTEADDR")) ||
880 (s = getenv (t = "SSH2_CLIENT"))) {
881 if (v = strchr (s,' ')) *v = '\0';
882 sprintf (v = tmp,"%.80s=%.80s",t,s);
883 }
884 else v = "UNKNOWN";
885 myClientHost = cpystr (v);
886 }
887 else { /* get stdin's peer name */
888 myClientHost = tcp_name (sadr,T);
889 if (!myClientAddr) myClientAddr = cpystr (ip_sockaddrtostring (sadr));
890 if (myClientPort < 0) myClientPort = ip_sockaddrtoport (sadr);
891 }
892 fs_give ((void **) &sadr);
893 }
894 return myClientHost;
895 }
898 /* TCP/IP get client port number (server calls only)
899 * Returns: client port number
900 */
902 long tcp_clientport ()
903 {
904 if (!myClientHost && !myClientAddr) tcp_clientaddr ();
905 return myClientPort;
906 }
908 /* TCP/IP get server host address (server calls only)
909 * Returns: server host address
910 */
912 char *tcp_serveraddr ()
913 {
914 if (!myServerAddr) {
915 size_t sadrlen;
916 struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
917 if (getsockname (0,sadr,(void *) &sadrlen))
918 myServerAddr = cpystr ("UNKNOWN");
919 else { /* get stdin's name */
920 myServerAddr = cpystr (ip_sockaddrtostring (sadr));
921 if (myServerPort < 0) myServerPort = ip_sockaddrtoport (sadr);
922 }
923 fs_give ((void **) &sadr);
924 }
925 return myServerAddr;
926 }
929 /* TCP/IP get server host name (server calls only)
930 * Returns: server host name
931 */
933 char *tcp_serverhost ()
934 {
935 if (!myServerHost) { /* once-only */
936 size_t sadrlen;
937 struct sockaddr *sadr = ip_newsockaddr (&sadrlen);
938 /* get stdin's name */
939 if (getsockname (0,sadr,(void *) &sadrlen) ||
940 (myServerPort = ip_sockaddrtoport (sadr)) < 0)
941 myServerHost = cpystr (mylocalhost ());
942 else { /* get stdin's name */
943 myServerHost = tcp_name (sadr,NIL);
944 if (!myServerAddr) myServerAddr = cpystr (ip_sockaddrtostring (sadr));
945 if (myServerPort < 0) myServerPort = ip_sockaddrtoport (sadr);
946 }
947 fs_give ((void **) &sadr);
948 }
949 return myServerHost;
950 }
953 /* TCP/IP get server port number (server calls only)
954 * Returns: server port number
955 */
957 long tcp_serverport ()
958 {
959 if (!myServerHost && !myServerAddr) tcp_serveraddr ();
960 return myServerPort;
961 }
963 /* TCP/IP return canonical form of host name
964 * Accepts: host name
965 * Returns: canonical form of host name
966 */
968 char *tcp_canonical (char *name)
969 {
970 char *ret,host[MAILTMPLEN];
971 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
972 void *data;
973 /* look like domain literal? */
974 if (name[0] == '[' && name[strlen (name) - 1] == ']') return name;
975 (*bn) (BLOCK_DNSLOOKUP,NIL); /* quell alarms */
976 data = (*bn) (BLOCK_SENSITIVE,NIL);
977 if (tcpdebug) {
978 sprintf (host,"DNS canonicalization %.80s",name);
979 mm_log (host,TCPDEBUG);
980 }
981 /* get canonical name */
982 if (!ip_nametoaddr (name,NIL,NIL,&ret,NIL)) ret = name;
983 (*bn) (BLOCK_NONSENSITIVE,data);
984 (*bn) (BLOCK_NONE,NIL); /* alarms OK now */
985 if (tcpdebug) mm_log ("DNS canonicalization done",TCPDEBUG);
986 return ret;
987 }
989 /* TCP/IP return name from socket
990 * Accepts: socket
991 * verbose flag
992 * Returns: cpystr name
993 */
995 char *tcp_name (struct sockaddr *sadr,long flag)
996 {
997 char *ret,*t,adr[MAILTMPLEN],tmp[MAILTMPLEN];
998 sprintf (ret = adr,"[%.80s]",ip_sockaddrtostring (sadr));
999 if (allowreversedns) {
1000 blocknotify_t bn = (blocknotify_t)mail_parameters(NIL,GET_BLOCKNOTIFY,NIL);
1001 void *data;
1002 if (tcpdebug) {
1003 sprintf (tmp,"Reverse DNS resolution %s",adr);
1004 mm_log (tmp,TCPDEBUG);
1006 (*bn) (BLOCK_DNSLOOKUP,NIL);/* quell alarms */
1007 data = (*bn) (BLOCK_SENSITIVE,NIL);
1008 /* translate address to name */
1009 if (t = tcp_name_valid (ip_sockaddrtoname (sadr))) {
1010 /* produce verbose form if needed */
1011 if (flag) sprintf (ret = tmp,"%s %s",t,adr);
1012 else ret = t;
1014 (*bn) (BLOCK_NONSENSITIVE,data);
1015 (*bn) (BLOCK_NONE,NIL); /* alarms OK now */
1016 if (tcpdebug) mm_log ("Reverse DNS resolution done",TCPDEBUG);
1018 return cpystr (ret);
1022 /* TCP/IP validate name
1023 * Accepts: domain name
1024 * Returns: name if valid, NIL otherwise
1025 */
1027 char *tcp_name_valid (char *s)
1029 int c;
1030 char *ret,*tail;
1031 /* must be non-empty and not too long */
1032 if ((ret = (s && *s) ? s : NIL) && (tail = ret + NETMAXHOST)) {
1033 /* must be alnum, dot, or hyphen */
1034 while ((c = *s++) && (s <= tail) &&
1035 (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) ||
1036 ((c >= '0') && (c <= '9')) || (c == '-') || (c == '.')));
1037 if (c) ret = NIL;
1039 return ret;
1042 /* TCP/IP check if client is given host name
1043 * Accepts: candidate host name
1044 * Returns: T if match, NIL otherwise
1045 */
1047 long tcp_isclienthost (char *host)
1049 int family;
1050 size_t adrlen,sadrlen,len;
1051 void *adr,*next;
1052 struct sockaddr *sadr;
1053 long ret = NIL;
1054 /* make sure that myClientAddr is set */
1055 if (tcp_clienthost () && myClientAddr)
1056 /* get sockaddr of client */
1057 for (adr = ip_nametoaddr (host,&adrlen,&family,NIL,&next); adr && !ret;
1058 adr = ip_nametoaddr (NIL,&adrlen,&family,NIL,&next)) {
1059 /* build sockaddr of given address */
1060 sadr = ip_sockaddr (family,adr,adrlen,1,&len);
1061 if (!strcmp (myClientAddr,ip_sockaddrtostring (sadr))) ret = LONGT;
1062 fs_give ((void **) &sadr); /* done with client sockaddr */
1064 return ret;
1067 /* Following statement must be at end of this module */
1069 #undef fork /* undo any use of vfork() */

UW-IMAP'd extensions by yuuji