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.
7 * i18n by Arnaldo Carvalho de Melo <acme@conectiva.com.br> 7-Nov-1998
18 #endif /* HAVE_MEMORY_H */
19 #if defined(STDC_HEADERS)
22 #if defined(HAVE_UNISTD_H)
25 #if defined(HAVE_STDARG_H)
30 #if defined(HAVE_SYS_ITIMER_H)
31 #include <sys/itimer.h>
36 #ifdef HAVE_RES_SEARCH
39 #endif /* HAVE_RES_SEARCH */
43 #include <kerberosIV/des.h>
44 #include <kerberosIV/krb.h>
46 #if defined (__bsdi__)
47 #include <des.h> /* order of includes matters */
49 #define krb_get_err_text(e) (krb_err_txt[e])
51 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__)
52 #define krb_get_err_text(e) (krb_err_txt[e])
58 #endif /* ! defined (__FreeBSD__) */
59 #endif /* ! defined (__bsdi__) */
60 #endif /* KERBEROS_V5 */
61 #include <netinet/in.h>
63 #endif /* KERBEROS_V4 */
67 #endif /* KERBEROS_V5 */
71 #include "fetchmail.h"
74 #ifndef strstr /* glibc-2.1 declares this as a macro */
75 extern char *strstr(); /* needed on sysV68 R3V7.1. */
78 int fetchlimit; /* how often to tear down the server connection */
79 int batchcount; /* count of messages sent in current batch */
80 flag peek_capable; /* can we peek for better error recovery? */
81 int pass; /* how many times have we re-polled? */
82 int phase; /* where are we, for error-logging purposes? */
84 static const struct method *protocol;
85 static jmp_buf restart;
89 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
91 static char shroud[PASSWORDLEN]; /* string to shroud in debug output */
92 static int mytimeout; /* value of nonreponse timeout */
93 static int timeoutcount; /* count consecutive timeouts */
94 static int msglen; /* actual message length */
96 void set_timeout(int timeleft)
97 /* reset the nonresponse-timeout */
100 struct itimerval ntimeout;
105 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
106 ntimeout.it_value.tv_sec = timeleft;
107 ntimeout.it_value.tv_usec = 0;
108 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
112 static void timeout_handler (int signal)
113 /* handle server-timeout SIGALRM signal */
119 static int accept_count, reject_count;
121 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
122 /* add given name to xmit_names if it matches declared localnames */
123 /* name: name to map */
124 /* ctl: list of permissible aliases */
125 /* xmit_names: list of recipient names parsed out */
130 lname = idpair_find(&ctl->localnames, name+off);
131 if (!lname && ctl->wildcard)
134 if (lname != (char *)NULL)
136 if (outlevel >= O_DEBUG)
137 error(0, 0, _("mapped %s to local %s"), name, lname);
138 save_str(xmit_names, lname, XMIT_ACCEPT);
143 void find_server_names(const char *hdr, struct query *ctl, 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]))
262 /* extract space-delimited token after "by" */
263 for (sp = ok + 2; isspace(*sp); sp++)
266 for (; !isspace(*sp); sp++)
270 /* look for embedded periods */
271 if (strchr(rbuf, '.'))
274 ok = sp - 1; /* arrange to skip this token */
280 * If it's a DNS name of the mail server, look for the
281 * recipient name after a following "for". Otherwise
284 if (is_host_alias(rbuf, ctl))
286 if (outlevel >= O_DEBUG)
288 _("line accepted, %s is an alias of the mailserver"), rbuf);
292 if (outlevel >= O_DEBUG)
294 _("line rejected, %s is not an alias of the mailserver"),
299 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
300 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
302 if (!(ok = strstr(base, "for")))
304 else if (!isspace(ok[-1]) || !isspace(ok[3]))
313 /* extract space-delimited token after "for" */
314 for (sp = ok + 3; isspace(*sp); sp++)
317 for (; !isspace(*sp); sp++)
321 if (strchr(rbuf, '@'))
324 ok = sp - 1; /* arrange to skip this token */
329 flag want_gt = FALSE;
332 /* char after "for" could be space or a continuation newline */
333 for (sp = ok + 4; isspace(*sp); sp++)
336 *tp++ = ':'; /* Here is the hack. This is to be friends */
337 *tp++ = ' '; /* with nxtaddr()... */
343 while (*sp == '@') /* skip routes */
344 while (*sp && *sp++ != ':')
347 && (want_gt ? (*sp != '>') : !isspace(*sp))
353 /* uh oh -- whitespace here can't be right! */
359 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
367 if (outlevel >= O_DEBUG)
368 error(0, 0, _("no Received address found"));
373 if (outlevel >= O_DEBUG) {
374 char *lf = rbuf + strlen(rbuf)-1;
376 if (outlevel >= O_DEBUG)
377 error(0, 0, _("found Received address `%s'"), rbuf+2);
384 /* shared by readheaders and readbody */
385 static int sizeticker;
386 static struct msgblk msgblk;
388 #define EMPTYLINE(s) ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
390 static int readheaders(int sock, long fetchlen, long reallen, struct query *ctl, int num)
391 /* read message headers and ship to SMTP or MDA */
392 /* sock: to which the server is connected */
393 /* fetchlen: length of message according to fetch response */
394 /* reallen: length of message according to getsizes */
395 /* ctl: query control record */
396 /* num: index of message */
401 struct addrblk *next;
403 struct addrblk *to_addrchain = NULL;
404 struct addrblk **to_chainptr = &to_addrchain;
405 struct addrblk *resent_to_addrchain = NULL;
406 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
408 char buf[MSGBUFSIZE+1];
409 int from_offs, reply_to_offs, resent_from_offs;
410 int app_from_offs, sender_offs, resent_sender_offs;
412 char *received_for, *rcv, *cp;
413 int n, linelen, oldlen, ch, remaining, skipcount;
415 flag no_local_matches = FALSE;
416 flag headers_ok, has_nuls;
417 int olderrs, good_addresses, bad_addresses;
420 has_nuls = headers_ok = FALSE;
421 msgblk.return_path[0] = '\0';
422 olderrs = ctl->errcount;
424 /* read message headers */
425 msgblk.reallen = reallen;
426 msgblk.headers = received_for = NULL;
427 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
428 sender_offs = resent_sender_offs = env_offs = -1;
434 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
438 line = xmalloc(sizeof(buf));
442 set_timeout(mytimeout);
443 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
446 free(msgblk.headers);
453 /* lines may not be properly CRLF terminated; fix this for qmail */
456 cp = buf + strlen(buf) - 1;
457 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
466 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
470 /* check for end of headers */
474 has_nuls = (linelen != strlen(line));
476 goto process_headers;
480 * Check for end of message immediately. If one of your folders
481 * has been mangled, the delimiter may occur directly after the
484 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
487 has_nuls = (linelen != strlen(line));
488 goto process_headers;
491 /* check for RFC822 continuations */
492 set_timeout(mytimeout);
496 (ch == ' ' || ch == '\t'); /* continuation to next line? */
498 /* write the message size dots */
499 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
501 sizeticker += linelen;
502 while (sizeticker >= SIZETICKER)
505 sizeticker -= SIZETICKER;
509 /* we see an ordinary (non-header, non-message-delimiter line */
510 has_nuls = (linelen != strlen(line));
513 * The University of Washington IMAP server (the reference
514 * implementation of IMAP4 written by Mark Crispin) relies
515 * on being able to keep base-UID information in a special
516 * message at the head of the mailbox. This message should
517 * neither be deleted nor forwarded.
521 * We disable this check under POP2 because there's no way to
522 * prevent deletion of the message. So at least we ought to
523 * forward it to the user so he or she will have some clue
524 * that things have gone awry.
526 if (protocol->port != 109)
527 #endif /* POP2_ENABLE */
528 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
530 free(msgblk.headers);
535 * This code prevents fetchmail from becoming an accessory after
536 * the fact to upstream sendmails with the `E' option on. It also
537 * copes with certain brain-dead POP servers (like NT's) that pass
538 * through Unix from_ lines.
540 * Either of these bugs can result in a non-RFC822 line at the
541 * beginning of the headers. If fetchmail just passes it
542 * through, the client listener may think the message has *no*
543 * headers (since the first) line it sees doesn't look
544 * RFC822-conformant) and fake up a set.
546 * What the user would see in this case is bogus (synthesized)
547 * headers, followed by a blank line, followed by the >From,
548 * followed by the real headers, followed by a blank line,
551 * We forestall this lossage by tossing anything that looks
552 * like an escaped or passed-through From_ line in headers.
553 * These aren't RFC822 so our conscience is clear...
555 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
562 * If we see a Status line, it may have been inserted by an MUA
563 * on the mail host, or it may have been inserted by the server
564 * program after the headers in the transaction stream. This
565 * can actually hose some new-mail notifiers such as xbuffy,
566 * which assumes any Status line came from a *local* MDA and
567 * therefore indicates that the message has been seen.
569 * Some buggy POP servers (including at least the 3.3(20)
570 * version of the one distributed with IMAP) insert empty
571 * Status lines in the transaction stream; we'll chuck those
572 * unconditionally. Nonempty ones get chucked if the user
573 * turns on the dropstatus flag.
578 if (!strncasecmp(line, "Status:", 7))
580 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
585 while (*cp && isspace(*cp)) cp++;
586 if (!*cp || ctl->dropstatus)
595 line = reply_hack(line, ctl->server.truename);
598 * OK, this is messy. If we're forwarding by SMTP, it's the
599 * SMTP-receiver's job (according to RFC821, page 22, section
600 * 4.1.1) to generate a Return-Path line on final delivery.
601 * The trouble is, we've already got one because the
602 * mailserver's SMTP thought *it* was responsible for final
605 * Stash away the contents of Return-Path (as modified by reply_hack)
606 * for use in generating MAIL FROM later on, then prevent the header
607 * from being saved with the others. In effect, we strip it off here.
609 * If the SMTP server conforms to the standards, and fetchmail gets the
610 * envelope sender from the Return-Path, the new Return-Path should be
611 * exactly the same as the original one.
613 * We do *not* want to ignore empty Return-Path headers. These should
614 * be passed through as a way of indicating that a message should
615 * not trigger bounces if delivery fails. What we *do* need to do is
616 * make sure we never try to rewrite such a blank Return-Path. We
617 * handle this with a check for <> in the rewrite logic above.
619 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
621 strcpy(msgblk.return_path, cp);
630 oldlen = strlen(line);
631 msgblk.headers = xmalloc(oldlen + 1);
632 (void) strcpy(msgblk.headers, line);
634 line = msgblk.headers;
640 newlen = oldlen + strlen(line);
641 msgblk.headers = (char *) realloc(msgblk.headers, newlen + 1);
642 if (msgblk.headers == NULL) {
646 strcpy(msgblk.headers + oldlen, line);
648 line = msgblk.headers + oldlen;
652 if (!strncasecmp("From:", line, 5))
653 from_offs = (line - msgblk.headers);
654 else if (!strncasecmp("Reply-To:", line, 9))
655 reply_to_offs = (line - msgblk.headers);
656 else if (!strncasecmp("Resent-From:", line, 12))
657 resent_from_offs = (line - msgblk.headers);
658 else if (!strncasecmp("Apparently-From:", line, 16))
659 app_from_offs = (line - msgblk.headers);
660 else if (!strncasecmp("Sender:", line, 7))
661 sender_offs = (line - msgblk.headers);
662 else if (!strncasecmp("Resent-Sender:", line, 14))
663 resent_sender_offs = (line - msgblk.headers);
665 else if (!strncasecmp("Message-Id:", buf, 11))
667 if (ctl->server.uidl)
671 buf[IDLEN+12] = 0; /* prevent stack overflow */
672 sscanf(buf+12, "%s", id);
673 if (!str_find( &ctl->newsaved, num))
675 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
676 new->val.status.num = num;
681 else if (!MULTIDROP(ctl))
684 else if (!strncasecmp("To:", line, 3)
685 || !strncasecmp("Cc:", line, 3)
686 || !strncasecmp("Bcc:", line, 4)
687 || !strncasecmp("Apparently-To:", line, 14))
689 *to_chainptr = xmalloc(sizeof(struct addrblk));
690 (*to_chainptr)->offset = (line - msgblk.headers);
691 to_chainptr = &(*to_chainptr)->next;
695 else if (!strncasecmp("Resent-To:", line, 10)
696 || !strncasecmp("Resent-Cc:", line, 10)
697 || !strncasecmp("Resent-Bcc:", line, 11))
699 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
700 (*resent_to_chainptr)->offset = (line - msgblk.headers);
701 resent_to_chainptr = &(*resent_to_chainptr)->next;
702 *resent_to_chainptr = NULL;
705 else if (ctl->server.envelope != STRING_DISABLED)
707 if (ctl->server.envelope
708 && strcasecmp(ctl->server.envelope, "Received"))
710 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
712 strlen(ctl->server.envelope)))
714 if (skipcount++ != ctl->server.envskip)
716 env_offs = (line - msgblk.headers);
719 else if (!received_for && !strncasecmp("Received:", line, 9))
721 if (skipcount++ != ctl->server.envskip)
723 received_for = parse_received(ctl, line);
730 * We want to detect this early in case there are so few headers that the
731 * dispatch logic barfs.
735 if (outlevel > O_SILENT)
736 error(0,0,_("message delimiter found while scanning headers"));
740 * Hack time. If the first line of the message was blank, with no headers
741 * (this happens occasionally due to bad gatewaying software) cons up
742 * a set of fake headers.
744 * If you modify the fake header template below, be sure you don't
745 * make either From or To address @-less, otherwise the reply_hack
746 * logic will do bad things.
748 if (msgblk.headers == (char *)NULL)
751 snprintf(buf, sizeof(buf),
754 #endif /* HAVE_SNPRINTF */
755 "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
756 user, fetchmailhost, ctl->remotename, ctl->server.truename);
757 msgblk.headers = xstrdup(buf);
761 * We can now process message headers before reading the text.
762 * In fact we have to, as this will tell us where to forward to.
765 /* Decode MIME encoded headers. We MUST do this before
766 * looking at the Content-Type / Content-Transfer-Encoding
767 * headers (RFC 2046).
769 if (ctl->mimedecode) {
770 UnMimeHeader(msgblk.headers);
772 /* Check for MIME headers indicating possible 8-bit data */
773 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
776 * If there is a Return-Path address on the message, this was
777 * almost certainly the MAIL FROM address given the originating
778 * sendmail. This is the best thing to use for logging the
779 * message origin (it sets up the right behavior for bounces and
780 * mailing lists). Otherwise, fall down to the next available
781 * envelope address (which is the most probable real sender).
782 * *** The order is important! ***
783 * This is especially useful when receiving mailing list
784 * messages in multidrop mode. if a local address doesn't
785 * exist, the bounce message won't be returned blindly to the
786 * author or to the list itself but rather to the list manager
787 * (ex: specified by "Sender:") which is much less annoying. This
788 * is true for most mailing list packages.
790 if( !msgblk.return_path[0] ){
792 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
793 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
794 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
795 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
796 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
797 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
798 if (ap) strcpy( msgblk.return_path, ap );
801 /* cons up a list of local recipients */
802 msgblk.recipients = (struct idlist *)NULL;
803 accept_count = reject_count = 0;
804 /* is this a multidrop box? */
807 if (env_offs > -1) /* We have the actual envelope addressee */
808 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
809 else if (received_for)
811 * We have the Received for addressee.
812 * It has to be a mailserver address, or we
813 * wouldn't have got here.
814 * We use find_server_names() to let local
815 * hostnames go through.
817 find_server_names(received_for, ctl, &msgblk.recipients);
821 find_server_names(sdps_envto, ctl, &msgblk.recipients);
824 #endif /* SDPS_ENABLE */
828 * We haven't extracted the envelope address.
829 * So check all the "Resent-To" header addresses if
830 * they exist. If and only if they don't, consider
833 register struct addrblk *nextptr;
834 if (resent_to_addrchain) {
835 /* delete the "To" chain and substitute it
836 * with the "Resent-To" list
838 while (to_addrchain) {
839 nextptr = to_addrchain->next;
841 to_addrchain = nextptr;
843 to_addrchain = resent_to_addrchain;
844 resent_to_addrchain = NULL;
846 /* now look for remaining adresses */
847 while (to_addrchain) {
848 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
849 nextptr = to_addrchain->next;
851 to_addrchain = nextptr;
856 no_local_matches = TRUE;
857 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
858 if (outlevel >= O_DEBUG)
860 _("no local matches, forwarding to %s"),
864 else /* it's a single-drop box, use first localname */
865 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
869 * Time to either address the message or decide we can't deliver it yet.
871 if (ctl->errcount > olderrs) /* there were DNS errors above */
873 if (outlevel >= O_DEBUG)
874 error(0,0, _("forwarding and deletion suppressed due to DNS errors"));
875 free(msgblk.headers);
876 free_str_list(&msgblk.recipients);
877 return(PS_TRANSIENT);
881 /* set up stuffline() so we can deliver the message body through it */
882 if ((n = open_sink(ctl, &msgblk,
883 &good_addresses, &bad_addresses)) != PS_SUCCESS)
885 free(msgblk.headers);
886 free_str_list(&msgblk.recipients);
893 * Some server/sendmail combinations cause problems when our
894 * synthetic Received line is before the From header. Cope
897 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
898 rcv = msgblk.headers;
899 /* handle ">Received:" lines too */
900 while (rcv > msgblk.headers && rcv[-1] != '\n')
902 if (rcv > msgblk.headers)
907 n = stuffline(ctl, msgblk.headers);
910 if (!run.invisible && n != -1)
912 /* utter any per-message Received information we need here */
913 sprintf(buf, "Received: from %s\r\n", ctl->server.truename);
914 n = stuffline(ctl, buf);
918 * This header is technically invalid under RFC822.
919 * POP3, IMAP, etc. are not legal mail-parameter values.
921 * We used to include ctl->remotename in this log line,
922 * but this can be secure information that would be bad
925 sprintf(buf, "\tby %s with %s (fetchmail-%s)\r\n",
929 n = stuffline(ctl, buf);
933 if (good_addresses == 0)
936 "for %s@%s (by default); ",
937 user, ctl->destaddr);
939 else if (good_addresses == 1)
941 for (idp = msgblk.recipients; idp; idp = idp->next)
942 if (idp->val.status.mark == XMIT_ACCEPT)
943 break; /* only report first address */
944 if (strchr(idp->id, '@'))
945 sprintf(buf+1, "for %s", idp->id);
948 * This could be a bit misleading, as destaddr is
949 * the forwarding host rather than the actual
950 * destination. Most of the time they coincide.
952 sprintf(buf+1, "for %s@%s", idp->id, ctl->destaddr);
953 sprintf(buf+strlen(buf), " (%s); ",
954 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
959 strcat(buf, rfc822timestamp());
961 n = stuffline(ctl, buf);
967 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
971 error(0, errno, _("writing RFC822 msgblk.headers"));
973 free(msgblk.headers);
974 free_str_list(&msgblk.recipients);
977 else if (!run.use_syslog && outlevel >= O_VERBOSE)
980 /* write error notifications */
981 if (no_local_matches || has_nuls || bad_addresses)
984 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
987 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
988 if (no_local_matches)
990 if (reject_count != 1)
991 strcat(errhd, _("no recipient addresses matched declared local names"));
994 for (idp = msgblk.recipients; idp; idp = idp->next)
995 if (idp->val.status.mark == XMIT_REJECT)
997 sprintf(errhd+strlen(errhd), _("recipient address %s didn't match any local name"), idp->id);
1003 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1004 strcat(errhd, "; ");
1005 strcat(errhd, _("message has embedded NULs"));
1010 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1011 strcat(errhd, "; ");
1012 strcat(errhd, _("SMTP listener rejected local recipient addresses: "));
1013 errlen = strlen(errhd);
1014 for (idp = msgblk.recipients; idp; idp = idp->next)
1015 if (idp->val.status.mark == XMIT_ANTISPAM)
1016 errlen += strlen(idp->id) + 2;
1018 xalloca(errmsg, char *, errlen+3);
1019 (void) strcpy(errmsg, errhd);
1020 for (idp = msgblk.recipients; idp; idp = idp->next)
1021 if (idp->val.status.mark == XMIT_ANTISPAM)
1023 strcat(errmsg, idp->id);
1025 strcat(errmsg, ", ");
1030 strcat(errmsg, "\r\n");
1032 /* ship out the error line */
1033 stuffline(ctl, errmsg);
1036 /* issue the delimiter line */
1041 stuffline(ctl, buf);
1043 free(msgblk.headers);
1044 free_str_list(&msgblk.recipients);
1045 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1048 static int readbody(int sock, struct query *ctl, flag forward, int len)
1049 /* read and dispose of a message body presented on sock */
1050 /* ctl: query control record */
1051 /* sock: to which the server is connected */
1052 /* len: length of message */
1053 /* forward: TRUE to forward */
1056 unsigned char buf[MSGBUFSIZE+4];
1057 unsigned char *inbufp = buf;
1058 flag issoftline = FALSE;
1060 /* pass through the text lines */
1061 while (protocol->delimited || len > 0)
1063 set_timeout(mytimeout);
1064 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1072 /* write the message size dots */
1075 sizeticker += linelen;
1076 while (sizeticker >= SIZETICKER)
1078 if (!run.use_syslog && outlevel > O_SILENT)
1080 sizeticker -= SIZETICKER;
1085 /* check for end of message */
1086 if (protocol->delimited && *inbufp == '.')
1087 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1089 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1092 msglen--; /* subtract the size of the dot escape */
1096 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1097 issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1098 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1101 * Soft linebreak, but less than 200 bytes left in
1102 * input buffer. Rather than doing a buffer overrun,
1103 * ignore the soft linebreak, NL-terminate data and
1104 * deliver what we have now.
1105 * (Who writes lines longer than 2K anyway?)
1107 *inbufp = '\n'; *(inbufp+1) = '\0';
1112 /* ship out the text line */
1113 if (forward && (!issoftline))
1118 /* guard against very long lines */
1119 buf[MSGBUFSIZE+1] = '\r';
1120 buf[MSGBUFSIZE+2] = '\n';
1121 buf[MSGBUFSIZE+3] = '\0';
1123 n = stuffline(ctl, buf);
1127 error(0, errno, _("writing message text"));
1131 else if (outlevel >= O_VERBOSE)
1141 kerberos_auth (socket, canonical)
1142 /* authenticate to the server host using Kerberos V4 */
1143 int socket; /* socket to server host */
1145 char *canonical; /* server name */
1147 const char *canonical; /* server name */
1150 char * host_primary;
1154 Key_schedule schedule;
1157 xalloca(ticket, KTEXT, sizeof (KTEXT_ST));
1158 rem = (krb_sendauth (0L, socket, ticket, "pop",
1160 ((char *) (krb_realmofhost (canonical))),
1161 ((unsigned long) 0),
1165 ((struct sockaddr_in *) 0),
1166 ((struct sockaddr_in *) 0),
1168 if (rem != KSUCCESS)
1170 error(0, -1, _("kerberos error %s"), (krb_get_err_text (rem)));
1171 return (PS_AUTHFAIL);
1175 #endif /* KERBEROS_V4 */
1179 kerberos5_auth(socket, canonical)
1180 /* authenticate to the server host using Kerberos V5 */
1181 int socket; /* socket to server host */
1182 const char *canonical; /* server name */
1184 krb5_error_code retval;
1185 krb5_context context;
1187 krb5_principal client = NULL, server = NULL;
1188 krb5_error *err_ret = NULL;
1190 krb5_auth_context auth_context = NULL;
1192 krb5_init_context(&context);
1193 krb5_init_ets(context);
1194 krb5_auth_con_init(context, &auth_context);
1196 if (retval = krb5_cc_default(context, &ccdef)) {
1197 error(0, 0, "krb5_cc_default: %s", error_message(retval));
1201 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1202 error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1206 if (retval = krb5_sname_to_principal(context, canonical, "pop",
1209 error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1213 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1214 "KPOPV1.0", client, server,
1215 AP_OPTS_MUTUAL_REQUIRED,
1216 NULL, /* no data to checksum */
1217 0, /* no creds, use ccache instead */
1221 NULL); /* don't need reply */
1223 krb5_free_principal(context, server);
1224 krb5_free_principal(context, client);
1225 krb5_auth_con_free(context, auth_context);
1228 if (err_ret && err_ret->text.length) {
1229 error(0, 0, _("krb5_sendauth: %s [server says '%*s'] "),
1230 error_message(retval),
1231 err_ret->text.length,
1232 err_ret->text.data);
1233 krb5_free_error(context, err_ret);
1235 error(0, 0, "krb5_sendauth: %s", error_message(retval));
1241 #endif /* KERBEROS_V5 */
1243 static void clean_skipped_list(struct idlist **skipped_list)
1244 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
1246 struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
1247 prev = current = head = *skipped_list;
1253 /* if item has no reference, remove it */
1254 if (current && current->val.status.mark == 0)
1256 if (current == head) /* remove first item (head) */
1258 head = current->next;
1259 if (current->id) free(current->id);
1261 prev = current = head;
1263 else /* remove middle/last item */
1265 tmp = current->next;
1267 if (current->id) free(current->id);
1272 else /* skip this item */
1275 current = current->next;
1279 *skipped_list = head;
1282 static void send_size_warnings(struct query *ctl)
1283 /* send warning mail with skipped msg; reset msg count when user notified */
1286 int msg_to_send = FALSE;
1287 struct idlist *head=NULL, *current=NULL;
1288 int max_warning_poll_count, good, bad;
1289 #define OVERHD "Subject: Fetchmail oversized-messages warning.\r\n\r\nThe following oversized messages remain on the mail server:"
1291 head = ctl->skipped;
1295 /* don't start a notification message unless we need to */
1296 for (current = head; current; current = current->next)
1297 if (current->val.status.num == 0 && current->val.status.mark)
1303 * There's no good way to recover if we can't send notification mail,
1304 * but it's not a disaster, either, since the skipped mail will not
1307 if (open_warning_by_mail(ctl, (struct msgblk *)NULL))
1309 stuff_warning(ctl, OVERHD);
1311 if (run.poll_interval == 0)
1312 max_warning_poll_count = 0;
1314 max_warning_poll_count = ctl->warnings/run.poll_interval;
1316 /* parse list of skipped msg, adding items to the mail */
1317 for (current = head; current; current = current->next)
1319 if (current->val.status.num == 0 && current->val.status.mark)
1321 nbr = current->val.status.mark;
1322 size = atoi(current->id);
1324 _("\t%d msg %d octets long skipped by fetchmail."),
1327 current->val.status.num++;
1328 current->val.status.mark = 0;
1330 if (current->val.status.num >= max_warning_poll_count)
1331 current->val.status.num = 0;
1334 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1338 int do_protocol(ctl, proto)
1339 /* retrieve messages from server using given protocol method table */
1340 struct query *ctl; /* parsed options with merged-in defaults */
1341 const struct method *proto; /* protocol method table */
1344 #ifdef HAVE_VOLATILE
1345 volatile int sock = -1; /* pacifies -Wall */
1348 #endif /* HAVE_VOLATILE */
1350 void (*sigsave)(int);
1351 struct idlist *current=NULL, *tmp=NULL;
1354 ctl->server.base_protocol = protocol;
1357 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1359 error(0, -1, _("Kerberos V4 support not linked."));
1362 #endif /* KERBEROS_V4 */
1365 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1367 error(0, -1, _("Kerberos V5 support not linked."));
1370 #endif /* KERBEROS_V5 */
1372 /* lacking methods, there are some options that may fail */
1375 /* check for unsupported options */
1378 _("Option --flush is not supported with %s"),
1382 else if (ctl->fetchall) {
1384 _("Option --all is not supported with %s"),
1389 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1392 _("Option --limit is not supported with %s"),
1399 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1402 /* set up the server-nonresponse timeout */
1403 sigsave = signal(SIGALRM, timeout_handler);
1404 mytimeout = ctl->server.timeout;
1406 if ((js = setjmp(restart)) == 1)
1408 if (phase == OPEN_WAIT)
1410 _("timeout after %d seconds waiting to connect to server %s."),
1411 ctl->server.timeout, ctl->server.pollname);
1412 else if (phase == SERVER_WAIT)
1414 _("timeout after %d seconds waiting for server %s."),
1415 ctl->server.timeout, ctl->server.pollname);
1416 else if (phase == FORWARDING_WAIT)
1418 _("timeout after %d seconds waiting for %s."),
1419 ctl->server.timeout,
1420 ctl->mda ? "MDA" : "SMTP");
1421 else if (phase == LISTENER_WAIT)
1423 _("timeout after %d seconds waiting for listener to respond."));
1425 error(0, 0, _("timeout after %d seconds."), ctl->server.timeout);
1428 if (ctl->smtp_socket != -1)
1429 close(ctl->smtp_socket);
1434 * If we've exceeded our threshold for consecutive timeouts,
1435 * try to notify the user, then mark the connection wedged.
1437 if (timeoutcount > MAX_TIMEOUTS
1438 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1441 _("Subject: fetchmail sees repeated timeouts\r\n"));
1443 _("Fetchmail saw more than %d timouts while attempting to get mail from %s@%s."),
1446 ctl->server.truename);
1448 _("This could mean that your mailserver is stuck, or that your SMTP listener"));
1450 _("is wedged, or that your mailbox file on the server has been corrupted by"));
1452 _("a server error. You can run `fetchmail -v -v' to diagnose the problem."));
1454 _("Fetchmail won't poll this mailbox again until you restart it."));
1455 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1463 char buf[POPBUFSIZE+1], *realhost;
1464 int len, num, count, new, bytes, deletions = 0, *msgsizes = NULL;
1466 int fetches, dispatches;
1468 int port, fetches, dispatches, oldphase;
1472 /* execute pre-initialization command, if any */
1473 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1475 sprintf(buf, _("pre-connection command failed with status %d"), ok);
1481 /* open a socket to the mail server */
1484 set_timeout(mytimeout);
1486 port = ctl->server.port ? ctl->server.port : protocol->port;
1488 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1490 if ((sock = SockOpen(realhost,
1491 ctl->server.service ? ctl->server.service : protocol->service,
1492 ctl->server.netsec)) == -1, ctl->server.plugin
1495 if ((sock = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
1500 #ifdef HAVE_RES_SEARCH
1501 if (err_no != 0 && h_errno != 0)
1502 error(0, 0, _("fetchmail: internal inconsistency"));
1505 * Avoid generating a bogus error every poll cycle when we're
1506 * in daemon mode but the connection to the outside world
1509 if (err_no == EHOSTUNREACH && run.poll_interval)
1512 error_build(_("fetchmail: %s connection to %s failed"),
1513 protocol->name, ctl->server.pollname);
1514 #ifdef HAVE_RES_SEARCH
1517 if (h_errno == HOST_NOT_FOUND)
1518 error_complete(0, 0, _(": host is unknown"));
1519 else if (h_errno == NO_ADDRESS)
1520 error_complete(0, 0, _(": name is valid but has no IP address"));
1521 else if (h_errno == NO_RECOVERY)
1522 error_complete(0, 0, _(": unrecoverable name server error"));
1523 else if (h_errno == TRY_AGAIN)
1524 error_complete(0, 0, _(": temporary name server error"));
1526 error_complete(0, 0, _(": unknown DNS error %d"), h_errno);
1529 #endif /* HAVE_RES_SEARCH */
1531 error_complete(0, err_no, "");
1544 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1546 set_timeout(mytimeout);
1547 ok = kerberos_auth(sock, ctl->server.truename);
1552 #endif /* KERBEROS_V4 */
1555 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1557 set_timeout(mytimeout);
1558 ok = kerberos5_auth(sock, ctl->server.truename);
1563 #endif /* KERBEROS_V5 */
1565 /* accept greeting message from mail server */
1566 ok = (protocol->parse_response)(sock, buf);
1570 /* try to get authorized to fetch mail */
1571 if (protocol->getauth)
1573 if (protocol->password_canonify)
1574 (protocol->password_canonify)(shroud, ctl->password);
1576 strcpy(shroud, ctl->password);
1578 ok = (protocol->getauth)(sock, ctl, buf);
1581 if (ok == PS_LOCKBUSY)
1582 error(0, -1, _("Lock-busy error on %s@%s"),
1584 ctl->server.truename);
1589 error(0, -1, _("Authorization failure on %s@%s"),
1591 ctl->server.truename);
1594 * If we're running in background, try to mail the
1595 * calling user a heads-up about the authentication
1596 * failure the first time it happens.
1598 if (run.poll_interval
1600 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1603 _("Subject: fetchmail authentication failed\r\n"));
1605 _("Fetchmail could not get mail from %s@%s."),
1607 ctl->server.truename);
1609 _("The attempt to get authorization failed."));
1611 _("This probably means your password is invalid."));
1612 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1620 ctl->errcount = fetches = 0;
1622 /* now iterate over each folder selected */
1623 for (idp = ctl->mailboxes; idp; idp = idp->next)
1630 if (outlevel >= O_DEBUG)
1632 error(0, 0, _("selecting or re-polling folder %s"), idp->id);
1634 error(0, 0, _("selecting or re-polling default folder"));
1636 /* compute # of messages and number of new messages waiting */
1637 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
1642 * We need the size of each message before it's
1643 * loaded in order to pass via the ESMTP SIZE
1644 * option. If the protocol has a getsizes method,
1645 * we presume this means it doesn't get reliable
1646 * sizes from message fetch responses.
1648 if (count > 0 && proto->getsizes)
1652 xalloca(msgsizes, int *, sizeof(int) * count);
1653 for (i = 0; i < count; i++)
1656 ok = (proto->getsizes)(sock, count, msgsizes);
1663 for (i = 0; i < count; i++)
1664 bytes += msgsizes[i];
1668 /* show user how many messages we downloaded */
1670 (void) sprintf(buf, _("%s at %s (folder %s)"),
1671 ctl->remotename, ctl->server.truename, idp->id);
1673 (void) sprintf(buf, _("%s at %s"),
1674 ctl->remotename, ctl->server.truename);
1675 if (outlevel > O_SILENT)
1676 if (count == -1) /* only used for ETRN */
1677 error(0, 0, _("Polling %s"), ctl->server.truename);
1678 else if (count != 0)
1680 if (new != -1 && (count - new) > 0)
1681 error_build(_("%d %s (%d seen) for %s"),
1682 count, count > 1 ? _("messages") :
1686 error_build(_("%d %s for %s"),
1687 count, count > 1 ? _("messages") :
1690 error_complete(0, 0, ".");
1692 error_complete(0, 0, _(" (%d octets)."), bytes);
1696 /* these are pointless in normal daemon mode */
1697 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1698 error(0, 0, _("No mail for %s"), buf);
1701 /* very important, this is where we leave the do loop */
1707 if (new == -1 || ctl->fetchall)
1709 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1714 flag force_retrieval;
1717 * What forces this code is that in POP2 and
1718 * IMAP2bis you can't fetch a message without
1719 * having it marked `seen'. In POP3 and IMAP4, on the
1720 * other hand, you can (peek_capable is set by
1721 * each driver module to convey this; it's not a
1722 * method constant because of the difference between
1723 * IMAP2bis and IMAP4, and because POP3 doesn't peek
1724 * if fetchall is on).
1726 * The result of being unable to peek is that if there's
1727 * any kind of transient error (DNS lookup failure, or
1728 * sendmail refusing delivery due to process-table limits)
1729 * the message will be marked "seen" on the server without
1730 * having been delivered. This is not a big problem if
1731 * fetchmail is running in foreground, because the user
1732 * will see a "skipped" message when it next runs and get
1735 * But in daemon mode this leads to the message
1736 * being silently ignored forever. This is not
1739 * We compensate for this by checking the error
1740 * count from the previous pass and forcing all
1741 * messages to be considered new if it's nonzero.
1743 force_retrieval = !peek_capable && (ctl->errcount > 0);
1745 /* read, forward, and delete messages */
1746 for (num = 1; num <= count; num++)
1748 flag toolarge = NUM_NONZERO(ctl->limit)
1749 && msgsizes && (msgsizes[num-1] > ctl->limit);
1750 flag oldmsg = (protocol->is_old && (protocol->is_old)(sock,ctl,num));
1751 flag fetch_it = !toolarge
1752 && (ctl->fetchall || force_retrieval || !oldmsg);
1753 flag suppress_delete = FALSE;
1754 flag suppress_forward = FALSE;
1755 flag suppress_readbody = FALSE;
1756 flag retained = FALSE;
1759 * This check copes with Post Office/NT's
1760 * annoying habit of randomly prepending bogus
1761 * LIST items of length -1. Patrick Audley
1762 * <paudley@pobox.com> tells us: LIST shows a
1763 * size of -1, RETR and TOP return "-ERR
1764 * System error - couldn't open message", and
1765 * DELE succeeds but doesn't actually delete
1768 if (msgsizes && msgsizes[num-1] == -1)
1770 if (outlevel >= O_VERBOSE)
1772 _("Skipping message %d, length -1"),
1777 /* we may want to reject this message if it's old */
1780 if (outlevel > O_SILENT)
1782 error_build(_("skipping message %d"), num);
1783 if (toolarge && !check_only)
1788 /* convert sz to string */
1789 sprintf(size, "%d", msgsizes[num-1]);
1791 /* build a list of skipped messages
1792 * val.id = size of msg (string cnvt)
1793 * val.status.num = warning_poll_count
1794 * val.status.mask = nbr of msg this size
1797 current = ctl->skipped;
1799 /* initialise warning_poll_count to the
1800 * current value so that all new msg will
1801 * be included in the next mail
1803 cnt = current? current->val.status.num : 0;
1805 /* if entry exists, increment the count */
1807 str_in_list(¤t, size, FALSE))
1810 current = current->next)
1812 if (strcmp(current->id, size) == 0)
1814 current->val.status.mark++;
1819 /* otherwise, create a new entry */
1820 /* initialise with current poll count */
1823 tmp = save_str(&ctl->skipped, size, 1);
1824 tmp->val.status.num = cnt;
1827 error_build(_(" (oversized, %d octets)"),
1834 flag wholesize = !protocol->fetch_body;
1836 /* request a message */
1837 ok = (protocol->fetch_headers)(sock,ctl,num, &len);
1841 /* -1 means we didn't see a size in the response */
1842 if (len == -1 && msgsizes)
1844 len = msgsizes[num - 1];
1848 if (outlevel > O_SILENT)
1850 error_build(_("reading message %d of %d"),
1854 error_build(_(" (%d %soctets)"),
1855 len, wholesize ? "" : _("header "));
1856 if (outlevel >= O_VERBOSE)
1857 error_complete(0, 0, "");
1863 * Read the message headers and ship them to the
1866 ok = readheaders(sock, len, msgsizes[num-1],
1868 if (ok == PS_RETAINED)
1869 suppress_forward = retained = TRUE;
1870 else if (ok == PS_TRANSIENT)
1871 suppress_delete = suppress_forward = TRUE;
1872 else if (ok == PS_REFUSED)
1873 suppress_forward = TRUE;
1874 else if (ok == PS_TRUNCATED)
1875 suppress_readbody = TRUE;
1880 * If we're using IMAP4 or something else that
1881 * can fetch headers separately from bodies,
1882 * it's time to request the body now. This
1883 * fetch may be skipped if we got an anti-spam
1884 * or other PS_REFUSED error response during
1887 if (protocol->fetch_body && !suppress_readbody)
1889 if (outlevel >= O_VERBOSE)
1890 fputc('\n', stderr);
1892 if ((ok = (protocol->trail)(sock, ctl, num)))
1895 if (!suppress_forward)
1897 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1899 if (outlevel > O_SILENT && !wholesize)
1900 error_build(_(" (%d body octets) "), len);
1904 /* process the body now */
1907 if (suppress_readbody)
1909 /* When readheaders returns PS_TRUNCATED,
1910 the body (which has no content
1911 has already been read by readheaders,
1912 so we say readbody returned PS_SUCCESS */
1922 if (ok == PS_TRANSIENT)
1923 suppress_delete = suppress_forward = TRUE;
1927 /* tell server we got it OK and resynchronize */
1928 if (protocol->trail)
1930 if (outlevel >= O_VERBOSE)
1931 fputc('\n', stderr);
1933 ok = (protocol->trail)(sock, ctl, num);
1939 /* count # messages forwarded on this pass */
1940 if (!suppress_forward)
1944 * Check to see if the numbers matched?
1946 * Yes, some servers foo this up horribly.
1947 * All IMAP servers seem to get it right, and
1948 * so does Eudora QPOP at least in 2.xx
1951 * Microsoft Exchange gets it completely
1952 * wrong, reporting compressed rather than
1953 * actual sizes (so the actual length of
1954 * message is longer than the reported size).
1955 * Another fine example of Microsoft brain death!
1957 * Some older POP servers, like the old UCB
1958 * POP server and the pre-QPOP QUALCOMM
1959 * versions, report a longer size in the LIST
1960 * response than actually gets shipped up.
1961 * It's unclear what is going on here, as the
1962 * QUALCOMM server (at least) seems to be
1963 * reporting the on-disk size correctly.
1965 if (msgsizes && msglen != msgsizes[num-1])
1967 if (outlevel >= O_DEBUG)
1969 _("message %d was not the expected length (%d actual != %d expected)"),
1970 num, msglen, msgsizes[num-1]);
1973 /* end-of-message processing starts here */
1974 if (!close_sink(ctl, &msgblk, !suppress_forward))
1977 suppress_delete = TRUE;
1983 * At this point in flow of control, either
1984 * we've bombed on a protocol error or had
1985 * delivery refused by the SMTP server
1986 * (unlikely -- I've never seen it) or we've
1987 * seen `accepted for delivery' and the
1988 * message is shipped. It's safe to mark the
1989 * message seen and delete it on the server
1993 /* tell the UID code we've seen this */
1998 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
1999 if (sdp->val.status.num == num)
2000 sdp->val.status.mark = UID_SEEN;
2003 /* maybe we delete this message now? */
2006 if (outlevel > O_SILENT)
2007 error_complete(0, 0, _(" retained"));
2009 else if (protocol->delete
2011 && (fetch_it ? !ctl->keep : ctl->flush))
2014 if (outlevel > O_SILENT)
2015 error_complete(0, 0, _(" flushed"));
2016 ok = (protocol->delete)(sock, ctl, num);
2020 delete_str(&ctl->newsaved, num);
2021 #endif /* POP3_ENABLE */
2023 else if (outlevel > O_SILENT)
2024 error_complete(0, 0, _(" not flushed"));
2026 /* perhaps this as many as we're ready to handle */
2027 if (NUM_NONZERO(ctl->fetchlimit)
2028 && ctl->fetchlimit <= fetches)
2030 error(0, 0, _("fetchlimit reached; %d messages left on server"),
2036 if (!check_only && ctl->skipped)
2038 clean_skipped_list(&ctl->skipped);
2039 send_size_warnings(ctl);
2044 * Only re-poll if we had some actual forwards, allowed
2045 * deletions and had no errors.
2046 * Otherwise it is far too easy to get into infinite loops.
2048 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2052 ok = (protocol->logout_cmd)(sock, ctl);
2054 * Hmmmm...arguably this would be incorrect if we had fetches but
2055 * no dispatches (due to oversized messages, etc.)
2058 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2063 if (ok != 0 && ok != PS_SOCKET)
2064 (protocol->logout_cmd)(sock, ctl);
2068 msg = (const char *)NULL; /* sacrifice to -Wall */
2075 msg = _("authorization");
2078 msg = _("missing or bad RFC822 header");
2084 msg = _("client/server synchronization");
2087 msg = _("client/server protocol");
2090 msg = _("lock busy on server");
2093 msg = _("SMTP transaction");
2096 msg = _("DNS lookup");
2099 error(0, 0, _("undefined"));
2102 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2103 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2104 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2105 error(0,-1, _("%s error while fetching from %s"), msg, ctl->server.pollname);
2108 /* execute post-initialization command, if any */
2109 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2113 sprintf(buf, _("post-connection command failed with status %d"), ok);
2115 if (ok == PS_SUCCESS)
2119 signal(SIGALRM, sigsave);
2123 #if defined(HAVE_STDARG_H)
2124 void gen_send(int sock, const char *fmt, ... )
2126 void gen_send(sock, fmt, va_alist)
2127 int sock; /* socket to which server is connected */
2128 const char *fmt; /* printf-style format */
2131 /* assemble command in printf(3) style and send to the server */
2133 char buf [MSGBUFSIZE+1];
2136 if (protocol->tagged)
2137 (void) sprintf(buf, "%s ", GENSYM);
2141 #if defined(HAVE_STDARG_H)
2146 #ifdef HAVE_VSNPRINTF
2147 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2149 vsprintf(buf + strlen(buf), fmt, ap);
2153 strcat(buf, "\r\n");
2154 SockWrite(sock, buf, strlen(buf));
2156 if (outlevel >= O_MONITOR)
2160 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2164 sp = cp + strlen(shroud);
2170 buf[strlen(buf)-2] = '\0';
2171 error(0, 0, "%s> %s", protocol->name, buf);
2175 int gen_recv(sock, buf, size)
2176 /* get one line of input from the server */
2177 int sock; /* socket to which server is connected */
2178 char *buf; /* buffer to receive input */
2179 int size; /* length of buffer */
2181 int oldphase = phase; /* we don't have to be re-entrant */
2183 phase = SERVER_WAIT;
2184 set_timeout(mytimeout);
2185 if (SockRead(sock, buf, size) == -1)
2194 if (buf[strlen(buf)-1] == '\n')
2195 buf[strlen(buf)-1] = '\0';
2196 if (buf[strlen(buf)-1] == '\r')
2197 buf[strlen(buf)-1] = '\0';
2198 if (outlevel >= O_MONITOR)
2199 error(0, 0, "%s< %s", protocol->name, buf);
2205 #if defined(HAVE_STDARG_H)
2206 int gen_transact(int sock, const char *fmt, ... )
2208 int gen_transact(int sock, fmt, va_alist)
2209 int sock; /* socket to which server is connected */
2210 const char *fmt; /* printf-style format */
2213 /* assemble command in printf(3) style, send to server, accept a response */
2216 char buf [MSGBUFSIZE+1];
2218 int oldphase = phase; /* we don't have to be re-entrant */
2220 phase = SERVER_WAIT;
2222 if (protocol->tagged)
2223 (void) sprintf(buf, "%s ", GENSYM);
2227 #if defined(HAVE_STDARG_H)
2232 #ifdef HAVE_VSNPRINTF
2233 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2235 vsprintf(buf + strlen(buf), fmt, ap);
2239 strcat(buf, "\r\n");
2240 SockWrite(sock, buf, strlen(buf));
2242 if (outlevel >= O_MONITOR)
2246 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2250 sp = cp + strlen(shroud);
2256 buf[strlen(buf)-1] = '\0';
2257 error(0, 0, "%s> %s", protocol->name, buf);
2260 /* we presume this does its own response echoing */
2261 ok = (protocol->parse_response)(sock, buf);
2267 /* driver.c ends here */