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