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 */
41 #include <kerberosIV/des.h>
42 #include <kerberosIV/krb.h>
44 #if defined (__bsdi__)
45 #include <des.h> /* order of includes matters */
47 #define krb_get_err_text(e) (krb_err_txt[e])
49 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__)
50 #define krb_get_err_text(e) (krb_err_txt[e])
56 #endif /* ! defined (__FreeBSD__) */
57 #endif /* ! defined (__bsdi__) */
58 #endif /* KERBEROS_V5 */
59 #include <netinet/in.h>
61 #endif /* KERBEROS_V4 */
65 #endif /* KERBEROS_V5 */
69 #include "fetchmail.h"
72 #ifndef strstr /* glibc-2.1 declares this as a macro */
73 extern char *strstr(); /* needed on sysV68 R3V7.1. */
76 int fetchlimit; /* how often to tear down the server connection */
77 int batchcount; /* count of messages sent in current batch */
78 flag peek_capable; /* can we peek for better error recovery? */
79 int pass; /* how many times have we re-polled? */
80 int phase; /* where are we, for error-logging purposes? */
82 static const struct method *protocol;
83 static jmp_buf restart;
87 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
89 static char shroud[PASSWORDLEN]; /* string to shroud in debug output */
90 static int mytimeout; /* value of nonreponse timeout */
91 static int timeoutcount; /* count consecutive timeouts */
92 static int msglen; /* actual message length */
94 void set_timeout(int timeleft)
95 /* reset the nonresponse-timeout */
98 struct itimerval ntimeout;
103 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
104 ntimeout.it_value.tv_sec = timeleft;
105 ntimeout.it_value.tv_usec = 0;
106 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
110 static void timeout_handler (int signal)
111 /* handle server-timeout SIGALRM signal */
117 static int accept_count, reject_count;
119 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
120 /* add given name to xmit_names if it matches declared localnames */
121 /* name: name to map */
122 /* ctl: list of permissible aliases */
123 /* xmit_names: list of recipient names parsed out */
128 lname = idpair_find(&ctl->localnames, name+off);
129 if (!lname && ctl->wildcard)
132 if (lname != (char *)NULL)
134 if (outlevel >= O_DEBUG)
135 error(0, 0, _("mapped %s to local %s"), name, lname);
136 save_str(xmit_names, lname, XMIT_ACCEPT);
141 static void find_server_names(const char *hdr,
143 struct idlist **xmit_names)
144 /* parse names out of a RFC822 header into an ID list */
145 /* hdr: RFC822 header in question */
146 /* ctl: list of permissible aliases */
147 /* xmit_names: list of recipient names parsed out */
149 if (hdr == (char *)NULL)
155 for (cp = nxtaddr(hdr);
162 * If the name of the user begins with a qmail virtual
163 * domain prefix, ignore the prefix. Doing this here
164 * means qvirtual will work either with ordinary name
165 * mapping or with a localdomains option.
167 if (ctl->server.qvirtual)
169 int sl = strlen(ctl->server.qvirtual);
171 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
175 if ((atsign = strchr(cp, '@'))) {
179 * Does a trailing segment of the hostname match something
180 * on the localdomains list? If so, save the whole name
183 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
186 rhs = atsign + (strlen(atsign) - strlen(idp->id));
188 (rhs[-1] == '.' || rhs[-1] == '@') &&
189 strcasecmp(rhs, idp->id) == 0)
191 if (outlevel >= O_DEBUG)
192 error(0, 0, _("passed through %s matching %s"),
194 save_str(xmit_names, cp, XMIT_ACCEPT);
200 /* if we matched a local domain, idp != NULL */
204 * Check to see if the right-hand part is an alias
205 * or MX equivalent of the mailserver. If it's
206 * not, skip this name. If it is, we'll keep
207 * going and try to find a mapping to a client name.
209 if (!is_host_alias(atsign+1, ctl))
211 save_str(xmit_names, cp, XMIT_REJECT);
217 map_name(cp, ctl, xmit_names);
224 static char *parse_received(struct query *ctl, char *bufp)
225 /* try to extract real address from the Received line */
226 /* If a valid Received: line is found, we return the full address in
227 * a buffer which can be parsed from nxtaddr(). This is to ansure that
228 * the local domain part of the address can be passed along in
229 * find_server_names() if it contains one.
230 * Note: We should return a dummy header containing the address
231 * which makes nxtaddr() behave correctly.
234 char *base, *ok = (char *)NULL;
235 static char rbuf[HOSTLEN + USERNAMELEN + 4];
238 * Try to extract the real envelope addressee. We look here
239 * specifically for the mailserver's Received line.
240 * Note: this will only work for sendmail, or an MTA that
241 * shares sendmail's convention for embedding the envelope
242 * address in the Received line. Sendmail itself only
243 * does this when the mail has a single recipient.
245 if (outlevel >= O_DEBUG)
246 error(0, 0, _("analyzing Received line:\n%s"), bufp);
248 /* search for whitepace-surrounded "by" followed by xxxx.yyyy */
249 for (base = bufp; ; base = ok + 2)
251 if (!(ok = strstr(base, "by")))
253 else if (!isspace(ok[-1]) || !isspace(ok[2]))
259 /* extract space-delimited token after "by" */
260 for (sp = ok + 2; isspace(*sp); sp++)
263 for (; !isspace(*sp); sp++)
267 /* look for embedded periods */
268 if (strchr(rbuf, '.'))
271 ok = sp - 1; /* arrange to skip this token */
277 * If it's a DNS name of the mail server, look for the
278 * recipient name after a following "for". Otherwise
281 if (is_host_alias(rbuf, ctl))
283 if (outlevel >= O_DEBUG)
285 _("line accepted, %s is an alias of the mailserver"), rbuf);
289 if (outlevel >= O_DEBUG)
291 _("line rejected, %s is not an alias of the mailserver"),
296 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
297 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
299 if (!(ok = strstr(base, "for")))
301 else if (!isspace(ok[-1]) || !isspace(ok[3]))
307 /* extract space-delimited token after "for" */
308 for (sp = ok + 3; isspace(*sp); sp++)
311 for (; !isspace(*sp); sp++)
315 if (strchr(rbuf, '@'))
318 ok = sp - 1; /* arrange to skip this token */
323 flag want_gt = FALSE;
326 /* char after "for" could be space or a continuation newline */
327 for (sp = ok + 4; isspace(*sp); sp++)
330 *tp++ = ':'; /* Here is the hack. This is to be friends */
331 *tp++ = ' '; /* with nxtaddr()... */
337 while (*sp == '@') /* skip routes */
338 while (*sp && *sp++ != ':')
341 && (want_gt ? (*sp != '>') : !isspace(*sp))
347 /* uh oh -- whitespace here can't be right! */
353 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
361 if (outlevel >= O_DEBUG)
362 error(0, 0, _("no Received address found"));
367 if (outlevel >= O_DEBUG) {
368 char *lf = rbuf + strlen(rbuf)-1;
370 if (outlevel >= O_DEBUG)
371 error(0, 0, _("found Received address `%s'"), rbuf+2);
378 /* shared by readheaders and readbody */
379 static int sizeticker;
380 static struct msgblk msgblk;
382 #define EMPTYLINE(s) ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
384 static int readheaders(int sock,
389 /* read message headers and ship to SMTP or MDA */
390 /* sock: to which the server is connected */
391 /* fetchlen: length of message according to fetch response */
392 /* reallen: length of message according to getsizes */
393 /* ctl: query control record */
394 /* num: index of message */
399 struct addrblk *next;
401 struct addrblk *to_addrchain = NULL;
402 struct addrblk **to_chainptr = &to_addrchain;
403 struct addrblk *resent_to_addrchain = NULL;
404 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
406 char buf[MSGBUFSIZE+1];
407 int from_offs, reply_to_offs, resent_from_offs;
408 int app_from_offs, sender_offs, resent_sender_offs;
410 char *received_for, *rcv, *cp;
411 int n, linelen, oldlen, ch, remaining, skipcount;
413 flag no_local_matches = FALSE;
414 flag headers_ok, has_nuls;
415 int olderrs, good_addresses, bad_addresses;
418 has_nuls = headers_ok = FALSE;
419 msgblk.return_path[0] = '\0';
420 olderrs = ctl->errcount;
422 /* read message headers */
423 msgblk.reallen = reallen;
424 msgblk.headers = received_for = NULL;
425 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
426 sender_offs = resent_sender_offs = env_offs = -1;
432 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
436 line = xmalloc(sizeof(buf));
440 set_timeout(mytimeout);
441 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
444 free(msgblk.headers);
451 /* lines may not be properly CRLF terminated; fix this for qmail */
454 cp = buf + strlen(buf) - 1;
455 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
464 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
468 /* check for end of headers */
472 has_nuls = (linelen != strlen(line));
474 goto process_headers;
478 * Check for end of message immediately. If one of your folders
479 * has been mangled, the delimiter may occur directly after the
482 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
485 has_nuls = (linelen != strlen(line));
486 goto process_headers;
489 /* check for RFC822 continuations */
490 set_timeout(mytimeout);
494 (ch == ' ' || ch == '\t'); /* continuation to next line? */
496 /* write the message size dots */
497 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
499 sizeticker += linelen;
500 while (sizeticker >= SIZETICKER)
503 sizeticker -= SIZETICKER;
507 /* we see an ordinary (non-header, non-message-delimiter line */
508 has_nuls = (linelen != strlen(line));
511 * The University of Washington IMAP server (the reference
512 * implementation of IMAP4 written by Mark Crispin) relies
513 * on being able to keep base-UID information in a special
514 * message at the head of the mailbox. This message should
515 * neither be deleted nor forwarded.
519 * We disable this check under POP2 because there's no way to
520 * prevent deletion of the message. So at least we ought to
521 * forward it to the user so he or she will have some clue
522 * that things have gone awry.
524 if (protocol->port != 109)
525 #endif /* POP2_ENABLE */
526 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
528 free(msgblk.headers);
533 * This code prevents fetchmail from becoming an accessory after
534 * the fact to upstream sendmails with the `E' option on. It also
535 * copes with certain brain-dead POP servers (like NT's) that pass
536 * through Unix from_ lines.
538 * Either of these bugs can result in a non-RFC822 line at the
539 * beginning of the headers. If fetchmail just passes it
540 * through, the client listener may think the message has *no*
541 * headers (since the first) line it sees doesn't look
542 * RFC822-conformant) and fake up a set.
544 * What the user would see in this case is bogus (synthesized)
545 * headers, followed by a blank line, followed by the >From,
546 * followed by the real headers, followed by a blank line,
549 * We forestall this lossage by tossing anything that looks
550 * like an escaped or passed-through From_ line in headers.
551 * These aren't RFC822 so our conscience is clear...
553 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
560 * If we see a Status line, it may have been inserted by an MUA
561 * on the mail host, or it may have been inserted by the server
562 * program after the headers in the transaction stream. This
563 * can actually hose some new-mail notifiers such as xbuffy,
564 * which assumes any Status line came from a *local* MDA and
565 * therefore indicates that the message has been seen.
567 * Some buggy POP servers (including at least the 3.3(20)
568 * version of the one distributed with IMAP) insert empty
569 * Status lines in the transaction stream; we'll chuck those
570 * unconditionally. Nonempty ones get chucked if the user
571 * turns on the dropstatus flag.
576 if (!strncasecmp(line, "Status:", 7))
578 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
583 while (*cp && isspace(*cp)) cp++;
584 if (!*cp || ctl->dropstatus)
593 line = reply_hack(line, ctl->server.truename);
596 * OK, this is messy. If we're forwarding by SMTP, it's the
597 * SMTP-receiver's job (according to RFC821, page 22, section
598 * 4.1.1) to generate a Return-Path line on final delivery.
599 * The trouble is, we've already got one because the
600 * mailserver's SMTP thought *it* was responsible for final
603 * Stash away the contents of Return-Path (as modified by reply_hack)
604 * for use in generating MAIL FROM later on, then prevent the header
605 * from being saved with the others. In effect, we strip it off here.
607 * If the SMTP server conforms to the standards, and fetchmail gets the
608 * envelope sender from the Return-Path, the new Return-Path should be
609 * exactly the same as the original one.
611 * We do *not* want to ignore empty Return-Path headers. These should
612 * be passed through as a way of indicating that a message should
613 * not trigger bounces if delivery fails. What we *do* need to do is
614 * make sure we never try to rewrite such a blank Return-Path. We
615 * handle this with a check for <> in the rewrite logic above.
617 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
619 strcpy(msgblk.return_path, cp);
628 oldlen = strlen(line);
629 msgblk.headers = xmalloc(oldlen + 1);
630 (void) strcpy(msgblk.headers, line);
632 line = msgblk.headers;
638 newlen = oldlen + strlen(line);
639 msgblk.headers = (char *) realloc(msgblk.headers, newlen + 1);
640 if (msgblk.headers == NULL) {
644 strcpy(msgblk.headers + oldlen, line);
646 line = msgblk.headers + oldlen;
650 if (!strncasecmp("From:", line, 5))
651 from_offs = (line - msgblk.headers);
652 else if (!strncasecmp("Reply-To:", line, 9))
653 reply_to_offs = (line - msgblk.headers);
654 else if (!strncasecmp("Resent-From:", line, 12))
655 resent_from_offs = (line - msgblk.headers);
656 else if (!strncasecmp("Apparently-From:", line, 16))
657 app_from_offs = (line - msgblk.headers);
658 else if (!strncasecmp("Sender:", line, 7))
659 sender_offs = (line - msgblk.headers);
660 else if (!strncasecmp("Resent-Sender:", line, 14))
661 resent_sender_offs = (line - msgblk.headers);
663 else if (!strncasecmp("Message-Id:", buf, 11))
665 if (ctl->server.uidl)
669 buf[IDLEN+12] = 0; /* prevent stack overflow */
670 sscanf(buf+12, "%s", id);
671 if (!str_find( &ctl->newsaved, num))
673 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
674 new->val.status.num = num;
679 else if (!MULTIDROP(ctl))
682 else if (!strncasecmp("To:", line, 3)
683 || !strncasecmp("Cc:", line, 3)
684 || !strncasecmp("Bcc:", line, 4)
685 || !strncasecmp("Apparently-To:", line, 14))
687 *to_chainptr = xmalloc(sizeof(struct addrblk));
688 (*to_chainptr)->offset = (line - msgblk.headers);
689 to_chainptr = &(*to_chainptr)->next;
693 else if (!strncasecmp("Resent-To:", line, 10)
694 || !strncasecmp("Resent-Cc:", line, 10)
695 || !strncasecmp("Resent-Bcc:", line, 11))
697 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
698 (*resent_to_chainptr)->offset = (line - msgblk.headers);
699 resent_to_chainptr = &(*resent_to_chainptr)->next;
700 *resent_to_chainptr = NULL;
703 else if (ctl->server.envelope != STRING_DISABLED)
705 if (ctl->server.envelope
706 && strcasecmp(ctl->server.envelope, "Received"))
708 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
710 strlen(ctl->server.envelope)))
712 if (skipcount++ != ctl->server.envskip)
714 env_offs = (line - msgblk.headers);
717 else if (!received_for && !strncasecmp("Received:", line, 9))
719 if (skipcount++ != ctl->server.envskip)
721 received_for = parse_received(ctl, line);
728 * We want to detect this early in case there are so few headers that the
729 * dispatch logic barfs.
733 if (outlevel > O_SILENT)
734 error(0,0,_("message delimiter found while scanning headers"));
738 * Hack time. If the first line of the message was blank, with no headers
739 * (this happens occasionally due to bad gatewaying software) cons up
740 * a set of fake headers.
742 * If you modify the fake header template below, be sure you don't
743 * make either From or To address @-less, otherwise the reply_hack
744 * logic will do bad things.
746 if (msgblk.headers == (char *)NULL)
749 snprintf(buf, sizeof(buf),
752 #endif /* HAVE_SNPRINTF */
753 "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
754 user, fetchmailhost, ctl->remotename, ctl->server.truename);
755 msgblk.headers = xstrdup(buf);
759 * We can now process message headers before reading the text.
760 * In fact we have to, as this will tell us where to forward to.
763 /* Decode MIME encoded headers. We MUST do this before
764 * looking at the Content-Type / Content-Transfer-Encoding
765 * headers (RFC 2046).
767 if (ctl->mimedecode) {
768 UnMimeHeader(msgblk.headers);
770 /* Check for MIME headers indicating possible 8-bit data */
771 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
774 * If there is a Return-Path address on the message, this was
775 * almost certainly the MAIL FROM address given the originating
776 * sendmail. This is the best thing to use for logging the
777 * message origin (it sets up the right behavior for bounces and
778 * mailing lists). Otherwise, fall down to the next available
779 * envelope address (which is the most probable real sender).
780 * *** The order is important! ***
781 * This is especially useful when receiving mailing list
782 * messages in multidrop mode. if a local address doesn't
783 * exist, the bounce message won't be returned blindly to the
784 * author or to the list itself but rather to the list manager
785 * (ex: specified by "Sender:") which is much less annoying. This
786 * is true for most mailing list packages.
788 if( !msgblk.return_path[0] ){
790 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
791 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
792 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
793 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
794 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
795 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
796 if (ap) strcpy( msgblk.return_path, ap );
799 /* cons up a list of local recipients */
800 msgblk.recipients = (struct idlist *)NULL;
801 accept_count = reject_count = 0;
802 /* is this a multidrop box? */
805 if (env_offs > -1) /* We have the actual envelope addressee */
806 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
807 else if (received_for)
809 * We have the Received for addressee.
810 * It has to be a mailserver address, or we
811 * wouldn't have got here.
812 * We use find_server_names() to let local
813 * hostnames go through.
815 find_server_names(received_for, ctl, &msgblk.recipients);
819 find_server_names(sdps_envto, ctl, &msgblk.recipients);
822 #endif /* SDPS_ENABLE */
826 * We haven't extracted the envelope address.
827 * So check all the "Resent-To" header addresses if
828 * they exist. If and only if they don't, consider
831 register struct addrblk *nextptr;
832 if (resent_to_addrchain) {
833 /* delete the "To" chain and substitute it
834 * with the "Resent-To" list
836 while (to_addrchain) {
837 nextptr = to_addrchain->next;
839 to_addrchain = nextptr;
841 to_addrchain = resent_to_addrchain;
842 resent_to_addrchain = NULL;
844 /* now look for remaining adresses */
845 while (to_addrchain) {
846 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
847 nextptr = to_addrchain->next;
849 to_addrchain = nextptr;
854 no_local_matches = TRUE;
855 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
856 if (outlevel >= O_DEBUG)
858 _("no local matches, forwarding to %s"),
862 else /* it's a single-drop box, use first localname */
863 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
867 * Time to either address the message or decide we can't deliver it yet.
869 if (ctl->errcount > olderrs) /* there were DNS errors above */
871 if (outlevel >= O_DEBUG)
872 error(0,0, _("forwarding and deletion suppressed due to DNS errors"));
873 free(msgblk.headers);
874 free_str_list(&msgblk.recipients);
875 return(PS_TRANSIENT);
879 /* set up stuffline() so we can deliver the message body through it */
880 if ((n = open_sink(ctl, &msgblk,
881 &good_addresses, &bad_addresses)) != PS_SUCCESS)
883 free(msgblk.headers);
884 free_str_list(&msgblk.recipients);
891 * Some server/sendmail combinations cause problems when our
892 * synthetic Received line is before the From header. Cope
895 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
896 rcv = msgblk.headers;
897 /* handle ">Received:" lines too */
898 while (rcv > msgblk.headers && rcv[-1] != '\n')
900 if (rcv > msgblk.headers)
905 n = stuffline(ctl, msgblk.headers);
908 if (!run.invisible && n != -1)
910 /* utter any per-message Received information we need here */
911 sprintf(buf, "Received: from %s\r\n", ctl->server.truename);
912 n = stuffline(ctl, buf);
916 * This header is technically invalid under RFC822.
917 * POP3, IMAP, etc. are not legal mail-parameter values.
919 * We used to include ctl->remotename in this log line,
920 * but this can be secure information that would be bad
923 sprintf(buf, "\tby %s with %s (fetchmail-%s)\r\n",
927 n = stuffline(ctl, buf);
931 if (good_addresses == 0)
934 "for %s@%s (by default); ",
935 user, ctl->destaddr);
937 else if (good_addresses == 1)
939 for (idp = msgblk.recipients; idp; idp = idp->next)
940 if (idp->val.status.mark == XMIT_ACCEPT)
941 break; /* only report first address */
942 if (strchr(idp->id, '@'))
943 sprintf(buf+1, "for %s", idp->id);
946 * This could be a bit misleading, as destaddr is
947 * the forwarding host rather than the actual
948 * destination. Most of the time they coincide.
950 sprintf(buf+1, "for %s@%s", idp->id, ctl->destaddr);
951 sprintf(buf+strlen(buf), " (%s); ",
952 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
957 strcat(buf, rfc822timestamp());
959 n = stuffline(ctl, buf);
965 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
969 error(0, errno, _("writing RFC822 msgblk.headers"));
971 free(msgblk.headers);
972 free_str_list(&msgblk.recipients);
975 else if (!run.use_syslog && outlevel >= O_VERBOSE)
978 /* write error notifications */
979 if (no_local_matches || has_nuls || bad_addresses)
982 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
985 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
986 if (no_local_matches)
988 if (reject_count != 1)
989 strcat(errhd, _("no recipient addresses matched declared local names"));
992 for (idp = msgblk.recipients; idp; idp = idp->next)
993 if (idp->val.status.mark == XMIT_REJECT)
995 sprintf(errhd+strlen(errhd), _("recipient address %s didn't match any local name"), idp->id);
1001 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1002 strcat(errhd, "; ");
1003 strcat(errhd, _("message has embedded NULs"));
1008 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1009 strcat(errhd, "; ");
1010 strcat(errhd, _("SMTP listener rejected local recipient addresses: "));
1011 errlen = strlen(errhd);
1012 for (idp = msgblk.recipients; idp; idp = idp->next)
1013 if (idp->val.status.mark == XMIT_RCPTBAD)
1014 errlen += strlen(idp->id) + 2;
1016 xalloca(errmsg, char *, errlen+3);
1017 (void) strcpy(errmsg, errhd);
1018 for (idp = msgblk.recipients; idp; idp = idp->next)
1019 if (idp->val.status.mark == XMIT_RCPTBAD)
1021 strcat(errmsg, idp->id);
1023 strcat(errmsg, ", ");
1028 strcat(errmsg, "\r\n");
1030 /* ship out the error line */
1031 stuffline(ctl, errmsg);
1034 /* issue the delimiter line */
1039 stuffline(ctl, buf);
1041 free(msgblk.headers);
1042 free_str_list(&msgblk.recipients);
1043 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1046 static int readbody(int sock, struct query *ctl, flag forward, int len)
1047 /* read and dispose of a message body presented on sock */
1048 /* ctl: query control record */
1049 /* sock: to which the server is connected */
1050 /* len: length of message */
1051 /* forward: TRUE to forward */
1054 unsigned char buf[MSGBUFSIZE+4];
1055 unsigned char *inbufp = buf;
1056 flag issoftline = FALSE;
1058 /* pass through the text lines */
1059 while (protocol->delimited || len > 0)
1061 set_timeout(mytimeout);
1062 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1070 /* write the message size dots */
1073 sizeticker += linelen;
1074 while (sizeticker >= SIZETICKER)
1076 if (!run.use_syslog && outlevel > O_SILENT)
1078 sizeticker -= SIZETICKER;
1083 /* check for end of message */
1084 if (protocol->delimited && *inbufp == '.')
1085 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1087 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1090 msglen--; /* subtract the size of the dot escape */
1094 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1095 issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1096 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1099 * Soft linebreak, but less than 200 bytes left in
1100 * input buffer. Rather than doing a buffer overrun,
1101 * ignore the soft linebreak, NL-terminate data and
1102 * deliver what we have now.
1103 * (Who writes lines longer than 2K anyway?)
1105 *inbufp = '\n'; *(inbufp+1) = '\0';
1110 /* ship out the text line */
1111 if (forward && (!issoftline))
1116 /* guard against very long lines */
1117 buf[MSGBUFSIZE+1] = '\r';
1118 buf[MSGBUFSIZE+2] = '\n';
1119 buf[MSGBUFSIZE+3] = '\0';
1121 n = stuffline(ctl, buf);
1125 error(0, errno, _("writing message text"));
1129 else if (outlevel >= O_VERBOSE)
1139 kerberos_auth (socket, canonical)
1140 /* authenticate to the server host using Kerberos V4 */
1141 int socket; /* socket to server host */
1143 char *canonical; /* server name */
1145 const char *canonical; /* server name */
1148 char * host_primary;
1152 Key_schedule schedule;
1155 xalloca(ticket, KTEXT, sizeof (KTEXT_ST));
1156 rem = (krb_sendauth (0L, socket, ticket, "pop",
1158 ((char *) (krb_realmofhost (canonical))),
1159 ((unsigned long) 0),
1163 ((struct sockaddr_in *) 0),
1164 ((struct sockaddr_in *) 0),
1166 if (rem != KSUCCESS)
1168 error(0, -1, _("kerberos error %s"), (krb_get_err_text (rem)));
1169 return (PS_AUTHFAIL);
1173 #endif /* KERBEROS_V4 */
1176 static int kerberos5_auth(socket, canonical)
1177 /* authenticate to the server host using Kerberos V5 */
1178 int socket; /* socket to server host */
1179 const char *canonical; /* server name */
1181 krb5_error_code retval;
1182 krb5_context context;
1184 krb5_principal client = NULL, server = NULL;
1185 krb5_error *err_ret = NULL;
1187 krb5_auth_context auth_context = NULL;
1189 krb5_init_context(&context);
1190 krb5_init_ets(context);
1191 krb5_auth_con_init(context, &auth_context);
1193 if (retval = krb5_cc_default(context, &ccdef)) {
1194 error(0, 0, "krb5_cc_default: %s", error_message(retval));
1198 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1199 error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1203 if (retval = krb5_sname_to_principal(context, canonical, "pop",
1206 error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1210 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1211 "KPOPV1.0", client, server,
1212 AP_OPTS_MUTUAL_REQUIRED,
1213 NULL, /* no data to checksum */
1214 0, /* no creds, use ccache instead */
1218 NULL); /* don't need reply */
1220 krb5_free_principal(context, server);
1221 krb5_free_principal(context, client);
1222 krb5_auth_con_free(context, auth_context);
1225 if (err_ret && err_ret->text.length) {
1226 error(0, 0, _("krb5_sendauth: %s [server says '%*s'] "),
1227 error_message(retval),
1228 err_ret->text.length,
1229 err_ret->text.data);
1230 krb5_free_error(context, err_ret);
1232 error(0, 0, "krb5_sendauth: %s", error_message(retval));
1238 #endif /* KERBEROS_V5 */
1240 static void clean_skipped_list(struct idlist **skipped_list)
1241 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
1243 struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
1244 prev = current = head = *skipped_list;
1250 /* if item has no reference, remove it */
1251 if (current && current->val.status.mark == 0)
1253 if (current == head) /* remove first item (head) */
1255 head = current->next;
1256 if (current->id) free(current->id);
1258 prev = current = head;
1260 else /* remove middle/last item */
1262 tmp = current->next;
1264 if (current->id) free(current->id);
1269 else /* skip this item */
1272 current = current->next;
1276 *skipped_list = head;
1279 static void send_size_warnings(struct query *ctl)
1280 /* send warning mail with skipped msg; reset msg count when user notified */
1283 int msg_to_send = FALSE;
1284 struct idlist *head=NULL, *current=NULL;
1285 int max_warning_poll_count, good, bad;
1286 #define OVERHD "Subject: Fetchmail oversized-messages warning.\r\n\r\nThe following oversized messages remain on the mail server:"
1288 head = ctl->skipped;
1292 /* don't start a notification message unless we need to */
1293 for (current = head; current; current = current->next)
1294 if (current->val.status.num == 0 && current->val.status.mark)
1300 * There's no good way to recover if we can't send notification mail,
1301 * but it's not a disaster, either, since the skipped mail will not
1304 if (open_warning_by_mail(ctl, (struct msgblk *)NULL))
1306 stuff_warning(ctl, OVERHD);
1308 if (run.poll_interval == 0)
1309 max_warning_poll_count = 0;
1311 max_warning_poll_count = ctl->warnings/run.poll_interval;
1313 /* parse list of skipped msg, adding items to the mail */
1314 for (current = head; current; current = current->next)
1316 if (current->val.status.num == 0 && current->val.status.mark)
1318 nbr = current->val.status.mark;
1319 size = atoi(current->id);
1321 _("\t%d msg %d octets long skipped by fetchmail."),
1324 current->val.status.num++;
1325 current->val.status.mark = 0;
1327 if (current->val.status.num >= max_warning_poll_count)
1328 current->val.status.num = 0;
1331 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1335 int do_protocol(ctl, proto)
1336 /* retrieve messages from server using given protocol method table */
1337 struct query *ctl; /* parsed options with merged-in defaults */
1338 const struct method *proto; /* protocol method table */
1341 #ifdef HAVE_VOLATILE
1342 volatile int sock = -1; /* pacifies -Wall */
1345 #endif /* HAVE_VOLATILE */
1347 void (*sigsave)(int);
1348 struct idlist *current=NULL, *tmp=NULL;
1351 ctl->server.base_protocol = protocol;
1354 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1356 error(0, -1, _("Kerberos V4 support not linked."));
1359 #endif /* KERBEROS_V4 */
1362 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1364 error(0, -1, _("Kerberos V5 support not linked."));
1367 #endif /* KERBEROS_V5 */
1369 /* lacking methods, there are some options that may fail */
1372 /* check for unsupported options */
1375 _("Option --flush is not supported with %s"),
1379 else if (ctl->fetchall) {
1381 _("Option --all is not supported with %s"),
1386 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1389 _("Option --limit is not supported with %s"),
1396 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1399 /* set up the server-nonresponse timeout */
1400 sigsave = signal(SIGALRM, timeout_handler);
1401 mytimeout = ctl->server.timeout;
1403 if ((js = setjmp(restart)) == 1)
1405 if (phase == OPEN_WAIT)
1407 _("timeout after %d seconds waiting to connect to server %s."),
1408 ctl->server.timeout, ctl->server.pollname);
1409 else if (phase == SERVER_WAIT)
1411 _("timeout after %d seconds waiting for server %s."),
1412 ctl->server.timeout, ctl->server.pollname);
1413 else if (phase == FORWARDING_WAIT)
1415 _("timeout after %d seconds waiting for %s."),
1416 ctl->server.timeout,
1417 ctl->mda ? "MDA" : "SMTP");
1418 else if (phase == LISTENER_WAIT)
1420 _("timeout after %d seconds waiting for listener to respond."));
1422 error(0, 0, _("timeout after %d seconds."), ctl->server.timeout);
1425 if (ctl->smtp_socket != -1)
1426 close(ctl->smtp_socket);
1431 * If we've exceeded our threshold for consecutive timeouts,
1432 * try to notify the user, then mark the connection wedged.
1434 if (timeoutcount > MAX_TIMEOUTS
1435 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1438 _("Subject: fetchmail sees repeated timeouts\r\n"));
1440 _("Fetchmail saw more than %d timouts while attempting to get mail from %s@%s."),
1443 ctl->server.truename);
1445 _("This could mean that your mailserver is stuck, or that your SMTP listener"));
1447 _("is wedged, or that your mailbox file on the server has been corrupted by"));
1449 _("a server error. You can run `fetchmail -v -v' to diagnose the problem."));
1451 _("Fetchmail won't poll this mailbox again until you restart it."));
1452 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1460 char buf[POPBUFSIZE+1], *realhost;
1461 int len, num, count, new, bytes, deletions = 0, *msgsizes = NULL;
1463 int fetches, dispatches;
1465 int port, fetches, dispatches, oldphase;
1469 /* execute pre-initialization command, if any */
1470 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1472 sprintf(buf, _("pre-connection command failed with status %d"), ok);
1478 /* open a socket to the mail server */
1481 set_timeout(mytimeout);
1483 port = ctl->server.port ? ctl->server.port : protocol->port;
1485 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1487 if ((sock = SockOpen(realhost,
1488 ctl->server.service ? ctl->server.service : protocol->service,
1489 ctl->server.netsec)) == -1, ctl->server.plugin
1492 if ((sock = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
1497 #ifdef HAVE_RES_SEARCH
1498 if (err_no != 0 && h_errno != 0)
1499 error(0, 0, _("fetchmail: internal inconsistency"));
1502 * Avoid generating a bogus error every poll cycle when we're
1503 * in daemon mode but the connection to the outside world
1506 if (err_no == EHOSTUNREACH && run.poll_interval)
1509 error_build(_("fetchmail: %s connection to %s failed"),
1510 protocol->name, ctl->server.pollname);
1511 #ifdef HAVE_RES_SEARCH
1514 if (h_errno == HOST_NOT_FOUND)
1515 error_complete(0, 0, _(": host is unknown"));
1516 else if (h_errno == NO_ADDRESS)
1517 error_complete(0, 0, _(": name is valid but has no IP address"));
1518 else if (h_errno == NO_RECOVERY)
1519 error_complete(0, 0, _(": unrecoverable name server error"));
1520 else if (h_errno == TRY_AGAIN)
1521 error_complete(0, 0, _(": temporary name server error"));
1523 error_complete(0, 0, _(": unknown DNS error %d"), h_errno);
1526 #endif /* HAVE_RES_SEARCH */
1528 error_complete(0, err_no, "");
1541 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1543 set_timeout(mytimeout);
1544 ok = kerberos_auth(sock, ctl->server.truename);
1549 #endif /* KERBEROS_V4 */
1552 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1554 set_timeout(mytimeout);
1555 ok = kerberos5_auth(sock, ctl->server.truename);
1560 #endif /* KERBEROS_V5 */
1562 /* accept greeting message from mail server */
1563 ok = (protocol->parse_response)(sock, buf);
1567 /* try to get authorized to fetch mail */
1568 if (protocol->getauth)
1570 if (protocol->password_canonify)
1571 (protocol->password_canonify)(shroud, ctl->password);
1573 strcpy(shroud, ctl->password);
1575 ok = (protocol->getauth)(sock, ctl, buf);
1578 if (ok == PS_LOCKBUSY)
1579 error(0, -1, _("Lock-busy error on %s@%s"),
1581 ctl->server.truename);
1586 error(0, -1, _("Authorization failure on %s@%s"),
1588 ctl->server.truename);
1591 * If we're running in background, try to mail the
1592 * calling user a heads-up about the authentication
1593 * failure the first time it happens.
1595 if (run.poll_interval
1597 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1600 _("Subject: fetchmail authentication failed\r\n"));
1602 _("Fetchmail could not get mail from %s@%s."),
1604 ctl->server.truename);
1606 _("The attempt to get authorization failed."));
1608 _("This probably means your password is invalid."));
1609 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1617 ctl->errcount = fetches = 0;
1619 /* now iterate over each folder selected */
1620 for (idp = ctl->mailboxes; idp; idp = idp->next)
1627 if (outlevel >= O_DEBUG)
1629 error(0, 0, _("selecting or re-polling folder %s"), idp->id);
1631 error(0, 0, _("selecting or re-polling default folder"));
1633 /* compute # of messages and number of new messages waiting */
1634 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
1639 * We need the size of each message before it's
1640 * loaded in order to pass via the ESMTP SIZE
1641 * option. If the protocol has a getsizes method,
1642 * we presume this means it doesn't get reliable
1643 * sizes from message fetch responses.
1645 if (count > 0 && proto->getsizes)
1649 xalloca(msgsizes, int *, sizeof(int) * count);
1650 for (i = 0; i < count; i++)
1653 ok = (proto->getsizes)(sock, count, msgsizes);
1660 for (i = 0; i < count; i++)
1661 bytes += msgsizes[i];
1665 /* show user how many messages we downloaded */
1667 (void) sprintf(buf, _("%s at %s (folder %s)"),
1668 ctl->remotename, ctl->server.truename, idp->id);
1670 (void) sprintf(buf, _("%s at %s"),
1671 ctl->remotename, ctl->server.truename);
1672 if (outlevel > O_SILENT)
1673 if (count == -1) /* only used for ETRN */
1674 error(0, 0, _("Polling %s"), ctl->server.truename);
1675 else if (count != 0)
1677 if (new != -1 && (count - new) > 0)
1678 error_build(_("%d %s (%d seen) for %s"),
1679 count, count > 1 ? _("messages") :
1683 error_build(_("%d %s for %s"),
1684 count, count > 1 ? _("messages") :
1687 error_complete(0, 0, ".");
1689 error_complete(0, 0, _(" (%d octets)."), bytes);
1693 /* these are pointless in normal daemon mode */
1694 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1695 error(0, 0, _("No mail for %s"), buf);
1698 /* very important, this is where we leave the do loop */
1704 if (new == -1 || ctl->fetchall)
1706 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1711 flag force_retrieval;
1714 * What forces this code is that in POP2 and
1715 * IMAP2bis you can't fetch a message without
1716 * having it marked `seen'. In POP3 and IMAP4, on the
1717 * other hand, you can (peek_capable is set by
1718 * each driver module to convey this; it's not a
1719 * method constant because of the difference between
1720 * IMAP2bis and IMAP4, and because POP3 doesn't peek
1721 * if fetchall is on).
1723 * The result of being unable to peek is that if there's
1724 * any kind of transient error (DNS lookup failure, or
1725 * sendmail refusing delivery due to process-table limits)
1726 * the message will be marked "seen" on the server without
1727 * having been delivered. This is not a big problem if
1728 * fetchmail is running in foreground, because the user
1729 * will see a "skipped" message when it next runs and get
1732 * But in daemon mode this leads to the message
1733 * being silently ignored forever. This is not
1736 * We compensate for this by checking the error
1737 * count from the previous pass and forcing all
1738 * messages to be considered new if it's nonzero.
1740 force_retrieval = !peek_capable && (ctl->errcount > 0);
1742 /* read, forward, and delete messages */
1743 for (num = 1; num <= count; num++)
1745 flag toolarge = NUM_NONZERO(ctl->limit)
1746 && msgsizes && (msgsizes[num-1] > ctl->limit);
1747 flag oldmsg = (!new) || (protocol->is_old && (protocol->is_old)(sock,ctl,num));
1748 flag fetch_it = !toolarge
1749 && (ctl->fetchall || force_retrieval || !oldmsg);
1750 flag suppress_delete = FALSE;
1751 flag suppress_forward = FALSE;
1752 flag suppress_readbody = FALSE;
1753 flag retained = FALSE;
1756 * This check copes with Post Office/NT's
1757 * annoying habit of randomly prepending bogus
1758 * LIST items of length -1. Patrick Audley
1759 * <paudley@pobox.com> tells us: LIST shows a
1760 * size of -1, RETR and TOP return "-ERR
1761 * System error - couldn't open message", and
1762 * DELE succeeds but doesn't actually delete
1765 if (msgsizes && msgsizes[num-1] == -1)
1767 if (outlevel >= O_VERBOSE)
1769 _("Skipping message %d, length -1"),
1774 /* we may want to reject this message if it's old */
1777 if (outlevel > O_SILENT)
1779 error_build(_("skipping message %d"), num);
1780 if (toolarge && !check_only)
1785 /* convert sz to string */
1786 sprintf(size, "%d", msgsizes[num-1]);
1788 /* build a list of skipped messages
1789 * val.id = size of msg (string cnvt)
1790 * val.status.num = warning_poll_count
1791 * val.status.mask = nbr of msg this size
1794 current = ctl->skipped;
1796 /* initialise warning_poll_count to the
1797 * current value so that all new msg will
1798 * be included in the next mail
1800 cnt = current? current->val.status.num : 0;
1802 /* if entry exists, increment the count */
1804 str_in_list(¤t, size, FALSE))
1807 current = current->next)
1809 if (strcmp(current->id, size) == 0)
1811 current->val.status.mark++;
1816 /* otherwise, create a new entry */
1817 /* initialise with current poll count */
1820 tmp = save_str(&ctl->skipped, size, 1);
1821 tmp->val.status.num = cnt;
1824 error_build(_(" (oversized, %d octets)"),
1831 flag wholesize = !protocol->fetch_body;
1833 /* request a message */
1834 ok = (protocol->fetch_headers)(sock,ctl,num, &len);
1838 /* -1 means we didn't see a size in the response */
1839 if (len == -1 && msgsizes)
1841 len = msgsizes[num - 1];
1845 if (outlevel > O_SILENT)
1847 error_build(_("reading message %d of %d"),
1851 error_build(_(" (%d %soctets)"),
1852 len, wholesize ? "" : _("header "));
1853 if (outlevel >= O_VERBOSE)
1854 error_complete(0, 0, "");
1860 * Read the message headers and ship them to the
1863 ok = readheaders(sock, len, msgsizes[num-1],
1865 if (ok == PS_RETAINED)
1866 suppress_forward = retained = TRUE;
1867 else if (ok == PS_TRANSIENT)
1868 suppress_delete = suppress_forward = TRUE;
1869 else if (ok == PS_REFUSED)
1870 suppress_forward = TRUE;
1871 else if (ok == PS_TRUNCATED)
1872 suppress_readbody = TRUE;
1877 * If we're using IMAP4 or something else that
1878 * can fetch headers separately from bodies,
1879 * it's time to request the body now. This
1880 * fetch may be skipped if we got an anti-spam
1881 * or other PS_REFUSED error response during
1884 if (protocol->fetch_body && !suppress_readbody)
1886 if (outlevel >= O_VERBOSE)
1887 fputc('\n', stderr);
1889 if ((ok = (protocol->trail)(sock, ctl, num)))
1892 if (!suppress_forward)
1894 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1896 if (outlevel > O_SILENT && !wholesize)
1897 error_build(_(" (%d body octets) "), len);
1901 /* process the body now */
1904 if (suppress_readbody)
1906 /* When readheaders returns PS_TRUNCATED,
1907 the body (which has no content
1908 has already been read by readheaders,
1909 so we say readbody returned PS_SUCCESS */
1919 if (ok == PS_TRANSIENT)
1920 suppress_delete = suppress_forward = TRUE;
1924 /* tell server we got it OK and resynchronize */
1925 if (protocol->trail)
1927 if (outlevel >= O_VERBOSE)
1928 fputc('\n', stderr);
1930 ok = (protocol->trail)(sock, ctl, num);
1936 /* count # messages forwarded on this pass */
1937 if (!suppress_forward)
1941 * Check to see if the numbers matched?
1943 * Yes, some servers foo this up horribly.
1944 * All IMAP servers seem to get it right, and
1945 * so does Eudora QPOP at least in 2.xx
1948 * Microsoft Exchange gets it completely
1949 * wrong, reporting compressed rather than
1950 * actual sizes (so the actual length of
1951 * message is longer than the reported size).
1952 * Another fine example of Microsoft brain death!
1954 * Some older POP servers, like the old UCB
1955 * POP server and the pre-QPOP QUALCOMM
1956 * versions, report a longer size in the LIST
1957 * response than actually gets shipped up.
1958 * It's unclear what is going on here, as the
1959 * QUALCOMM server (at least) seems to be
1960 * reporting the on-disk size correctly.
1962 if (msgsizes && msglen != msgsizes[num-1])
1964 if (outlevel >= O_DEBUG)
1966 _("message %d was not the expected length (%d actual != %d expected)"),
1967 num, msglen, msgsizes[num-1]);
1970 /* end-of-message processing starts here */
1971 if (!close_sink(ctl, &msgblk, !suppress_forward))
1974 suppress_delete = TRUE;
1980 * At this point in flow of control, either
1981 * we've bombed on a protocol error or had
1982 * delivery refused by the SMTP server
1983 * (unlikely -- I've never seen it) or we've
1984 * seen `accepted for delivery' and the
1985 * message is shipped. It's safe to mark the
1986 * message seen and delete it on the server
1990 /* tell the UID code we've seen this */
1995 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
1996 if (sdp->val.status.num == num)
1997 sdp->val.status.mark = UID_SEEN;
2000 /* maybe we delete this message now? */
2003 if (outlevel > O_SILENT)
2004 error_complete(0, 0, _(" retained"));
2006 else if (protocol->delete
2008 && (fetch_it ? !ctl->keep : ctl->flush))
2011 if (outlevel > O_SILENT)
2012 error_complete(0, 0, _(" flushed"));
2013 ok = (protocol->delete)(sock, ctl, num);
2017 delete_str(&ctl->newsaved, num);
2018 #endif /* POP3_ENABLE */
2020 else if (outlevel > O_SILENT)
2021 error_complete(0, 0, _(" not flushed"));
2023 /* perhaps this as many as we're ready to handle */
2024 if (NUM_NONZERO(ctl->fetchlimit)
2025 && ctl->fetchlimit <= fetches)
2027 error(0, 0, _("fetchlimit reached; %d messages left on server"),
2033 if (!check_only && ctl->skipped)
2035 clean_skipped_list(&ctl->skipped);
2036 send_size_warnings(ctl);
2041 * Only re-poll if we had some actual forwards, allowed
2042 * deletions and had no errors.
2043 * Otherwise it is far too easy to get into infinite loops.
2045 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2049 /* ordinary termination with no errors -- officially log out */
2050 ok = (protocol->logout_cmd)(sock, ctl);
2052 * Hmmmm...arguably this would be incorrect if we had fetches but
2053 * no dispatches (due to oversized messages, etc.)
2056 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2061 /* we only get here on error */
2062 if (ok != 0 && ok != PS_SOCKET)
2063 (protocol->logout_cmd)(sock, ctl);
2067 msg = (const char *)NULL; /* sacrifice to -Wall */
2074 msg = _("authorization");
2077 msg = _("missing or bad RFC822 header");
2083 msg = _("client/server synchronization");
2086 msg = _("client/server protocol");
2089 msg = _("lock busy on server");
2092 msg = _("SMTP transaction");
2095 msg = _("DNS lookup");
2098 error(0, 0, _("undefined"));
2101 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2102 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2103 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2104 error(0,-1, _("%s error while fetching from %s"), msg, ctl->server.pollname);
2107 /* execute post-initialization command, if any */
2108 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2112 sprintf(buf, _("post-connection command failed with status %d"), ok);
2114 if (ok == PS_SUCCESS)
2118 signal(SIGALRM, sigsave);
2122 #if defined(HAVE_STDARG_H)
2123 void gen_send(int sock, const char *fmt, ... )
2125 void gen_send(sock, fmt, va_alist)
2126 int sock; /* socket to which server is connected */
2127 const char *fmt; /* printf-style format */
2130 /* assemble command in printf(3) style and send to the server */
2132 char buf [MSGBUFSIZE+1];
2135 if (protocol->tagged)
2136 (void) sprintf(buf, "%s ", GENSYM);
2140 #if defined(HAVE_STDARG_H)
2145 #ifdef HAVE_VSNPRINTF
2146 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2148 vsprintf(buf + strlen(buf), fmt, ap);
2152 strcat(buf, "\r\n");
2153 SockWrite(sock, buf, strlen(buf));
2155 if (outlevel >= O_MONITOR)
2159 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2163 sp = cp + strlen(shroud);
2169 buf[strlen(buf)-2] = '\0';
2170 error(0, 0, "%s> %s", protocol->name, buf);
2174 int gen_recv(sock, buf, size)
2175 /* get one line of input from the server */
2176 int sock; /* socket to which server is connected */
2177 char *buf; /* buffer to receive input */
2178 int size; /* length of buffer */
2180 int oldphase = phase; /* we don't have to be re-entrant */
2182 phase = SERVER_WAIT;
2183 set_timeout(mytimeout);
2184 if (SockRead(sock, buf, size) == -1)
2193 if (buf[strlen(buf)-1] == '\n')
2194 buf[strlen(buf)-1] = '\0';
2195 if (buf[strlen(buf)-1] == '\r')
2196 buf[strlen(buf)-1] = '\0';
2197 if (outlevel >= O_MONITOR)
2198 error(0, 0, "%s< %s", protocol->name, buf);
2204 #if defined(HAVE_STDARG_H)
2205 int gen_transact(int sock, const char *fmt, ... )
2207 int gen_transact(int sock, fmt, va_alist)
2208 int sock; /* socket to which server is connected */
2209 const char *fmt; /* printf-style format */
2212 /* assemble command in printf(3) style, send to server, accept a response */
2215 char buf [MSGBUFSIZE+1];
2217 int oldphase = phase; /* we don't have to be re-entrant */
2219 phase = SERVER_WAIT;
2221 if (protocol->tagged)
2222 (void) sprintf(buf, "%s ", GENSYM);
2226 #if defined(HAVE_STDARG_H)
2231 #ifdef HAVE_VSNPRINTF
2232 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2234 vsprintf(buf + strlen(buf), fmt, ap);
2238 strcat(buf, "\r\n");
2239 SockWrite(sock, buf, strlen(buf));
2241 if (outlevel >= O_MONITOR)
2245 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2249 sp = cp + strlen(shroud);
2255 buf[strlen(buf)-1] = '\0';
2256 error(0, 0, "%s> %s", protocol->name, buf);
2259 /* we presume this does its own response echoing */
2260 ok = (protocol->parse_response)(sock, buf);
2266 /* driver.c ends here */