File: client.c

package info (click to toggle)
dspam 3.10.1+dfsg-11
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 6,656 kB
  • sloc: ansic: 26,034; sh: 12,546; perl: 5,469; makefile: 690; sql: 379
file content (967 lines) | stat: -rw-r--r-- 23,045 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
/* $Id: client.c,v 1.691 2011/06/28 00:13:48 sbajic Exp $ */

/*
 DSPAM
 COPYRIGHT (C) 2002-2011 DSPAM PROJECT

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

/*
 * client.c - client-based functions (for operating in client/daemon mode)c
 *
 * DESCRIPTION
 *   Client-based functions are called when --client is specified on the
 *   commandline or by dspamc (where --client is inferred). The client
 *   functions connect to a DSPAM server for processing (rather than the
 *   usual behavior which is to process the message itself). Client
 *   functions are also used when delivering via LMTP or SMTP.
 */

#ifdef HAVE_CONFIG_H
#include <auto-config.h>
#endif

#ifdef DAEMON

#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <error.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#ifndef _WIN32
#include <unistd.h>
#include <pwd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <sysexits.h>

#include "client.h"
#include "dspam.h"
#include "config.h"
#include "util.h"
#include "language.h"
#include "buffer.h"

/*
 * client_process(AGENT_CTX *, buffer *)
 *
 * DESCRIPTION
 *   connect to a dspam daemon socket and attempt to process a message
 *   this function is called by the dspam agent when --client is specified
 *
 * INPUT ARGUMENTS
 *      ATX     	agent context
 *      message		message to be processed
 *
 * RETURN VALUES
 *   returns 0 on success
*/

int client_process(AGENT_CTX *ATX, buffer *message) {
  char buf[1024], err[256];
  struct nt_node *node_nt;
  struct nt_c c_nt;
  int exitcode = 0, msglen;
  THREAD_CTX TTX;
  int i;

  TTX.sockfd = client_connect(ATX, 0);
  if (TTX.sockfd <0) {
    LOG(LOG_WARNING, ERR_CLIENT_CONNECT);
    STATUS(ERR_CLIENT_CONNECT);
    return TTX.sockfd;
  }

  TTX.packet_buffer = buffer_create(NULL);
  if (TTX.packet_buffer == NULL) 
    goto BAIL;

  /* LHLO / MAIL FROM - Authenticate on the server */

  if (client_authenticate(&TTX, ATX->client_args)<0) {
    LOG(LOG_WARNING, ERR_CLIENT_AUTH_FAILED);
    STATUS(ERR_CLIENT_AUTH_FAILED);
    goto QUIT;
  }

  /* RCPT TO - Send recipient information */

  strcpy(buf, "RCPT TO: ");
  node_nt = c_nt_first(ATX->users, &c_nt);
  while(node_nt != NULL) {
    const char *ptr = (const char *) node_nt->ptr;
    snprintf(buf, sizeof(buf), "RCPT TO: <%s>", ptr);
    if (send_socket(&TTX, buf)<=0) {
      STATUS(ERR_CLIENT_SEND_FAILED);
      goto BAIL;
    }

    if (client_getcode(&TTX, err, sizeof(err))!=LMTP_OK) {
      STATUS("%s", err);
      goto QUIT;
    }

    node_nt = c_nt_next(ATX->users, &c_nt);
  }

  /* DATA - Send message */

  if (send_socket(&TTX, "DATA")<=0) 
    goto BAIL;

  if (client_getcode(&TTX, err, sizeof(err))!=LMTP_DATA) {
    STATUS("%s", err);
    goto QUIT;
  }

  i = 0;
  msglen = strlen(message->data);
  while(i<msglen) {
    int r;
    int t;
    int buflen;

    /*
     * fill buf with partial msg, replacing \n with \r\n
     * and do dot stuffing, if needed.
     */
    buflen = 0;
    while ((size_t)buflen < (sizeof(buf) - 4) && i < msglen) {
      if (i > 0) {
        if (message->data[i] == '\n') {
          /* only replace \n and not \r\n */
          if (message->data[i - 1] != '\r') {
            buf[buflen] = '\r';
            buflen++;
          }
          /* take care of dot stuffing \n */
          if (message->data[i + 1] && message->data[i + 1] == '.') {
            buf[buflen] = '\n';
            buflen++;
            buf[buflen] = '.';
            buflen++;
            buf[buflen] = '.';
            buflen++;
            i += 2;
            continue;
          }
        }
      }

      buf[buflen] = message->data[i];
      buflen++;
      i++;
    }

    /* send buf */
    t = 0;
    while (t < buflen) {
      r = send(TTX.sockfd, buf+t, buflen - t, 0);
      if (r <= 0) {
        LOG(LOG_ERR, ERR_CLIENT_SEND_FAILED);
        STATUS(ERR_CLIENT_SEND_FAILED);
        goto BAIL;
      }
      t += r;
    }
  }

  if (message->data[msglen-1]!= '\n') {
    if (send_socket(&TTX, "")<=0) {
     STATUS(ERR_CLIENT_SEND_FAILED);
     goto BAIL;
    }
  }

  if (send_socket(&TTX, ".")<=0) {
    STATUS(ERR_CLIENT_SEND_FAILED);
    goto BAIL;
  }

  /* Server response */

  if (ATX->flags & DAF_STDOUT || ATX->flags & DAF_SUMMARY ||
      ATX->operating_mode == DSM_CLASSIFY) 
   {
    char *line = NULL;
    int head = !(ATX->flags & DAF_STDOUT);

    if (ATX->flags & DAF_SUMMARY)
      head = 1;

    line = client_getline(&TTX, 300);

    while(line != NULL && strcmp(line, ".")) {
      chomp(line);
      if (!head) {
        head = 1;
        if (!strncmp(line, "250 ", 4)) {
          free(line);
          goto QUIT;
        }

        if (!strcmp(line, "X-Daemon-Classification: SPAM") && 
            _ds_match_attribute(agent_config, "Broken", "returnCodes")) 
        {
          exitcode = 99;
        }
      } else {
        printf("%s\n", line);
      } 
      free(line);
      line = client_getline(&TTX, 300);
      if (line) chomp(line);
    }
    free(line);
  } else {
    for(i=0;i<ATX->users->items;i++) {
      char *input = client_getline(&TTX, 300);
      char *x;
      int code = 500;

      if (!input) {
        goto BAIL;
      }
      x = strtok(input, " ");
      if (x) {
        code = atoi(x);
        if (code != LMTP_OK) {
          if (exitcode > 0) 
            exitcode = 0;
          exitcode--;
        } else {
          if (_ds_match_attribute(agent_config, "Broken", "returnCodes")) {
            x = strtok(NULL, ":");
            if (x)
              x = strtok(NULL, ":");
            if (x && strstr(x, "SPAM") && exitcode == 0)
              exitcode = 99;
          }
        }
      }
    }
  }

  send_socket(&TTX, "QUIT");
  client_getcode(&TTX, err, sizeof(err));
  close(TTX.sockfd);
  buffer_destroy(TTX.packet_buffer);
  return exitcode;

QUIT:
  send_socket(&TTX, "QUIT");
  client_getcode(&TTX, err, sizeof(err));

BAIL:
  exitcode = EFAILURE;
  buffer_destroy(TTX.packet_buffer);
  close(TTX.sockfd);
  return exitcode;
}

/*
 * client_connect(AGENT_CTX ATX, int flags)
 *
 * DESCRIPTION
 *   establish a connection to a server
 *
 * INPUT ARGUMENTS
 *      ATX             agent context
 *      flags		connection flags
 *
 * FLAGS
 *    CCF_PROCESS     Use ClientHost as destination
 *    CCF_DELIVERY    Use DeliveryHost as destination
 *
 *  RETURN VALUES
 *    returns 0 on success
 */

int client_connect(AGENT_CTX *ATX, int flags) {
  struct sockaddr_in addr;
  struct sockaddr_un saun;
  int sockfd;
  int yes = 1;
  int port = 24;
  int domain = 0;
  int addr_len;
  char *host;

  if (flags & CCF_DELIVERY) {
    host = _ds_read_attribute(agent_config, "DeliveryHost");

    if (_ds_read_attribute(agent_config, "DeliveryPort"))
      port = atoi(_ds_read_attribute(agent_config, "DeliveryPort"));

    if (ATX->recipient && ATX->recipient[0]) {
      char *domain = strchr(ATX->recipient, '@');
      if (domain) {
        char key[128];
        char lcdomain[strlen(ATX->recipient)];
        lc(lcdomain, domain+1);
        snprintf(key, sizeof(key), "DeliveryHost.%s", lcdomain);
        if (_ds_read_attribute(agent_config, key))
          host = _ds_read_attribute(agent_config, key);
        snprintf(key, sizeof(key), "DeliveryPort.%s", lcdomain);
        if (_ds_read_attribute(agent_config, key))
          port = atoi(_ds_read_attribute(agent_config, key));
      }
    }

    if (host && host[0] == '/') 
      domain = 1;

  } else {
    host = _ds_read_attribute(agent_config, "ClientHost");

    if (_ds_read_attribute(agent_config, "ClientPort"))
      port = atoi(_ds_read_attribute(agent_config, "ClientPort"));

    if (host && host[0] == '/')
      domain = 1;
  }

  if (host == NULL) {
    LOG(LOG_CRIT, ERR_CLIENT_INVALID_CONFIG);
    STATUS(ERR_CLIENT_INVALID_CONFIG);
    return EINVAL;
  }

  /* Connect (domain socket) */

  if (domain) {
    sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
    saun.sun_family = AF_UNIX;
    strcpy(saun.sun_path, host);
    addr_len = sizeof(saun.sun_family) + strlen(saun.sun_path) + 1;

    LOGDEBUG(INFO_CLIENT_CONNECTING, host, 0);
    if(connect(sockfd, (struct sockaddr *)&saun, addr_len)<0) {
      LOG(LOG_ERR, ERR_CLIENT_CONNECT_SOCKET, host, strerror(errno));
      STATUS("%s", strerror(errno));
      close(sockfd);
      return EFAILURE;
    }

  /* Connect (TCP socket) */

  } else {
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&addr, 0, sizeof(struct sockaddr_in));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(host);
    addr.sin_port = htons(port);
    addr_len = sizeof(struct sockaddr_in);
    LOGDEBUG(INFO_CLIENT_CONNECTING, host, port);
    if(connect(sockfd, (struct sockaddr *)&addr, addr_len)<0) {
      LOG(LOG_ERR, ERR_CLIENT_CONNECT_HOST, host, port, strerror(errno));
      STATUS("%s", strerror(errno));
      close(sockfd);
      return EFAILURE;
    }
  }

  LOGDEBUG(INFO_CLIENT_CONNECTED);
  setsockopt(sockfd,SOL_SOCKET,TCP_NODELAY,&yes,sizeof(int));

  return sockfd;
}

/*
 * client_authenticate(AGENT_CTX *ATX, const char *mode)
 *
 * DESCRIPTION
 *   greet and authenticate on a server
 *
 * INPUT ARGUMENTS
 *      ATX             agent context
 *      mode		processing mode
 *
 * NOTES
 *   the process mode is passed using the DSPAMPROCESSMODE service tag
 *
 * RETURN VALUES
 *   returns 0 on success
 */

int client_authenticate(THREAD_CTX *TTX, const char *mode) {
  char *ident = _ds_read_attribute(agent_config, "ClientIdent");
  char buf[1024], err[128];
  char *ptr;
  char pmode[1024];

  pmode[0] = 0;
  if (mode) {
    int pos = 0, cpos = 0;
    for(;mode[cpos]&&(size_t)pos<(sizeof(pmode)-1);cpos++) {
      if (mode[cpos] == '"') {
        pmode[pos] = '\\';
        pos++;
      }
      pmode[pos] = mode[cpos];
      pos++;
    }
    pmode[pos] = 0;
  }

  if (!ident || !strchr(ident, '@')) {
    LOG(LOG_ERR, ERR_CLIENT_IDENT);
    return EINVAL;
  }

  ptr = client_expect(TTX, LMTP_GREETING, err, sizeof(err));
  if (ptr == NULL) {
    LOG(LOG_ERR, ERR_CLIENT_WHILE_AUTH, err);
    return EFAILURE;
  }
  free(ptr);

  snprintf(buf, sizeof(buf), "LHLO %s", strchr(ident, '@')+1);
  if (send_socket(TTX, buf)<=0) 
    return EFAILURE;

  if (client_getcode(TTX, err, sizeof(err))!=LMTP_OK) {
    return EFAILURE;
  }

  if (mode) {
    snprintf(buf, sizeof(buf), "MAIL FROM: <%s> DSPAMPROCESSMODE=\"%s\"", ident, pmode);
  } else {
    snprintf(buf, sizeof(buf), "MAIL FROM: <%s>", ident);
  }
  if (send_socket(TTX, buf)<=0) {
    return EFAILURE;
  }

  if (client_getcode(TTX, err, sizeof(err))!=LMTP_OK) {
    LOG(LOG_ERR, ERR_CLIENT_AUTHENTICATE);
    return EFAILURE;
  }

  return 0;
}

/*
 * client_expect(THREAD_CTX *TTX, int code, char *err, size_t len)
 *
 * DESCRIPTION
 *   wait for the appropriate return code, then return
 *
 * INPUT ARGUMENTS
 *    ATX    agent context
 *    code   return code to wait for
 *    err    error buffer
 *    len    buffer len
 *
 * RETURN VALUES
 *   allocated pointer to acknowledgement line, NULL on error
 *   err buffer is populated on error
 */

char * client_expect(THREAD_CTX *TTX, int code, char *err, size_t len) {
  char *inp, *dup, *ptr, *ptrptr;
  int recv_code;

  inp = client_getline(TTX, 300);
  while(inp != NULL) {
    recv_code = 0;
    dup = strdup(inp);
    if (!dup) {
      free(inp);
      LOG(LOG_CRIT, ERR_MEM_ALLOC);
      strlcpy(err, ERR_MEM_ALLOC, len);
      return NULL;
    }
    if (strncmp(dup, "250-", 4)) {
      ptr = strtok_r(dup, " ", &ptrptr);
      if (ptr) 
        recv_code = atoi(ptr);
      free(dup);
      if (recv_code == code) {
        err[0] = 0;
        return inp;
      }
      LOG(LOG_WARNING, ERR_CLIENT_RESPONSE_CODE, code, inp);
    }
    
    strlcpy(err, inp, len);
    free(inp);
    inp = client_getline(TTX, 300);
  }

  return NULL;
}

/*
 * client_parsecode(const char *err)
 *
 * DESCRIPTION
 *   parse response code from plain text
 *
 * INPUT ARGUMENTS
 *      err    error message to parse
 *
 * RETURN VALUES
 *   integer value of response code
 */

int client_parsecode(char *error) {
  char code[4];
  code[3] = 0;
  strncpy(code, error, 3);
  return atoi(code);
}

/*
 * client_getcode(THREAD_CTX *TTX, char *err, size_t len)
 *
 * DESCRIPTION
 *   retrieve a line of input and return response code
 *
 * INPUT ARGUMENTS  
 *     TTX    thread context containing sockfd
 *     err    error buffer
 *     len    buffer len
 *
 * RETURN VALUES
 *   integer value of response code
 */

int client_getcode(THREAD_CTX *TTX, char *err, size_t len) {
  char *inp, *ptr, *ptrptr = NULL;
  int i;

  inp = client_getline(TTX, 300);
  if (!inp)
    return EFAILURE;

  while(inp && !strncmp(inp, "250-", 4)) {
    free(inp);
    inp = client_getline(TTX, 300);
  }

  strlcpy(err, inp, len);
  ptr = strtok_r(inp, " ", &ptrptr);
  if (ptr == NULL)
    return EFAILURE;
  i = atoi(ptr);
  free(inp);
  return i;
}

/*
 * client_getline(THREAD_CTX *TTX, int timeout)
 *
 * DESCRIPTION
 *   read a complete line from a socket
 *
 * INPUT ARGUMENTS  
 *      TTX        thread context containing sockfd
 *      timeout    timeout (in seconds) to wait for input
 *
 * RETURN VALUES
 *   allocated pointer to input
 */

char *client_getline(THREAD_CTX *TTX, int timeout) {
  struct timeval tv;
  long recv_len;
  char buf[1024];
  char *pop;
  fd_set fds;
  int i;

  pop = pop_buffer(TTX);
  while(!pop) {
    tv.tv_sec = timeout;
    tv.tv_usec = 0;
    FD_ZERO(&fds);
    FD_SET(TTX->sockfd, &fds);
    i = select(TTX->sockfd+1, &fds, NULL, NULL, &tv);
    if (i<=0)
      return NULL;

    recv_len = recv(TTX->sockfd, buf, sizeof(buf)-1, 0);
    buf[recv_len] = 0;
    if (recv_len == 0)
      return NULL;
    buffer_cat(TTX->packet_buffer, buf);
    pop = pop_buffer(TTX);
  }

#ifdef VERBOSE
  LOGDEBUG("RECV: %s", pop);
#endif

  return pop;
}

/*
 * pop_buffer (THREAD_CTX *TTX)
 *
 * DESCRIPTION
 *   pop a line off the packet buffer
 *
 * INPUT ARGUMENTS
 *      TTX     thread context containing the packet buffer
 * 
 * RETURN VALUES
 *   allocated pointer to line, NULL if complete line isn't available
 */

char *pop_buffer(THREAD_CTX *TTX) {
  char *buf, *eol;
  long len;

  if (!TTX || !TTX->packet_buffer || !TTX->packet_buffer->data)
    return NULL;

  eol = strchr(TTX->packet_buffer->data, 10);
  if (!eol)
    return NULL;
  len = (eol - TTX->packet_buffer->data) + 1;
  buf = calloc(1, len+1);
  if (!buf) {
    LOG(LOG_CRIT, ERR_MEM_ALLOC);
    return NULL;
  }
  memcpy(buf, TTX->packet_buffer->data, len);
  memmove(TTX->packet_buffer->data, eol+1, strlen(eol+1)+1);
  TTX->packet_buffer->used -= len;
  return buf;
}

/*
 * send_socket(THREAD_CTX *TTX, const char *text)
 *
 * DESCRIPTION
 *   send a line of text to a socket
 *
 * INPUT ARGUMENTS
 *      TTX     thread context containing sockfd
 *      text    text to send
 *
 * RETURN VALUES
 *   number of bytes sent
 */

int send_socket(THREAD_CTX *TTX, const char *text) {
  int i = 0, r, msglen;

#ifdef VERBOSE
  LOGDEBUG("SEND: %s", text);
#endif

  msglen = strlen(text);
  while(i<msglen) {
    r = send(TTX->sockfd, text+i, msglen-i, 0);
    if (r <= 0) {
      return r;
    }
    i += r;
  }

  r = send(TTX->sockfd, "\r\n", 2, 0);
  if (r > 0) {
    i += r;
  }
  return i;
}

/*
 * deliver_socket(AGENT_CTX *ATX, const char *msg, int proto)
 *
 * DESCRIPTION
 *   delivers message via LMTP or SMTP (instead of TrustedDeliveryAgent) 
 *
 *   If LMTP/SMTP delivery was specified in dspam.conf, this function will be 
 *   called by deliver_message(). This function connects to and delivers the 
 *   message using standard LMTP or SMTP. Depending on how DSPAM was originally 
 *   called, either the address supplied with the incoming RCPT TO or the 
 *   address supplied on the commandline with --rcpt-to  will be used. If 
 *   neither are present, the username will be used. 
 *
 * INPUT ARGUMENTS
 *     ATX      agent context
 *     msg      message to send
 *     proto    protocol to use
 *
 * PROTOCOLS
 *     DDP_LMTP    LMTP
 *     DDP_SMTP    SMTP
 *
 * RETURN VALUES
 *   returns 0 on success
 */

int deliver_socket(AGENT_CTX *ATX, const char *msg, int proto) {
  THREAD_CTX TTX;
  char buf[1024], err[256];
  char *ident = _ds_read_attribute(agent_config, "DeliveryIdent");
  int exitcode = EFAILURE;
  int msglen, code;
  int buflen;
  char *inp;
  int i;
  int size_extension = 0;

  err[0] = 0;

  TTX.sockfd = client_connect(ATX, CCF_DELIVERY);
  if (TTX.sockfd <0) {
    STATUS(ERR_CLIENT_CONNECT);
    LOG(LOG_ERR, ERR_CLIENT_CONNECT);
    return TTX.sockfd;
  }

  TTX.packet_buffer = buffer_create(NULL);
  if (TTX.packet_buffer == NULL) {
    LOG(LOG_CRIT, ERR_MEM_ALLOC);
    STATUS(ERR_MEM_ALLOC);
    goto BAIL;
  }

  inp = client_expect(&TTX, LMTP_GREETING, err, sizeof(err));
  if (inp == NULL) {
    LOG(LOG_ERR, ERR_CLIENT_ON_GREETING, err);
    STATUS("%s", err);
    goto BAIL;
  }
  free(inp);

  /* LHLO / HELO */

  snprintf(buf, sizeof(buf), "%s %s", (proto == DDP_LMTP) ? "LHLO" : "HELO",
           (ident) ? ident : "localhost");
  if (send_socket(&TTX, buf)<=0) {
    LOG(LOG_ERR, ERR_CLIENT_SEND_FAILED);
    STATUS(ERR_CLIENT_SEND_FAILED);
    goto BAIL;
  }

  /* Check for SIZE extension */

  if (proto == DDP_LMTP) {
    char *dup, *ptr, *ptrptr;
    inp = client_getline(&TTX, 300);
    while(inp != NULL) {
      code = 0;
      dup = strdup(inp);
      if (!dup) {
        free(inp);
        LOG(LOG_CRIT, ERR_MEM_ALLOC);
        LOG(LOG_ERR, ERR_CLIENT_INVALID_RESPONSE, "LHLO", ERR_MEM_ALLOC);
        STATUS("LHLO: %s", ERR_MEM_ALLOC);
        goto QUIT;
      }
      if (!strcmp(dup, "250-SIZE") || (!strncmp(dup, "250-SIZE", 8) && strlen(dup)>=8 && isspace(dup[8]))) {
        free(inp);
        free(dup);
        size_extension = 1;
        inp = client_expect(&TTX, LMTP_OK, err, sizeof(err));
        break;
      } else if (strncmp(dup, "250-", 4)) {
        ptr = strtok_r(dup, " ", &ptrptr);
        if (ptr)
          code = atoi(ptr);
        if (code == LMTP_OK) {
          ptr = strtok_r(NULL, " ", &ptrptr);
          if (ptr && !strcmp(ptr, "SIZE"))
            size_extension = 1;
        }
        free(dup);
        if (code == LMTP_OK) {
          err[0] = 0;
          break;
        }
        LOG(LOG_WARNING, ERR_CLIENT_RESPONSE_CODE, code, inp);
      }
      strlcpy(err, inp, sizeof(err));
      free(inp);
      inp = client_getline(&TTX, 300);
    }
  } else {
    inp = client_expect(&TTX, LMTP_OK, err, sizeof(err));
  }
  if (inp == NULL) {
    LOG(LOG_ERR, ERR_CLIENT_INVALID_RESPONSE,
      (proto == DDP_LMTP) ? "LHLO" : "HELO", err);
    STATUS("%s: %s", (proto == DDP_LMTP) ? "LHLO" : "HELO", err);
    goto QUIT;
  }
  free(inp);

  /* MAIL FROM */

  if (proto == DDP_LMTP && size_extension == 1) {
    snprintf(buf, sizeof(buf), "MAIL FROM:<%s> SIZE=%ld",
             ATX->mailfrom, (long) strlen(msg));
  } else {
    snprintf(buf, sizeof(buf), "MAIL FROM:<%s>", ATX->mailfrom);
  }

  if (send_socket(&TTX, buf)<=0) {
    LOG(LOG_ERR, ERR_CLIENT_SEND_FAILED);
    STATUS(ERR_CLIENT_SEND_FAILED);
    goto BAIL;
  }

  code = client_getcode(&TTX, err, sizeof(err));

  if (code!=LMTP_OK) {
    LOG(LOG_ERR, ERR_CLIENT_RESPONSE, code, "MAIL FROM", err);
    if (code >= 500) 
      exitcode = EINVAL;
    chomp(err);
    STATUS((code >= 500) ? "Fatal: %s" : "Deferred: %s", err);
    goto QUIT;
  }

  /* RCPT TO */

  snprintf(buf, sizeof(buf), "RCPT TO:<%s>", (ATX->recipient) ? ATX->recipient : "");
  if (send_socket(&TTX, buf)<=0) {
    LOG(LOG_ERR, ERR_CLIENT_SEND_FAILED);
    STATUS(ERR_CLIENT_SEND_FAILED);
    goto BAIL;
  }

  code = client_getcode(&TTX, err, sizeof(err));

  if (code!=LMTP_OK) {
    LOG(LOG_ERR, ERR_CLIENT_RESPONSE, code, "RCPT TO", err);
    if (code >= 500)
      exitcode = EINVAL;  
    chomp(err);
    STATUS((code >= 500) ? "Fatal: %s" : "Deferred: %s", err);
    goto QUIT;
  }

  /* DATA */

  if (send_socket(&TTX, "DATA")<=0) {
    LOG(LOG_ERR, ERR_CLIENT_SEND_FAILED);
    STATUS(ERR_CLIENT_SEND_FAILED);
    goto BAIL;
  }

  code = client_getcode(&TTX, err, sizeof(err));
  if (code!=LMTP_DATA) {
    LOG(LOG_ERR, ERR_CLIENT_RESPONSE, code, "DATA", err);
    if (code >= 500)
      exitcode = EINVAL;
    chomp(err);
    STATUS((code >= 500) ? "Fatal: %s" : "Deferred: %s", err);
    goto QUIT;
  }

  i = 0;
  msglen = strlen(msg);
  while(i<msglen) {
    int r;
    int t;

    /* fill buf with partial msg, replacing \n with \r\n */
    buflen = 0;
    while ((size_t)buflen < (sizeof(buf) - 2) && i < msglen) {
      /* only replace \n and not \r\n */
      if (i > 0 && msg[i] == '\n' && msg[i - 1] != '\r') {
        buf[buflen] = '\r';
        buflen++;
      }

      /* escape dot if first character on line */
      if (msg[i] == '.' && (i == 0 || msg[i - 1] == '\n')) {
        buf[buflen] = '.';
        buflen++;
      }

      buf[buflen] = msg[i];
      buflen++;
      i++;
    }

    /* send buf */
    t = 0;
    while (t < buflen) {
      r = send(TTX.sockfd, buf+t, buflen - t, 0);
      if (r <= 0) {
        LOG(LOG_ERR, ERR_CLIENT_SEND_FAILED);
        STATUS(ERR_CLIENT_SEND_FAILED);
        goto BAIL;
      }
      t += r;
    }
  }

  if (msg[strlen(msg)-1]!= '\n') {
    if (send_socket(&TTX, "")<=0) {
      LOG(LOG_ERR, ERR_CLIENT_SEND_FAILED);
      STATUS(ERR_CLIENT_SEND_FAILED);
      goto BAIL;
    }
  }

  if (send_socket(&TTX, "\r\n.")<=0) {
    LOG(LOG_ERR, ERR_CLIENT_SEND_FAILED);
    STATUS(ERR_CLIENT_SEND_FAILED);
    goto BAIL;
  }

  /* server response */

  code = client_getcode(&TTX, err, sizeof(err));
  if (code < 200 || code >= 300) {
    LOG(LOG_ERR, ERR_CLIENT_RESPONSE, code, "message data", err);
    if (code >= 400 && code < 500)
      exitcode = EX_TEMPFAIL;
    else if (code >= 500)
      exitcode = EINVAL;
    chomp(err);
    STATUS((code >= 500) ? "Fatal: %s" : "Deferred: %s", err);
    goto QUIT;
  }

  send_socket(&TTX, "QUIT");
  client_getcode(&TTX, err, sizeof(err));
  close(TTX.sockfd);
  buffer_destroy(TTX.packet_buffer);
  return 0;

QUIT:
  send_socket(&TTX, "QUIT");
  client_getcode(&TTX, err, sizeof(err));
  buffer_destroy(TTX.packet_buffer);
  close(TTX.sockfd);
  return exitcode;

BAIL:
  LOG(LOG_ERR, ERR_CLIENT_DELIVERY_FAILED);
  buffer_destroy(TTX.packet_buffer);
  close(TTX.sockfd);
  return exitcode;
}

#endif /* DAEMON */