2 * driver.c -- generic driver for mail fetch method protocols
4 * Copyright 1997 by Eric S. Raymond
5 * For license terms, see the file COPYING in this directory.
16 #endif /* HAVE_MEMORY_H */
17 #if defined(STDC_HEADERS)
20 #if defined(HAVE_UNISTD_H)
23 #if defined(HAVE_STDARG_H)
28 #if defined(HAVE_SYS_ITIMER_H)
29 #include <sys/itimer.h>
34 #ifdef HAVE_RES_SEARCH
37 #endif /* HAVE_RES_SEARCH */
40 #if defined (__bsdi__)
41 #include <des.h> /* order of includes matters */
43 #define krb_get_err_text(e) (krb_err_txt[e])
45 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__)
46 #define krb_get_err_text(e) (krb_err_txt[e])
52 #endif /* ! defined (__FreeBSD__) */
53 #endif /* ! defined (__bsdi__) */
54 #include <netinet/in.h>
56 #endif /* KERBEROS_V4 */
60 #endif /* KERBEROS_V5 */
63 #include "fetchmail.h"
66 #define SMTP_PORT "smtp" /* standard SMTP service port */
68 #define SMTP_PORT 25 /* standard SMTP service port */
71 #ifndef strstr /* glibc-2.1 declares this as a macro */
72 extern char *strstr(); /* needed on sysV68 R3V7.1. */
75 int fetchlimit; /* how often to tear down the server connection */
76 int batchcount; /* count of messages sent in current batch */
77 flag peek_capable; /* can we peek for better error recovery? */
78 int pass; /* how many times have we re-polled? */
79 int phase; /* where are we, for error-logging purposes? */
81 static const struct method *protocol;
82 static jmp_buf restart;
86 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
88 static char shroud[PASSWORDLEN]; /* string to shroud in debug output */
89 static int mytimeout; /* value of nonreponse timeout */
90 static int msglen; /* actual message length */
92 void set_timeout(int timeleft)
93 /* reset the nonresponse-timeout */
96 struct itimerval ntimeout;
98 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
99 ntimeout.it_value.tv_sec = timeleft;
100 ntimeout.it_value.tv_usec = 0;
101 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
105 static void timeout_handler (int signal)
106 /* handle server-timeout SIGALRM signal */
111 static int accept_count, reject_count;
113 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
114 /* add given name to xmit_names if it matches declared localnames */
115 /* name: name to map */
116 /* ctl: list of permissible aliases */
117 /* xmit_names: list of recipient names parsed out */
122 lname = idpair_find(&ctl->localnames, name+off);
123 if (!lname && ctl->wildcard)
126 if (lname != (char *)NULL)
128 if (outlevel >= O_DEBUG)
129 error(0, 0, "mapped %s to local %s", name, lname);
130 save_str(xmit_names, lname, XMIT_ACCEPT);
135 void find_server_names(const char *hdr, struct query *ctl, struct idlist **xmit_names)
136 /* parse names out of a RFC822 header into an ID list */
137 /* hdr: RFC822 header in question */
138 /* ctl: list of permissible aliases */
139 /* xmit_names: list of recipient names parsed out */
141 if (hdr == (char *)NULL)
147 for (cp = nxtaddr(hdr);
154 * If the name of the user begins with a qmail virtual
155 * domain prefix, ignore the prefix. Doing this here
156 * means qvirtual will work either with ordinary name
157 * mapping or with a localdomains option.
159 if (ctl->server.qvirtual)
161 int sl = strlen(ctl->server.qvirtual);
163 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
167 if ((atsign = strchr(cp, '@'))) {
171 * Does a trailing segment of the hostname match something
172 * on the localdomains list? If so, save the whole name
175 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
178 rhs = atsign + (strlen(atsign) - strlen(idp->id));
180 (rhs[-1] == '.' || rhs[-1] == '@') &&
181 strcasecmp(rhs, idp->id) == 0)
183 if (outlevel >= O_DEBUG)
184 error(0, 0, "passed through %s matching %s",
186 save_str(xmit_names, cp, XMIT_ACCEPT);
192 /* if we matched a local domain, idp != NULL */
196 * Check to see if the right-hand part is an alias
197 * or MX equivalent of the mailserver. If it's
198 * not, skip this name. If it is, we'll keep
199 * going and try to find a mapping to a client name.
201 if (!is_host_alias(atsign+1, ctl))
203 save_str(xmit_names, cp, XMIT_REJECT);
209 map_name(cp, ctl, xmit_names);
216 static char *parse_received(struct query *ctl, char *bufp)
217 /* try to extract real address from the Received line */
218 /* If a valid Received: line is found, we return the full address in
219 * a buffer which can be parsed from nxtaddr(). This is to ansure that
220 * the local domain part of the address can be passed along in
221 * find_server_names() if it contains one.
222 * Note: We should return a dummy header containing the address
223 * which makes nxtaddr() behave correctly.
226 char *ok = (char *)NULL;
227 static char rbuf[HOSTLEN + USERNAMELEN + 4];
229 if (outlevel >= O_DEBUG)
230 error(0, 0, "analyzing Received line:\n%s", bufp);
232 * Try to extract the real envelope addressee. We look here
233 * specifically for the mailserver's Received line.
234 * Note: this will only work for sendmail, or an MTA that
235 * shares sendmail's convention for embedding the envelope
236 * address in the Received line. Sendmail itself only
237 * does this when the mail has a single recipient.
239 if ((ok = strstr(bufp, "by ")) && isspace(ok[-1]))
243 /* extract space-delimited token after "by " */
244 for (sp = ok + 3; isspace(*sp); sp++)
247 for (; !isspace(*sp); sp++)
252 * If it's a DNS name of the mail server, look for the
253 * recipient name after a following "for". Otherwise
256 if (is_host_alias(rbuf, ctl))
258 if (outlevel >= O_DEBUG)
260 "line accepted, %s is an alias of the mailserver", rbuf);
264 if (outlevel >= O_DEBUG)
266 "line rejected, %s is not an alias of the mailserver",
271 if ((ok = strstr(sp, "for ")) && isspace(ok[-1]))
273 flag want_gt = FALSE;
277 *tp++ = ':'; /* Here is the hack. This is to be friends */
278 *tp++ = ' '; /* with nxtaddr()... */
284 while (*sp == '@') /* skip routes */
285 while (*sp && *sp++ != ':')
288 && (want_gt ? (*sp != '>') : !isspace(*sp))
294 /* uh oh -- whitespace here can't be right! */
300 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
308 if (outlevel >= O_DEBUG)
309 error(0, 0, "no Received address found");
314 if (outlevel >= O_DEBUG) {
315 char *lf = rbuf + strlen(rbuf)-1;
317 if (outlevel >= O_DEBUG)
318 error(0, 0, "found Received address `%s'", rbuf+2);
325 /* shared by readheaders and readbody */
326 static int sizeticker;
328 #define EMPTYLINE(s) ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
330 static int readheaders(int sock, long fetchlen, long reallen, struct query *ctl, int num)
331 /* read message headers and ship to SMTP or MDA */
332 /* sock: to which the server is connected */
333 /* fetchlen: length of message according to fetch response */
334 /* reallen: length of message according to getsizes */
335 /* ctl: query control record */
336 /* num: index of message */
341 struct addrblk *next;
343 struct addrblk *to_addrchain = NULL;
344 struct addrblk **to_chainptr = &to_addrchain;
345 struct addrblk *resent_to_addrchain = NULL;
346 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
348 char buf[MSGBUFSIZE+1];
349 char return_path[HOSTLEN + USERNAMELEN + 4];
350 int from_offs, reply_to_offs, resent_from_offs;
351 int app_from_offs, sender_offs, resent_sender_offs;
353 char *headers, *received_for, *rcv, *cp;
354 int n, linelen, oldlen, ch, remaining, skipcount;
355 struct idlist *idp, *xmit_names;
356 flag no_local_matches = FALSE;
357 flag headers_ok, has_nuls;
358 int olderrs, good_addresses, bad_addresses;
361 has_nuls = headers_ok = FALSE;
362 return_path[0] = '\0';
363 olderrs = ctl->errcount;
365 /* read message headers */
366 headers = received_for = NULL;
367 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
368 sender_offs = resent_sender_offs = env_offs = -1;
374 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
378 line = xmalloc(sizeof(buf));
382 set_timeout(mytimeout);
383 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
393 /* lines may not be properly CRLF terminated; fix this for qmail */
396 cp = buf + strlen(buf) - 1;
397 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
406 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
410 /* check for end of headers */
414 has_nuls = (linelen != strlen(line));
416 goto process_headers;
420 * Check for end of message immediately. If one of your folders
421 * has been mangled, the delimiter may occur directly after the
424 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
427 has_nuls = (linelen != strlen(line));
428 goto process_headers;
431 /* we may need to grab RFC822 continuations */
432 ((ch = SockPeek(sock)) == ' ' || ch == '\t');
434 /* write the message size dots */
435 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
437 sizeticker += linelen;
438 while (sizeticker >= SIZETICKER)
441 sizeticker -= SIZETICKER;
445 /* we see an ordinary (non-header, non-message-delimiter line */
446 has_nuls = (linelen != strlen(line));
449 * The University of Washington IMAP server (the reference
450 * implementation of IMAP4 written by Mark Crispin) relies
451 * on being able to keep base-UID information in a special
452 * message at the head of the mailbox. This message should
453 * neither be deleted nor forwarded.
457 * We disable this check under POP2 because there's no way to
458 * prevent deletion of the message. So at least we ought to
459 * forward it to the user so he or she will have some clue
460 * that things have gone awry.
462 if (protocol->port != 109)
463 #endif /* POP2_ENABLE */
464 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
471 * This code prevents fetchmail from becoming an accessory after
472 * the fact to upstream sendmails with the `E' option on. It also
473 * copes with certain brain-dead POP servers (like NT's) that pass
474 * through Unix from_ lines.
476 * Either of these bugs can result in a non-RFC822 line at the
477 * beginning of the headers. If fetchmail just passes it
478 * through, the client listener may think the message has *no*
479 * headers (since the first) line it sees doesn't look
480 * RFC822-conformant) and fake up a set.
482 * What the user would see in this case is bogus (synthesized)
483 * headers, followed by a blank line, followed by the >From,
484 * followed by the real headers, followed by a blank line,
487 * We forestall this lossage by tossing anything that looks
488 * like an escaped or passed-through From_ line in headers.
489 * These aren't RFC822 so our conscience is clear...
491 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
498 * If we see a Status line, it may have been inserted by an MUA
499 * on the mail host, or it may have been inserted by the server
500 * program after the headers in the transaction stream. This
501 * can actually hose some new-mail notifiers such as xbuffy,
502 * which assumes any Status line came from a *local* MDA and
503 * therefore indicates that the message has been seen.
505 * Some buggy POP servers (including at least the 3.3(20)
506 * version of the one distributed with IMAP) insert empty
507 * Status lines in the transaction stream; we'll chuck those
508 * unconditionally. Nonempty ones get chucked if the user
509 * turns on the dropstatus flag.
514 if (!strncasecmp(line, "Status:", 7))
516 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
521 while (*cp && isspace(*cp)) cp++;
522 if (!*cp || ctl->dropstatus)
531 line = reply_hack(line, ctl->server.truename);
534 * OK, this is messy. If we're forwarding by SMTP, it's the
535 * SMTP-receiver's job (according to RFC821, page 22, section
536 * 4.1.1) to generate a Return-Path line on final delivery.
537 * The trouble is, we've already got one because the
538 * mailserver's SMTP thought *it* was responsible for final
541 * Stash away the contents of Return-Path (as modified by reply_hack)
542 * for use in generating MAIL FROM later on, then prevent the header
543 * from being saved with the others. In effect, we strip it off here.
545 * If the SMTP server conforms to the standards, and fetchmail gets the
546 * envelope sender from the Return-Path, the new Return-Path should be
547 * exactly the same as the original one.
549 * We do *not* want to ignore empty Return-Path headers. These should
550 * be passed through as a way of indicating that a message should
551 * not trigger bounces if delivery fails. What we *do* need to do is
552 * make sure we never try to rewrite such a blank Return-Path. We
553 * handle this with a check for <> in the rewrite logic above.
555 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
557 strcpy(return_path, cp);
566 oldlen = strlen(line);
567 headers = xmalloc(oldlen + 1);
568 (void) strcpy(headers, line);
576 newlen = oldlen + strlen(line);
577 headers = (char *) realloc(headers, newlen + 1);
578 if (headers == NULL) {
582 strcpy(headers + oldlen, line);
584 line = headers + oldlen;
588 if (!strncasecmp("From:", line, 5))
589 from_offs = (line - headers);
590 else if (!strncasecmp("Reply-To:", line, 9))
591 reply_to_offs = (line - headers);
592 else if (!strncasecmp("Resent-From:", line, 12))
593 resent_from_offs = (line - headers);
594 else if (!strncasecmp("Apparently-From:", line, 16))
595 app_from_offs = (line - headers);
596 else if (!strncasecmp("Sender:", line, 7))
597 sender_offs = (line - headers);
598 else if (!strncasecmp("Resent_Sender:", line, 14))
599 resent_sender_offs = (line - headers);
601 else if (!strncasecmp("Message-Id:", buf, 11))
603 if (ctl->server.uidl)
607 buf[IDLEN+12] = 0; /* prevent stack overflow */
608 sscanf(buf+12, "%s", id);
609 if (!str_find( &ctl->newsaved, num))
611 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
612 new->val.status.num = num;
617 else if (!MULTIDROP(ctl))
620 else if (!strncasecmp("To:", line, 3)
621 || !strncasecmp("Cc:", line, 3)
622 || !strncasecmp("Bcc:", line, 4)
623 || !strncasecmp("Apparently-To:", line, 14))
625 *to_chainptr = xmalloc(sizeof(struct addrblk));
626 (*to_chainptr)->offset = (line - headers);
627 to_chainptr = &(*to_chainptr)->next;
631 else if (!strncasecmp("Resent-To:", line, 10)
632 || !strncasecmp("Resent-Cc:", line, 10)
633 || !strncasecmp("Resent-Bcc:", line, 11))
635 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
636 (*resent_to_chainptr)->offset = (line - headers);
637 resent_to_chainptr = &(*resent_to_chainptr)->next;
638 *resent_to_chainptr = NULL;
641 else if (ctl->server.envelope != STRING_DISABLED)
643 if (ctl->server.envelope
644 && strcasecmp(ctl->server.envelope, "Received"))
646 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
648 strlen(ctl->server.envelope)))
650 if (skipcount++ != ctl->server.envskip)
652 env_offs = (line - headers);
655 else if (!received_for && !strncasecmp("Received:", line, 9))
657 if (skipcount++ != ctl->server.envskip)
659 received_for = parse_received(ctl, line);
666 * We want to detect this early in case there are so few headers that the
667 * dispatch logic barfs.
671 if (outlevel > O_SILENT)
672 error(0,0,"message delimiter found while scanning headers");
676 * Hack time. If the first line of the message was blank, with no headers
677 * (this happens occasionally due to bad gatewaying software) cons up
678 * a set of fake headers.
680 * If you modify the fake header template below, be sure you don't
681 * make either From or To address @-less, otherwise the reply_hack
682 * logic will do bad things.
684 if (headers == (char *)NULL)
687 snprintf(buf, sizeof(buf),
690 #endif /* HAVE_SNPRINTF */
691 "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
692 user, fetchmailhost, ctl->remotename, ctl->server.truename);
693 headers = xstrdup(buf);
697 * We can now process message headers before reading the text.
698 * In fact we have to, as this will tell us where to forward to.
701 /* Decode MIME encoded headers. We MUST do this before
702 * looking at the Content-Type / Content-Transfer-Encoding
703 * headers (RFC 2046).
705 if (ctl->mimedecode) {
706 UnMimeHeader(headers);
708 /* Check for MIME headers indicating possible 8-bit data */
709 ctl->mimemsg = MimeBodyType(headers, ctl->mimedecode);
712 * If there is a Return-Path address on the message, this was
713 * almost certainly the MAIL FROM address given the originating
714 * sendmail. This is the best thing to use for logging the
715 * message origin (it sets up the right behavior for bounces and
716 * mailing lists). Otherwise, fall down to the next available
717 * envelope address (which is the most probable real sender).
718 * *** The order is important! ***
719 * This is especially useful when receiving mailing list
720 * messages in multidrop mode. if a local address doesn't
721 * exist, the bounce message won't be returned blindly to the
722 * author or to the list itself but rather to the list manager
723 * (ex: specified by "Sender:") which is much less annoying. This
724 * is true for most mailing list packages.
726 if( !return_path[0] ){
728 if (resent_sender_offs >= 0 && (ap = nxtaddr(headers + resent_sender_offs)));
729 else if (sender_offs >= 0 && (ap = nxtaddr(headers + sender_offs)));
730 else if (resent_from_offs >= 0 && (ap = nxtaddr(headers + resent_from_offs)));
731 else if (from_offs >= 0 && (ap = nxtaddr(headers + from_offs)));
732 else if (reply_to_offs >= 0 && (ap = nxtaddr(headers + reply_to_offs)));
733 else if (app_from_offs >= 0 && (ap = nxtaddr(headers + app_from_offs)));
734 if (ap) strcpy( return_path, ap );
737 /* cons up a list of local recipients */
738 xmit_names = (struct idlist *)NULL;
739 accept_count = reject_count = 0;
740 /* is this a multidrop box? */
743 if (env_offs > -1) /* We have the actual envelope addressee */
744 find_server_names(headers + env_offs, ctl, &xmit_names);
745 else if (received_for)
747 * We have the Received for addressee.
748 * It has to be a mailserver address, or we
749 * wouldn't have got here.
750 * We use find_server_names() to let local
751 * hostnames go through.
753 find_server_names(received_for, ctl, &xmit_names);
757 find_server_names(sdps_envto, ctl, &xmit_names);
760 #endif /* SDPS_ENABLE */
764 * We haven't extracted the envelope address.
765 * So check all the "Resent-To" header addresses if
766 * they exist. If and only if they don't, consider
769 register struct addrblk *nextptr;
770 if (resent_to_addrchain) {
771 /* delete the "To" chain and substitute it
772 * with the "Resent-To" list
774 while (to_addrchain) {
775 nextptr = to_addrchain->next;
777 to_addrchain = nextptr;
779 to_addrchain = resent_to_addrchain;
780 resent_to_addrchain = NULL;
782 /* now look for remaining adresses */
783 while (to_addrchain) {
784 find_server_names(headers+to_addrchain->offset, ctl, &xmit_names);
785 nextptr = to_addrchain->next;
787 to_addrchain = nextptr;
792 no_local_matches = TRUE;
793 save_str(&xmit_names, run.postmaster, XMIT_ACCEPT);
794 if (outlevel >= O_DEBUG)
796 "no local matches, forwarding to %s",
800 else /* it's a single-drop box, use first localname */
801 save_str(&xmit_names, ctl->localnames->id, XMIT_ACCEPT);
805 * Time to either address the message or decide we can't deliver it yet.
807 if (ctl->errcount > olderrs) /* there were DNS errors above */
809 if (outlevel >= O_DEBUG)
810 error(0,0, "forwarding and deletion suppressed due to DNS errors");
812 free_str_list(&xmit_names);
813 return(PS_TRANSIENT);
817 /* set up stuffline() so we can deliver the message body through it */
818 if ((n = open_sink(ctl, return_path, xmit_names, reallen,
819 &good_addresses, &bad_addresses)) != PS_SUCCESS)
822 free_str_list(&xmit_names);
829 * Some server/sendmail combinations cause problems when our
830 * synthetic Received line is before the From header. Cope
833 if ((rcv = strstr(headers, "Received:")) == (char *)NULL)
835 /* handle ">Received:" lines too */
836 while (rcv > headers && rcv[-1] != '\n')
843 n = stuffline(ctl, headers);
846 if (!run.invisible && n != -1)
848 /* utter any per-message Received information we need here */
849 sprintf(buf, "Received: from %s\r\n", ctl->server.truename);
850 n = stuffline(ctl, buf);
854 * We used to include ctl->remotename in this log line,
855 * but this can be secure information that would be bad
858 sprintf(buf, "\tby fetchmail-%s %s\r\n",
861 n = stuffline(ctl, buf);
865 if (good_addresses == 0)
868 "for <%s@%s> (by default); ",
869 user, ctl->destaddr);
871 else if (good_addresses == 1)
873 for (idp = xmit_names; idp; idp = idp->next)
874 if (idp->val.status.mark == XMIT_ACCEPT)
875 break; /* only report first address */
876 if (strchr(idp->id, '@'))
877 sprintf(buf+1, "for <%s>", idp->id);
879 sprintf(buf+1, "for <%s/%s>", idp->id, ctl->destaddr);
880 sprintf(buf+strlen(buf), " (%s); ",
881 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
886 strcat(buf, rfc822timestamp());
888 n = stuffline(ctl, buf);
894 n = stuffline(ctl, rcv); /* ship out rest of headers */
898 error(0, errno, "writing RFC822 headers");
901 free_str_list(&xmit_names);
904 else if (!run.use_syslog && outlevel >= O_VERBOSE)
907 /* write error notifications */
908 if (no_local_matches || has_nuls || bad_addresses)
911 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
914 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
915 if (no_local_matches)
917 if (reject_count != 1)
918 strcat(errhd, "no recipient addresses matched declared local names");
921 for (idp = xmit_names; idp; idp = idp->next)
922 if (idp->val.status.mark == XMIT_REJECT)
924 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
930 if (errhd[sizeof("X-Fetchmail-Warning: ")])
932 strcat(errhd, "message has embedded NULs");
937 if (errhd[sizeof("X-Fetchmail-Warning: ")])
939 strcat(errhd, "SMTP listener rejected local recipient addresses: ");
940 errlen = strlen(errhd);
941 for (idp = xmit_names; idp; idp = idp->next)
942 if (idp->val.status.mark == XMIT_ANTISPAM)
943 errlen += strlen(idp->id) + 2;
945 xalloca(errmsg, char *, errlen+3);
946 (void) strcpy(errmsg, errhd);
947 for (idp = xmit_names; idp; idp = idp->next)
948 if (idp->val.status.mark == XMIT_ANTISPAM)
950 strcat(errmsg, idp->id);
952 strcat(errmsg, ", ");
957 strcat(errmsg, "\r\n");
959 /* ship out the error line */
960 stuffline(ctl, errmsg);
963 /* issue the delimiter line */
971 free_str_list(&xmit_names);
972 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
975 static int readbody(int sock, struct query *ctl, flag forward, int len)
976 /* read and dispose of a message body presented on sock */
977 /* ctl: query control record */
978 /* sock: to which the server is connected */
979 /* len: length of message */
980 /* forward: TRUE to forward */
983 unsigned char buf[MSGBUFSIZE+4];
984 unsigned char *inbufp = buf;
985 flag issoftline = FALSE;
987 /* pass through the text lines */
988 while (protocol->delimited || len > 0)
990 set_timeout(mytimeout);
991 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
999 /* write the message size dots */
1002 sizeticker += linelen;
1003 while (sizeticker >= SIZETICKER)
1005 if (!run.use_syslog && outlevel > O_SILENT)
1007 sizeticker -= SIZETICKER;
1012 /* check for end of message */
1013 if (protocol->delimited && *inbufp == '.')
1014 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1016 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1019 msglen--; /* subtract the size of the dot escape */
1023 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1024 issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1025 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1028 * Soft linebreak, but less than 200 bytes left in
1029 * input buffer. Rather than doing a buffer overrun,
1030 * ignore the soft linebreak, NL-terminate data and
1031 * deliver what we have now.
1032 * (Who writes lines longer than 2K anyway?)
1034 *inbufp = '\n'; *(inbufp+1) = '\0';
1039 /* ship out the text line */
1040 if (forward && (!issoftline))
1045 /* guard against very long lines */
1046 buf[MSGBUFSIZE+1] = '\r';
1047 buf[MSGBUFSIZE+2] = '\n';
1048 buf[MSGBUFSIZE+3] = '\0';
1050 n = stuffline(ctl, buf);
1054 error(0, errno, "writing message text");
1058 else if (outlevel >= O_VERBOSE)
1068 kerberos_auth (socket, canonical)
1069 /* authenticate to the server host using Kerberos V4 */
1070 int socket; /* socket to server host */
1072 char *canonical; /* server name */
1074 const char *canonical; /* server name */
1077 char * host_primary;
1081 Key_schedule schedule;
1084 xalloca(ticket, KTEXT, sizeof (KTEXT_ST));
1085 rem = (krb_sendauth (0L, socket, ticket, "pop",
1087 ((char *) (krb_realmofhost (canonical))),
1088 ((unsigned long) 0),
1092 ((struct sockaddr_in *) 0),
1093 ((struct sockaddr_in *) 0),
1095 if (rem != KSUCCESS)
1097 error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1098 return (PS_AUTHFAIL);
1102 #endif /* KERBEROS_V4 */
1106 kerberos5_auth(socket, canonical)
1107 /* authenticate to the server host using Kerberos V5 */
1108 int socket; /* socket to server host */
1109 const char *canonical; /* server name */
1111 krb5_error_code retval;
1112 krb5_context context;
1114 krb5_principal client = NULL, server = NULL;
1115 krb5_error *err_ret = NULL;
1117 krb5_auth_context auth_context = NULL;
1119 krb5_init_context(&context);
1120 krb5_init_ets(context);
1121 krb5_auth_con_init(context, &auth_context);
1123 if (retval = krb5_cc_default(context, &ccdef)) {
1124 error(0, 0, "krb5_cc_default: %s", error_message(retval));
1128 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1129 error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1133 if (retval = krb5_sname_to_principal(context, canonical, "pop",
1136 error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1140 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1141 "KPOPV1.0", client, server,
1142 AP_OPTS_MUTUAL_REQUIRED,
1143 NULL, /* no data to checksum */
1144 0, /* no creds, use ccache instead */
1148 NULL); /* don't need reply */
1150 krb5_free_principal(context, server);
1151 krb5_free_principal(context, client);
1152 krb5_auth_con_free(context, auth_context);
1155 if (err_ret && err_ret->text.length) {
1156 error(0, 0, "krb5_sendauth: %s [server says '%*s'] ",
1157 error_message(retval),
1158 err_ret->text.length,
1159 err_ret->text.data);
1160 krb5_free_error(context, err_ret);
1162 error(0, 0, "krb5_sendauth: %s", error_message(retval));
1168 #endif /* KERBEROS_V5 */
1170 static void clean_skipped_list(struct idlist **skipped_list)
1171 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
1173 struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
1174 prev = current = head = *skipped_list;
1180 /* if item has no reference, remove it */
1181 if (current && current->val.status.mark == 0)
1183 if (current == head) /* remove first item (head) */
1185 head = current->next;
1186 if (current->id) free(current->id);
1188 prev = current = head;
1190 else /* remove middle/last item */
1192 tmp = current->next;
1194 if (current->id) free(current->id);
1199 else /* skip this item */
1202 current = current->next;
1206 *skipped_list = head;
1209 static open_warning_by_mail(struct query *ctl)
1210 /* set up output sink for a mailed warning to calling user */
1215 * We give a null address list as arg 3 because we actually *want*
1216 * this message to go to run.postmaster. The zero length arg 4 means
1217 * we won't pass a SIZE option to ESMTP; the message length would
1218 * be more trouble than it's worth to compute.
1220 return(open_sink(ctl, "FETCHMAIL-DAEMON", NULL, 0, &good, &bad));
1223 #if defined(HAVE_STDARG_H)
1224 void stuff_warning_line(struct query *ctl, const char *fmt, ... )
1226 void stuff_warning_line(struct query *ctl, fmt, va_alist)
1228 const char *fmt; /* printf-style format */
1231 /* format and ship a warning message line by mail */
1233 char buf[POPBUFSIZE];
1237 * stuffline() requires its input to be writeable (for CR stripping),
1238 * so we needed to copy the message to a writeable buffer anyway in
1239 * case it was a string constant. We make a virtue of that necessity
1240 * here by supporting stdargs/varargs.
1242 #if defined(HAVE_STDARG_H)
1247 #ifdef HAVE_VSNPRINTF
1248 vsnprintf(buf, sizeof(buf), fmt, ap);
1250 vsprintf(buf, fmt, ap);
1254 strcat(buf, "\r\n");
1256 stuffline(ctl, buf);
1259 static close_warning_by_mail(struct query *ctl)
1260 /* sign and send mailed warnings */
1262 stuff_warning_line(ctl, "--\r\n\t\t\t\tThe Fetchmail Daemon\r\n");
1263 close_sink(ctl, TRUE);
1266 static void send_size_warnings(struct query *ctl)
1267 /* send warning mail with skipped msg; reset msg count when user notified */
1270 int msg_to_send = FALSE;
1271 struct idlist *head=NULL, *current=NULL;
1272 int max_warning_poll_count, good, bad;
1273 #define OVERHD "Subject: Fetchmail oversized-messages warning.\r\n\r\nThe following oversized messages remain on the mail server:"
1275 head = ctl->skipped;
1279 /* don't start a notification message unless we need to */
1280 for (current = head; current; current = current->next)
1281 if (current->val.status.num == 0 && current->val.status.mark)
1287 * There's no good way to recover if we can't send notification mail,
1288 * but it's not a disaster, either, since the skipped mail will not
1291 if (open_warning_by_mail(ctl))
1293 stuff_warning_line(ctl, OVERHD);
1295 if (run.poll_interval == 0)
1296 max_warning_poll_count = 0;
1298 max_warning_poll_count = ctl->warnings/run.poll_interval;
1300 /* parse list of skipped msg, adding items to the mail */
1301 for (current = head; current; current = current->next)
1303 if (current->val.status.num == 0 && current->val.status.mark)
1305 nbr = current->val.status.mark;
1306 size = atoi(current->id);
1307 stuff_warning_line(ctl,
1308 "\t%d msg %d octets long skipped by fetchmail.",
1311 current->val.status.num++;
1312 current->val.status.mark = 0;
1314 if (current->val.status.num >= max_warning_poll_count)
1315 current->val.status.num = 0;
1318 close_warning_by_mail(ctl);
1322 int do_protocol(ctl, proto)
1323 /* retrieve messages from server using given protocol method table */
1324 struct query *ctl; /* parsed options with merged-in defaults */
1325 const struct method *proto; /* protocol method table */
1328 #ifdef HAVE_VOLATILE
1329 volatile int sock = -1; /* pacifies -Wall */
1332 #endif /* HAVE_VOLATILE */
1334 void (*sigsave)(int);
1335 struct idlist *current=NULL, *tmp=NULL;
1338 ctl->server.base_protocol = protocol;
1341 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1343 error(0, -1, "Kerberos V4 support not linked.");
1346 #endif /* KERBEROS_V4 */
1349 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1351 error(0, -1, "Kerberos V5 support not linked.");
1354 #endif /* KERBEROS_V5 */
1356 /* lacking methods, there are some options that may fail */
1359 /* check for unsupported options */
1362 "Option --flush is not supported with %s",
1366 else if (ctl->fetchall) {
1368 "Option --all is not supported with %s",
1373 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1376 "Option --limit is not supported with %s",
1383 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1386 /* set up the server-nonresponse timeout */
1387 sigsave = signal(SIGALRM, timeout_handler);
1388 mytimeout = ctl->server.timeout;
1390 if ((js = setjmp(restart)) == 1)
1392 if (phase == OPEN_WAIT)
1394 "timeout after %d seconds waiting to connect to server %s.",
1395 ctl->server.timeout, ctl->server.pollname);
1396 else if (phase == SERVER_WAIT)
1398 "timeout after %d seconds waiting for server %s.",
1399 ctl->server.timeout, ctl->server.pollname);
1400 else if (phase == FORWARDING_WAIT)
1402 "timeout after %d seconds waiting for %s.",
1403 ctl->server.timeout,
1404 ctl->mda ? "MDA" : "SMTP");
1405 else if (phase == LISTENER_WAIT)
1407 "timeout after %d seconds waiting for listener to respond.");
1409 error(0, 0, "timeout after %d seconds.", ctl->server.timeout);
1412 if (ctl->smtp_socket != -1)
1413 close(ctl->smtp_socket);
1420 char buf [POPBUFSIZE+1], *realhost;
1421 int len, num, count, new, bytes, deletions = 0, *msgsizes = NULL;
1423 int fetches, dispatches;
1425 int port, fetches, dispatches, oldphase;
1429 /* execute pre-initialization command, if any */
1430 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1432 sprintf(buf, "pre-connection command failed with status %d", ok);
1438 /* open a socket to the mail server */
1441 set_timeout(mytimeout);
1443 port = ctl->server.port ? ctl->server.port : protocol->port;
1445 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1447 if ((sock = SockOpen(realhost,
1448 ctl->server.service ? ctl->server.service : protocol->service,
1449 ctl->server.netsec)) == -1, ctl->server.plugin
1452 if ((sock = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
1456 #ifdef HAVE_RES_SEARCH
1457 if (errno != 0 && h_errno != 0)
1458 error(0, 0, "fetchmail: internal inconsistency");
1460 error_build("fetchmail: %s connection to %s failed",
1461 protocol->name, ctl->server.pollname);
1462 #ifdef HAVE_RES_SEARCH
1465 if (h_errno == HOST_NOT_FOUND)
1466 error_complete(0, 0, ": host is unknown");
1467 else if (h_errno == NO_ADDRESS)
1468 error_complete(0, 0, ": name is valid but has no IP address");
1469 else if (h_errno == NO_RECOVERY)
1470 error_complete(0, 0, ": unrecoverable name server error");
1471 else if (h_errno == TRY_AGAIN)
1472 error_complete(0, 0, ": temporary name server error");
1474 error_complete(0, 0, ": unknown DNS error %d", h_errno);
1476 #endif /* HAVE_RES_SEARCH */
1479 error_complete(0, errno, "");
1490 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1492 set_timeout(mytimeout);
1493 ok = kerberos_auth(sock, ctl->server.truename);
1498 #endif /* KERBEROS_V4 */
1501 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1503 set_timeout(mytimeout);
1504 ok = kerberos5_auth(sock, ctl->server.truename);
1509 #endif /* KERBEROS_V5 */
1511 /* accept greeting message from mail server */
1512 ok = (protocol->parse_response)(sock, buf);
1516 /* try to get authorized to fetch mail */
1517 if (protocol->getauth)
1519 if (protocol->password_canonify)
1520 (protocol->password_canonify)(shroud, ctl->password);
1522 strcpy(shroud, ctl->password);
1524 ok = (protocol->getauth)(sock, ctl, buf);
1527 if (ok == PS_LOCKBUSY)
1528 error(0, -1, "Lock-busy error on %s@%s",
1530 ctl->server.truename);
1535 error(0, -1, "Authorization failure on %s@%s",
1537 ctl->server.truename);
1540 * If we're running in background, try to mail the
1541 * calling user a heads-up about the authentication
1542 * failure the first time it happens.
1544 if (run.poll_interval && !nodetach
1545 && !ctl->authfailcount && !open_warning_by_mail(ctl))
1547 stuff_warning_line(ctl,
1548 "Subject: fetchmail authentication failed\r\n");
1549 stuff_warning_line(ctl,
1550 "Fetchmail could not get mail from %s@%s.",
1552 ctl->server.truename);
1553 stuff_warning_line(ctl,
1554 "The attempt to get authorization failed.");
1555 stuff_warning_line(ctl,
1556 "This probably means your password is invalid.");
1557 close_warning_by_mail(ctl);
1558 ctl->authfailcount++;
1565 ctl->errcount = fetches = 0;
1567 /* now iterate over each folder selected */
1568 for (idp = ctl->mailboxes; idp; idp = idp->next)
1575 if (outlevel >= O_DEBUG)
1577 error(0, 0, "selecting or re-polling folder %s", idp->id);
1579 error(0, 0, "selecting or re-polling default folder");
1581 /* compute # of messages and number of new messages waiting */
1582 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
1587 * We need the size of each message before it's
1588 * loaded in order to pass via the ESMTP SIZE
1589 * option. If the protocol has a getsizes method,
1590 * we presume this means it doesn't get reliable
1591 * sizes from message fetch responses.
1593 if (count > 0 && proto->getsizes)
1597 xalloca(msgsizes, int *, sizeof(int) * count);
1598 for (i = 0; i < count; i++)
1601 ok = (proto->getsizes)(sock, count, msgsizes);
1608 for (i = 0; i < count; i++)
1609 bytes += msgsizes[i];
1613 /* show user how many messages we downloaded */
1615 (void) sprintf(buf, "%s at %s (folder %s)",
1616 ctl->remotename, ctl->server.truename, idp->id);
1618 (void) sprintf(buf, "%s at %s",
1619 ctl->remotename, ctl->server.truename);
1620 if (outlevel > O_SILENT)
1621 if (count == -1) /* only used for ETRN */
1622 error(0, 0, "Polling %s", ctl->server.truename);
1623 else if (count != 0)
1625 if (new != -1 && (count - new) > 0)
1626 error_build("%d message%s (%d seen) for %s",
1627 count, count > 1 ? "s" : "", count-new, buf);
1629 error_build("%d message%s for %s",
1630 count, count > 1 ? "s" : "", buf);
1632 error_complete(0, 0, ".");
1634 error_complete(0, 0, " (%d octets).", bytes);
1638 /* these are pointless in normal daemon mode */
1639 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1640 error(0, 0, "No mail for %s", buf);
1643 /* very important, this is where we leave the do loop */
1649 if (new == -1 || ctl->fetchall)
1651 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1656 flag force_retrieval;
1659 * What forces this code is that in POP2 and
1660 * IMAP2bis you can't fetch a message without
1661 * having it marked `seen'. In POP3 and IMAP4, on the
1662 * other hand, you can (peek_capable is set by
1663 * each driver module to convey this; it's not a
1664 * method constant because of the difference between
1665 * IMAP2bis and IMAP4).
1667 * The result of being unable to peek is that if there's
1668 * any kind of transient error (DNS lookup failure, or
1669 * sendmail refusing delivery due to process-table limits)
1670 * the message will be marked "seen" on the server without
1671 * having been delivered. This is not a big problem if
1672 * fetchmail is running in foreground, because the user
1673 * will see a "skipped" message when it next runs and get
1676 * But in daemon mode this leads to the message
1677 * being silently ignored forever. This is not
1680 * We compensate for this by checking the error
1681 * count from the previous pass and forcing all
1682 * messages to be considered new if it's nonzero.
1684 force_retrieval = !peek_capable && (ctl->errcount > 0);
1686 /* read, forward, and delete messages */
1687 for (num = 1; num <= count; num++)
1689 flag toolarge = NUM_NONZERO(ctl->limit)
1690 && msgsizes && (msgsizes[num-1] > ctl->limit);
1691 flag oldmsg = (protocol->is_old && (protocol->is_old)(sock,ctl,num));
1692 flag fetch_it = !toolarge
1693 && (ctl->fetchall || force_retrieval || !oldmsg);
1694 flag suppress_delete = FALSE;
1695 flag suppress_forward = FALSE;
1696 flag suppress_readbody = FALSE;
1697 flag retained = FALSE;
1700 * This check copes with Post Office/NT's
1701 * annoying habit of randomly prepending bogus
1702 * LIST items of length -1. Patrick Audley
1703 * <paudley@pobox.com> tells us: LIST shows a
1704 * size of -1, RETR and TOP return "-ERR
1705 * System error - couldn't open message", and
1706 * DELE succeeds but doesn't actually delete
1709 if (msgsizes && msgsizes[num-1] == -1)
1711 if (outlevel >= O_VERBOSE)
1713 "Skipping message %d, length -1",
1718 /* we may want to reject this message if it's old */
1721 if (outlevel > O_SILENT)
1723 error_build("skipping message %d", num);
1724 if (toolarge && !check_only)
1729 /* convert sz to string */
1730 sprintf(size, "%d", msgsizes[num-1]);
1732 /* build a list of skipped messages
1733 * val.id = size of msg (string cnvt)
1734 * val.status.num = warning_poll_count
1735 * val.status.mask = nbr of msg this size
1738 current = ctl->skipped;
1740 /* initialise warning_poll_count to the
1741 * current value so that all new msg will
1742 * be included in the next mail
1744 cnt = current? current->val.status.num : 0;
1746 /* if entry exists, increment the count */
1748 str_in_list(¤t, size, FALSE))
1751 current = current->next)
1753 if (strcmp(current->id, size) == 0)
1755 current->val.status.mark++;
1760 /* otherwise, create a new entry */
1761 /* initialise with current poll count */
1764 tmp = save_str(&ctl->skipped, size, 1);
1765 tmp->val.status.num = cnt;
1768 error_build(" (oversized, %d octets)",
1775 flag wholesize = !protocol->fetch_body;
1777 /* request a message */
1778 ok = (protocol->fetch_headers)(sock,ctl,num, &len);
1782 /* -1 means we didn't see a size in the response */
1783 if (len == -1 && msgsizes)
1785 len = msgsizes[num - 1];
1789 if (outlevel > O_SILENT)
1791 error_build("reading message %d of %d",
1795 error_build(" (%d %soctets)",
1796 len, wholesize ? "" : "header ");
1797 if (outlevel >= O_VERBOSE)
1798 error_complete(0, 0, "");
1804 * Read the message headers and ship them to the
1807 ok = readheaders(sock, len, msgsizes[num-1],
1809 if (ok == PS_RETAINED)
1810 suppress_forward = retained = TRUE;
1811 else if (ok == PS_TRANSIENT)
1812 suppress_delete = suppress_forward = TRUE;
1813 else if (ok == PS_REFUSED)
1814 suppress_forward = TRUE;
1815 else if (ok == PS_TRUNCATED)
1816 suppress_readbody = TRUE;
1821 * If we're using IMAP4 or something else that
1822 * can fetch headers separately from bodies,
1823 * it's time to request the body now. This
1824 * fetch may be skipped if we got an anti-spam
1825 * or other PS_REFUSED error response during
1828 if (protocol->fetch_body && !suppress_readbody)
1830 if (outlevel >= O_VERBOSE)
1831 fputc('\n', stderr);
1833 if ((ok = (protocol->trail)(sock, ctl, num)))
1836 if (!suppress_forward)
1838 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1840 if (outlevel > O_SILENT && !wholesize)
1841 error_build(" (%d body octets) ", len);
1845 /* process the body now */
1848 if (suppress_readbody)
1850 /* When readheaders returns PS_TRUNCATED,
1851 the body (which has no content
1852 has already been read by readheaders,
1853 so we say readbody returned PS_SUCCESS */
1863 if (ok == PS_TRANSIENT)
1864 suppress_delete = suppress_forward = TRUE;
1868 /* tell server we got it OK and resynchronize */
1869 if (protocol->trail)
1871 if (outlevel >= O_VERBOSE)
1872 fputc('\n', stderr);
1874 ok = (protocol->trail)(sock, ctl, num);
1880 /* count # messages forwarded on this pass */
1881 if (!suppress_forward)
1885 * Check to see if the numbers matched?
1887 * Yes, some servers foo this up horribly.
1888 * All IMAP servers seem to get it right, and
1889 * so does Eudora QPOP at least in 2.xx
1892 * Microsoft Exchange gets it completely
1893 * wrong, reporting compressed rather than
1894 * actual sizes (so the actual length of
1895 * message is longer than the reported size).
1896 * Another fine example of Microsoft brain death!
1898 * Some older POP servers, like the old UCB
1899 * POP server and the pre-QPOP QUALCOMM
1900 * versions, report a longer size in the LIST
1901 * response than actually gets shipped up.
1902 * It's unclear what is going on here, as the
1903 * QUALCOMM server (at least) seems to be
1904 * reporting the on-disk size correctly.
1906 if (msgsizes && msglen != msgsizes[num-1])
1908 if (outlevel >= O_DEBUG)
1910 "message %d was not the expected length (%d actual != %d expected)",
1911 num, msglen, msgsizes[num-1]);
1914 /* end-of-message processing starts here */
1915 if (!close_sink(ctl, !suppress_forward))
1918 suppress_delete = TRUE;
1924 * At this point in flow of control, either
1925 * we've bombed on a protocol error or had
1926 * delivery refused by the SMTP server
1927 * (unlikely -- I've never seen it) or we've
1928 * seen `accepted for delivery' and the
1929 * message is shipped. It's safe to mark the
1930 * message seen and delete it on the server
1934 /* tell the UID code we've seen this */
1939 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
1940 if (sdp->val.status.num == num)
1941 sdp->val.status.mark = UID_SEEN;
1944 /* maybe we delete this message now? */
1947 if (outlevel > O_SILENT)
1948 error_complete(0, 0, " retained");
1950 else if (protocol->delete
1952 && (fetch_it ? !ctl->keep : ctl->flush))
1955 if (outlevel > O_SILENT)
1956 error_complete(0, 0, " flushed");
1957 ok = (protocol->delete)(sock, ctl, num);
1961 delete_str(&ctl->newsaved, num);
1962 #endif /* POP3_ENABLE */
1964 else if (outlevel > O_SILENT)
1965 error_complete(0, 0, " not flushed");
1967 /* perhaps this as many as we're ready to handle */
1968 if (NUM_NONZERO(ctl->fetchlimit) && ctl->fetchlimit <= fetches)
1972 if (!check_only && ctl->skipped)
1974 clean_skipped_list(&ctl->skipped);
1975 send_size_warnings(ctl);
1980 * Only re-poll if we had some actual forwards, allowed
1981 * deletions and had no errors.
1982 * Otherwise it is far too easy to get into infinite loops.
1984 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
1988 ok = (protocol->logout_cmd)(sock, ctl);
1990 * Hmmmm...arguably this would be incorrect if we had fetches but
1991 * no dispatches (due to oversized messages, etc.)
1994 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
1999 if (ok != 0 && ok != PS_SOCKET)
2000 (protocol->logout_cmd)(sock, ctl);
2004 msg = (const char *)NULL; /* sacrifice to -Wall */
2011 msg = "authorization";
2014 msg = "missing or bad RFC822 header";
2020 msg = "client/server synchronization";
2023 msg = "client/server protocol";
2026 msg = "lock busy on server";
2029 msg = "SMTP transaction";
2035 error(0, 0, "undefined");
2038 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2039 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2040 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2041 error(0,-1, "%s error while fetching from %s", msg, ctl->server.pollname);
2044 /* execute post-initialization command, if any */
2045 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2049 sprintf(buf, "post-connection command failed with status %d", ok);
2051 if (ok == PS_SUCCESS)
2055 signal(SIGALRM, sigsave);
2059 #if defined(HAVE_STDARG_H)
2060 void gen_send(int sock, const char *fmt, ... )
2062 void gen_send(sock, fmt, va_alist)
2063 int sock; /* socket to which server is connected */
2064 const char *fmt; /* printf-style format */
2067 /* assemble command in printf(3) style and send to the server */
2069 char buf [MSGBUFSIZE+1];
2072 if (protocol->tagged)
2073 (void) sprintf(buf, "%s ", GENSYM);
2077 #if defined(HAVE_STDARG_H)
2082 #ifdef HAVE_VSNPRINTF
2083 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2085 vsprintf(buf + strlen(buf), fmt, ap);
2089 strcat(buf, "\r\n");
2090 SockWrite(sock, buf, strlen(buf));
2092 if (outlevel >= O_MONITOR)
2096 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2100 sp = cp + strlen(shroud);
2106 buf[strlen(buf)-2] = '\0';
2107 error(0, 0, "%s> %s", protocol->name, buf);
2111 int gen_recv(sock, buf, size)
2112 /* get one line of input from the server */
2113 int sock; /* socket to which server is connected */
2114 char *buf; /* buffer to receive input */
2115 int size; /* length of buffer */
2117 int oldphase = phase; /* we don't have to be re-entrant */
2119 phase = SERVER_WAIT;
2120 set_timeout(mytimeout);
2121 if (SockRead(sock, buf, size) == -1)
2130 if (buf[strlen(buf)-1] == '\n')
2131 buf[strlen(buf)-1] = '\0';
2132 if (buf[strlen(buf)-1] == '\r')
2133 buf[strlen(buf)-1] = '\0';
2134 if (outlevel >= O_MONITOR)
2135 error(0, 0, "%s< %s", protocol->name, buf);
2141 #if defined(HAVE_STDARG_H)
2142 int gen_transact(int sock, const char *fmt, ... )
2144 int gen_transact(int sock, fmt, va_alist)
2145 int sock; /* socket to which server is connected */
2146 const char *fmt; /* printf-style format */
2149 /* assemble command in printf(3) style, send to server, accept a response */
2152 char buf [MSGBUFSIZE+1];
2154 int oldphase = phase; /* we don't have to be re-entrant */
2156 phase = SERVER_WAIT;
2158 if (protocol->tagged)
2159 (void) sprintf(buf, "%s ", GENSYM);
2163 #if defined(HAVE_STDARG_H)
2168 #ifdef HAVE_VSNPRINTF
2169 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2171 vsprintf(buf + strlen(buf), fmt, ap);
2175 strcat(buf, "\r\n");
2176 SockWrite(sock, buf, strlen(buf));
2178 if (outlevel >= O_MONITOR)
2182 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2186 sp = cp + strlen(shroud);
2192 buf[strlen(buf)-1] = '\0';
2193 error(0, 0, "%s> %s", protocol->name, buf);
2196 /* we presume this does its own response echoing */
2197 ok = (protocol->parse_response)(sock, buf);
2203 /* driver.c ends here */