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