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