merge with latest
[external/uw-imap-toolkit.git] / imap-2007e / c-client / smtp.c
1 /* ========================================================================
2  * Copyright 1988-2008 University of Washington
3  * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd.
4
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * 
12  * ========================================================================
13  */
14
15 /*
16  * Program:     Simple Mail Transfer Protocol (SMTP) routines
17  *
18  * Author:      Mark Crispin
19  *              Networks and Distributed Computing
20  *              Computing & Communications
21  *              University of Washington
22  *              Administration Building, AG-44
23  *              Seattle, WA  98195
24  *              Internet: MRC@CAC.Washington.EDU
25  *
26  * Date:        27 July 1988
27  * Last Edited: 28 January 2008
28  *
29  * This original version of this file is
30  * Copyright 1988 Stanford University
31  * and was developed in the Symbolic Systems Resources Group of the Knowledge
32  * Systems Laboratory at Stanford University in 1987-88, and was funded by the
33  * Biomedical Research Technology Program of the National Institutes of Health
34  * under grant number RR-00785.
35  */
36
37
38 #include <ctype.h>
39 #include <stdio.h>
40 #include "c-client.h"
41 \f
42 /* Constants */
43
44 #define SMTPSSLPORT (long) 465  /* former assigned SSL TCP contact port */
45 #define SMTPGREET (long) 220    /* SMTP successful greeting */
46 #define SMTPAUTHED (long) 235   /* SMTP successful authentication */
47 #define SMTPOK (long) 250       /* SMTP OK code */
48 #define SMTPAUTHREADY (long) 334/* SMTP ready for authentication */
49 #define SMTPREADY (long) 354    /* SMTP ready for data */
50 #define SMTPSOFTFATAL (long) 421/* SMTP soft fatal code */
51 #define SMTPWANTAUTH (long) 505 /* SMTP authentication needed */
52 #define SMTPWANTAUTH2 (long) 530/* SMTP authentication needed */
53 #define SMTPUNAVAIL (long) 550  /* SMTP mailbox unavailable */
54 #define SMTPHARDERROR (long) 554/* SMTP miscellaneous hard failure */
55
56
57 /* Convenient access to protocol-specific data */
58
59 #define ESMTP stream->protocol.esmtp
60
61
62 /* Function prototypes */
63
64 void *smtp_challenge (void *s,unsigned long *len);
65 long smtp_response (void *s,char *response,unsigned long size);
66 long smtp_auth (SENDSTREAM *stream,NETMBX *mb,char *tmp);
67 long smtp_rcpt (SENDSTREAM *stream,ADDRESS *adr,long *error);
68 long smtp_send (SENDSTREAM *stream,char *command,char *args);
69 long smtp_reply (SENDSTREAM *stream);
70 long smtp_ehlo (SENDSTREAM *stream,char *host,NETMBX *mb);
71 long smtp_fake (SENDSTREAM *stream,char *text);
72 static long smtp_seterror (SENDSTREAM *stream,long code,char *text);
73 long smtp_soutr (void *stream,char *s);
74 \f
75 /* Mailer parameters */
76
77 static unsigned long smtp_maxlogintrials = MAXLOGINTRIALS;
78 static long smtp_port = 0;      /* default port override */
79 static long smtp_sslport = 0;
80
81
82 #ifndef RFC2821
83 #define RFC2821                 /* RFC 2821 compliance */
84 #endif
85
86 /* SMTP limits, current as of RFC 2821 */
87
88 #define SMTPMAXLOCALPART 64
89 #define SMTPMAXDOMAIN 255
90 #define SMTPMAXPATH 256
91
92
93 /* I have seen local parts of more than 64 octets, in spite of the SMTP
94  * limits.  So, we'll have a more generous limit that's still guaranteed
95  * not to pop the buffer, and let the server worry about it.  As of this
96  * writing, it comes out to 240.  Anyone with a mailbox name larger than
97  * that is in serious need of a life or at least a new ISP!  23 June 1998
98  */
99
100 #define MAXLOCALPART ((MAILTMPLEN - (SMTPMAXDOMAIN + SMTPMAXPATH + 32)) / 2)
101 \f
102 /* Mail Transfer Protocol manipulate driver parameters
103  * Accepts: function code
104  *          function-dependent value
105  * Returns: function-dependent return value
106  */
107
108 void *smtp_parameters (long function,void *value)
109 {
110   switch ((int) function) {
111   case SET_MAXLOGINTRIALS:
112     smtp_maxlogintrials = (unsigned long) value;
113     break;
114   case GET_MAXLOGINTRIALS:
115     value = (void *) smtp_maxlogintrials;
116     break;
117   case SET_SMTPPORT:
118     smtp_port = (long) value;
119     break;
120   case GET_SMTPPORT:
121     value = (void *) smtp_port;
122     break;
123   case SET_SSLSMTPPORT:
124     smtp_sslport = (long) value;
125     break;
126   case GET_SSLSMTPPORT:
127     value = (void *) smtp_sslport;
128     break;
129   default:
130     value = NIL;                /* error case */
131     break;
132   }
133   return value;
134 }
135 \f
136 /* Mail Transfer Protocol open connection
137  * Accepts: network driver
138  *          service host list
139  *          port number
140  *          service name
141  *          SMTP open options
142  * Returns: SEND stream on success, NIL on failure
143  */
144
145 SENDSTREAM *smtp_open_full (NETDRIVER *dv,char **hostlist,char *service,
146                             unsigned long port,long options)
147 {
148   SENDSTREAM *stream = NIL;
149   long reply;
150   char *s,tmp[MAILTMPLEN];
151   NETSTREAM *netstream;
152   NETMBX mb;
153   if (!(hostlist && *hostlist)) mm_log ("Missing SMTP service host",ERROR);
154                                 /* maximum domain name is 64 characters */
155   else do if (strlen (*hostlist) < SMTPMAXDOMAIN) {
156     sprintf (tmp,"{%.1000s}",*hostlist);
157     if (!mail_valid_net_parse_work (tmp,&mb,service ? service : "smtp") ||
158         mb.anoflag || mb.readonlyflag) {
159       sprintf (tmp,"Invalid host specifier: %.80s",*hostlist);
160       mm_log (tmp,ERROR);
161     }
162     else {                      /* light tryssl flag if requested */
163       mb.trysslflag = (options & SOP_TRYSSL) ? T : NIL;
164                                 /* explicit port overrides all */
165       if (mb.port) port = mb.port;
166                                 /* else /submit overrides port argument */
167       else if (!compare_cstring (mb.service,"submit")) {
168         port = SUBMITTCPPORT;   /* override port, use IANA name */
169         strcpy (mb.service,"submission");
170       }
171                                 /* else port argument overrides SMTP port */
172       else if (!port) port = smtp_port ? smtp_port : SMTPTCPPORT;
173       if (netstream =           /* try to open ordinary connection */
174           net_open (&mb,dv,port,
175                     (NETDRIVER *) mail_parameters (NIL,GET_SSLDRIVER,NIL),
176                     "*smtps",smtp_sslport ? smtp_sslport : SMTPSSLPORT)) {
177         stream = (SENDSTREAM *) memset (fs_get (sizeof (SENDSTREAM)),0,
178                                         sizeof (SENDSTREAM));
179         stream->netstream = netstream;
180         stream->host = cpystr ((long) mail_parameters (NIL,GET_TRUSTDNS,NIL) ?
181                                net_host (netstream) : mb.host);
182         stream->debug = (mb.dbgflag || (options & OP_DEBUG)) ? T : NIL;
183         if (options & SOP_SECURE) mb.secflag = T;
184                                 /* get name of local host to use */
185         s = compare_cstring ("localhost",mb.host) ?
186           net_localhost (netstream) : "localhost";
187
188         // SMTP GREETING
189         do reply = smtp_reply (stream);
190         while ((reply < 100) || (stream->reply[3] == '-'));
191         if (reply != SMTPGREET){/* get SMTP greeting */
192           sprintf (tmp,"SMTP greeting failure: %.80s",stream->reply);
193           mm_log (tmp,ERROR);
194           stream = smtp_close (stream);
195         }
196                                 /* try EHLO first, then HELO */
197         else if (((reply = smtp_ehlo (stream,s,&mb)) != SMTPOK) &&
198                  ((reply = smtp_send (stream,"HELO",s)) != SMTPOK)) {
199           sprintf (tmp,"SMTP hello failure: %.80s",stream->reply);
200           mm_log (tmp,ERROR);
201           stream = smtp_close (stream);
202         }
203         else {
204           NETDRIVER *ssld =(NETDRIVER *)mail_parameters(NIL,GET_SSLDRIVER,NIL);
205           sslstart_t stls = (sslstart_t) mail_parameters(NIL,GET_SSLSTART,NIL);
206           ESMTP.ok = T;         /* ESMTP server, start TLS if present */
207           if (!dv && stls && ESMTP.service.starttls &&
208               !mb.sslflag && !mb.notlsflag &&
209               (smtp_send (stream,"STARTTLS",NIL) == SMTPGREET)) {
210             mb.tlsflag = T;     /* TLS OK, get into TLS at this end */
211             stream->netstream->dtb = ssld;
212                                 /* TLS started, negotiate it */
213             if (!(stream->netstream->stream = (*stls)
214                   (stream->netstream->stream,mb.host,
215                    (mb.tlssslv23 ? NIL : NET_TLSCLIENT) |
216                    (mb.novalidate ? NET_NOVALIDATECERT:NIL)))){
217                                 /* TLS negotiation failed after STARTTLS */
218               sprintf (tmp,"Unable to negotiate TLS with this server: %.80s",
219                        mb.host);
220               mm_log (tmp,ERROR);
221                                 /* close without doing QUIT */
222               if (stream->netstream) net_close (stream->netstream);
223               stream->netstream = NIL;
224               stream = smtp_close (stream);
225             }
226                                 /* TLS OK, re-negotiate EHLO */
227             else if ((reply = smtp_ehlo (stream,s,&mb)) != SMTPOK) {
228               sprintf (tmp,"SMTP EHLO failure after STARTTLS: %.80s",
229                        stream->reply);
230               mm_log (tmp,ERROR);
231               stream = smtp_close (stream);
232             }
233             else ESMTP.ok = T;  /* TLS OK and EHLO successful */
234           }
235           else if (mb.tlsflag) {/* user specified /tls but can't do it */
236             sprintf (tmp,"TLS unavailable with this server: %.80s",mb.host);
237             mm_log (tmp,ERROR);
238             stream = smtp_close (stream);
239           }
240 \f
241                                 /* remote name for authentication */
242           if (stream && ((mb.secflag || mb.user[0]))) {
243             if (ESMTP.auth) {   /* use authenticator? */
244               if ((long) mail_parameters (NIL,GET_TRUSTDNS,NIL)) {
245                                 /* remote name for authentication */
246                 strncpy (mb.host,
247                          (long) mail_parameters (NIL,GET_SASLUSESPTRNAME,NIL) ?
248                          net_remotehost (netstream) : net_host (netstream),
249                          NETMAXHOST-1);
250                 mb.host[NETMAXHOST-1] = '\0';
251               }
252               if(mb.auth_method > 0) {
253                   if (!smtp_auth (stream,&mb,tmp)) stream = smtp_close (stream);
254               }
255             }
256             else {              /* no available authenticators? */
257               sprintf (tmp,"%sSMTP authentication not available: %.80s", mb.secflag ? "Secure " : "",mb.host);
258               mm_log (tmp,ERROR);
259               stream = smtp_close (stream);
260             }
261           }
262         }
263       }
264     }
265   } while (!stream && *++hostlist);
266   if (stream) {                 /* set stream options if have a stream */
267     if (options &(SOP_DSN | SOP_DSN_NOTIFY_FAILURE | SOP_DSN_NOTIFY_DELAY |
268                   SOP_DSN_NOTIFY_SUCCESS | SOP_DSN_RETURN_FULL)) {
269       ESMTP.dsn.want = T;
270       if (options & SOP_DSN_NOTIFY_FAILURE) ESMTP.dsn.notify.failure = T;
271       if (options & SOP_DSN_NOTIFY_DELAY) ESMTP.dsn.notify.delay = T;
272       if (options & SOP_DSN_NOTIFY_SUCCESS) ESMTP.dsn.notify.success = T;
273       if (options & SOP_DSN_RETURN_FULL) ESMTP.dsn.full = T;
274     }
275     if (options & SOP_8BITMIME) ESMTP.eightbit.want = T;
276   }
277   return stream;
278 }
279 \f
280 /* SMTP authenticate
281  * Accepts: stream to login
282  *          parsed network mailbox structure
283  *          scratch buffer
284  *          place to return user name
285  * Returns: T on success, NIL on failure
286  */
287
288 long smtp_auth (SENDSTREAM *stream,NETMBX *mb,char *tmp)
289 {
290   unsigned long trial,auths;
291   char *lsterr = NIL;
292   char usr[MAILTMPLEN];
293   AUTHENTICATOR *at;
294   long ret = NIL;
295
296   for (auths = ESMTP.auth, stream->saslcancel = NIL;
297        !ret && stream->netstream && auths &&
298        (at = mail_lookup_auth (find_rightmost_bit (&auths) + 1)); ) {
299
300     sprintf (tmp,"Trying using %s authentication. ", at->name);
301     mm_log (tmp,NIL);
302     if (lsterr) {               /* previous authenticator failed? */
303       sprintf (tmp,"Retrying using %s authentication after %.80s", at->name,lsterr);
304       mm_log (tmp,NIL);
305       fs_give ((void **) &lsterr);
306     }
307     trial = 0;                  /* initial trial count */
308     tmp[0] = '\0';              /* empty buffer */
309     if (stream->netstream) do {
310       if (lsterr) {
311         sprintf (tmp,"Retrying %s authentication after %.80s",at->name,lsterr);
312         mm_log (tmp,WARN);
313         fs_give ((void **) &lsterr);
314       }
315       stream->saslcancel = NIL;
316       if (smtp_send (stream,"AUTH",at->name) == SMTPAUTHREADY) {
317                                 /* hide client authentication responses */
318         if (!(at->flags & AU_SECURE)) stream->sensitive = T;
319         if ((*at->client) (smtp_challenge,smtp_response,"smtp",mb,stream,
320                            &trial,usr)) {
321           if (stream->replycode == SMTPAUTHED) {
322             ESMTP.auth = NIL;   /* disable authenticators */
323             ret = LONGT;
324           }
325                                 /* if main program requested cancellation */
326           else if (!trial) mm_log ("SMTP Authentication cancelled",ERROR);
327         }
328         stream->sensitive = NIL;/* unhide */
329       }
330           /* remember response if error and no cancel */
331       if (!ret && trial) lsterr = cpystr (stream->reply);
332     } while (!ret && stream->netstream && trial &&
333              (trial < smtp_maxlogintrials));
334   }
335   if (lsterr) {                 /* previous authenticator failed? */
336     if (!stream->saslcancel) {  /* don't do this if a cancel */
337       sprintf (tmp,"Can not authenticate to SMTP server: %.80s",lsterr);
338       mm_log (tmp,ERROR);
339     }
340     fs_give ((void **) &lsterr);
341   }
342   return ret;                   /* authentication failed */
343 }
344 \f
345 /* Get challenge to authenticator in binary
346  * Accepts: stream
347  *          pointer to returned size
348  * Returns: challenge or NIL if not challenge
349  */
350
351 void *smtp_challenge (void *s,unsigned long *len)
352 {
353   char tmp[MAILTMPLEN];
354   void *ret = NIL;
355   SENDSTREAM *stream = (SENDSTREAM *) s;
356   // for smtp.mail.yahoo.co.kr
357         if (!strcmp(stream->reply+4, "ok, go on")) {
358                 sprintf (tmp,"smtp_challenge : Server bug: non-empty initial PLAIN challenge 3: %.80s",stream->reply+4);
359                 mm_log (tmp,WARN);
360                 
361                 *len = 0;               // MUST BE
362                 return cpystr("ok, go on");
363         }
364         // for smtp.naver.com or other servers that reply only "THREE" response digit code whose string length is 3
365         if ( (stream->replycode == SMTPAUTHREADY) && 
366                 strlen(stream->reply) <= 3 )                            // only response digit code exists in the reply buffer
367         {
368                 *len = 0;
369                 return cpystr("");
370         }
371   if ((stream->replycode == SMTPAUTHREADY) &&
372       !(ret = rfc822_base64 ((unsigned char *) stream->reply + 4,
373                              strlen (stream->reply + 4),len))) {
374     sprintf (tmp,"SMTP SERVER BUG (invalid challenge): %.80s",stream->reply+4);
375     mm_log (tmp,ERROR);
376   }
377   return ret;
378 }
379
380
381 /* Send authenticator response in BASE64
382  * Accepts: MAIL stream
383  *          string to send
384  *          length of string
385  * Returns: T, always
386  */
387
388 long smtp_response (void *s,char *response,unsigned long size)
389 {
390   SENDSTREAM *stream = (SENDSTREAM *) s;
391   unsigned long i,j;
392   char *t,*u;
393
394   if (response) {               /* make CRLFless BASE64 string */
395     if (size) {
396       for (t = (char *) rfc822_binary ((void *) response,size,&i),u = t,j = 0;
397            j < i; j++) if (t[j] > ' ') *u++ = t[j];
398       *u = '\0';                /* tie off string */
399
400       i = smtp_send (stream,t,NIL);
401       fs_give ((void **) &t);
402     }
403     else
404     {
405         i = smtp_send (stream,"",NIL);
406     }
407   }
408   else {                        /* abort requested */
409     i = smtp_send (stream,"*",NIL);
410     stream->saslcancel = T;     /* mark protocol-requested SASL cancel */
411   }
412   return LONGT;
413 }
414 \f
415 /* Mail Transfer Protocol close connection
416  * Accepts: SEND stream
417  * Returns: NIL always
418  */
419
420 SENDSTREAM *smtp_close (SENDSTREAM *stream)
421 {
422   if (stream) {                 /* send "QUIT" */
423     if (stream->netstream) {    /* do close actions if have netstream */
424       smtp_send (stream,"QUIT",NIL);
425       if (stream->netstream)    /* could have been closed during "QUIT" */
426         net_close (stream->netstream);
427     }
428                                 /* clean up */
429     if (stream->host) fs_give ((void **) &stream->host);
430     if (stream->reply) fs_give ((void **) &stream->reply);
431     if (ESMTP.dsn.envid) fs_give ((void **) &ESMTP.dsn.envid);
432     if (ESMTP.atrn.domains) fs_give ((void **) &ESMTP.atrn.domains);
433     fs_give ((void **) &stream);/* flush the stream */
434   }
435   return NIL;
436 }
437 \f
438 /* Mail Transfer Protocol deliver mail
439  * Accepts: SEND stream
440  *          delivery option (MAIL, SEND, SAML, SOML)
441  *          message envelope
442  *          message body
443  * Returns: T on success, NIL on failure
444  */
445
446 long smtp_mail (SENDSTREAM *stream,char *type,ENVELOPE *env,BODY *body)
447 {
448   RFC822BUFFER buf;
449   char tmp[SENDBUFLEN+1];
450   long error = NIL;
451   long retry = NIL;
452   buf.f = smtp_soutr;           /* initialize buffer */
453   buf.s = stream->netstream;
454   buf.end = (buf.beg = buf.cur = tmp) + SENDBUFLEN;
455   tmp[SENDBUFLEN] = '\0';       /* must have additional null guard byte */
456   if (!(env->to || env->cc || env->bcc)) {
457                                 /* no recipients in request */
458     smtp_seterror (stream,SMTPHARDERROR,"No recipients specified");
459     return NIL;
460   }
461   do {                          /* make sure stream is in good shape */
462     smtp_send (stream,"RSET",NIL);
463     if (retry) {                /* need to retry with authentication? */
464       NETMBX mb;
465                                 /* yes, build remote name for authentication */
466       sprintf (tmp,"{%.200s/smtp%s}<none>",
467                (long) mail_parameters (NIL,GET_TRUSTDNS,NIL) ?
468                ((long) mail_parameters (NIL,GET_SASLUSESPTRNAME,NIL) ?
469                 net_remotehost (stream->netstream) :
470                 net_host (stream->netstream)) :
471                stream->host,
472                (stream->netstream->dtb ==
473                 (NETDRIVER *) mail_parameters (NIL,GET_SSLDRIVER,NIL)) ?
474                "/ssl" : "");
475       mail_valid_net_parse (tmp,&mb);
476       if (!smtp_auth (stream,&mb,tmp)) return NIL;
477       retry = NIL;              /* no retry at this point */
478     }
479 \f
480     strcpy (tmp,"FROM:<");      /* compose "MAIL FROM:<return-path>" */
481 #ifdef RFC2821
482     if (env->return_path && env->return_path->host &&
483         !((strlen (env->return_path->mailbox) > SMTPMAXLOCALPART) ||
484           (strlen (env->return_path->host) > SMTPMAXDOMAIN))) {
485       rfc822_cat (tmp,env->return_path->mailbox,NIL);
486       sprintf (tmp + strlen (tmp),"@%s",env->return_path->host);
487     }
488 #else                           /* old code with A-D-L support */
489     if (env->return_path && env->return_path->host &&
490         !((env->return_path->adl &&
491            (strlen (env->return_path->adl) > SMTPMAXPATH)) ||
492           (strlen (env->return_path->mailbox) > SMTPMAXLOCALPART) ||
493           (strlen (env->return_path->host) > SMTPMAXDOMAIN)))
494       rfc822_address (tmp,env->return_path);
495 #endif
496     strcat (tmp,">");
497     if (ESMTP.ok) {
498       if (ESMTP.eightbit.ok && ESMTP.eightbit.want)
499         strcat (tmp," BODY=8BITMIME");
500       if (ESMTP.dsn.ok && ESMTP.dsn.want) {
501         strcat (tmp,ESMTP.dsn.full ? " RET=FULL" : " RET=HDRS");
502         if (ESMTP.dsn.envid)
503           sprintf (tmp + strlen (tmp)," ENVID=%.100s",ESMTP.dsn.envid);
504       }
505     }
506                                 /* send "MAIL FROM" command */
507     switch (smtp_send (stream,type,tmp)) {
508     case SMTPUNAVAIL:           /* mailbox unavailable? */
509     case SMTPWANTAUTH:          /* wants authentication? */
510     case SMTPWANTAUTH2:
511       if (ESMTP.auth) retry = T;/* yes, retry with authentication */
512     case SMTPOK:                /* looks good */
513       break;
514     default:                    /* other failure */
515       return NIL;
516     }
517                                 /* negotiate the recipients */
518     if (!retry && env->to) retry = smtp_rcpt (stream,env->to,&error);
519     if (!retry && env->cc) retry = smtp_rcpt (stream,env->cc,&error);
520     if (!retry && env->bcc) retry = smtp_rcpt (stream,env->bcc,&error);
521     if (!retry && error) {      /* any recipients failed? */
522       smtp_send (stream,"RSET",NIL);
523       smtp_seterror (stream,SMTPHARDERROR,"One or more recipients failed");
524       return NIL;
525     }
526   } while (retry);
527                                 /* negotiate data command */
528   if (!(smtp_send (stream,"DATA",NIL) == SMTPREADY)) return NIL;
529                                 /* send message data */
530   if (!rfc822_output_full (&buf,env,body,
531                            ESMTP.eightbit.ok && ESMTP.eightbit.want)) {
532     smtp_fake (stream,"SMTP connection broken (message data)");
533     return NIL;                 /* can't do much else here */
534   }
535                                 /* send trailing dot */
536   return (smtp_send (stream,".",NIL) == SMTPOK) ? LONGT : NIL;
537 }
538 \f
539 /* Simple Mail Transfer Protocol send VERBose
540  * Accepts: SMTP stream
541  * Returns: T if successful, else NIL
542  *
543  * Descriptive text formerly in [al]pine sources:
544  * At worst, this command may cause the SMTP connection to get nuked.  Modern
545  * sendmail's recognize it, and possibly other SMTP implementations (the "ON"
546  * arg is for PMDF).  What's more, if it works, the reply code and accompanying
547  * text may vary from server to server.
548  */
549
550 long smtp_verbose (SENDSTREAM *stream)
551 {
552                                 /* accept any 2xx reply code */
553   return ((smtp_send (stream,"VERB","ON") / (long) 100) == 2) ? LONGT : NIL;
554 }
555 \f
556 /* Internal routines */
557
558
559 /* Simple Mail Transfer Protocol send recipient
560  * Accepts: SMTP stream
561  *          address list
562  *          pointer to error flag
563  * Returns: T if should retry, else NIL
564  */
565
566 long smtp_rcpt (SENDSTREAM *stream,ADDRESS *adr,long *error)
567 {
568  char *s,tmp[2*MAILTMPLEN],orcpt[MAILTMPLEN];
569   while (adr) {                 /* for each address on the list */
570                                 /* clear any former error */
571     if (adr->error) fs_give ((void **) &adr->error);
572     if (adr->host) {            /* ignore group syntax */
573                                 /* enforce SMTP limits to protect the buffer */
574       if (strlen (adr->mailbox) > MAXLOCALPART) {
575         adr->error = cpystr ("501 Recipient name too long");
576         *error = T;
577       }
578       else if ((strlen (adr->host) > SMTPMAXDOMAIN)) {
579         adr->error = cpystr ("501 Recipient domain too long");
580         *error = T;
581       }
582 #ifndef RFC2821                 /* old code with A-D-L support */
583       else if (adr->adl && (strlen (adr->adl) > SMTPMAXPATH)) {
584         adr->error = cpystr ("501 Path too long");
585         *error = T;
586       }
587 #endif
588 \f
589       else {
590         strcpy (tmp,"TO:<");    /* compose "RCPT TO:<return-path>" */
591 #ifdef RFC2821
592         rfc822_cat (tmp,adr->mailbox,NIL);
593         sprintf (tmp + strlen (tmp),"@%s>",adr->host);
594 #else                           /* old code with A-D-L support */
595         rfc822_address (tmp,adr);
596         strcat (tmp,">");
597 #endif
598                                 /* want notifications */
599         if (ESMTP.ok && ESMTP.dsn.ok && ESMTP.dsn.want) {
600                                 /* yes, start with prefix */
601           strcat (tmp," NOTIFY=");
602           s = tmp + strlen (tmp);
603           if (ESMTP.dsn.notify.failure) strcat (s,"FAILURE,");
604           if (ESMTP.dsn.notify.delay) strcat (s,"DELAY,");
605           if (ESMTP.dsn.notify.success) strcat (s,"SUCCESS,");
606                                 /* tie off last comma */
607           if (*s) s[strlen (s) - 1] = '\0';
608           else strcat (tmp,"NEVER");
609           if (adr->orcpt.addr) {
610             sprintf (orcpt,"%.498s;%.498s",
611                      adr->orcpt.type ? adr->orcpt.type : "rfc822",
612                      adr->orcpt.addr);
613             sprintf (tmp + strlen (tmp)," ORCPT=%.500s",orcpt);
614           }
615         }
616         switch (smtp_send (stream,"RCPT",tmp)) {
617         case SMTPOK:            /* looks good */
618           break;
619         case SMTPUNAVAIL:       /* mailbox unavailable? */
620         case SMTPWANTAUTH:      /* wants authentication? */
621         case SMTPWANTAUTH2:
622           if (ESMTP.auth) return T;
623         default:                /* other failure */
624           *error = T;           /* note that an error occurred */
625           adr->error = cpystr (stream->reply);
626         }
627       }
628     }
629     adr = adr->next;            /* do any subsequent recipients */
630   }
631   return NIL;                   /* no retry called for */
632 }
633 \f
634 /* Simple Mail Transfer Protocol send command
635  * Accepts: SEND stream
636  *          text
637  * Returns: reply code
638  */
639
640 long smtp_send (SENDSTREAM *stream,char *command,char *args)
641 {
642   long ret;
643   char *s = (char *) fs_get (strlen (command) + (args ? strlen (args) + 1 : 0)
644                              + 3);
645                                 /* build the complete command */
646   if (args) sprintf (s,"%s %s",command,args);
647   else strcpy (s,command);
648
649   if (stream->debug) mail_dlog (s,stream->sensitive);
650   strcat (s,"\015\012");
651                                 /* send the command */
652   if (stream->netstream && net_soutr (stream->netstream,s)) {
653     do stream->replycode = smtp_reply (stream);
654     while ((stream->replycode < 100) || (stream->reply[3] == '-'));
655     ret = stream->replycode;
656   }
657   else ret = smtp_fake (stream,"SMTP connection broken (command)");
658   fs_give ((void **) &s);
659   return ret;
660 }
661
662
663 /* Simple Mail Transfer Protocol get reply
664  * Accepts: SMTP stream
665  * Returns: reply code
666  */
667
668 long smtp_reply (SENDSTREAM *stream)
669 {
670   smtpverbose_t pv = (smtpverbose_t) mail_parameters (NIL,GET_SMTPVERBOSE,NIL);
671   long reply;
672                                 /* flush old reply */
673   if (stream->reply) fs_give ((void **) &stream->reply);
674                                 /* get reply */
675   if (stream->netstream && (stream->reply = net_getline (stream->netstream))) {
676     if (stream->debug) mm_dlog (stream->reply);
677                                 /* return response code */
678     reply = atol (stream->reply);
679     if (pv && (reply < 100)) (*pv) (stream->reply);
680   }
681   else reply = smtp_fake (stream,"SMTP connection broken (reply)");
682   return reply;
683 }
684 \f
685 /* Simple Mail Transfer Protocol send EHLO
686  * Accepts: SMTP stream
687  *          host name to use in EHLO
688  *          NETMBX structure
689  * Returns: reply code
690  */
691
692 long smtp_ehlo (SENDSTREAM *stream,char *host,NETMBX *mb)
693 {
694   unsigned long i,j;
695   long flags = (mb->secflag ? AU_SECURE : NIL) |
696     (mb->authuser[0] ? AU_AUTHUSER : NIL);
697   char *s,*t,*r,tmp[MAILTMPLEN];
698                                 /* clear ESMTP data */
699   memset (&ESMTP,0,sizeof (ESMTP));
700   if (mb->loser) return 500;    /* never do EHLO if a loser */
701   sprintf (tmp,"EHLO %s",host); /* build the complete command */
702   if (stream->debug) mm_dlog (tmp);
703   strcat (tmp,"\015\012");
704                                 /* send the command */
705   if (!net_soutr (stream->netstream,tmp))
706     return smtp_fake (stream,"SMTP connection broken (EHLO)");
707                                 /* got an OK reply? */
708   do if ((i = smtp_reply (stream)) == SMTPOK) {
709                                 /* hack for AUTH= */
710     if (stream->reply[4] && stream->reply[5] && stream->reply[6] &&
711         stream->reply[7] && (stream->reply[8] == '=')) stream->reply[8] = ' ';
712                                 /* get option code */
713     if (!(s = strtok_r (stream->reply+4," ",&r)));
714                                 /* have option, does it have a value */
715     else if ((t = strtok_r (NIL," ",&r)) && *t) {
716                                 /* EHLO options which take arguments */
717       if (!compare_cstring (s,"SIZE")) {
718         if (isdigit (*t)) ESMTP.size.limit = strtoul (t,&t,10);
719         ESMTP.size.ok = T;
720       }
721       else if (!compare_cstring (s,"DELIVERBY")) {
722         if (isdigit (*t)) ESMTP.deliverby.minby = strtoul (t,&t,10);
723         ESMTP.deliverby.ok = T;
724       }
725       else if (!compare_cstring (s,"ATRN")) {
726         ESMTP.atrn.domains = cpystr (t);
727         ESMTP.atrn.ok = T;
728       }
729       else if (!compare_cstring (s,"AUTH"))
730         do if ((j = mail_lookup_auth_name (t,flags)) &&
731        (--j < MAXAUTHENTICATORS)) ESMTP.auth |= (1 << j);
732         while ((t = strtok_r (NIL," ",&r)) && *t);
733     }
734                                 /* EHLO options which do not take arguments */
735     else if (!compare_cstring (s,"SIZE")) ESMTP.size.ok = T;
736     else if (!compare_cstring (s,"8BITMIME")) ESMTP.eightbit.ok = T;
737     else if (!compare_cstring (s,"DSN")) ESMTP.dsn.ok = T;
738     else if (!compare_cstring (s,"ATRN")) ESMTP.atrn.ok = T;
739     else if (!compare_cstring (s,"SEND")) ESMTP.service.send = T;
740     else if (!compare_cstring (s,"SOML")) ESMTP.service.soml = T;
741     else if (!compare_cstring (s,"SAML")) ESMTP.service.saml = T;
742     else if (!compare_cstring (s,"EXPN")) ESMTP.service.expn = T;
743     else if (!compare_cstring (s,"HELP")) ESMTP.service.help = T;
744     else if (!compare_cstring (s,"TURN")) ESMTP.service.turn = T;
745     else if (!compare_cstring (s,"ETRN")) ESMTP.service.etrn = T;
746     else if (!compare_cstring (s,"STARTTLS")) ESMTP.service.starttls = T;
747     else if (!compare_cstring (s,"RELAY")) ESMTP.service.relay = T;
748     else if (!compare_cstring (s,"PIPELINING")) ESMTP.service.pipe = T;
749     else if (!compare_cstring (s,"ENHANCEDSTATUSCODES"))
750       ESMTP.service.ensc = T;
751     else if (!compare_cstring (s,"BINARYMIME")) ESMTP.service.bmime = T;
752     else if (!compare_cstring (s,"CHUNKING")) ESMTP.service.chunk = T;
753   }
754   while ((i < 100) || (stream->reply[3] == '-'));
755                                 /* disable LOGIN if PLAIN also advertised */
756   /*
757   if ((j = mail_lookup_auth_name ("PLAIN",NIL)) && (--j < MAXAUTHENTICATORS) &&
758       (ESMTP.auth & (1 << j)) &&
759       (j = mail_lookup_auth_name ("LOGIN",NIL)) && (--j < MAXAUTHENTICATORS))
760     ESMTP.auth &= ~(1 << j);
761    */
762   return i;                     /* return the response code */
763 }
764 \f
765 /* Simple Mail Transfer Protocol set fake error and abort
766  * Accepts: SMTP stream
767  *          error text
768  * Returns: SMTPSOFTFATAL, always
769  */
770
771 long smtp_fake (SENDSTREAM *stream,char *text)
772 {
773   if (stream->netstream) {      /* close net connection if still open */
774     net_close (stream->netstream);
775     stream->netstream = NIL;
776   }
777                                 /* set last error */
778   return smtp_seterror (stream,SMTPSOFTFATAL,text);
779 }
780
781
782 /* Simple Mail Transfer Protocol set error
783  * Accepts: SMTP stream
784  *          SMTP error code
785  *          error text
786  * Returns: error code
787  */
788
789 static long smtp_seterror (SENDSTREAM *stream,long code,char *text)
790 {
791                                 /* flush any old reply */
792   if (stream->reply ) fs_give ((void **) &stream->reply);
793                                 /* set up pseudo-reply string */
794   stream->reply = (char *) fs_get (20+strlen (text));
795   sprintf (stream->reply,"%ld %s",code,text);
796   return code;                  /* return error code */
797 }
798
799
800 #ifdef __FEATURE_SEND_OPTMIZATION__
801 /* Simple Mail Transfer Protocol filter mail
802  * Accepts: stream
803  *          string
804  * Returns: T on success, NIL on failure
805  */
806 __attribute__((visibility("default"))) long smtp_soutr_test (void *stream, char *s)
807 {
808         char *c,*t;
809
810         /* "." on first line */
811
812         if (s[0] == '.') 
813                 net_sout (stream,".",1);        /* find lines beginning with a "." */
814
815         c = s;
816
817         while (t = strstr (c,"\015\012.")) 
818         {
819                 t += 2;         /* Increment the end point */   
820                 
821                 /* Pump minimum of 8K data */
822                 if((t-s) > 8192)                
823                 {
824                         if (!net_sout (stream,s,t-s)) /* output prefix */
825                                 return NIL;
826                         c = s = t; /* Move search as well as data pointer ahead */
827                 }
828                 else
829                 {       
830                         c = t;  /* Move the serach pointer ahead "." */
831                 }       
832         }               
833                 /* output remainder of text */
834         return *s ? net_soutr (stream,s) : T;
835
836 }
837 #endif
838
839 /* Simple Mail Transfer Protocol filter mail
840  * Accepts: stream
841  *          string
842  * Returns: T on success, NIL on failure
843  */
844
845 long smtp_soutr (void *stream,char *s)
846 {
847   char c,*t;
848                                 /* "." on first line */
849   if (s[0] == '.') net_sout (stream,".",1);
850                                 /* find lines beginning with a "." */
851   while (t = strstr (s,"\015\012.")) {
852     c = *(t += 3);              /* remember next character after "." */
853     *t = '\0';                  /* tie off string */
854                                 /* output prefix */
855     if (!net_sout (stream,s,t-s)) return NIL;
856     *t = c;                     /* restore delimiter */
857     s = t - 1;                  /* push pointer up to the "." */
858   }
859                                 /* output remainder of text */
860   return *s ? net_soutr (stream,s) : T;
861 }