]> Pileus Git - ~andy/fetchmail/blob - transact.c
5ddcba991b56cc40fec41968efdf9de2a29ab53b
[~andy/fetchmail] / transact.c
1 /*
2  * transact.c -- transaction primitives for the fetchmail driver loop
3  *
4  * Copyright 2001 by Eric S. Raymond
5  * For license terms, see the file COPYING in this directory.
6  *
7  * 
8  */
9
10 #include  "config.h"
11 #include  <stdio.h>
12 #include  <string.h>
13 #include  <ctype.h> /* isspace() */
14 #ifdef HAVE_MEMORY_H
15 #include  <memory.h>
16 #endif /* HAVE_MEMORY_H */
17 #if defined(STDC_HEADERS)
18 #include  <stdlib.h>
19 #endif
20 #if defined(HAVE_UNISTD_H)
21 #include <unistd.h>
22 #endif
23 #if defined(HAVE_STDARG_H)
24 #include  <stdarg.h>
25 #else
26 #include  <varargs.h>
27 #endif
28
29 #ifdef HAVE_NET_SOCKET_H
30 #include <net/socket.h>
31 #endif
32
33 #include "i18n.h"
34 #include "socket.h"
35 #include "fetchmail.h"
36
37 #ifndef strstr          /* glibc-2.1 declares this as a macro */
38 extern char *strstr();  /* needed on sysV68 R3V7.1. */
39 #endif /* strstr */
40
41 int mytimeout;          /* value of nonreponse timeout */
42 int suppress_tags;      /* emit tags? */
43 char shroud[PASSWORDLEN*2+1];   /* string to shroud in debug output */
44 struct msgblk msgblk;
45
46 char tag[TAGLEN];
47 static int tagnum;
48 #define GENSYM  (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
49
50 static int accept_count, reject_count;
51 static struct method *protocol;
52
53 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
54 /* add given name to xmit_names if it matches declared localnames */
55 /*   name:       name to map */
56 /*   ctl:        list of permissible aliases */
57 /*   xmit_names: list of recipient names parsed out */
58 {
59     const char  *lname;
60     int off = 0;
61     
62     lname = idpair_find(&ctl->localnames, name+off);
63     if (!lname && ctl->wildcard)
64         lname = name+off;
65
66     if (lname != (char *)NULL)
67     {
68         if (outlevel >= O_DEBUG)
69             report(stdout, GT_("mapped %s to local %s\n"), name, lname);
70         save_str(xmit_names, lname, XMIT_ACCEPT);
71         accept_count++;
72     }
73 }
74
75 static void find_server_names(const char *hdr,
76                               struct query *ctl,
77                               struct idlist **xmit_names)
78 /* parse names out of a RFC822 header into an ID list */
79 /*   hdr:               RFC822 header in question */
80 /*   ctl:               list of permissible aliases */
81 /*   xmit_names:        list of recipient names parsed out */
82 {
83     if (hdr == (char *)NULL)
84         return;
85     else
86     {
87         char    *cp;
88
89         for (cp = nxtaddr(hdr);
90              cp != NULL;
91              cp = nxtaddr(NULL))
92         {
93             char        *atsign;
94
95             /* 
96              * Handle empty address from a To: header containing only 
97              * a comment.
98              */
99             if (!*cp)
100                 continue;
101
102             /*
103              * If the name of the user begins with a qmail virtual
104              * domain prefix, ignore the prefix.  Doing this here
105              * means qvirtual will work either with ordinary name
106              * mapping or with a localdomains option.
107              */
108             if (ctl->server.qvirtual)
109             {
110                 int sl = strlen(ctl->server.qvirtual);
111  
112                 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
113                     cp += sl;
114             }
115
116             if ((atsign = strchr(cp, '@'))) {
117                 struct idlist   *idp;
118
119                 /*
120                  * Does a trailing segment of the hostname match something
121                  * on the localdomains list?  If so, save the whole name
122                  * and keep going.
123                  */
124                 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
125                     char        *rhs;
126
127                     rhs = atsign + (strlen(atsign) - strlen(idp->id));
128                     if (rhs > atsign &&
129                         (rhs[-1] == '.' || rhs[-1] == '@') &&
130                         strcasecmp(rhs, idp->id) == 0)
131                     {
132                         if (outlevel >= O_DEBUG)
133                             report(stdout, GT_("passed through %s matching %s\n"), 
134                                   cp, idp->id);
135                         save_str(xmit_names, cp, XMIT_ACCEPT);
136                         accept_count++;
137                         goto nomap;
138                     }
139                 }
140
141                 /* if we matched a local domain, idp != NULL */
142                 if (!idp)
143                 {
144                     /*
145                      * Check to see if the right-hand part is an alias
146                      * or MX equivalent of the mailserver.  If it's
147                      * not, skip this name.  If it is, we'll keep
148                      * going and try to find a mapping to a client name.
149                      */
150                     if (!is_host_alias(atsign+1, ctl))
151                     {
152                         save_str(xmit_names, cp, XMIT_REJECT);
153                         reject_count++;
154                         continue;
155                     }
156                 }
157                 atsign[0] = '\0';
158                 map_name(cp, ctl, xmit_names);
159             nomap:;
160             }
161         }
162     }
163 }
164
165 /*
166  * Return zero on a syntactically invalid address, nz on a valid one.
167  *
168  * This used to be strchr(a, '.'), but it turns out that lines like this
169  *
170  * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
171  *          id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
172  *
173  * are not uncommon.  So now we just check that the following token is
174  * not itself an email address.
175  */
176 #define VALID_ADDRESS(a)        !strchr(a, '@')
177
178 static char *parse_received(struct query *ctl, char *bufp)
179 /* try to extract real address from the Received line */
180 /* If a valid Received: line is found, we return the full address in
181  * a buffer which can be parsed from nxtaddr().  This is to ansure that
182  * the local domain part of the address can be passed along in 
183  * find_server_names() if it contains one.
184  * Note: We should return a dummy header containing the address 
185  * which makes nxtaddr() behave correctly. 
186  */
187 {
188     char *base, *ok = (char *)NULL;
189     static char rbuf[HOSTLEN + USERNAMELEN + 4]; 
190
191 #define RBUF_WRITE(value) if (tp < rbuf+sizeof(rbuf)-1) *tp++=value
192
193     /*
194      * Try to extract the real envelope addressee.  We look here
195      * specifically for the mailserver's Received line.
196      * Note: this will only work for sendmail, or an MTA that
197      * shares sendmail's convention for embedding the envelope
198      * address in the Received line.  Sendmail itself only
199      * does this when the mail has a single recipient.
200      */
201     if (outlevel >= O_DEBUG)
202         report(stdout, GT_("analyzing Received line:\n%s"), bufp);
203
204     /* search for whitepace-surrounded "by" followed by valid address */
205     for (base = bufp;  ; base = ok + 2)
206     {
207         if (!(ok = strstr(base, "by")))
208             break;
209         else if (!isspace(ok[-1]) || !isspace(ok[2]))
210             continue;
211         else
212         {
213             char        *sp, *tp;
214
215             /* extract space-delimited token after "by" */
216             for (sp = ok + 2; isspace(*sp); sp++)
217                 continue;
218             tp = rbuf;
219             for (; !isspace(*sp); sp++)
220                 RBUF_WRITE(*sp);
221             *tp = '\0';
222
223             /* look for valid address */
224             if (VALID_ADDRESS(rbuf))
225                 break;
226             else
227                 ok = sp - 1;    /* arrange to skip this token */
228         }
229     }
230     if (ok)
231     {
232         /*
233          * If it's a DNS name of the mail server, look for the
234          * recipient name after a following "for".  Otherwise
235          * punt.
236          */
237         if (is_host_alias(rbuf, ctl))
238         {
239             if (outlevel >= O_DEBUG)
240                 report(stdout, 
241                       GT_("line accepted, %s is an alias of the mailserver\n"), rbuf);
242         }
243         else
244         {
245             if (outlevel >= O_DEBUG)
246                 report(stdout, 
247                       GT_("line rejected, %s is not an alias of the mailserver\n"), 
248                       rbuf);
249             return(NULL);
250         }
251
252         /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
253         for (base = ok + 4 + strlen(rbuf);  ; base = ok + 2)
254         {
255             if (!(ok = strstr(base, "for")))
256                 break;
257             else if (!isspace(ok[-1]) || !isspace(ok[3]))
258                 continue;
259             else
260             {
261                 char    *sp, *tp;
262
263                 /* extract space-delimited token after "for" */
264                 for (sp = ok + 3; isspace(*sp); sp++)
265                     continue;
266                 tp = rbuf;
267                 for (; !isspace(*sp); sp++)
268                     RBUF_WRITE(*sp);
269                 *tp = '\0';
270
271                 if (strchr(rbuf, '@'))
272                     break;
273                 else
274                     ok = sp - 1;        /* arrange to skip this token */
275             }
276         }
277         if (ok)
278         {
279             flag        want_gt = FALSE;
280             char        *sp, *tp;
281
282             /* char after "for" could be space or a continuation newline */
283             for (sp = ok + 4; isspace(*sp); sp++)
284                 continue;
285             tp = rbuf;
286             RBUF_WRITE(':');    /* Here is the hack.  This is to be friends */
287             RBUF_WRITE(' ');    /* with nxtaddr()... */
288             if (*sp == '<')
289             {
290                 want_gt = TRUE;
291                 sp++;
292             }
293             while (*sp == '@')          /* skip routes */
294                 while (*sp && *sp++ != ':')
295                     continue;
296             while (*sp
297                    && (want_gt ? (*sp != '>') : !isspace(*sp))
298                    && *sp != ';')
299                 if (!isspace(*sp))
300                 {
301                     RBUF_WRITE(*sp);
302                     sp++;
303                 }    
304                 else
305                 {
306                     /* uh oh -- whitespace here can't be right! */
307                     ok = (char *)NULL;
308                     break;
309                 }
310             RBUF_WRITE('\n');
311             *tp = '\0';
312             if (strlen(rbuf) <= 3)      /* apparently nothing has been found */
313                 ok = NULL;
314         } else
315             ok = (char *)NULL;
316     }
317
318     if (!ok)
319     {
320         if (outlevel >= O_DEBUG)
321             report(stdout, GT_("no Received address found\n"));
322         return(NULL);
323     }
324     else
325     {
326         if (outlevel >= O_DEBUG) {
327             char *lf = rbuf + strlen(rbuf)-1;
328             *lf = '\0';
329             if (outlevel >= O_DEBUG)
330                 report(stdout, GT_("found Received address `%s'\n"), rbuf+2);
331             *lf = '\n';
332         }
333         return(rbuf);
334     }
335 }
336
337 /* shared by readheaders and readbody */
338 static int sizeticker;
339
340 #define EMPTYLINE(s)    ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
341
342 int readheaders(int sock,
343                        long fetchlen,
344                        long reallen,
345                        struct query *ctl,
346                        int num)
347 /* read message headers and ship to SMTP or MDA */
348 /*   sock:              to which the server is connected */
349 /*   fetchlen:          length of message according to fetch response */
350 /*   reallen:           length of message according to getsizes */
351 /*   ctl:               query control record */
352 /*   num:               index of message */
353 {
354     struct addrblk
355     {
356         int             offset;
357         struct addrblk  *next;
358     };
359     struct addrblk      *to_addrchain = NULL;
360     struct addrblk      **to_chainptr = &to_addrchain;
361     struct addrblk      *resent_to_addrchain = NULL;
362     struct addrblk      **resent_to_chainptr = &resent_to_addrchain;
363
364     char                buf[MSGBUFSIZE+1];
365     int                 from_offs, reply_to_offs, resent_from_offs;
366     int                 app_from_offs, sender_offs, resent_sender_offs;
367     int                 env_offs;
368     char                *received_for, *rcv, *cp;
369     static char         *delivered_to = NULL;
370     int                 n, linelen, oldlen, ch, remaining, skipcount;
371     struct idlist       *idp;
372     flag                no_local_matches = FALSE;
373     flag                headers_ok, has_nuls;
374     int                 olderrs, good_addresses, bad_addresses;
375     int                 retain_mail = 0;
376
377     sizeticker = 0;
378     has_nuls = headers_ok = FALSE;
379     msgblk.return_path[0] = '\0';
380     olderrs = ctl->errcount;
381
382     /* read message headers */
383     msgblk.reallen = reallen;
384
385     /*
386      * We used to free the header block unconditionally at the end of 
387      * readheaders, but it turns out that if close_sink() hits an error
388      * condition the code for sending bouncemail will actually look
389      * at the freed storage and coredump...
390      */
391     if (msgblk.headers)
392        free(msgblk.headers);
393     free_str_list(&msgblk.recipients);
394     if (delivered_to)
395         free(delivered_to);
396
397     /* initially, no message ID */
398     if (ctl->thisid)
399         free(ctl->thisid);
400     ctl->thisid = NULL;
401
402     msgblk.headers = received_for = delivered_to = NULL;
403     from_offs = reply_to_offs = resent_from_offs = app_from_offs = 
404         sender_offs = resent_sender_offs = env_offs = -1;
405     oldlen = 0;
406     msgblk.msglen = 0;
407     skipcount = 0;
408     ctl->mimemsg = 0;
409
410     for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
411     {
412         char *line;
413         int overlong = FALSE;
414
415         line = xmalloc(sizeof(buf));
416         linelen = 0;
417         line[0] = '\0';
418         do {
419             set_timeout(mytimeout);
420             if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
421                 set_timeout(0);
422                 free(line);
423                 free(msgblk.headers);
424                 msgblk.headers = NULL;
425                 return(PS_SOCKET);
426             }
427             set_timeout(0);
428             linelen += n;
429             msgblk.msglen += n;
430
431                 /*
432                  * Try to gracefully handle the case, where the length of a
433                  * line exceeds MSGBUFSIZE.
434                  */
435                 if ( n && buf[n-1] != '\n' ) {
436                         unsigned int llen = strlen(line);
437                         overlong = TRUE;
438                         line = realloc(line, llen + n + 1);
439                         strcpy(line + llen, buf);
440                         ch = ' '; /* So the next iteration starts */
441                         continue;
442                 }
443
444             /* lines may not be properly CRLF terminated; fix this for qmail */
445             if (ctl->forcecr)
446             {
447                 cp = buf + strlen(buf) - 1;
448                 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
449                 {
450                     *cp++ = '\r';
451                     *cp++ = '\n';
452                     *cp++ = '\0';
453                 }
454             }
455
456                 /*
457                  * Decode MIME encoded headers. We MUST do this before
458                  * looking at the Content-Type / Content-Transfer-Encoding
459                  * headers (RFC 2046).
460                  */
461                 if ( ctl->mimedecode && overlong ) {
462                         /*
463                          * If we received an overlong line, we have to decode the
464                          * whole line at once.
465                          */
466                         line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
467                         strcat(line, buf);
468                         UnMimeHeader(line);
469                 }
470                 else {
471                         if ( ctl->mimedecode )
472                                 UnMimeHeader(buf);
473
474                         line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
475                         strcat(line, buf);
476                 }
477
478             /* check for end of headers */
479             if (EMPTYLINE(line))
480             {
481                 headers_ok = TRUE;
482                 has_nuls = (linelen != strlen(line));
483                 free(line);
484                 goto process_headers;
485             }
486
487             /*
488              * Check for end of message immediately.  If one of your folders
489              * has been mangled, the delimiter may occur directly after the
490              * header.
491              */
492             if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
493             {
494                 headers_ok = FALSE;
495                 has_nuls = (linelen != strlen(line));
496                 free(line);
497                 goto process_headers;
498             }
499
500             /*
501              * At least one brain-dead website (netmind.com) is known to
502              * send out robotmail that's missing the RFC822 delimiter blank
503              * line before the body! Without this check fetchmail segfaults.
504              * With it, we treat such messages as though they had the missing
505              * blank line.
506              */
507             if (!isspace(line[0]) && !strchr(line, ':'))
508             {
509                 headers_ok = FALSE;
510                 has_nuls = (linelen != strlen(line));
511                 free(line);
512                 goto process_headers;
513             }
514
515             /* check for RFC822 continuations */
516             set_timeout(mytimeout);
517             ch = SockPeek(sock);
518             set_timeout(0);
519         } while
520             (ch == ' ' || ch == '\t');  /* continuation to next line? */
521
522         /* write the message size dots */
523         if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
524         {
525             sizeticker += linelen;
526             while (sizeticker >= SIZETICKER)
527             {
528                 if ((!run.use_syslog && !isafile(1)) || run.showdots)
529                 {
530                     fputc('.', stdout);
531                     fflush(stdout);
532                 }
533                 sizeticker -= SIZETICKER;
534             }
535         }
536
537         /* we see an ordinary (non-header, non-message-delimiter line */
538         has_nuls = (linelen != strlen(line));
539
540         /* save the message's ID, we may use it for killing duplicates later */
541         if (MULTIDROP(ctl) && !strncasecmp(line, "Message-ID:", 11))
542             ctl->thisid = xstrdup(line);
543
544         /*
545          * The University of Washington IMAP server (the reference
546          * implementation of IMAP4 written by Mark Crispin) relies
547          * on being able to keep base-UID information in a special
548          * message at the head of the mailbox.  This message should
549          * neither be deleted nor forwarded.
550          */
551 #ifdef POP2_ENABLE
552         /*
553          * We disable this check under POP2 because there's no way to
554          * prevent deletion of the message.  So at least we ought to 
555          * forward it to the user so he or she will have some clue
556          * that things have gone awry.
557          */
558 #if INET6_ENABLE
559         if (strncmp(protocol->service, "pop2", 4))
560 #else /* INET6_ENABLE */
561         if (protocol->port != 109)
562 #endif /* INET6_ENABLE */
563 #endif /* POP2_ENABLE */
564             if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
565                 free(line);
566                 retain_mail = 1;
567                 continue;
568             }
569
570         /*
571          * This code prevents fetchmail from becoming an accessory after
572          * the fact to upstream sendmails with the `E' option on.  It also
573          * copes with certain brain-dead POP servers (like NT's) that pass
574          * through Unix from_ lines.
575          *
576          * Either of these bugs can result in a non-RFC822 line at the
577          * beginning of the headers.  If fetchmail just passes it
578          * through, the client listener may think the message has *no*
579          * headers (since the first) line it sees doesn't look
580          * RFC822-conformant) and fake up a set.
581          *
582          * What the user would see in this case is bogus (synthesized)
583          * headers, followed by a blank line, followed by the >From, 
584          * followed by the real headers, followed by a blank line,
585          * followed by text.
586          *
587          * We forestall this lossage by tossing anything that looks
588          * like an escaped or passed-through From_ line in headers.
589          * These aren't RFC822 so our conscience is clear...
590          */
591         if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
592         {
593             free(line);
594             continue;
595         }
596
597         /*
598          * We remove all Delivered-To: headers.
599          * 
600          * This is to avoid false mail loops messages when delivering
601          * local messages to and from a Postfix/qmail mailserver. 
602          */
603         if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13)) 
604         {
605             if (delivered_to)
606                 free(line);
607             else 
608                 delivered_to = line;
609             continue;
610         }
611
612         /*
613          * If we see a Status line, it may have been inserted by an MUA
614          * on the mail host, or it may have been inserted by the server
615          * program after the headers in the transaction stream.  This
616          * can actually hose some new-mail notifiers such as xbuffy,
617          * which assumes any Status line came from a *local* MDA and
618          * therefore indicates that the message has been seen.
619          *
620          * Some buggy POP servers (including at least the 3.3(20)
621          * version of the one distributed with IMAP) insert empty
622          * Status lines in the transaction stream; we'll chuck those
623          * unconditionally.  Nonempty ones get chucked if the user
624          * turns on the dropstatus flag.
625          */
626         {
627             char        *cp;
628
629             if (!strncasecmp(line, "Status:", 7))
630                 cp = line + 7;
631             else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
632                 cp = line + 17;
633             else
634                 cp = NULL;
635             if (cp) {
636                 while (*cp && isspace(*cp)) cp++;
637                 if (!*cp || ctl->dropstatus)
638                 {
639                     free(line);
640                     continue;
641                 }
642             }
643         }
644
645         if (ctl->rewrite)
646             line = reply_hack(line, ctl->server.truename);
647
648         /*
649          * OK, this is messy.  If we're forwarding by SMTP, it's the
650          * SMTP-receiver's job (according to RFC821, page 22, section
651          * 4.1.1) to generate a Return-Path line on final delivery.
652          * The trouble is, we've already got one because the
653          * mailserver's SMTP thought *it* was responsible for final
654          * delivery.
655          *
656          * Stash away the contents of Return-Path (as modified by reply_hack)
657          * for use in generating MAIL FROM later on, then prevent the header
658          * from being saved with the others.  In effect, we strip it off here.
659          *
660          * If the SMTP server conforms to the standards, and fetchmail gets the
661          * envelope sender from the Return-Path, the new Return-Path should be
662          * exactly the same as the original one.
663          *
664          * We do *not* want to ignore empty Return-Path headers.  These should
665          * be passed through as a way of indicating that a message should
666          * not trigger bounces if delivery fails.  What we *do* need to do is
667          * make sure we never try to rewrite such a blank Return-Path.  We
668          * handle this with a check for <> in the rewrite logic above.
669          */
670         if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
671         {
672             strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
673             msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
674             if (!ctl->mda) {
675                 free(line);
676                 continue;
677             }
678         }
679
680         if (!msgblk.headers)
681         {
682             oldlen = strlen(line);
683             msgblk.headers = xmalloc(oldlen + 1);
684             (void) strcpy(msgblk.headers, line);
685             free(line);
686             line = msgblk.headers;
687         }
688         else
689         {
690             char *newhdrs;
691             int newlen;
692
693             newlen = oldlen + strlen(line);
694             newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
695             if (newhdrs == NULL) {
696                 free(line);
697                 return(PS_IOERR);
698             }
699             msgblk.headers = newhdrs;
700             strcpy(msgblk.headers + oldlen, line);
701             free(line);
702             line = msgblk.headers + oldlen;
703             oldlen = newlen;
704         }
705
706         /* find offsets of various special headers */
707         if (!strncasecmp("From:", line, 5))
708             from_offs = (line - msgblk.headers);
709         else if (!strncasecmp("Reply-To:", line, 9))
710             reply_to_offs = (line - msgblk.headers);
711         else if (!strncasecmp("Resent-From:", line, 12))
712             resent_from_offs = (line - msgblk.headers);
713         else if (!strncasecmp("Apparently-From:", line, 16))
714             app_from_offs = (line - msgblk.headers);
715         /*
716          * Netscape 4.7 puts "Sender: zap" in mail headers.  Perverse...
717          *
718          * But a literal reading of RFC822 sec. 4.4.2 supports the idea
719          * that Sender: *doesn't* have to be a working email address.
720          *
721          * The definition of the Sender header in RFC822 says, in
722          * part, "The Sender mailbox specification includes a word
723          * sequence which must correspond to a specific agent (i.e., a
724          * human user or a computer program) rather than a standard
725          * address."  That implies that the contents of the Sender
726          * field don't need to be a legal email address at all So
727          * ignore any Sender or Resent-Semnder lines unless they
728          * contain @.
729          *
730          * (RFC2822 says the condents of Sender must be a valid mailbox
731          * address, which is also what RFC822 4.4.4 implies.)
732          */
733         else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
734             sender_offs = (line - msgblk.headers);
735         else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
736             resent_sender_offs = (line - msgblk.headers);
737
738 #ifdef __UNUSED__
739         else if (!strncasecmp("Message-Id:", line, 11))
740         {
741             if (ctl->server.uidl)
742             {
743                 char id[IDLEN+1];
744
745                 line[IDLEN+12] = 0;             /* prevent stack overflow */
746                 sscanf(line+12, "%s", id);
747                 if (!str_find( &ctl->newsaved, num))
748                 {
749                     struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
750                     new->val.status.num = num;
751                 }
752             }
753         }
754 #endif /* __UNUSED__ */
755
756         /* if multidrop is on, gather addressee headers */
757         if (MULTIDROP(ctl))
758         {
759             if (!strncasecmp("To:", line, 3)
760                 || !strncasecmp("Cc:", line, 3)
761                 || !strncasecmp("Bcc:", line, 4)
762                 || !strncasecmp("Apparently-To:", line, 14))
763             {
764                 *to_chainptr = xmalloc(sizeof(struct addrblk));
765                 (*to_chainptr)->offset = (line - msgblk.headers);
766                 to_chainptr = &(*to_chainptr)->next; 
767                 *to_chainptr = NULL;
768             }
769
770             else if (!strncasecmp("Resent-To:", line, 10)
771                      || !strncasecmp("Resent-Cc:", line, 10)
772                      || !strncasecmp("Resent-Bcc:", line, 11))
773             {
774                 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
775                 (*resent_to_chainptr)->offset = (line - msgblk.headers);
776                 resent_to_chainptr = &(*resent_to_chainptr)->next; 
777                 *resent_to_chainptr = NULL;
778             }
779
780             else if (ctl->server.envelope != STRING_DISABLED)
781             {
782                 if (ctl->server.envelope 
783                     && strcasecmp(ctl->server.envelope, "Received"))
784                 {
785                     if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
786                                                        line,
787                                                        strlen(ctl->server.envelope)))
788                     {                           
789                         if (skipcount++ < ctl->server.envskip)
790                             continue;
791                         env_offs = (line - msgblk.headers);
792                     }    
793                 }
794                 else if (!received_for && !strncasecmp("Received:", line, 9))
795                 {
796                     if (skipcount++ < ctl->server.envskip)
797                         continue;
798                     received_for = parse_received(ctl, line);
799                 }
800             }
801         }
802     }
803
804  process_headers:    
805
806     if (retain_mail)
807     {
808         free(msgblk.headers);
809         msgblk.headers = NULL;
810         return(PS_RETAINED);
811     }
812     /*
813      * When mail delivered to a multidrop mailbox on the server is
814      * addressed to multiple people on the client machine, there will
815      * be one copy left in the box for each recipient.  This is not a
816      * problem if we have the actual recipient address to dispatch on
817      * (e.g. because we've mined it out of sendmail trace headers, or
818      * a qmail Delivered-To line, or a declared sender envelope line).
819      *
820      * But if we're mining addressees out of the To/Cc/Bcc fields, and
821      * if the mail is addressed to N people, each recipient will
822      * get N copies.  This is bad when N > 1.
823      *
824      * Foil this by suppressing all but one copy of a message with
825      * a given Message-ID.  The accept_count test ensures that
826      * multiple pieces of email with the same Message-ID, each
827      * with a *single* addressee (the N == 1 case), won't be 
828      * suppressed.
829      *
830      * Note: This implementation only catches runs of successive
831      * messages with the same ID, but that should be good
832      * enough. A more general implementation would have to store
833      * ever-growing lists of seen message-IDs; in a long-running
834      * daemon this would turn into a memory leak even if the 
835      * implementation were perfect.
836      * 
837      * Don't mess with this code casually.  It would be way too easy
838      * to break it in a way that blackholed mail.  Better to pass
839      * the occasional duplicate than to do that...
840      */
841     if (!received_for && env_offs == -1 && !delivered_to)
842     {
843         if (ctl->lastid && ctl->thisid && !strcasecmp(ctl->lastid, ctl->thisid))
844         {
845             if (accept_count > 1)
846                 return(PS_REFUSED);
847         }
848         else
849         {
850             if (ctl->lastid)
851                 free(ctl->lastid);
852             ctl->lastid = ctl->thisid;
853             ctl->thisid = NULL;
854         }
855     }
856
857     /*
858      * We want to detect this early in case there are so few headers that the
859      * dispatch logic barfs.
860      */
861     if (!headers_ok)
862     {
863         if (outlevel > O_SILENT)
864             report(stdout,
865                    GT_("message delimiter found while scanning headers\n"));
866         return(PS_TRUNCATED);
867     }
868
869     /*
870      * Hack time.  If the first line of the message was blank, with no headers
871      * (this happens occasionally due to bad gatewaying software) cons up
872      * a set of fake headers.  
873      *
874      * If you modify the fake header template below, be sure you don't
875      * make either From or To address @-less, otherwise the reply_hack
876      * logic will do bad things.
877      */
878     if (msgblk.headers == (char *)NULL)
879     {
880 #ifdef HAVE_SNPRINTF
881         snprintf(buf, sizeof(buf),
882 #else
883         sprintf(buf, 
884 #endif /* HAVE_SNPRINTF */
885         "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
886                 user, fetchmailhost, ctl->remotename, ctl->server.truename);
887         msgblk.headers = xstrdup(buf);
888     }
889
890     /*
891      * We can now process message headers before reading the text.
892      * In fact we have to, as this will tell us where to forward to.
893      */
894
895     /* Check for MIME headers indicating possible 8-bit data */
896     ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
897
898 #ifdef SDPS_ENABLE
899     if (ctl->server.sdps && sdps_envfrom)
900     {
901         /* We have the real envelope return-path, stored out of band by
902          * SDPS - that's more accurate than any header is going to be.
903          */
904         strcpy(msgblk.return_path, sdps_envfrom);
905         free(sdps_envfrom);
906     } else
907 #endif /* SDPS_ENABLE */
908     /*
909      * If there is a Return-Path address on the message, this was
910      * almost certainly the MAIL FROM address given the originating
911      * sendmail.  This is the best thing to use for logging the
912      * message origin (it sets up the right behavior for bounces and
913      * mailing lists).  Otherwise, fall down to the next available 
914      * envelope address (which is the most probable real sender).
915      * *** The order is important! ***
916      * This is especially useful when receiving mailing list
917      * messages in multidrop mode.  if a local address doesn't
918      * exist, the bounce message won't be returned blindly to the 
919      * author or to the list itself but rather to the list manager
920      * (ex: specified by "Sender:") which is much less annoying.  This 
921      * is true for most mailing list packages.
922      */
923     if( !msgblk.return_path[0] ){
924         char *ap = NULL;
925         if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
926         else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
927         else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
928         else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
929         else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
930         else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
931         /* multi-line MAIL FROM addresses confuse SMTP terribly */
932         if (ap && !strchr(ap, '\n')) {
933             strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
934             msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
935         }
936     }
937
938     /* cons up a list of local recipients */
939     msgblk.recipients = (struct idlist *)NULL;
940     accept_count = reject_count = 0;
941     /* is this a multidrop box? */
942     if (MULTIDROP(ctl))
943     {
944 #ifdef SDPS_ENABLE
945         if (ctl->server.sdps && sdps_envto)
946         {
947             /* We have the real envelope recipient, stored out of band by
948              * SDPS - that's more accurate than any header is going to be.
949              */
950             find_server_names(sdps_envto, ctl, &msgblk.recipients);
951             free(sdps_envto);
952         } else
953 #endif /* SDPS_ENABLE */ 
954         if (env_offs > -1)          /* We have the actual envelope addressee */
955             find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
956         else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
957       ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
958    {
959             find_server_names(delivered_to, ctl, &msgblk.recipients);
960        free(delivered_to);
961        delivered_to = NULL;
962    }
963         else if (received_for)
964             /*
965              * We have the Received for addressee.  
966              * It has to be a mailserver address, or we
967              * wouldn't have got here.
968              * We use find_server_names() to let local 
969              * hostnames go through.
970              */
971             find_server_names(received_for, ctl, &msgblk.recipients);
972         else
973         {
974             /*
975              * We haven't extracted the envelope address.
976              * So check all the "Resent-To" header addresses if 
977              * they exist.  If and only if they don't, consider
978              * the "To" addresses.
979              */
980             register struct addrblk *nextptr;
981             if (resent_to_addrchain) {
982                 /* delete the "To" chain and substitute it 
983                  * with the "Resent-To" list 
984                  */
985                 while (to_addrchain) {
986                     nextptr = to_addrchain->next;
987                     free(to_addrchain);
988                     to_addrchain = nextptr;
989                 }
990                 to_addrchain = resent_to_addrchain;
991                 resent_to_addrchain = NULL;
992             }
993             /* now look for remaining adresses */
994             while (to_addrchain) {
995                 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
996                 nextptr = to_addrchain->next;
997                 free(to_addrchain);
998                 to_addrchain = nextptr;
999             }
1000         }
1001         if (!accept_count)
1002         {
1003             no_local_matches = TRUE;
1004             save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
1005             if (outlevel >= O_DEBUG)
1006                 report(stdout,
1007                       GT_("no local matches, forwarding to %s\n"),
1008                       run.postmaster);
1009         }
1010     }
1011     else        /* it's a single-drop box, use first localname */
1012         save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1013
1014
1015     /*
1016      * Time to either address the message or decide we can't deliver it yet.
1017      */
1018     if (ctl->errcount > olderrs)        /* there were DNS errors above */
1019     {
1020         if (outlevel >= O_DEBUG)
1021             report(stdout,
1022                    GT_("forwarding and deletion suppressed due to DNS errors\n"));
1023         free(msgblk.headers);
1024         msgblk.headers = NULL;
1025         free_str_list(&msgblk.recipients);
1026         return(PS_TRANSIENT);
1027     }
1028     else
1029     {
1030         /* set up stuffline() so we can deliver the message body through it */ 
1031         if ((n = open_sink(ctl, &msgblk,
1032                            &good_addresses, &bad_addresses)) != PS_SUCCESS)
1033         {
1034             free(msgblk.headers);
1035             msgblk.headers = NULL;
1036             free_str_list(&msgblk.recipients);
1037             return(n);
1038         }
1039     }
1040
1041     n = 0;
1042     /*
1043      * Some server/sendmail combinations cause problems when our
1044      * synthetic Received line is before the From header.  Cope
1045      * with this...
1046      */
1047     if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1048         rcv = msgblk.headers;
1049     /* handle ">Received:" lines too */
1050     while (rcv > msgblk.headers && rcv[-1] != '\n')
1051         rcv--;
1052     if (rcv > msgblk.headers)
1053     {
1054         char    c = *rcv;
1055
1056         *rcv = '\0';
1057         n = stuffline(ctl, msgblk.headers);
1058         *rcv = c;
1059     }
1060     if (!run.invisible && n != -1)
1061     {
1062         /* utter any per-message Received information we need here */
1063         if (ctl->server.trueaddr) {
1064 #ifdef HAVE_SNPRINTF
1065             snprintf(buf, sizeof(buf),
1066 #else
1067             sprintf(buf, 
1068 #endif /* HAVE_SNPRINTF */
1069                     "Received: from %s [%u.%u.%u.%u]\r\n", 
1070                     ctl->server.truename,
1071                     (unsigned char)ctl->server.trueaddr[0],
1072                     (unsigned char)ctl->server.trueaddr[1],
1073                     (unsigned char)ctl->server.trueaddr[2],
1074                     (unsigned char)ctl->server.trueaddr[3]);
1075         } else {
1076 #ifdef HAVE_SNPRINTF
1077           snprintf(buf, sizeof(buf),
1078 #else                       
1079           sprintf(buf,
1080 #endif /* HAVE_SNPRINTF */
1081                   "Received: from %s\r\n", ctl->server.truename);
1082         }
1083         n = stuffline(ctl, buf);
1084         if (n != -1)
1085         {
1086             /*
1087              * This header is technically invalid under RFC822.
1088              * POP3, IMAP, etc. are not legal mail-parameter values.
1089              */
1090 #ifdef HAVE_SNPRINTF
1091             snprintf(buf, sizeof(buf),
1092 #else
1093             sprintf(buf,
1094 #endif /* HAVE_SNPRINTF */
1095                     "\tby %s with %s (fetchmail-%s",
1096                     fetchmailhost,
1097                     protocol->name,
1098                     VERSION);
1099             if (ctl->tracepolls)
1100             {
1101                 sprintf(buf + strlen(buf), " polling %s account %s",
1102                         ctl->server.pollname, 
1103                         ctl->remotename);
1104             }
1105 #ifdef HAVE_SNPRINTF
1106             snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1107 #else
1108             strcat(buf, ")\r\n");
1109 #endif /* HAVE_SNPRINTF */
1110             n = stuffline(ctl, buf);
1111             if (n != -1)
1112             {
1113                 buf[0] = '\t';
1114                 if (good_addresses == 0)
1115                 {
1116 #ifdef HAVE_SNPRINTF
1117                     snprintf(buf+1, sizeof(buf)-1,
1118 #else
1119                     sprintf(buf+1,
1120 #endif /* HAVE_SNPRINTF */
1121                             "for %s (by default); ",
1122                             rcpt_address (ctl, run.postmaster, 0));
1123                 }
1124                 else if (good_addresses == 1)
1125                 {
1126                     for (idp = msgblk.recipients; idp; idp = idp->next)
1127                         if (idp->val.status.mark == XMIT_ACCEPT)
1128                             break;      /* only report first address */
1129 #ifdef HAVE_SNPRINTF
1130                     snprintf(buf+1, sizeof(buf)-1,
1131 #else                       
1132                     sprintf(buf+1,
1133 #endif /* HAVE_SNPRINTF */
1134                             "for %s", rcpt_address (ctl, idp->id, 1));
1135                     sprintf(buf+strlen(buf), " (%s); ",
1136                             MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1137                 }
1138                 else
1139                     buf[1] = '\0';
1140
1141 #ifdef HAVE_SNPRINTF
1142                 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1143                         rfc822timestamp());
1144 #else
1145                 strcat(buf, rfc822timestamp());
1146                 strcat(buf, "\r\n");
1147 #endif /* HAVE_SNPRINTF */
1148                 n = stuffline(ctl, buf);
1149             }
1150         }
1151     }
1152
1153     if (n != -1)
1154         n = stuffline(ctl, rcv);        /* ship out rest of msgblk.headers */
1155
1156     if (n == -1)
1157     {
1158         report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1159         release_sink(ctl);
1160         free(msgblk.headers);
1161         msgblk.headers = NULL;
1162         free_str_list(&msgblk.recipients);
1163         return(PS_IOERR);
1164     }
1165     else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && !isafile(2))
1166         fputs("#", stdout);
1167
1168     /* write error notifications */
1169     if (no_local_matches || has_nuls || bad_addresses)
1170     {
1171         int     errlen = 0;
1172         char    errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1173
1174         errmsg = errhd;
1175         (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1176         if (no_local_matches)
1177         {
1178             if (reject_count != 1)
1179                 strcat(errhd, GT_("no recipient addresses matched declared local names"));
1180             else
1181             {
1182                 for (idp = msgblk.recipients; idp; idp = idp->next)
1183                     if (idp->val.status.mark == XMIT_REJECT)
1184                         break;
1185 #ifdef HAVE_SNPRINTF
1186                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1187 #else
1188                 sprintf(errhd+strlen(errhd),
1189 #endif /* HAVE_SNPRINTF */
1190                         GT_("recipient address %s didn't match any local name"), idp->id);
1191             }
1192         }
1193
1194         if (has_nuls)
1195         {
1196             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1197 #ifdef HAVE_SNPRINTF
1198                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1199             snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1200 #else
1201                 strcat(errhd, "; ");
1202             strcat(errhd,
1203 #endif /* HAVE_SNPRINTF */
1204                         GT_("message has embedded NULs"));
1205         }
1206
1207         if (bad_addresses)
1208         {
1209             if (errhd[sizeof("X-Fetchmail-Warning: ")])
1210 #ifdef HAVE_SNPRINTF
1211                 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1212             snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1213 #else
1214                 strcat(errhd, "; ");
1215             strcat(errhd,
1216 #endif /* HAVE_SNPRINTF */
1217                         GT_("SMTP listener rejected local recipient addresses: "));
1218             errlen = strlen(errhd);
1219             for (idp = msgblk.recipients; idp; idp = idp->next)
1220                 if (idp->val.status.mark == XMIT_RCPTBAD)
1221                     errlen += strlen(idp->id) + 2;
1222
1223             xalloca(errmsg, char *, errlen+3);
1224             (void) strcpy(errmsg, errhd);
1225             for (idp = msgblk.recipients; idp; idp = idp->next)
1226                 if (idp->val.status.mark == XMIT_RCPTBAD)
1227                 {
1228                     strcat(errmsg, idp->id);
1229                     if (idp->next)
1230                         strcat(errmsg, ", ");
1231                 }
1232
1233         }
1234
1235         strcat(errmsg, "\r\n");
1236
1237         /* ship out the error line */
1238         stuffline(ctl, errmsg);
1239     }
1240
1241     /* issue the delimiter line */
1242     cp = buf;
1243     *cp++ = '\r';
1244     *cp++ = '\n';
1245     *cp++ = '\0';
1246     stuffline(ctl, buf);
1247
1248     return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1249 }
1250
1251 int readbody(int sock, struct query *ctl, flag forward, int len)
1252 /* read and dispose of a message body presented on sock */
1253 /*   ctl:               query control record */
1254 /*   sock:              to which the server is connected */
1255 /*   len:               length of message */
1256 /*   forward:           TRUE to forward */
1257 {
1258     int linelen;
1259     unsigned char buf[MSGBUFSIZE+4];
1260     unsigned char *inbufp = buf;
1261     flag issoftline = FALSE;
1262
1263     /*
1264      * Pass through the text lines in the body.
1265      *
1266      * Yes, this wants to be ||, not &&.  The problem is that in the most
1267      * important delimited protocol, POP3, the length is not reliable.
1268      * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1269      * So, for delimited protocols we need to ignore the length here and
1270      * instead drop out of the loop with a break statement when we see
1271      * the message delimiter.
1272      */
1273     while (protocol->delimited || len > 0)
1274     {
1275         set_timeout(mytimeout);
1276         if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1277         {
1278             set_timeout(0);
1279             release_sink(ctl);
1280             return(PS_SOCKET);
1281         }
1282         set_timeout(0);
1283
1284         /* write the message size dots */
1285         if (linelen > 0)
1286         {
1287             sizeticker += linelen;
1288             while (sizeticker >= SIZETICKER)
1289             {
1290                 if (outlevel > O_SILENT && (((run.poll_interval == 0 || nodetach) && !isafile(1)) || run.showdots))
1291                 {
1292                     fputc('.', stdout);
1293                     fflush(stdout);
1294                 }
1295                 sizeticker -= SIZETICKER;
1296             }
1297         }
1298         len -= linelen;
1299
1300         /* check for end of message */
1301         if (protocol->delimited && *inbufp == '.')
1302         {
1303             if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1304                 break;
1305             else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1306                 break;
1307             else
1308                 msgblk.msglen--;        /* subtract the size of the dot escape */
1309         }
1310
1311         msgblk.msglen += linelen;
1312
1313         if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1314             issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1315             if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1316             {
1317                 /*
1318                  * Soft linebreak, but less than 200 bytes left in
1319                  * input buffer. Rather than doing a buffer overrun,
1320                  * ignore the soft linebreak, NL-terminate data and
1321                  * deliver what we have now.
1322                  * (Who writes lines longer than 2K anyway?)
1323                  */
1324                 *inbufp = '\n'; *(inbufp+1) = '\0';
1325                 issoftline = 0;
1326             }
1327         }
1328
1329         /* ship out the text line */
1330         if (forward && (!issoftline))
1331         {
1332             int n;
1333             inbufp = buf;
1334
1335             /* guard against very long lines */
1336             buf[MSGBUFSIZE+1] = '\r';
1337             buf[MSGBUFSIZE+2] = '\n';
1338             buf[MSGBUFSIZE+3] = '\0';
1339
1340             n = stuffline(ctl, buf);
1341
1342             if (n < 0)
1343             {
1344                 report(stdout, GT_("writing message text\n"));
1345                 release_sink(ctl);
1346                 return(PS_IOERR);
1347             }
1348             else if (outlevel >= O_VERBOSE && !isafile(1))
1349             {
1350                 fputc('*', stdout);
1351                 fflush(stdout);
1352             }
1353         }
1354     }
1355
1356     return(PS_SUCCESS);
1357 }
1358
1359 void init_transact(const struct method *proto)
1360 /* initialize state for the send and receive functions */
1361 {
1362     tagnum = 0;
1363     tag[0] = '\0';      /* nuke any tag hanging out from previous query */
1364     protocol = (struct method *)proto;
1365 }
1366
1367 static void enshroud(char *buf)
1368 /* shroud a password in the given buffer */
1369 {
1370     char *cp;
1371
1372     if (shroud[0] && (cp = strstr(buf, shroud)))
1373     {
1374        char    *sp;
1375
1376        sp = cp + strlen(shroud);
1377        *cp = '*';
1378        while (*sp)
1379            *cp++ = *sp++;
1380        *cp = '\0';
1381     }
1382 }
1383
1384 #if defined(HAVE_STDARG_H)
1385 void gen_send(int sock, const char *fmt, ... )
1386 #else
1387 void gen_send(sock, fmt, va_alist)
1388 int sock;               /* socket to which server is connected */
1389 const char *fmt;        /* printf-style format */
1390 va_dcl
1391 #endif
1392 /* assemble command in printf(3) style and send to the server */
1393 {
1394     char buf [MSGBUFSIZE+1];
1395     va_list ap;
1396
1397     if (protocol->tagged && !suppress_tags)
1398         (void) sprintf(buf, "%s ", GENSYM);
1399     else
1400         buf[0] = '\0';
1401
1402 #if defined(HAVE_STDARG_H)
1403     va_start(ap, fmt);
1404 #else
1405     va_start(ap);
1406 #endif
1407 #ifdef HAVE_VSNPRINTF
1408     vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1409 #else
1410     vsprintf(buf + strlen(buf), fmt, ap);
1411 #endif
1412     va_end(ap);
1413
1414 #ifdef HAVE_SNPRINTF
1415     snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1416 #else
1417     strcat(buf, "\r\n");
1418 #endif /* HAVE_SNPRINTF */
1419     SockWrite(sock, buf, strlen(buf));
1420
1421     if (outlevel >= O_MONITOR)
1422     {
1423         enshroud(buf);
1424         buf[strlen(buf)-2] = '\0';
1425         report(stdout, "%s> %s\n", protocol->name, buf);
1426     }
1427 }
1428
1429 int gen_recv(sock, buf, size)
1430 /* get one line of input from the server */
1431 int sock;       /* socket to which server is connected */
1432 char *buf;      /* buffer to receive input */
1433 int size;       /* length of buffer */
1434 {
1435     int oldphase = phase;       /* we don't have to be re-entrant */
1436
1437     phase = SERVER_WAIT;
1438     set_timeout(mytimeout);
1439     if (SockRead(sock, buf, size) == -1)
1440     {
1441         set_timeout(0);
1442         phase = oldphase;
1443         return(PS_SOCKET);
1444     }
1445     else
1446     {
1447         set_timeout(0);
1448         if (buf[strlen(buf)-1] == '\n')
1449             buf[strlen(buf)-1] = '\0';
1450         if (buf[strlen(buf)-1] == '\r')
1451             buf[strlen(buf)-1] = '\0';
1452         if (outlevel >= O_MONITOR)
1453             report(stdout, "%s< %s\n", protocol->name, buf);
1454         phase = oldphase;
1455         return(PS_SUCCESS);
1456     }
1457 }
1458
1459 #if defined(HAVE_STDARG_H)
1460 int gen_transact(int sock, const char *fmt, ... )
1461 #else
1462 int gen_transact(int sock, fmt, va_alist)
1463 int sock;               /* socket to which server is connected */
1464 const char *fmt;        /* printf-style format */
1465 va_dcl
1466 #endif
1467 /* assemble command in printf(3) style, send to server, accept a response */
1468 {
1469     int ok;
1470     char buf [MSGBUFSIZE+1];
1471     va_list ap;
1472     int oldphase = phase;       /* we don't have to be re-entrant */
1473
1474     phase = SERVER_WAIT;
1475
1476     if (protocol->tagged && !suppress_tags)
1477         (void) sprintf(buf, "%s ", GENSYM);
1478     else
1479         buf[0] = '\0';
1480
1481 #if defined(HAVE_STDARG_H)
1482     va_start(ap, fmt) ;
1483 #else
1484     va_start(ap);
1485 #endif
1486 #ifdef HAVE_VSNPRINTF
1487     vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1488 #else
1489     vsprintf(buf + strlen(buf), fmt, ap);
1490 #endif
1491     va_end(ap);
1492
1493 #ifdef HAVE_SNPRINTF
1494     snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1495 #else
1496     strcat(buf, "\r\n");
1497 #endif /* HAVE_SNPRINTF */
1498     SockWrite(sock, buf, strlen(buf));
1499
1500     if (outlevel >= O_MONITOR)
1501     {
1502         enshroud(buf);
1503         buf[strlen(buf)-2] = '\0';
1504         report(stdout, "%s> %s\n", protocol->name, buf);
1505     }
1506
1507     /* we presume this does its own response echoing */
1508     ok = (protocol->parse_response)(sock, buf);
1509
1510     phase = oldphase;
1511     return(ok);
1512 }
1513
1514 /* transact.c ends here */