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