Testsuite: fix munge for mailq
[exim.git] / src / src / smtp_out.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2023 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
9
10 /* A number of functions for driving outgoing SMTP calls. */
11
12
13 #include "exim.h"
14 #include "transports/smtp.h"
15
16
17
18 /*************************************************
19 *           Find an outgoing interface           *
20 *************************************************/
21
22 /* This function is called from the smtp transport and also from the callout
23 code in verify.c. Its job is to expand a string to get a list of interfaces,
24 and choose a suitable one (IPv4 or IPv6) for the outgoing address.
25
26 Arguments:
27   istring    string interface setting, may be NULL, meaning "any", in
28                which case the function does nothing
29   host_af    AF_INET or AF_INET6 for the outgoing IP address
30   addr       the mail address being handled (for setting errors)
31   interface  point this to the interface if there is one defined
32   msg        to add to any error message
33
34 Returns:     TRUE on success, FALSE on failure, with error message
35                set in addr and transport_return set to PANIC
36 */
37
38 BOOL
39 smtp_get_interface(uschar *istring, int host_af, address_item *addr,
40   uschar **interface, uschar *msg)
41 {
42 const uschar * expint;
43 uschar *iface;
44 int sep = 0;
45
46 if (!istring) return TRUE;
47
48 if (!(expint = expand_string(istring)))
49   {
50   if (f.expand_string_forcedfail) return TRUE;
51   addr->transport_return = PANIC;
52   addr->message = string_sprintf("failed to expand \"interface\" "
53       "option for %s: %s", msg, expand_string_message);
54   return FALSE;
55   }
56
57 if (is_tainted(expint))
58   {
59   log_write(0, LOG_MAIN|LOG_PANIC,
60     "attempt to use tainted value '%s' from '%s' for interface",
61     expint, istring);
62   addr->transport_return = PANIC;
63   addr->message = string_sprintf("failed to expand \"interface\" "
64       "option for %s: configuration error", msg);
65   return FALSE;
66   }
67
68 Uskip_whitespace(&expint);
69 if (!*expint) return TRUE;
70
71 while ((iface = string_nextinlist(&expint, &sep, NULL, 0)))
72   {
73   int if_af = string_is_ip_address(iface, NULL);
74   if (if_af == 0)
75     {
76     addr->transport_return = PANIC;
77     addr->message = string_sprintf("\"%s\" is not a valid IP "
78       "address for the \"interface\" option for %s",
79       iface, msg);
80     return FALSE;
81     }
82
83   if ((if_af == 4 ? AF_INET : AF_INET6) == host_af)
84     break;
85   }
86
87 *interface = iface;
88 return TRUE;
89 }
90
91
92
93 /*************************************************
94 *           Find an outgoing port                *
95 *************************************************/
96
97 /* This function is called from the smtp transport and also from the callout
98 code in verify.c. Its job is to find a port number. Note that getservbyname()
99 produces the number in network byte order.
100
101 Arguments:
102   rstring     raw (unexpanded) string representation of the port
103   addr        the mail address being handled (for setting errors)
104   port        stick the port in here
105   msg         for adding to error message
106
107 Returns:      TRUE on success, FALSE on failure, with error message set
108                 in addr, and transport_return set to PANIC
109 */
110
111 BOOL
112 smtp_get_port(uschar *rstring, address_item *addr, int *port, uschar *msg)
113 {
114 uschar *pstring = expand_string(rstring);
115
116 if (!pstring)
117   {
118   addr->transport_return = PANIC;
119   addr->message = string_sprintf("failed to expand \"%s\" (\"port\" option) "
120     "for %s: %s", rstring, msg, expand_string_message);
121   return FALSE;
122   }
123
124 if (isdigit(*pstring))
125   {
126   uschar *end;
127   *port = Ustrtol(pstring, &end, 0);
128   if (end != pstring + Ustrlen(pstring))
129     {
130     addr->transport_return = PANIC;
131     addr->message = string_sprintf("invalid port number for %s: %s", msg,
132       pstring);
133     return FALSE;
134     }
135   }
136
137 else
138   {
139   struct servent *smtp_service = getservbyname(CS pstring, "tcp");
140   if (!smtp_service)
141     {
142     addr->transport_return = PANIC;
143     addr->message = string_sprintf("TCP port \"%s\" is not defined for %s",
144       pstring, msg);
145     return FALSE;
146     }
147   *port = ntohs(smtp_service->s_port);
148   }
149
150 return TRUE;
151 }
152
153
154
155
156 #ifdef TCP_FASTOPEN
157 /* Try to record if TFO was attmepted and if it was successfully used.  */
158
159 static void
160 tfo_out_check(int sock)
161 {
162 static BOOL done_once = FALSE;
163
164 if (done_once) return;
165 done_once = TRUE;
166
167 # ifdef __FreeBSD__
168 struct tcp_info tinfo;
169 socklen_t len = sizeof(tinfo);
170
171 /* A getsockopt TCP_FASTOPEN unfortunately returns "was-used" for a TFO/R as
172 well as a TFO/C.  Use what we can of the Linux hack below; reliability issues ditto. */
173 switch (tcp_out_fastopen)
174   {
175   case TFO_ATTEMPTED_NODATA:
176     if (  getsockopt(sock, IPPROTO_TCP, TCP_INFO, &tinfo, &len) == 0
177        && tinfo.tcpi_state == TCPS_SYN_SENT
178        && tinfo.__tcpi_unacked > 0
179        )
180       {
181       DEBUG(D_transport|D_v)
182        debug_printf("TCP_FASTOPEN tcpi_unacked %d\n", tinfo.__tcpi_unacked);
183       tcp_out_fastopen = TFO_USED_NODATA;
184       }
185     break;
186   /*
187   case TFO_ATTEMPTED_DATA:
188   case TFO_ATTEMPTED_DATA:
189        if (tinfo.tcpi_options & TCPI_OPT_SYN_DATA)   XXX no equvalent as of 12.2
190   */
191   }
192
193 switch (tcp_out_fastopen)
194   {
195   case TFO_ATTEMPTED_DATA:      tcp_out_fastopen = TFO_USED_DATA; break;
196   default: break; /* compiler quietening */
197   }
198
199 # else  /* Linux & Apple */
200 #  if defined(TCP_INFO) && defined(EXIM_HAVE_TCPI_UNACKED)
201 struct tcp_info tinfo;
202 socklen_t len = sizeof(tinfo);
203
204 switch (tcp_out_fastopen)
205   {
206     /* This is a somewhat dubious detection method; totally undocumented so likely
207     to fail in future kernels.  There seems to be no documented way.  What we really
208     want to know is if the server sent smtp-banner data before our ACK of his SYN,ACK
209     hit him.  What this (possibly?) detects is whether we sent a TFO cookie with our
210     SYN, as distinct from a TFO request.  This gets a false-positive when the server
211     key is rotated; we send the old one (which this test sees) but the server returns
212     the new one and does not send its SMTP banner before we ACK his SYN,ACK.
213      To force that rotation case:
214      '# echo -n "00000000-00000000-00000000-0000000" >/proc/sys/net/ipv4/tcp_fastopen_key'
215     The kernel seems to be counting unack'd packets. */
216
217   case TFO_ATTEMPTED_NODATA:
218     if (  getsockopt(sock, IPPROTO_TCP, TCP_INFO, &tinfo, &len) == 0
219        && tinfo.tcpi_state == TCP_SYN_SENT
220        && tinfo.tcpi_unacked > 1
221        )
222       {
223       DEBUG(D_transport|D_v)
224         debug_printf("TCP_FASTOPEN tcpi_unacked %d\n", tinfo.tcpi_unacked);
225       tcp_out_fastopen = TFO_USED_NODATA;
226       }
227     break;
228
229     /* When called after waiting for received data we should be able
230     to tell if data we sent was accepted. */
231
232   case TFO_ATTEMPTED_DATA:
233     if (  getsockopt(sock, IPPROTO_TCP, TCP_INFO, &tinfo, &len) == 0
234        && tinfo.tcpi_state == TCP_ESTABLISHED
235        )
236       if (tinfo.tcpi_options & TCPI_OPT_SYN_DATA)
237         {
238         DEBUG(D_transport|D_v) debug_printf("TFO: data was acked\n");
239         tcp_out_fastopen = TFO_USED_DATA;
240         }
241       else
242         {
243         DEBUG(D_transport|D_v) debug_printf("TFO: had to retransmit\n");
244         tcp_out_fastopen = TFO_NOT_USED;
245         }
246     break;
247
248   default: break; /* compiler quietening */
249   }
250 #  endif
251 # endif /* Linux & Apple */
252 }
253 #endif
254
255
256 /* Create and bind a socket, given the connect-args.
257 Update those with the state.  Return the fd, or -1 with errno set.
258 */
259
260 int
261 smtp_boundsock(smtp_connect_args * sc)
262 {
263 transport_instance * tb = sc->tblock;
264 smtp_transport_options_block * ob =
265   (smtp_transport_options_block *)tb->options_block;
266 const uschar * dscp = ob->dscp;
267 int sock, dscp_value, dscp_level, dscp_option;
268
269 if ((sock = ip_socket(SOCK_STREAM, sc->host_af)) < 0)
270   return -1;
271
272 /* Set TCP_NODELAY; Exim does its own buffering. */
273
274 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, US &on, sizeof(on)))
275   HDEBUG(D_transport|D_acl|D_v)
276     debug_printf_indent("failed to set NODELAY: %s ", strerror(errno));
277
278 /* Set DSCP value, if we can. For now, if we fail to set the value, we don't
279 bomb out, just log it and continue in default traffic class. */
280
281 GET_OPTION("dscp");
282 if (dscp && dscp_lookup(dscp, sc->host_af, &dscp_level, &dscp_option, &dscp_value))
283   {
284   HDEBUG(D_transport|D_acl|D_v)
285     debug_printf_indent("DSCP \"%s\"=%x ", dscp, dscp_value);
286   if (setsockopt(sock, dscp_level, dscp_option, &dscp_value, sizeof(dscp_value)) < 0)
287     HDEBUG(D_transport|D_acl|D_v)
288       debug_printf_indent("failed to set DSCP: %s ", strerror(errno));
289   /* If the kernel supports IPv4 and IPv6 on an IPv6 socket, we need to set the
290   option for both; ignore failures here */
291   if (sc->host_af == AF_INET6 &&
292       dscp_lookup(dscp, AF_INET, &dscp_level, &dscp_option, &dscp_value))
293     (void) setsockopt(sock, dscp_level, dscp_option, &dscp_value, sizeof(dscp_value));
294   }
295
296 /* Bind to a specific interface if requested. Caller must ensure the interface
297 is the same type (IPv4 or IPv6) as the outgoing address. */
298
299 if (sc->interface)
300   {
301   union sockaddr_46 interface_sock;
302   EXIM_SOCKLEN_T size = sizeof(interface_sock);
303
304   if (  ip_bind(sock, sc->host_af, sc->interface, 0) < 0
305      || getsockname(sock, (struct sockaddr *) &interface_sock, &size) < 0
306      )
307     {
308     HDEBUG(D_transport|D_acl|D_v)
309       debug_printf_indent("unable to bind outgoing SMTP call to %s: %s\n", sc->interface,
310         strerror(errno));
311     close(sock);
312     return -1;
313     }
314   sending_ip_address = host_ntoa(-1, &interface_sock, NULL, &sending_port);
315   }
316
317 sc->sock = sock;
318 return sock;
319 }
320
321
322 /* Arguments:
323   host        host item containing name and address and port
324   host_af     AF_INET or AF_INET6
325   port        TCP port number
326   interface   outgoing interface address or NULL
327   tb          transport
328   timeout     timeout value or 0
329   early_data    if non-NULL, idempotent data to be sent -
330                 preferably in the TCP SYN segment
331               Special case: non-NULL but with NULL blob.data - caller is
332               client-data-first (eg. TLS-on-connect) and a lazy-TCP-connect is
333               acceptable.
334
335 Returns:      connected socket number, or -1 with errno set
336 */
337
338 int
339 smtp_sock_connect(smtp_connect_args * sc, int timeout, const blob * early_data)
340 {
341 smtp_transport_options_block * ob =
342   (smtp_transport_options_block *)sc->tblock->options_block;
343 int sock;
344 int save_errno = 0;
345 const blob * fastopen_blob = NULL;
346
347
348 #ifndef DISABLE_EVENT
349 deliver_host_address = sc->host->address;
350 deliver_host_port = sc->host->port;
351 if (event_raise(sc->tblock->event_action, US"tcp:connect", NULL, &errno)) return -1;
352 #endif
353
354 if (  (sock = sc->sock) < 0
355    && (sock = smtp_boundsock(sc)) < 0)
356   save_errno = errno;
357 sc->sock = -1;
358
359 /* Connect to the remote host, and add keepalive to the socket before returning
360 it, if requested.  If the build supports TFO, request it - and if the caller
361 requested some early-data then include that in the TFO request.  If there is
362 early-data but no TFO support, send it after connecting. */
363
364 if (!save_errno)
365   {
366 #ifdef TCP_FASTOPEN
367   /* See if TCP Fast Open usable.  Default is a traditional 3WHS connect */
368   expand_level++;
369   if (verify_check_given_host(CUSS &ob->hosts_try_fastopen, sc->host) == OK)
370     {
371     if (!early_data)
372       fastopen_blob = &tcp_fastopen_nodata;     /* TFO, with no data */
373     else if (early_data->data)
374       fastopen_blob = early_data;               /* TFO, with data */
375 # ifdef TCP_FASTOPEN_CONNECT
376     else
377       {                                         /* expecting client data */
378       DEBUG(D_transport|D_acl|D_v) debug_printf(" set up lazy-connect\n");
379       setsockopt(sock, IPPROTO_TCP, TCP_FASTOPEN_CONNECT, US &on, sizeof(on));
380       /* fastopen_blob = NULL;           lazy TFO, triggered by data write */
381       }
382 # endif
383     }
384   expand_level--;
385 #endif
386
387   if (ip_connect(sock, sc->host_af, sc->host->address, sc->host->port, timeout, fastopen_blob) < 0)
388     save_errno = errno;
389   else if (early_data && !fastopen_blob && early_data->data && early_data->len)
390     {
391     /* We had some early-data to send, but couldn't do TFO */
392     HDEBUG(D_transport|D_acl|D_v)
393       debug_printf("sending %ld nonTFO early-data\n", (long)early_data->len);
394
395 #ifdef TCP_QUICKACK_notdef
396     (void) setsockopt(sock, IPPROTO_TCP, TCP_QUICKACK, US &off, sizeof(off));
397 #endif
398     if (send(sock, early_data->data, early_data->len, 0) < 0)
399       save_errno = errno;
400     }
401 #ifdef TCP_QUICKACK_notdef
402   /* Under TFO (with openssl & pipe-conn; testcase 4069, as of
403   5.10.8-100.fc32.x86_64) this seems to be inop.
404   Perhaps overwritten when we (client) go -> ESTABLISHED on seeing the 3rd-ACK?
405   For that case, added at smtp_reap_banner(). */
406   (void) setsockopt(sock, IPPROTO_TCP, TCP_QUICKACK, US &off, sizeof(off));
407 #endif
408   }
409
410 if (!save_errno)
411   {
412   union sockaddr_46 interface_sock;
413   EXIM_SOCKLEN_T size = sizeof(interface_sock);
414
415   /* Both bind() and connect() succeeded, and any early-data */
416
417   HDEBUG(D_transport|D_acl|D_v) debug_printf_indent("connected\n");
418   if (getsockname(sock, (struct sockaddr *)(&interface_sock), &size) == 0)
419     sending_ip_address = host_ntoa(-1, &interface_sock, NULL, &sending_port);
420   else
421     {
422     log_write(0, LOG_MAIN | ((errno == ECONNRESET)? 0 : LOG_PANIC),
423       "getsockname() failed: %s", strerror(errno));
424     close(sock);
425     return -1;
426     }
427
428   if (ob->keepalive) ip_keepalive(sock, sc->host->address, TRUE);
429 #ifdef TCP_FASTOPEN
430   tfo_out_check(sock);
431 #endif
432   return sock;
433   }
434
435 /* Either bind() or connect() failed */
436
437 HDEBUG(D_transport|D_acl|D_v)
438   {
439   debug_printf_indent(" failed: %s", CUstrerror(save_errno));
440   if (save_errno == ETIMEDOUT)
441     debug_printf(" (timeout=%s)", readconf_printtime(timeout));
442   debug_printf("\n");
443   }
444 (void)close(sock);
445 errno = save_errno;
446 return -1;
447 }
448
449
450
451
452
453 void
454 smtp_port_for_connect(host_item * host, int port)
455 {
456 if (host->port != PORT_NONE)
457   {
458   HDEBUG(D_transport|D_acl|D_v) if (port != host->port)
459     debug_printf_indent("Transport port=%d replaced by host-specific port=%d\n", port,
460       host->port);
461   port = host->port;
462   }
463 else host->port = port;    /* Set the port actually used */
464 }
465
466
467 /*************************************************
468 *           Connect to remote host               *
469 *************************************************/
470
471 /* Create a socket, and connect it to a remote host. IPv6 addresses are
472 detected by checking for a colon in the address. AF_INET6 is defined even on
473 non-IPv6 systems, to enable the code to be less messy. However, on such systems
474 host->address will always be an IPv4 address.
475
476 Arguments:
477   sc          details for making connection: host, af, interface, transport
478   early_data  if non-NULL, data to be sent - preferably in the TCP SYN segment
479               Special case: non-NULL but with NULL blob.data - caller is
480               client-data-first (eg. TLS-on-connect) and a lazy-TCP-connect is
481               acceptable.
482
483 Returns:      connected socket number, or -1 with errno set
484 */
485
486 int
487 smtp_connect(smtp_connect_args * sc, const blob * early_data)
488 {
489 int port = sc->host->port;
490 smtp_transport_options_block * ob = sc->ob;
491
492 callout_address = string_sprintf("[%s]:%d", sc->host->address, port);
493
494 HDEBUG(D_transport|D_acl|D_v)
495   {
496   uschar * s = US" ";
497   if (sc->interface) s = string_sprintf(" from %s ", sc->interface);
498 #ifdef SUPPORT_SOCKS
499   if (ob->socks_proxy) s = string_sprintf("%svia proxy ", s);
500 #endif
501   debug_printf_indent("Connecting to %s %s%s...\n", sc->host->name, callout_address, s);
502   }
503
504 /* Create and connect the socket */
505
506 #ifdef SUPPORT_SOCKS
507 if (ob->socks_proxy)
508   {
509   int sock = socks_sock_connect(sc->host, sc->host_af, port, sc->interface,
510                                 sc->tblock, ob->connect_timeout);
511   
512   if (sock >= 0)
513     {
514     if (early_data && early_data->data && early_data->len)
515       if (send(sock, early_data->data, early_data->len, 0) < 0)
516         {
517         int save_errno = errno;
518         HDEBUG(D_transport|D_acl|D_v)
519           {
520           debug_printf_indent("failed: %s", CUstrerror(save_errno));
521           if (save_errno == ETIMEDOUT)
522             debug_printf(" (timeout=%s)", readconf_printtime(ob->connect_timeout));
523           debug_printf("\n");
524           }
525         (void)close(sock);
526         sock = -1;
527         errno = save_errno;
528         }
529     }
530   return sock;
531   }
532 #endif
533
534 return smtp_sock_connect(sc, ob->connect_timeout, early_data);
535 }
536
537
538 /*************************************************
539 *        Flush outgoing command buffer           *
540 *************************************************/
541
542 /* This function is called only from smtp_write_command() below. It flushes
543 the buffer of outgoing commands. There is more than one in the buffer only when
544 pipelining.
545
546 Argument:
547   outblock   the SMTP output block
548   mode       further data expected, or plain
549
550 Returns:     TRUE if OK, FALSE on error, with errno set
551 */
552
553 static BOOL
554 flush_buffer(smtp_outblock * outblock, int mode)
555 {
556 int rc;
557 int n = outblock->ptr - outblock->buffer;
558 BOOL more = mode == SCMD_MORE;
559 client_conn_ctx * cctx;
560
561 HDEBUG(D_transport|D_acl) debug_printf_indent("cmd buf flush %d bytes%s\n", n,
562   more ? " (more expected)" : "");
563
564 if (!(cctx = outblock->cctx))
565   {
566   log_write(0, LOG_MAIN|LOG_PANIC, "null conn-context pointer");
567   errno = 0;
568   return FALSE;
569   }
570
571 #ifndef DISABLE_TLS
572 if (cctx->tls_ctx)              /*XXX have seen a null cctx here, rvfy sending QUIT, hence check above */
573   rc = tls_write(cctx->tls_ctx, outblock->buffer, n, more);
574 else
575 #endif
576
577   {
578   if (outblock->conn_args)
579     {
580     blob early_data = { .data = outblock->buffer, .len = n };
581
582     /* We ignore the more-flag if we're doing a connect with early-data, which
583     means we won't get BDAT+data. A pity, but wise due to the idempotency
584     requirement: TFO with data can, in rare cases, replay the data to the
585     receiver. */
586
587     if (  (cctx->sock = smtp_connect(outblock->conn_args, &early_data))
588        < 0)
589       return FALSE;
590     outblock->conn_args = NULL;
591     rc = n;
592     }
593   else
594     {
595     rc = send(cctx->sock, outblock->buffer, n,
596 #ifdef MSG_MORE
597               more ? MSG_MORE : 0
598 #else
599               0
600 #endif
601              );
602
603 #if defined(__linux__)
604     /* This is a workaround for a current linux kernel bug: as of
605     5.6.8-200.fc31.x86_64  small (<MSS) writes get delayed by about 200ms,
606     This is despite NODELAY being active.
607     https://bugzilla.redhat.com/show_bug.cgi?id=1803806 */
608
609     if (!more)
610       setsockopt(cctx->sock, IPPROTO_TCP, TCP_CORK, &off, sizeof(off));
611 #endif
612     }
613   }
614
615 if (rc <= 0)
616   {
617   HDEBUG(D_transport|D_acl) debug_printf_indent("send failed: %s\n", strerror(errno));
618   return FALSE;
619   }
620
621 outblock->ptr = outblock->buffer;
622 outblock->cmd_count = 0;
623 return TRUE;
624 }
625
626
627
628 /* This might be called both due to callout and then from delivery.
629 Use memory that will not be released between those phases.
630 */
631 static void
632 smtp_debug_resp(const uschar * buf)
633 {
634 #ifndef DISABLE_CLIENT_CMD_LOG
635 int old_pool = store_pool;
636 store_pool = POOL_PERM;
637 client_cmd_log = string_append_listele_n(client_cmd_log, ':', buf,
638   buf[3] == ' ' ? 3 : 4);
639 store_pool = old_pool;
640 #endif
641 }
642
643
644 /*************************************************
645 *             Write SMTP command                 *
646 *************************************************/
647
648 /* The formatted command is left in big_buffer so that it can be reflected in
649 any error message.
650
651 Arguments:
652   sx         SMTP connection, contains buffer for pipelining, and socket
653   mode       buffer, write-with-more-likely, write
654   format     a format, starting with one of
655              of HELO, MAIL FROM, RCPT TO, DATA, BDAT, ".", or QUIT.
656              If NULL, flush pipeline buffer only.
657   ...        data for the format
658
659 Returns:     0 if command added to pipelining buffer, with nothing transmitted
660             +n if n commands transmitted (may still have buffered the new one)
661             -1 on error, with errno set
662 */
663
664 int
665 smtp_write_command(void * sx, int mode, const char * format, ...)
666 {
667 smtp_outblock * outblock = &((smtp_context *)sx)->outblock;
668 int rc = 0;
669
670 if (format)
671   {
672   gstring gs = { .size = big_buffer_size, .ptr = 0, .s = big_buffer };
673   va_list ap;
674
675   /* Use taint-unchecked routines for writing into big_buffer, trusting that
676   we'll never expand the results.  Actually, the error-message use - leaving
677   the results in big_buffer for potential later use - is uncomfortably distant.
678   XXX Would be better to assume all smtp commands are short, use normal pool
679   alloc rather than big_buffer, and another global for the data-for-error. */
680
681   va_start(ap, format);
682   if (!string_vformat(&gs, SVFMT_TAINT_NOCHK, CS format, ap))
683     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "overlong write_command in outgoing "
684       "SMTP");
685   va_end(ap);
686
687   if (gs.ptr > outblock->buffersize)
688     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "overlong write_command in outgoing "
689       "SMTP");
690
691   if (gs.ptr > outblock->buffersize - (outblock->ptr - outblock->buffer))
692     {
693     rc = outblock->cmd_count;                 /* flush resets */
694     if (!flush_buffer(outblock, SCMD_FLUSH)) return -1;
695     }
696
697   Ustrncpy(outblock->ptr, gs.s, gs.ptr);
698   outblock->ptr += gs.ptr;
699   outblock->cmd_count++;
700   gs.ptr -= 2; string_from_gstring(&gs); /* remove \r\n for error message */
701
702   /* We want to hide the actual data sent in AUTH transactions from reflections
703   and logs. While authenticating, a flag is set in the outblock to enable this.
704   The AUTH command itself gets any data flattened. Other lines are flattened
705   completely. */
706
707   if (outblock->authenticating)
708     {
709     uschar * p = big_buffer;
710     if (Ustrncmp(big_buffer, "AUTH ", 5) == 0)
711       {
712       p += 5;
713       Uskip_whitespace(&p);
714       Uskip_nonwhite(&p);
715       Uskip_whitespace(&p);
716       }
717     while (*p) *p++ = '*';
718     }
719
720   smtp_debug_cmd(big_buffer, mode);
721   }
722
723 if (mode != SCMD_BUFFER)
724   {
725   rc += outblock->cmd_count;                /* flush resets */
726   if (!flush_buffer(outblock, mode)) return -1;
727   }
728
729 return rc;
730 }
731
732
733
734 /*************************************************
735 *          Read one line of SMTP response        *
736 *************************************************/
737
738 /* This function reads one line of SMTP response from the server host. This may
739 not be a complete response - it could be just part of a multiline response. We
740 have to use a buffer for incoming packets, because when pipelining or using
741 LMTP, there may well be more than one response in a single packet. This
742 function is called only from the one that follows.
743
744 Arguments:
745   inblock   the SMTP input block (contains holding buffer, socket, etc.)
746   buffer    where to put the line
747   size      space available for the line
748   timelimit deadline for reading the lime, seconds past epoch
749
750 Returns:    length of a line that has been put in the buffer
751             -1 otherwise, with errno set, and inblock->ptr adjusted
752 */
753
754 static int
755 read_response_line(smtp_inblock *inblock, uschar *buffer, int size, time_t timelimit)
756 {
757 uschar *p = buffer;
758 uschar *ptr = inblock->ptr;
759 uschar *ptrend = inblock->ptrend;
760 client_conn_ctx * cctx = inblock->cctx;
761
762 /* Loop for reading multiple packets or reading another packet after emptying
763 a previously-read one. */
764
765 for (;;)
766   {
767   int rc;
768
769   /* If there is data in the input buffer left over from last time, copy
770   characters from it until the end of a line, at which point we can return,
771   having removed any whitespace (which will include CR) at the end of the line.
772   The rules for SMTP say that lines end in CRLF, but there are have been cases
773   of hosts using just LF, and other MTAs are reported to handle this, so we
774   just look for LF. If we run out of characters before the end of a line,
775   carry on to read the next incoming packet. */
776
777   while (ptr < ptrend)
778     {
779     int c = *ptr++;
780     if (c == '\n')
781       {
782       while (p > buffer && isspace(p[-1])) p--;
783       *p = 0;
784       inblock->ptr = ptr;
785       return p - buffer;
786       }
787     *p++ = c;
788     if (--size < 4)
789       {
790       *p = 0;                     /* Leave malformed line for error message */
791       errno = ERRNO_SMTPFORMAT;
792       inblock->ptr = ptr;
793       return -1;
794       }
795     }
796
797   /* Need to read a new input packet. */
798
799   if((rc = ip_recv(cctx, inblock->buffer, inblock->buffersize, timelimit)) <= 0)
800     {
801     DEBUG(D_deliver|D_transport|D_acl|D_v)
802       debug_printf_indent(errno ? "  SMTP(%s)<<\n" : "  SMTP(closed)<<\n",
803         strerror(errno));
804     break;
805     }
806
807   /* Another block of data has been successfully read. Set up the pointers
808   and let the loop continue. */
809
810   ptrend = inblock->ptrend = inblock->buffer + rc;
811   ptr = inblock->buffer;
812   DEBUG(D_transport|D_acl) debug_printf_indent("read response data: size=%d\n", rc);
813   }
814
815 /* Get here if there has been some kind of recv() error; errno is set, but we
816 ensure that the result buffer is empty before returning. */
817
818 inblock->ptr = inblock->ptrend = inblock->buffer;
819 *buffer = 0;
820 return -1;
821 }
822
823
824
825
826
827 /*************************************************
828 *              Read SMTP response                *
829 *************************************************/
830
831 /* This function reads an SMTP response with a timeout, and returns the
832 response in the given buffer, as a string. A multiline response will contain
833 newline characters between the lines. The function also analyzes the first
834 digit of the reply code and returns FALSE if it is not acceptable. FALSE is
835 also returned after a reading error. In this case buffer[0] will be zero, and
836 the error code will be in errno.
837
838 Arguments:
839   sx        the SMTP connection (contains input block with holding buffer,
840                 socket, etc.)
841   buffer    where to put the response
842   size      the size of the buffer
843   okdigit   the expected first digit of the response
844   timeout   the timeout to use, in seconds
845
846 Returns:    TRUE if a valid, non-error response was received; else FALSE
847 */
848 /*XXX could move to smtp transport; no other users */
849
850 BOOL
851 smtp_read_response(void * sx0, uschar * buffer, int size, int okdigit,
852    int timeout)
853 {
854 smtp_context * sx = sx0;
855 uschar * ptr = buffer;
856 int count = 0;
857 time_t timelimit = time(NULL) + timeout;
858 BOOL yield = FALSE;
859
860 errno = 0;  /* Ensure errno starts out zero */
861 buffer[0] = '\0';
862
863 #ifndef DISABLE_PIPE_CONNECT
864 if (sx->pending_BANNER || sx->pending_EHLO)
865   {
866   int rc;
867   if ((rc = smtp_reap_early_pipe(sx, &count)) != OK)
868     {
869     DEBUG(D_transport) debug_printf("failed reaping pipelined cmd responsess\n");
870     if (rc == DEFER) errno = ERRNO_TLSFAILURE;
871     goto out;
872     }
873   }
874 #endif
875
876 /* This is a loop to read and concatenate the lines that make up a multi-line
877 response. */
878
879 for (;;)
880   {
881   if ((count = read_response_line(&sx->inblock, ptr, size, timelimit)) < 0)
882     return FALSE;
883
884   HDEBUG(D_transport|D_acl|D_v)
885     debug_printf_indent("  %s %s\n", ptr == buffer ? "SMTP<<" : "      ", ptr);
886
887   /* Check the format of the response: it must start with three digits; if
888   these are followed by a space or end of line, the response is complete. If
889   they are followed by '-' this is a multi-line response and we must look for
890   another line until the final line is reached. The only use made of multi-line
891   responses is to pass them back as error messages. We therefore just
892   concatenate them all within the buffer, which should be large enough to
893   accept any reasonable number of lines. */
894
895   if (count < 3 ||
896      !isdigit(ptr[0]) ||
897      !isdigit(ptr[1]) ||
898      !isdigit(ptr[2]) ||
899      (ptr[3] != '-' && ptr[3] != ' ' && ptr[3] != 0))
900     {
901     errno = ERRNO_SMTPFORMAT;    /* format error */
902     goto out;
903     }
904
905   /* If the line we have just read is a terminal line, line, we are done.
906   Otherwise more data has to be read. */
907
908   if (ptr[3] != '-') break;
909
910   /* Move the reading pointer upwards in the buffer and insert \n between the
911   components of a multiline response. Space is left for this by read_response_
912   line(). */
913
914   ptr += count;
915   *ptr++ = '\n';
916   size -= count + 1;
917   }
918
919 #ifdef TCP_FASTOPEN
920 tfo_out_check(sx->cctx.sock);
921 #endif
922
923 /* Return a value that depends on the SMTP return code. On some systems a
924 non-zero value of errno has been seen at this point, so ensure it is zero,
925 because the caller of this function looks at errno when FALSE is returned, to
926 distinguish between an unexpected return code and other errors such as
927 timeouts, lost connections, etc. */
928
929 errno = 0;
930 yield = buffer[0] == okdigit;
931
932 out:
933   smtp_debug_resp(buffer);
934   return yield;
935 }
936
937 /* End of smtp_out.c */
938 /* vi: aw ai sw=2
939 */