2 * driver.c -- generic driver for mail fetch method protocols
4 * Copyright 1996 by Eric S. Raymond
6 * For license terms, see the file COPYING in this directory.
15 #if defined(STDC_HEADERS)
18 #if defined(HAVE_UNISTD_H)
21 #if defined(HAVE_STDARG_H)
26 #if defined(HAVE_ALLOCA_H)
32 #ifdef HAVE_GETHOSTBYNAME
35 #endif /* HAVE_GETHOSTBYNAME */
40 #include <netinet/in.h>
42 #endif /* KERBEROS_V4 */
44 #include "fetchmail.h"
48 /* BSD portability hack...I know, this is an ugly place to put it */
49 #if !defined(SIGCHLD) && defined(SIGCLD)
50 #define SIGCHLD SIGCLD
53 #define SMTP_PORT 25 /* standard SMTP service port */
55 extern char *strstr(); /* needed on sysV68 R3V7.1. */
57 int batchlimit; /* how often to tear down the delivery connection */
58 int fetchlimit; /* how often to tear down the server connection */
59 int batchcount; /* count of messages sent in current batch */
60 int peek_capable; /* can we peek for better error recovery? */
62 static const struct method *protocol;
63 static jmp_buf restart;
67 #define GENSYM (sprintf(tag, "a%04d", ++tagnum), tag)
69 static char *shroud; /* string to shroud in debug output, if non-NULL */
70 static int mytimeout; /* value of nonreponse timeout */
72 static void vtalarm(int timeleft)
73 /* reset the nonresponse-timeout */
75 struct itimerval ntimeout;
77 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
78 ntimeout.it_value.tv_sec = timeleft;
79 ntimeout.it_value.tv_usec = 0;
80 setitimer(ITIMER_VIRTUAL, &ntimeout, (struct itimerval *)NULL);
83 static void vtalarm_handler (int signal)
84 /* handle server-timeout SIGVTALARM signal */
89 #ifdef HAVE_RES_SEARCH
92 static int is_host_alias(const char *name, struct query *ctl)
93 /* determine whether name is a DNS alias of the hostname */
96 struct mxentry *mxp, *mxrecords;
99 * The first two checks are optimizations that will catch a good
100 * many cases. (1) check against the hostname the user
101 * specified. Odds are good this will either be the mailserver's
102 * FQDN or a suffix of it with the mailserver's domain's default
103 * host name omitted. Then check the rest of the `also known as'
104 * cache accumulated by previous DNS checks. This cache is primed
105 * by the aka list option.
107 * (2) check against the mailserver's FQDN, in case
108 * it's not the same as the declared hostname.
110 * Either of these on a mail address is definitive. Only if the
111 * name doesn't match either is it time to call the bind library.
112 * If this happens odds are good we're looking at an MX name.
114 if (str_in_list(&ctl->server.lead_server->names, name))
116 else if (strcmp(name, ctl->server.canonical_name) == 0)
118 else if (ctl->server.no_dns)
122 * We know DNS service was up at the beginning of this poll cycle.
123 * If it's down, our nameserver has crashed. We don't want to try
124 * delivering the current message or anything else from this
125 * mailbox until it's back up.
127 else if ((he = gethostbyname(name)) != (struct hostent *)NULL)
129 if (strcmp(ctl->server.canonical_name, he->h_name) == 0)
137 case HOST_NOT_FOUND: /* specified host is unknown */
138 case NO_ADDRESS: /* valid, but does not have an IP address */
141 case NO_RECOVERY: /* non-recoverable name server error */
142 case TRY_AGAIN: /* temporary error on authoritative server */
144 if (outlevel != O_SILENT)
145 putchar('\n'); /* terminate the progress message */
147 "nameserver failure while looking for `%s' during poll of %s.",
148 name, ctl->server.names->id);
150 longjmp(restart, 2); /* try again next poll cycle */
155 * We're only here if DNS was OK but the gethostbyname() failed
156 * with a HOST_NOT_FOUND or NO_ADDRESS error.
157 * Search for a name match on MX records pointing to the server.
160 if ((mxrecords = getmxrecords(name)) == (struct mxentry *)NULL)
164 case HOST_NOT_FOUND: /* specified host is unknown */
165 case NO_ADDRESS: /* valid, but does not have an IP address */
169 case NO_RECOVERY: /* non-recoverable name server error */
170 case TRY_AGAIN: /* temporary error on authoritative server */
173 "nameserver failure while looking for `%s' during poll of %s.",
174 name, ctl->server.names->id);
176 longjmp(restart, 2); /* try again next poll cycle */
182 for (mxp = mxrecords; mxp->name; mxp++)
183 if (strcmp(ctl->server.canonical_name, mxp->name) == 0)
189 /* add this name to relevant server's `also known as' list */
190 save_str(&ctl->server.lead_server->names, -1, name);
194 static void map_name(name, ctl, xmit_names)
195 /* add given name to xmit_names if it matches declared localnames */
196 const char *name; /* name to map */
197 struct query *ctl; /* list of permissible aliases */
198 struct idlist **xmit_names; /* list of recipient names parsed out */
202 lname = idpair_find(&ctl->localnames, name);
203 if (!lname && ctl->wildcard)
206 if (lname != (char *)NULL)
208 if (outlevel == O_VERBOSE)
209 error(0, 0, "mapped %s to local %s", name, lname);
210 save_str(xmit_names, -1, lname);
214 void find_server_names(hdr, ctl, xmit_names)
215 /* parse names out of a RFC822 header into an ID list */
216 const char *hdr; /* RFC822 header in question */
217 struct query *ctl; /* list of permissible aliases */
218 struct idlist **xmit_names; /* list of recipient names parsed out */
220 if (hdr == (char *)NULL)
226 if ((cp = nxtaddr(hdr)) != (char *)NULL)
230 if ((atsign = strchr(cp, '@')))
235 * Does a trailing segment of the hostname match something
236 * on the localdomains list? If so, save the whole name
239 for (idp = ctl->server.localdomains; idp; idp = idp->next)
243 rhs = atsign + 1 + (strlen(atsign) - strlen(idp->id));
244 if ((rhs[-1] == '.' || rhs[-1] == '@')
245 && strcmp(rhs, idp->id) == 0)
247 if (outlevel == O_VERBOSE)
248 error(0, 0, "passed through %s matching %s",
250 save_str(xmit_names, -1, cp);
256 * Check to see if the right-hand part is an alias
257 * or MX equivalent of the mailserver. If it's
258 * not, skip this name. If it is, we'll keep
259 * going and try to find a mapping to a client name.
261 if (!is_host_alias(atsign+1, ctl))
266 map_name(cp, ctl, xmit_names);
268 ((cp = nxtaddr((char *)NULL)) != (char *)NULL);
272 char *parse_received(struct query *ctl, char *bufp)
276 static char rbuf[HOSTLEN + USERNAMELEN + 4];
279 * Try to extract the real envelope addressee. We look here
280 * specifically for the mailserver's Received line.
281 * Note: this will only work for sendmail, or an MTA that
282 * shares sendmail's convention for embedding the envelope
283 * address in the Received line. Sendmail itself only
284 * does this when the mail has a single recipient.
286 if ((ok = strstr(bufp, "by ")) == (char *)NULL)
292 /* extract space-delimited token after "by " */
294 for (sp = ok + 3; !isspace(*sp); sp++)
299 * If it's a DNS name of the mail server, look for the
300 * recipient name after a following "for". Otherwise
303 if (is_host_alias(rbuf, ctl))
304 ok = strstr(sp, "for ");
317 while (*sp && *sp != '>' && *sp != '@' && *sp != ';')
322 /* uh oh -- whitespace here can't be right! */
333 if (outlevel == O_VERBOSE)
334 error(0, 0, "found Received address `%s'", rbuf);
338 #endif /* HAVE_RES_SEARCH */
340 static FILE *smtp_open(struct query *ctl)
341 /* try to open a socket to the appropriate SMTP server for this query */
345 lead = ctl->lead_smtp; /* go to the SMTP leader for this query */
347 /* maybe it's time to close the socket in order to force delivery */
348 if (batchlimit && lead->smtp_sockfp && batchcount++ == batchlimit)
350 fclose(lead->smtp_sockfp);
351 lead->smtp_sockfp = (FILE *)NULL;
356 * RFC 1123 requires that the domain name in HELO address is a
357 * "valid principal domain name" for the client host. We
358 * violate this with malice aforethought in order to make the
359 * Received headers and logging look right.
361 * In fact this code relies on the RFC1123 requirement that the
362 * SMTP listener must accept messages even if verification of the
363 * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
366 /* if no socket to this host is already set up, try to open ESMTP */
367 if (lead->smtp_sockfp == (FILE *)NULL)
369 if ((lead->smtp_sockfp = SockOpen(lead->smtphost, SMTP_PORT)) == (FILE *)NULL)
370 return((FILE *)NULL);
371 else if (SMTP_ok(lead->smtp_sockfp) != SM_OK
372 || SMTP_ehlo(lead->smtp_sockfp,
373 ctl->server.names->id,
374 &lead->server.esmtp_options) != SM_OK)
377 * RFC 1869 warns that some listeners hang up on a failed EHLO,
378 * so it's safest not to assume the socket will still be good.
380 fclose(lead->smtp_sockfp);
381 lead->smtp_sockfp = (FILE *)NULL;
385 /* if opening for ESMTP failed, try SMTP */
386 if (lead->smtp_sockfp == (FILE *)NULL)
388 if ((lead->smtp_sockfp = SockOpen(lead->smtphost, SMTP_PORT)) == (FILE *)NULL)
389 return((FILE *)NULL);
390 else if (SMTP_ok(lead->smtp_sockfp) != SM_OK
391 || SMTP_helo(lead->smtp_sockfp, ctl->server.names->id) != SM_OK)
393 fclose(lead->smtp_sockfp);
394 lead->smtp_sockfp = (FILE *)NULL;
398 return(lead->smtp_sockfp);
401 static int gen_readmsg(sockfp, len, delimited, ctl, realname)
402 /* read message content and ship to SMTP or MDA */
403 FILE *sockfp; /* to which the server is connected */
404 long len; /* length of message */
405 int delimited; /* does the protocol use a message delimiter? */
406 struct query *ctl; /* query control record */
407 char *realname; /* real name of host */
409 char buf [MSGBUFSIZE+1];
410 char *bufp, *headers, *fromhdr,*tohdr,*cchdr,*bcchdr,*received_for,*envto;
411 char *fromptr, *toptr, *ctthdr;
413 int inheaders, sizeticker, delete_ok;
415 RETSIGTYPE (*sigchld)();
416 #ifdef HAVE_GETHOSTBYNAME
417 char rbuf[HOSTLEN + USERNAMELEN + 4];
418 #endif /* HAVE_GETHOSTBYNAME */
420 /* read the message content from the server */
421 inheaders = delete_ok = TRUE;
422 headers = fromhdr = tohdr = cchdr = bcchdr = received_for = envto = ctthdr = NULL;
425 while (delimited || len > 0)
429 if (!SockGets(buf+strlen(buf), sizeof(buf)-strlen(buf)-1, sockfp))
431 vtalarm(ctl->server.timeout);
433 /* we may need to grab RFC822 continuations */
434 (inheaders && (ch = SockPeek(sockfp)) == ' ' || ch == '\t');
436 /* write the message size dots */
437 if ((n = strlen(buf)) > 0)
440 while (sizeticker >= SIZETICKER)
442 if (outlevel > O_SILENT)
444 sizeticker -= SIZETICKER;
449 if (buf[0] == '\r' && buf[1] == '\n')
451 if (delimited && *bufp == '.') {
452 if (bufp[1] == '\r' && bufp[2] == '\n')
453 break; /* end of message */
458 if (!ctl->no_rewrite)
459 reply_hack(bufp, realname);
463 oldlen = strlen(bufp);
464 headers = xmalloc(oldlen + 1);
465 (void) strcpy(headers, bufp);
472 newlen = oldlen + strlen(bufp);
473 headers = realloc(headers, newlen + 1);
476 strcpy(headers + oldlen, bufp);
477 bufp = headers + oldlen;
481 if (!fromhdr && !strncasecmp("From:", bufp, 5))
483 else if (!fromhdr && !strncasecmp("Resent-From:", bufp, 12))
485 else if (!fromhdr && !strncasecmp("Apparently-From:", bufp, 16))
488 else if (!strncasecmp("To:", bufp, 3))
491 else if (!envto && !strncasecmp("Apparently-To:", bufp, 14))
493 else if (!envto && !strncasecmp(ctl->server.envelope, bufp, 14))
496 else if (!strncasecmp("Cc:", bufp, 3))
499 else if (!strncasecmp("Bcc:", bufp, 4))
502 else if (!strncasecmp("Content-Transfer-Encoding:", bufp, 26))
505 #ifdef HAVE_RES_SEARCH
506 else if (MULTIDROP(ctl) && !strncasecmp("Received:", bufp, 9))
507 received_for = parse_received(ctl, bufp);
508 #endif /* HAVE_RES_SEARCH */
512 } /* if (inheaders) */
514 if (headers && (!inheaders || len == 0)) /* at end of headers now */
517 struct idlist *idp, *xmit_names;
518 int good_addresses, bad_addresses;
519 #ifdef HAVE_RES_SEARCH
520 int no_local_matches = FALSE;
521 #endif /* HAVE_RES_SEARCH */
523 /* cons up a list of local recipients */
524 xmit_names = (struct idlist *)NULL;
525 bad_addresses = good_addresses = 0;
526 #ifdef HAVE_RES_SEARCH
527 /* is this a multidrop box? */
530 if (envto) /* We have the actual envelope addressee */
531 find_server_names(envto, ctl, &xmit_names);
532 else if (received_for)
534 * We have the Received for addressee.
535 * It has to be a mailserver address, or we
536 * wouldn't have got here.
538 map_name(received_for, ctl, &xmit_names);
542 * We haven't extracted the envelope address.
543 * So check all the header addresses.
545 find_server_names(tohdr, ctl, &xmit_names);
546 find_server_names(cchdr, ctl, &xmit_names);
547 find_server_names(bcchdr, ctl, &xmit_names);
551 no_local_matches = TRUE;
552 save_str(&xmit_names, -1, user);
553 if (outlevel == O_VERBOSE)
555 "no local matches, forwarding to %s",
559 else /* it's a single-drop box, use first localname */
560 #endif /* HAVE_RES_SEARCH */
561 save_str(&xmit_names, -1, ctl->localnames->id);
563 /* time to address the message */
564 if (ctl->mda) /* we have a declared MDA */
570 * We go through this in order to be able to handle very
571 * long lists of users and (re)implement %s.
573 for (idp = xmit_names; idp; idp = idp->next)
574 length += (strlen(idp->id) + 1);
575 names = (char *)alloca(length);
577 for (idp = xmit_names; idp; idp = idp->next)
579 strcat(names, idp->id);
582 cmd = (char *)alloca(strlen(ctl->mda) + length);
583 sprintf(cmd, ctl->mda, names);
584 if (outlevel == O_VERBOSE)
585 error(0, 0, "about to deliver with: %s", cmd);
589 * Arrange to run with user's permissions if we're root.
590 * This will initialize the ownership of any files the
591 * MDA creates properly. (The seteuid call is available
592 * under all BSDs and Linux)
595 #endif /* HAVE_SETEUID */
597 sinkfp = popen(cmd, "w");
600 /* this will fail quietly if we didn't start as root */
602 #endif /* HAVE_SETEUID */
606 error(0, 0, "MDA open failed");
610 sigchld = signal(SIGCHLD, SIG_DFL);
614 char *ap, *ctt, options[MSGBUFSIZE];
617 /* build a connection to the SMTP listener */
618 if (!ctl->mda && ((sinkfp = smtp_open(ctl)) == NULL))
620 free_str_list(&xmit_names);
621 error(0, 0, "SMTP connect failed");
626 * Compute ESMTP options. It's a kluge to use nxtaddr()
627 * here because the contents of the Content-Transfer-Encoding
628 * headers isn't semantically an address. But it has the
629 * desired tokenizing effect.
632 if ((ctl->server.esmtp_options & ESMTP_8BITMIME)
634 && (ctt = nxtaddr(ctthdr))
635 && (!strcasecmp(ctt,"7BIT")||!strcasecmp(ctt,"8BIT")))
636 sprintf(options, " BODY=%s", ctt);
637 if ((ctl->server.esmtp_options & ESMTP_SIZE) && !delimited)
638 sprintf(options + strlen(options), " SIZE=%d", len);
641 * Try to get the SMTP listener to take the header
642 * From address as MAIL FROM (this makes the logging
643 * nicer). If it won't, fall back on the calling-user
644 * ID. This won't affect replies, which use the header
645 * From address anyway.
647 * RFC 1123 requires that the domain name part of the
648 * MAIL FROM address be "canonicalized", that is a
649 * FQDN or MX but not a CNAME. We'll assume the From
650 * header is already in this form here (it certainly
651 * is if rewrite is on). RFC 1123 is silent on whether
652 * a nonexistent hostname part is considered canonical.
654 * This is a potential problem if the MTAs further
655 * upstream didn't pass canonicalized From lines, *and*
656 * the local SMTP listener insists on them.
658 if (!fromhdr || !(ap = nxtaddr(fromhdr)))
660 if (SMTP_from(sinkfp, ap, options) != SM_OK)
662 int smtperr = atoi(smtp_response);
665 error(0, 0, "SMTP error: %s", smtp_response);
668 * There'a one problem with this flow of control;
669 * there's no way to avoid reading the whole message
670 * off the server, even if the MAIL FROM response
671 * tells us that it's just to be discarded. We could
672 * fix this under IMAP by reading headers first, then
673 * trying to issue the MAIL FROM, and *then* reading
674 * the body...but POP3 can't do this.
679 case 571: /* unsolicited email refused */
681 * SMTP listener explicitly refuses to deliver
682 * mail coming from this address, probably due
683 * to an anti-spam domain exclusion. Respect
684 * this. Don't try to ship the message, and
685 * don't prevent it from being deleted.
687 sinkfp = (FILE *)NULL;
690 case 452: /* insufficient system storage */
692 * Temporary out-of-queue-space condition on the
693 * ESMTP server. Don't try to ship the message,
694 * and suppress deletion so it can be retried on
695 * a future retrieval cycle.
698 sinkfp = (FILE *)NULL;
699 SMTP_rset(sockfp); /* required by RFC1870 */
702 case 552: /* message exceeds fixed maximum message size */
704 * Permanent no-go condition on the
705 * ESMTP server. Don't try to ship the message,
706 * and allow it to be deleted.
708 sinkfp = (FILE *)NULL;
709 SMTP_rset(sockfp); /* required by RFC1870 */
712 default: /* retry with invoking user's address */
713 if (SMTP_from(sinkfp, user, options) != SM_OK)
715 error(0,0,"SMTP error: %s", smtp_response);
716 return(PS_SMTP); /* should never happen */
722 * Now list the recipient addressees
724 * RFC 1123 requires that the domain name part of the
725 * RCPT TO address be "canonicalized", that is a FQDN
726 * or MX but not a CNAME. RFC1123 doesn't say whether
727 * the FQDN part can be null (as it frequently will be
728 * here), but it's hard to see how this could cause a
731 for (idp = xmit_names; idp; idp = idp->next)
732 if (SMTP_rcpt(sinkfp, idp->id) == SM_OK)
739 "SMTP listener doesn't like recipient address `%s'", idp->id);
741 if (!good_addresses && SMTP_rcpt(sinkfp, user) != SM_OK)
744 "can't even send to calling user!");
748 /* tell it we're ready to send data */
754 /* write all the headers */
756 n = fwrite(headers, 1, oldlen, sinkfp);
758 n = SockWrite(headers, 1, oldlen, sinkfp);
764 error(0, errno, "writing RFC822 headers");
768 signal(SIGCHLD, sigchld);
772 else if (outlevel == O_VERBOSE)
777 /* write error notifications */
778 #ifdef HAVE_RES_SEARCH
779 if (no_local_matches || bad_addresses)
782 #endif /* HAVE_RES_SEARCH */
785 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
788 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
789 #ifdef HAVE_RES_SEARCH
790 if (no_local_matches)
792 strcat(errhd, "no recipient addresses matched declared local names");
796 #endif /* HAVE_RES_SEARCH */
800 strcat(errhd, "SMTP listener rejected local recipient addresses: ");
801 errlen = strlen(errhd);
802 for (idp = xmit_names; idp; idp = idp->next)
804 errlen += strlen(idp->id) + 2;
806 errmsg = alloca(errlen+3);
807 (void) strcpy(errmsg, errhd);
808 for (idp = xmit_names; idp; idp = idp->next)
811 strcat(errmsg, idp->id);
813 strcat(errmsg, ", ");
817 strcat(errmsg, "\n");
819 /* ship out the error line */
821 fwrite(errmsg, 1, strlen(errmsg), sinkfp);
823 SockWrite(errmsg, 1, strlen(errmsg), sinkfp);
826 free_str_list(&xmit_names);
827 } /* else if (headers) */
829 /* output a crlf if zero length message body */
830 if (!len && inheaders)
833 fputs("\r\n", sinkfp);
835 SockWrite("\r\n", 1, 2, sinkfp);
839 /* following code is executed on non-header lines only */
841 /* SMTP byte-stuffing */
846 SockWrite(bufp, 1, 1, sinkfp);
848 /* ship out the text line */
850 n = fwrite(bufp, 1, strlen(bufp), sinkfp);
852 n = SockWrite(bufp, 1, strlen(bufp), sinkfp);
856 error(0, errno, "writing message text");
860 signal(SIGCHLD, sigchld);
864 else if (outlevel == O_VERBOSE)
868 if (outlevel == O_VERBOSE)
875 /* close the delivery pipe, we'll reopen before next message */
877 signal(SIGCHLD, sigchld);
880 error(0, 0, "MDA exited abnormally or returned nonzero status");
886 /* write message terminator */
887 if (SMTP_eom(sinkfp) != SM_OK)
889 error(0, 0, "SMTP listener refused delivery");
890 return(PS_TRANSIENT);
894 return(delete_ok ? PS_SUCCESS : PS_TRANSIENT);
899 kerberos_auth (socket, canonical)
900 /* authenticate to the server host using Kerberos V4 */
901 int socket; /* socket to server host */
902 const char *canonical; /* server name */
908 Key_schedule schedule;
911 ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
912 rem = (krb_sendauth (0L, socket, ticket, "pop",
914 ((char *) (krb_realmofhost (canonical))),
919 ((struct sockaddr_in *) 0),
920 ((struct sockaddr_in *) 0),
925 error(0, 0, "kerberos error %s", (krb_get_err_text (rem)));
930 #endif /* KERBEROS_V4 */
932 int do_protocol(ctl, proto)
933 /* retrieve messages from server using given protocol method table */
934 struct query *ctl; /* parsed options with merged-in defaults */
935 const struct method *proto; /* protocol method table */
938 char *msg, *sp, *cp, realname[HOSTLEN];
942 if (ctl->server.authenticate == A_KERBEROS)
944 error(0, 0, "Kerberos support not linked.");
947 #endif /* KERBEROS_V4 */
949 /* lacking methods, there are some options that may fail */
952 /* check for unsupported options */
955 "Option --flush is not supported with %s",
959 else if (ctl->fetchall) {
961 "Option --all is not supported with %s",
966 if (!proto->getsizes && ctl->limit)
969 "Option --limit is not supported with %s",
976 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
978 error_init(poll_interval == 0 && !logfile);
980 /* set up the server-nonresponse timeout */
981 sigsave = signal(SIGVTALRM, vtalarm_handler);
982 vtalarm(mytimeout = ctl->server.timeout);
984 if ((js = setjmp(restart)) == 1)
987 "timeout after %d seconds waiting for %s.",
988 ctl->server.timeout, ctl->server.names->id);
993 /* error message printed at point of longjmp */
998 char buf [POPBUFSIZE+1];
999 int *msgsizes, len, num, count, new, deletions = 0;
1001 /* execute pre-initialization command, if any */
1002 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1004 sprintf(buf, "pre-connection command failed with status %d", ok);
1010 /* open a socket to the mail server */
1011 if (!(sockfp = SockOpen(ctl->server.names->id,
1012 ctl->server.port ? ctl->server.port : protocol->port)))
1014 #ifndef EHOSTUNREACH
1015 #define EHOSTUNREACH (-1)
1017 if (errno != EHOSTUNREACH)
1018 error(0, errno, "connecting to host");
1024 if (ctl->authenticate == A_KERBEROS)
1026 ok = kerberos_auth(fileno(sockfp), ctl->server.canonical_name);
1029 vtalarm(ctl->server.timeout);
1031 #endif /* KERBEROS_V4 */
1033 /* accept greeting message from mail server */
1034 ok = (protocol->parse_response)(sockfp, buf);
1037 vtalarm(ctl->server.timeout);
1040 * Try to parse the host's actual name out of the greeting
1041 * message. We do this so that the progress messages will
1042 * make sense even if the connection is indirected through
1043 * ssh. *Do* use this for hacking reply headers, but *don't*
1044 * use it for error logging, as the names in the log should
1045 * correlate directly back to rc file entries.
1047 * This assumes that the first space-delimited token found
1048 * that contains at least two dots (with the characters on
1049 * each side of the dot alphanumeric to exclude version
1050 * numbers) is the hostname. The hostname candidate may not
1051 * contain @ -- if it does it's probably a mailserver
1052 * maintainer's name. If no such token is found, fall back on
1053 * the .fetchmailrc id.
1056 for (cp = buf; *cp; cp++)
1060 case 0: /* skip to end of current token */
1065 case 1: /* look for blank-delimited token */
1073 case 2: /* look for first dot */
1076 else if (*cp == ' ')
1078 else if (*cp == '.' && isalpha(cp[1]) && isalpha(cp[-1]))
1082 case 3: /* look for second dot */
1085 else if (*cp == ' ')
1087 else if (*cp == '.' && isalpha(cp[1]) && isalpha(cp[-1]))
1091 case 4: /* look for trailing space */
1094 else if (*cp == ' ')
1105 char *tp = realname;
1112 strcpy(realname, ctl->server.names->id);
1114 /* try to get authorized to fetch mail */
1115 shroud = ctl->password;
1116 ok = (protocol->getauth)(sockfp, ctl, buf);
1117 shroud = (char *)NULL;
1122 vtalarm(ctl->server.timeout);
1124 /* compute number of messages and number of new messages waiting */
1125 ok = (protocol->getrange)(sockfp, ctl, &count, &new);
1128 vtalarm(ctl->server.timeout);
1130 /* show user how many messages we downloaded */
1131 if (outlevel > O_SILENT)
1133 error(0, 0, "No mail from %s@%s",
1138 if (new != -1 && (count - new) > 0)
1139 error(0, 0, "%d message%s (%d seen) from %s@%s.",
1140 count, count > 1 ? "s" : "", count-new,
1144 error(0, 0, "%d message%s from %s@%s.", count, count > 1 ? "s" : "",
1149 /* we may need to get sizes in order to check message limits */
1150 msgsizes = (int *)NULL;
1151 if (!ctl->fetchall && proto->getsizes && ctl->limit)
1153 msgsizes = (int *)alloca(sizeof(int) * count);
1155 ok = (proto->getsizes)(sockfp, count, msgsizes);
1158 vtalarm(ctl->server.timeout);
1163 if (new == -1 || ctl->fetchall)
1165 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1171 * What forces this code is that in POP3 and IMAP2BIS you can't
1172 * fetch a message without having it marked `seen'. In IMAP4,
1173 * on the other hand, you can (peek_capable is set to convey
1176 * The result of being unable to peek is that if there's
1177 * any kind of transient error (DNS lookup failure, or
1178 * sendmail refusing delivery due to process-table limits)
1179 * the message will be marked "seen" on the server without
1180 * having been delivered. This is not a big problem if
1181 * fetchmail is running in foreground, because the user
1182 * will see a "skipped" message when it next runs and get
1185 * But in daemon mode this leads to the message being silently
1186 * ignored forever. This is not acceptable.
1188 * We compensate for this by checking the error count from the
1189 * previous pass and forcing all messages to be considered new
1192 int force_retrieval = !peek_capable && (ctl->errcount > 0);
1196 /* read, forward, and delete messages */
1197 for (num = 1; num <= count; num++)
1199 int toolarge = msgsizes && (msgsizes[num-1] > ctl->limit);
1200 int fetch_it = ctl->fetchall ||
1201 (!toolarge && (force_retrieval || !(protocol->is_old && (protocol->is_old)(sockfp,ctl,num))));
1202 int suppress_delete = FALSE;
1204 /* we may want to reject this message if it's old */
1207 if (outlevel > O_SILENT)
1209 error_build("skipping message %d", num);
1211 error_build(" (oversized, %d bytes)", msgsizes[num-1]);
1216 /* request a message */
1217 ok = (protocol->fetch)(sockfp, ctl, num, &len);
1220 vtalarm(ctl->server.timeout);
1222 if (outlevel > O_SILENT)
1224 error_build("reading message %d", num);
1226 error_build(" (%d bytes)", len);
1227 if (outlevel == O_VERBOSE)
1228 error_complete(0, 0, "");
1233 /* read the message and ship it to the output sink */
1234 ok = gen_readmsg(sockfp,
1236 protocol->delimited,
1239 if (ok == PS_TRANSIENT)
1240 suppress_delete = TRUE;
1243 vtalarm(ctl->server.timeout);
1245 /* tell the server we got it OK and resynchronize */
1246 if (protocol->trail)
1248 ok = (protocol->trail)(sockfp, ctl, num);
1251 vtalarm(ctl->server.timeout);
1256 * At this point in flow of control, either we've bombed
1257 * on a protocol error or had delivery refused by the SMTP
1258 * server (unlikely -- I've never seen it) or we've seen
1259 * `accepted for delivery' and the message is shipped.
1260 * It's safe to mark the message seen and delete it on the
1264 /* maybe we delete this message now? */
1265 if (protocol->delete
1267 && (fetch_it ? !ctl->keep : ctl->flush))
1270 if (outlevel > O_SILENT)
1271 error_complete(0, 0, " flushed");
1272 ok = (protocol->delete)(sockfp, ctl, num);
1275 vtalarm(ctl->server.timeout);
1276 delete_str(&ctl->newsaved, num);
1278 else if (outlevel > O_SILENT)
1279 error_complete(0, 0, " not flushed");
1281 /* perhaps this as many as we're ready to handle */
1282 if (ctl->fetchlimit && ctl->fetchlimit <= num)
1286 ok = gen_transact(sockfp, protocol->exit_cmd);
1294 ok = gen_transact(sockfp, protocol->exit_cmd);
1303 vtalarm(ctl->server.timeout);
1304 if (ok != 0 && ok != PS_SOCKET)
1305 gen_transact(sockfp, protocol->exit_cmd);
1316 msg = "authorization";
1319 msg = "missing or bad RFC822 header";
1325 msg = "client/server synchronization";
1328 msg = "client/server protocol";
1331 msg = "SMTP transaction";
1334 error(0, 0, "undefined");
1337 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX || ok==PS_IOERR
1338 || ok==PS_ERROR || ok==PS_PROTOCOL || ok==PS_SMTP)
1339 error(0, 0, "%s error while fetching from %s", msg, ctl->server.names->id);
1342 signal(SIGVTALRM, sigsave);
1346 #if defined(HAVE_STDARG_H)
1347 void gen_send(FILE *sockfp, char *fmt, ... )
1348 /* assemble command in printf(3) style and send to the server */
1350 void gen_send(sockfp, fmt, va_alist)
1351 /* assemble command in printf(3) style and send to the server */
1352 FILE *sockfp; /* socket to which server is connected */
1353 const char *fmt; /* printf-style format */
1357 char buf [POPBUFSIZE+1];
1360 if (protocol->tagged)
1361 (void) sprintf(buf, "%s ", GENSYM);
1365 #if defined(HAVE_STDARG_H)
1370 vsprintf(buf + strlen(buf), fmt, ap);
1373 strcat(buf, "\r\n");
1374 SockWrite(buf, 1, strlen(buf), sockfp);
1376 if (outlevel == O_VERBOSE)
1380 if (shroud && (cp = strstr(buf, shroud)))
1381 memset(cp, '*', strlen(shroud));
1382 buf[strlen(buf)-1] = '\0';
1383 error(0, 0, "%s> %s", protocol->name, buf);
1387 #if defined(HAVE_STDARG_H)
1388 int gen_transact(FILE *sockfp, char *fmt, ... )
1389 /* assemble command in printf(3) style, send to server, accept a response */
1391 int gen_transact(sockfp, fmt, va_alist)
1392 /* assemble command in printf(3) style, send to server, accept a response */
1393 FILE *sockfp; /* socket to which server is connected */
1394 const char *fmt; /* printf-style format */
1399 char buf [POPBUFSIZE+1];
1402 if (protocol->tagged)
1403 (void) sprintf(buf, "%s ", GENSYM);
1407 #if defined(HAVE_STDARG_H)
1412 vsprintf(buf + strlen(buf), fmt, ap);
1415 strcat(buf, "\r\n");
1416 SockWrite(buf, 1, strlen(buf), sockfp);
1418 if (outlevel == O_VERBOSE)
1422 if (shroud && (cp = strstr(buf, shroud)))
1423 memset(cp, '*', strlen(shroud));
1424 buf[strlen(buf)-1] = '\0';
1425 error(0, 0, "%s> %s", protocol->name, buf);
1428 /* we presume this does its own response echoing */
1429 ok = (protocol->parse_response)(sockfp, buf);
1435 /* driver.c ends here */