summaryrefslogtreecommitdiff
path: root/sapi/milter/php_milter.c
blob: 8679e25d31e1dfb278069afa22bf246d728b95c9 (plain)
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
/*
   +----------------------------------------------------------------------+
   | PHP Version 5                                                        |
   +----------------------------------------------------------------------+
   | Copyright (c) 1997-2010 The PHP Group                                |
   +----------------------------------------------------------------------+
   | This source file is subject to version 3.01 of the PHP license,      |
   | that is bundled with this package in the file LICENSE, and is        |
   | available through the world-wide-web at the following url:           |
   | http://www.php.net/license/3_01.txt                                  |
   | If you did not receive a copy of the PHP license and are unable to   |
   | obtain it through the world-wide-web, please send a note to          |
   | license@php.net so we can mail you a copy immediately.               |
   +----------------------------------------------------------------------+
   | Author: Harald Radi <phanto@php.net>                                 |
   |         Parts based on CGI SAPI Module by                            |
   |         Rasmus Lerdorf, Stig Bakken and Zeev Suraski                 |
   +----------------------------------------------------------------------+
*/

/* $Id$ */

#include "php.h"
#include "php_globals.h"
#include "php_variables.h"
#include "zend_modules.h"

#ifndef ZTS
#error SRM sapi module is only useable in thread-safe mode
#endif

#include "SAPI.h"

#include <stdio.h>
#include "php.h"
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_SIGNAL_H
#include <signal.h>
#endif
#if HAVE_SETLOCALE
#include <locale.h>
#endif
#include "zend.h"
#include "zend_extensions.h"
#include "php_ini.h"
#include "php_globals.h"
#include "php_main.h"
#include "fopen_wrappers.h"
#include "ext/standard/php_standard.h"

#ifdef __riscos__
#include <unixlib/local.h>
#endif

#include "zend_compile.h"
#include "zend_execute.h"
#include "zend_highlight.h"
#include "zend_indent.h"

#include "libmilter/mfapi.h"

#include "php_getopt.h"

#define OPTSTRING "ac:d:Def:hnp:vVz:?"
#define MG(v)  TSRMG(milter_globals_id, zend_milter_globals *, v)

#define IS_NONE "%s(): This function must not be called outside of a milter callback function's scope"
#define NOT_EOM "%s(): This function can only be used inside the milter_eom callback's scope"
#define NOT_INIT "%s(): This function can only be used inside the milter_init callback's scope"

#define MLFI_NONE		0
#define MLFI_CONNECT	1
#define MLFI_HELO		2
#define MLFI_ENVFROM	3
#define MLFI_ENVRCPT	4
#define MLFI_HEADER		5
#define MLFI_EOH		6
#define MLFI_BODY		7
#define MLFI_EOM		8
#define MLFI_ABORT		9
#define MLFI_CLOSE		10
#define MLFI_INIT		11

/* {{{ globals
 */
extern char *ap_php_optarg;
extern int ap_php_optind;

static int flag_debug=0;
static char *filename;

/* per thread */
ZEND_BEGIN_MODULE_GLOBALS(milter)
	SMFICTX *ctx;
	int state;
	int initialized;
ZEND_END_MODULE_GLOBALS(milter)

ZEND_DECLARE_MODULE_GLOBALS(milter)
/* }}} */

/* this method is called only once when the milter starts */
/* {{{ Init Milter
*/
static int mlfi_init()
{
	int ret = 0;
	zend_file_handle file_handle;
	zval function_name, retval;
	int status;
	TSRMLS_FETCH();

	/* request startup */
	if (php_request_startup(TSRMLS_C)==FAILURE) {
		SG(headers_sent) = 1;
		SG(request_info).no_headers = 1;
		php_request_shutdown((void *) 0);

		return -1;
	}
	
	/* disable headers */
	SG(headers_sent) = 1;
	SG(request_info).no_headers = 1;

	if (!(file_handle.handle.fp = VCWD_FOPEN(filename, "rb"))) {
		php_printf("Could not open input file: %s\n", filename);
		return SMFIS_TEMPFAIL;
	}

	file_handle.type = ZEND_HANDLE_FP;
	file_handle.filename = filename;
	file_handle.free_filename = 0;
	file_handle.opened_path = NULL;

	php_execute_script(&file_handle TSRMLS_CC);
	
	/* call userland */
	INIT_ZVAL(function_name);

	ZVAL_STRING(&function_name, "milter_init", 0);

	/* set the milter context for possible use in API functions */
	MG(state) = MLFI_INIT;

	status = call_user_function(CG(function_table), NULL, &function_name, &retval, 0, NULL TSRMLS_CC);

	MG(state) = MLFI_NONE;
	MG(initialized) = 1;

	if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) {
		ret = Z_LVAL(retval);
	}
	
	php_request_shutdown((void *) 0);
	
	return ret;
}
/* }}} */

/* {{{ Milter callback functions
 */

/* connection info filter, is called whenever sendmail connects to the milter */
/* {{{ mlfi_connect()
*/
static sfsistat	mlfi_connect(SMFICTX *ctx, char *hostname, _SOCK_ADDR *hostaddr)
{
	zend_file_handle file_handle;
	zval function_name, retval, *param[1];
	int status;
	TSRMLS_FETCH();

	/* request startup */
	if (php_request_startup(TSRMLS_C)==FAILURE) {
		SG(headers_sent) = 1;
		SG(request_info).no_headers = 1;
		php_request_shutdown((void *) 0);

		return SMFIS_TEMPFAIL;
	}
	
	/* disable headers */
	SG(headers_sent) = 1;
	SG(request_info).no_headers = 1;
	
	if (!(file_handle.handle.fp = VCWD_FOPEN(filename, "rb"))) {
		php_printf("Could not open input file: %s\n", filename);
		return SMFIS_TEMPFAIL;
	}

	file_handle.type = ZEND_HANDLE_FP;
	file_handle.filename = filename;
	file_handle.free_filename = 0;
	file_handle.opened_path = NULL;

	php_execute_script(&file_handle TSRMLS_CC);
	
	/* call userland */
	INIT_ZVAL(function_name);

	ALLOC_ZVAL(param[0]);
	INIT_PZVAL(param[0]);

	ZVAL_STRING(&function_name, "milter_connect", 0);
	ZVAL_STRING(param[0], hostname, 1);

	/* set the milter context for possible use in API functions */
	MG(ctx) = ctx;
	MG(state) = MLFI_CONNECT;

	status = call_user_function(CG(function_table), NULL, &function_name, &retval, 1, param TSRMLS_CC);

	MG(state) = MLFI_NONE;
	zval_ptr_dtor(param);
	if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) {
		return Z_LVAL(retval);
	}
	
	return SMFIS_CONTINUE;
}
/* }}} */

/* SMTP HELO command filter */
/* {{{ mlfi_helo()
*/
static sfsistat mlfi_helo(SMFICTX *ctx, char *helohost)
{
	zval function_name, retval, *param[1];
	int status;
	TSRMLS_FETCH();

	/* call userland */
	INIT_ZVAL(function_name);
	
	ALLOC_ZVAL(param[0]);
	INIT_PZVAL(param[0]);

	ZVAL_STRING(&function_name, "milter_helo", 0);
	ZVAL_STRING(param[0], helohost, 1);

	/* set the milter context for possible use in API functions */
	MG(ctx) = ctx;
	MG(state) = MLFI_HELO;
	
	status = call_user_function(CG(function_table), NULL, &function_name, &retval, 1, param TSRMLS_CC);

	MG(state) = MLFI_NONE;
	zval_ptr_dtor(param);
	
	if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) {
		return Z_LVAL(retval);
	}
	
	return SMFIS_CONTINUE;
}
/* }}} */

/* envelope sender filter */
/* {{{ mlfi_envform()
*/
static sfsistat mlfi_envfrom(SMFICTX *ctx, char **argv)
{
	zval function_name, retval, *param[1];
	int status;
	TSRMLS_FETCH();

	/* call userland */
	INIT_ZVAL(function_name);
	
	ALLOC_ZVAL(param[0]);
	INIT_PZVAL(param[0]);

	ZVAL_STRING(&function_name, "milter_envfrom", 0);
	array_init(param[0]);

	while (*argv) {
		add_next_index_string(param[0], *argv, 1);
		argv++;
	}

	/* set the milter context for possible use in API functions */
	MG(ctx) = ctx;
	MG(state) = MLFI_ENVFROM;
	
	status = call_user_function(CG(function_table), NULL, &function_name, &retval, 1, param TSRMLS_CC);

	MG(state) = MLFI_NONE;
	zval_ptr_dtor(param);
	
	if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) {
		return Z_LVAL(retval);
	}

	return SMFIS_CONTINUE;
}
/* }}} */

/* envelope recipient filter */
/* {{{ mlfi_envrcpt()
*/
static sfsistat mlfi_envrcpt(SMFICTX *ctx, char **argv)
{
	zval function_name, retval, *param[1];
	int status;
	TSRMLS_FETCH();

	/* call userland */
	INIT_ZVAL(function_name);
	
	ALLOC_ZVAL(param[0]);
	INIT_PZVAL(param[0]);

	ZVAL_STRING(&function_name, "milter_envrcpt", 0);
	array_init(param[0]);

	while (*argv) {
		add_next_index_string(param[0], *argv, 1);
		argv++;
	}

	/* set the milter context for possible use in API functions */
	MG(ctx) = ctx;
	MG(state) = MLFI_ENVRCPT;
	
	status = call_user_function(CG(function_table), NULL, &function_name, &retval, 1, param TSRMLS_CC);

	MG(state) = MLFI_NONE;
	
	zval_ptr_dtor(param);
	
	if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) {
		return Z_LVAL(retval);
	}

	return SMFIS_CONTINUE;
}
/* }}} */

/* header filter */
/* {{{ mlfi_header()
*/
static sfsistat mlfi_header(SMFICTX *ctx, char *headerf, char *headerv)
{
	zval function_name, retval, *param[2];
	int status;
	TSRMLS_FETCH();

	/* call userland */
	INIT_ZVAL(function_name);
	
	ALLOC_ZVAL(param[0]);
	ALLOC_ZVAL(param[1]);
	INIT_PZVAL(param[0]);
	INIT_PZVAL(param[1]);
	
	ZVAL_STRING(&function_name, "milter_header", 0);
	ZVAL_STRING(param[0], headerf, 1);
	ZVAL_STRING(param[1], headerv, 1);

	/* set the milter context for possible use in API functions */
	MG(ctx) = ctx;
	MG(state) = MLFI_HEADER;
	
	status = call_user_function(CG(function_table), NULL, &function_name, &retval, 2, param TSRMLS_CC);

	MG(state) = MLFI_NONE;
	
	zval_ptr_dtor(&param[0]);
	zval_ptr_dtor(&param[1]);	
	
	if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) {
		return Z_LVAL(retval);
	}
	
	return SMFIS_CONTINUE;
}
/* }}} */

/* end of header */
/* {{{ mlfi_eoh()
*/
static sfsistat mlfi_eoh(SMFICTX *ctx)
{
	zval function_name, retval;
	int status;
	TSRMLS_FETCH();

	/* call userland */
	INIT_ZVAL(function_name);
	ZVAL_STRING(&function_name, "milter_eoh", 0);

	/* set the milter context for possible use in API functions */
	MG(ctx) = ctx;
	MG(state) = MLFI_EOH;
	
	status = call_user_function(CG(function_table), NULL, &function_name, &retval, 0, NULL TSRMLS_CC);

	MG(state) = MLFI_NONE;
	
	if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) {
		return Z_LVAL(retval);
	}

	return SMFIS_CONTINUE;
}
/* }}} */

/* body block */
/* {{{ mlfi_body()
*/
static sfsistat mlfi_body(SMFICTX *ctx, u_char *bodyp, size_t len)
{
	zval function_name, retval, *param[1];
	int status;
	TSRMLS_FETCH();

	/* call userland */
	INIT_ZVAL(function_name);
	
	ALLOC_ZVAL(param[0]);
	INIT_PZVAL(param[0]);

	ZVAL_STRING(&function_name, "milter_body", 0);
	ZVAL_STRINGL(param[0], (char*)bodyp, len, 1); /*alex*/
	
	/* set the milter context for possible use in API functions */
	MG(ctx) = ctx;
	MG(state) = MLFI_BODY;
	
	status = call_user_function(CG(function_table), NULL, &function_name, &retval, 1, param TSRMLS_CC);

	MG(state) = MLFI_NONE;
	
	zval_ptr_dtor(param);	

	if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) {
		return Z_LVAL(retval);
	}

	return SMFIS_CONTINUE;
}
/* }}} */

/* end of message */
/* {{{ mlfi_eom()
*/
static sfsistat mlfi_eom(SMFICTX *ctx)
{
	zval function_name, retval;
	int status;
	TSRMLS_FETCH();

	/* call userland */
	INIT_ZVAL(function_name);
	ZVAL_STRING(&function_name, "milter_eom", 0);
	
	/* set the milter context for possible use in API functions */
	MG(ctx) = ctx;
	MG(state) = MLFI_EOM;

	status = call_user_function(CG(function_table), NULL, &function_name, &retval, 0, NULL TSRMLS_CC);

	MG(state) = MLFI_NONE;
	
	if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) {
		return Z_LVAL(retval);
	}

	return SMFIS_CONTINUE;
}
/* }}} */

/* message aborted */
/* {{{ mlfi_abort()
*/
static sfsistat mlfi_abort(SMFICTX *ctx)
{
	zval function_name, retval;
	int status;
	TSRMLS_FETCH();

	/* call userland */
	INIT_ZVAL(function_name);
	ZVAL_STRING(&function_name, "milter_abort", 0);
	
	/* set the milter context for possible use in API functions */
	MG(ctx) = ctx;
	MG(state) = MLFI_ABORT;
	
	status = call_user_function(CG(function_table), NULL, &function_name, &retval, 0, NULL TSRMLS_CC);

	MG(state) = MLFI_NONE;
	
	if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) {
		return Z_LVAL(retval);
	}

	return SMFIS_CONTINUE;
}
/* }}} */

/* connection cleanup */
/* {{{ mlfi_close()
*/
static sfsistat mlfi_close(SMFICTX *ctx)
{
	int ret = SMFIS_CONTINUE;
	zval function_name, retval;
	int status;
	TSRMLS_FETCH();

	/* call userland */
	INIT_ZVAL(function_name);
	ZVAL_STRING(&function_name, "milter_close", 0);
	
	/* set the milter context for possible use in API functions */
	MG(ctx) = ctx;
	MG(state) = MLFI_CLOSE;
	
	status = call_user_function(CG(function_table), NULL, &function_name, &retval, 0, NULL TSRMLS_CC);

	MG(state) = MLFI_NONE;
	
	if (status == SUCCESS && Z_TYPE(retval) == IS_LONG) {
		ret = Z_LVAL(retval);
	}
	
	php_request_shutdown((void *) 0);

	return ret;
}
/* }}} */
/* }}} */

/* {{{ Milter entry struct
 */
struct smfiDesc smfilter = {
    "php-milter",	/* filter name */
    SMFI_VERSION,   /* version code -- leave untouched */
    0,				/* flags */
    mlfi_connect,	/* info filter callback */
    mlfi_helo,		/* HELO filter callback */
    mlfi_envfrom,	/* envelope filter callback */
    mlfi_envrcpt,	/* envelope recipient filter callback */
    mlfi_header,	/* header filter callback */
    mlfi_eoh,		/* end of header callback */
    mlfi_body,		/* body filter callback */
    mlfi_eom,		/* end of message callback */
    mlfi_abort,		/* message aborted callback */
    mlfi_close,		/* connection cleanup callback */
};
/* }}} */

/* {{{ PHP Milter API
 */

/* {{{ proto void smfi_setflags(long flags)
   Sets the flags describing the actions the filter may take. */	
PHP_FUNCTION(smfi_setflags)
{
	long flags;
	
	/* valid only in the init callback */
	if (MG(state) != MLFI_INIT) {
		php_error(E_WARNING, NOT_INIT, get_active_function_name(TSRMLS_C));
	} else if (zend_parse_parameters(1 TSRMLS_CC, "l", &flags) == SUCCESS) {
		flags = flags & (SMFIF_ADDHDRS|SMFIF_CHGHDRS|SMFIF_CHGBODY|SMFIF_ADDRCPT|SMFIF_DELRCPT);
		smfilter.xxfi_flags = flags;
	}	
}
/* }}} */

/* {{{ proto void smfi_settimeout(long timeout)
   Sets the number of seconds libmilter will wait for an MTA connection before timing out a socket. */	
PHP_FUNCTION(smfi_settimeout)
{
	long timeout;
	
	/* valid only in the init callback */
	if (MG(state) != MLFI_INIT) {
		php_error(E_WARNING, NOT_INIT, get_active_function_name(TSRMLS_C));
	} else if (zend_parse_parameters(1 TSRMLS_CC, "l", &timeout) == SUCCESS) {
		smfi_settimeout(timeout);
	}	
}
/* }}} */

/* {{{ proto string smfi_getsymval(string macro)
   Returns the value of the given macro or NULL if the macro is not defined. */	
PHP_FUNCTION(smfi_getsymval)
{
	char *symname, *ret;
	int len;

	/* valid in any callback */
	if (MG(state) == MLFI_NONE) {
		php_error(E_WARNING, IS_NONE, get_active_function_name(TSRMLS_C));
	} else if (zend_parse_parameters(1 TSRMLS_CC, "s", &symname, &len) == SUCCESS) {
		if ((ret = smfi_getsymval(MG(ctx), symname)) != NULL) {
			RETURN_STRING(ret, 1);
		}
	}

	RETURN_NULL();
}
/* }}} */

/* {{{ proto bool smfi_setreply(string rcode, string xcode, string message)
   Directly set the SMTP error reply code for this connection.
   This code will be used on subsequent error replies resulting from actions taken by this filter. */	
PHP_FUNCTION(smfi_setreply)
{
	char *rcode, *xcode, *message;
	int len;
	
	/* valid in any callback */
	if (MG(state) == MLFI_NONE) {
		php_error(E_WARNING, IS_NONE, get_active_function_name(TSRMLS_C));
	} else if (zend_parse_parameters(3 TSRMLS_CC, "sss", &rcode, &len, &xcode, &len, &message, &len) == SUCCESS) {
		if (smfi_setreply(MG(ctx), rcode, xcode, message) == MI_SUCCESS) {
			RETURN_TRUE;
		}
	}
	
	RETURN_FALSE;
}
/* }}} */

/* {{{ proto bool smfi_addheader(string headerf, string headerv)
   Adds a header to the current message. */	
PHP_FUNCTION(smfi_addheader)
{
	char *f, *v;
	int len;
	
	/* valid only in milter_eom */
	if (MG(state) != MLFI_EOM) {
		php_error(E_WARNING, NOT_EOM, get_active_function_name(TSRMLS_C));
	} else if (zend_parse_parameters(2 TSRMLS_CC, "ss", &f, &len, &v, &len) == SUCCESS) {
		if (smfi_addheader(MG(ctx), f, v) == MI_SUCCESS) {
			RETURN_TRUE;
		}
	}
	
	RETURN_FALSE;
}
/* }}} */

/* {{{ proto bool smfi_chgheader(string headerf, string headerv)
   Changes a header's value for the current message. */	
PHP_FUNCTION(smfi_chgheader)
{
	char *f, *v;
	long idx;
	int len;
	
	/* valid only in milter_eom */
	if (MG(state) != MLFI_EOM) {
		php_error(E_WARNING, NOT_EOM, get_active_function_name(TSRMLS_C));
	} else if (zend_parse_parameters(3 TSRMLS_CC, "sls", &f, &len, &idx, &v, &len) == SUCCESS) {
		if (smfi_chgheader(MG(ctx), f, idx, v) == MI_SUCCESS) {
			RETURN_TRUE;
		}
	}
	
	RETURN_FALSE;
}
/* }}} */

/* {{{ proto bool smfi_addrcpt(string rcpt)
   Add a recipient to the message envelope. */	
PHP_FUNCTION(smfi_addrcpt)
{
	char *rcpt;
	int len;
	
	/* valid only in milter_eom */
	if (MG(state) != MLFI_EOM) {
		php_error(E_WARNING, NOT_EOM, get_active_function_name(TSRMLS_C));
	} else if (zend_parse_parameters(1 TSRMLS_CC, "s", &rcpt, &len) == SUCCESS) {
		if (smfi_addrcpt(MG(ctx), rcpt) == MI_SUCCESS) {
			RETURN_TRUE;
		}
	}
	
	RETURN_FALSE;
}
/* }}} */

/* {{{ proto bool smfi_delrcpt(string rcpt)
   Removes the named recipient from the current message's envelope. */	
PHP_FUNCTION(smfi_delrcpt)
{
	char *rcpt;
	int len;
	
	/* valid only in milter_eom */
	if (MG(state) != MLFI_EOM) {
		php_error(E_WARNING, NOT_EOM, get_active_function_name(TSRMLS_C));
	} else if (zend_parse_parameters(1 TSRMLS_CC, "s", &rcpt, &len) == SUCCESS) {
		if (smfi_delrcpt(MG(ctx), rcpt) == MI_SUCCESS) {
			RETURN_TRUE;
		}
	}
	
	RETURN_FALSE;
}
/* }}} */

/* {{{ proto bool smfi_replacebody(string body)
   Replaces the body of the current message. If called more than once,
   subsequent calls result in data being appended to the new body. */	
PHP_FUNCTION(smfi_replacebody)
{
	char *body;
	int len;
	
	/* valid only in milter_eom */
	if (MG(state) != MLFI_EOM) {
		php_error(E_WARNING, NOT_EOM, get_active_function_name(TSRMLS_C));
	} else if (zend_parse_parameters(1 TSRMLS_CC, "s", &body, &len) == SUCCESS) {
		if (smfi_replacebody(MG(ctx), (u_char*)body, len) == MI_SUCCESS) {
			RETURN_TRUE;
		}
	}
	
	RETURN_FALSE;
}
/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(milter)
{
	REGISTER_LONG_CONSTANT("SMFIS_CONTINUE",	SMFIS_CONTINUE,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("SMFIS_REJECT",		SMFIS_REJECT,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("SMFIS_DISCARD",		SMFIS_DISCARD,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("SMFIS_ACCEPT",		SMFIS_ACCEPT,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("SMFIS_TEMPFAIL",	SMFIS_TEMPFAIL,	CONST_CS | CONST_PERSISTENT);

	REGISTER_LONG_CONSTANT("SMFIF_ADDHDRS",		SMFIF_ADDHDRS,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("SMFIF_CHGHDRS",		SMFIF_CHGHDRS,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("SMFIF_CHGBODY",		SMFIF_CHGBODY,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("SMFIF_ADDRCPT",		SMFIF_ADDRCPT,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("SMFIF_DELRCPT",		SMFIF_DELRCPT,	CONST_CS | CONST_PERSISTENT);

	ZEND_INIT_MODULE_GLOBALS(milter, NULL, NULL);

	MG(state) = MLFI_NONE;
	MG(initialized) = 0;
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(milter)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "Milter support", "enabled");
	php_info_print_table_end();
}
/* }}} */
/* }}} */

/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_smfi_setflags, 0, 0, 1)
	ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_smfi_settimeout, 0, 0, 1)
	ZEND_ARG_INFO(0, timeout)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_smfi_getsymval, 0, 0, 1)
	ZEND_ARG_INFO(0, macro)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_smfi_setreply, 0, 0, 3)
	ZEND_ARG_INFO(0, rcode)
	ZEND_ARG_INFO(0, xcode)
	ZEND_ARG_INFO(0, message)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_smfi_addheader, 0, 0, 2)
	ZEND_ARG_INFO(0, headerf)
	ZEND_ARG_INFO(0, headerv)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_smfi_chgheader, 0, 0, 2)
	ZEND_ARG_INFO(0, headerf)
	ZEND_ARG_INFO(0, headerv)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_smfi_addrcpt, 0, 0, 1)
	ZEND_ARG_INFO(0, rcpt)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_smfi_delrcpt, 0, 0, 1)
	ZEND_ARG_INFO(0, rcpt)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_smfi_replacebody, 0, 0, 1)
	ZEND_ARG_INFO(0, body)
ZEND_END_ARG_INFO()
/* }}} */

/* {{{ milter_functions[]
*/
const static zend_function_entry milter_functions[] = {
	PHP_FE(smfi_setflags, 		arginfo_smfi_setflags)
	PHP_FE(smfi_settimeout, 	arginfo_smfi_settimeout)
	PHP_FE(smfi_getsymval, 		arginfo_smfi_getsymval)
	PHP_FE(smfi_setreply, 		arginfo_smfi_setreply)
	PHP_FE(smfi_addheader, 		arginfo_smfi_addheader)
	PHP_FE(smfi_chgheader, 		arginfo_smfi_chgheader)
	PHP_FE(smfi_addrcpt, 		arginfo_smfi_addrcpt)
	PHP_FE(smfi_delrcpt, 		arginfo_smfi_delrcpt)
	PHP_FE(smfi_replacebody, 	arginfo_smfi_replacebody)
	{ NULL, NULL, NULL }
};
/* }}} */

/* {{{ Zend module entry
*/
static zend_module_entry php_milter_module = {
	STANDARD_MODULE_HEADER,
	"Milter",
	milter_functions,
	PHP_MINIT(milter),
	NULL,
	NULL,
	NULL,
	PHP_MINFO(milter),
	"0.1.0",
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

/* {{{ Milter SAPI
*/
static int sapi_milter_ub_write(const char *str, uint str_length TSRMLS_DC)
{
	return str_length;
}

static void sapi_milter_flush(void *server_context)
{
}

static void sapi_milter_register_variables(zval *track_vars_array TSRMLS_DC)
{
	php_register_variable ("SERVER_SOFTWARE", "Sendmail Milter", track_vars_array TSRMLS_CC);
}

static int sapi_milter_post_read(char *buf, uint count_bytes TSRMLS_DC)
{
	return 0;
}

static char* sapi_milter_read_cookies(TSRMLS_D)
{
	return NULL;
}

static int sapi_milter_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC)
{
	return SAPI_HEADER_SENT_SUCCESSFULLY;
}

static int php_milter_startup(sapi_module_struct *sapi_module)
{
	if (php_module_startup(sapi_module, &php_milter_module, 1) == FAILURE) {
		return FAILURE;
	}
	return SUCCESS;
}
/* }}} */

/* {{{ sapi_module_struct milter_sapi_module
*/
static sapi_module_struct milter_sapi_module = {
	"milter",						/* name */
	"Sendmail Milter SAPI",			/* pretty name */

	php_milter_startup,				/* startup */
	php_module_shutdown_wrapper,	/* shutdown */

	NULL,							/* activate */
	NULL,							/* deactivate */

	sapi_milter_ub_write,			/* unbuffered write */
	sapi_milter_flush,				/* flush */
	NULL,							/* get uid */
	NULL,							/* getenv */

	php_error,						/* error handler */

	NULL,							/* header handler */
	sapi_milter_send_headers,		/* send headers handler */
	NULL,							/* send header handler */

	sapi_milter_post_read,			/* read POST data */
	sapi_milter_read_cookies,		/* read Cookies */

	sapi_milter_register_variables,	/* register server variables */
	NULL,							/* Log message */
	NULL,							/* Get request time */
	NULL,							/* Child terminate */

	NULL,							/* Block interruptions */
	NULL,							/* Unblock interruptions */

	STANDARD_SAPI_MODULE_PROPERTIES
};
/* }}} */

/****
* ripped from cli, has to be cleaned up !
*/

/* {{{ php_milter_usage
*/
static void php_milter_usage(char *argv0)
{
	char *prog;

	prog = strrchr(argv0, '/');
	if (prog) {
		prog++;
	} else {
		prog = "php-milter";
	}

	printf(     "Usage: %s [options] [-f] <file> [args...]\n"
	            "       %s [options] -r <code> [args...]\n"
	            "       %s [options] [-- args...]\n"
				"  -a               Run interactively\n"
				"  -c <path>|<file> Look for php.ini file in this directory\n"
				"  -n               No php.ini file will be used\n"
				"  -d foo[=bar]     Define INI entry foo with value 'bar'\n"
				"  -D               run as daemon\n"
				"  -e               Generate extended information for debugger/profiler\n"
				"  -f <file>        Parse <file>.\n"
				"  -h               This help\n"
				"  -p <socket>      path to create socket\n"
				"  -v               Version number\n"
				"  -V <n>           set debug level to n (1 or 2).\n"
				"  -z <file>        Load Zend extension <file>.\n"
				"  args...          Arguments passed to script. Use -- args when first argument \n"
				"                   starts with - or script is read from stdin\n"
				, prog, prog, prog);
}
/* }}} */

static void define_command_line_ini_entry(char *arg) /* {{{ */
{
	char *name, *value;

	name = arg;
	value = strchr(arg, '=');
	if (value) {
		*value = 0;
		value++;
	} else {
		value = "1";
	}
	zend_alter_ini_entry(name, strlen(name)+1, value, strlen(value), PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);
}
/* }}} */

/* {{{ main
*/
int main(int argc, char *argv[])
{
    char *sock = NULL;
	int dofork = 0;

	int exit_status = SUCCESS;
	int c;
/* temporary locals */
	int orig_optind=ap_php_optind;
	char *orig_optarg=ap_php_optarg;
	int interactive=0;
	char *param_error=NULL;
/* end of temporary locals */

	void ***tsrm_ls;

#ifdef HAVE_SIGNAL_H
#if defined(SIGPIPE) && defined(SIG_IGN)
	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
								that sockets created via fsockopen()
								don't kill PHP if the remote site
								closes it.  in apache|apxs mode apache
								does that for us!  thies@thieso.net
								20000419 */
#endif
#endif


	tsrm_startup(1, 1, 0, NULL);
	sapi_startup(&milter_sapi_module);
	
	while ((c=ap_php_getopt(argc, argv, OPTSTRING))!=-1) {
		switch (c) {
		case 'c':
			milter_sapi_module.php_ini_path_override = strdup(ap_php_optarg);
			break;
		case 'n':
			milter_sapi_module.php_ini_ignore = 1;
			break;
		}
	}
	ap_php_optind = orig_optind;
	ap_php_optarg = orig_optarg;

	milter_sapi_module.executable_location = argv[0];

	tsrm_ls = ts_resource(0);

	sapi_module.startup(&milter_sapi_module);

	zend_first_try {
		while ((c=ap_php_getopt(argc, argv, OPTSTRING))!=-1) {
			switch (c) {
			case '?':
				php_output_startup();
				php_output_activate(TSRMLS_C);
				SG(headers_sent) = 1;
				php_milter_usage(argv[0]);
				php_end_ob_buffers(1 TSRMLS_CC);
				exit(1);
				break;
			}
		}
		ap_php_optind = orig_optind;
		ap_php_optarg = orig_optarg;

        /* Set some CLI defaults */
		SG(options) |= SAPI_OPTION_NO_CHDIR;
		zend_alter_ini_entry("html_errors", 12, "0", 1, PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);
		zend_alter_ini_entry("max_execution_time", 19, "0", 1, PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE);

		zend_uv.html_errors = 0; /* tell the engine we're in non-html mode */

		while ((c = ap_php_getopt(argc, argv, OPTSTRING)) != -1) {
			switch (c) {

			case 'a':	/* interactive mode */
				printf("Interactive mode enabled\n\n");
				interactive=1;
				break;

			case 'C': /* don't chdir to the script directory */
				/* This is default so NOP */
				break;
			case 'd': /* define ini entries on command line */
				define_command_line_ini_entry(ap_php_optarg);
				break;

			case 'D': /* daemon */
				dofork = 1;
				break;

			case 'e': /* enable extended info output */
				CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
				break;

			case 'f': /* parse file */
				filename = ap_php_optarg;
				break;

			case 'h': /* help & quit */
			case '?':
				php_output_startup();
				php_output_activate(TSRMLS_C);
				SG(headers_sent) = 1;
				php_milter_usage(argv[0]);
				php_end_ob_buffers(1 TSRMLS_CC);
				exit(1);
				break;

			case 'p': /* socket */
				sock = strdup(ap_php_optarg);
				break;

			case 'v': /* show php version & quit */
				if (php_request_startup(TSRMLS_C)==FAILURE) {
					zend_ini_deactivate(TSRMLS_C);
					php_module_shutdown(TSRMLS_C);
					sapi_shutdown();
					tsrm_shutdown();

					exit(1);
				}
				SG(headers_sent) = 1;
				SG(request_info).no_headers = 1;
				php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2010 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
				php_end_ob_buffers(1 TSRMLS_CC);
				exit(1);
				break;

			case 'V': /* verbose */
				flag_debug = atoi(ap_php_optarg);
				break;

			case 'z': /* load extension file */
				zend_load_extension(ap_php_optarg);
				break;

			default:
				break;
			}
		}

		if (param_error) {
			SG(headers_sent) = 1;
			SG(request_info).no_headers = 1;
			PUTS(param_error);
			exit(1);
		}

		CG(interactive) = interactive;

		/* only set script_file if not set already and not in direct mode and not at end of parameter list */
		if (argc > ap_php_optind && !filename) {
			filename=argv[ap_php_optind];
			ap_php_optind++;
		}

		/* check if file exists, exit else */
		
		if (dofork) {
			switch(fork()) {
				case -1: /* Uh-oh, we have a problem forking. */
					fprintf(stderr, "Uh-oh, couldn't fork!\n");
					exit(errno);
					break;
				case 0: /* Child */
					break;
				default: /* Parent */
					exit(0);
			}
		}
			
		if (sock) {
			struct stat junk;
			if (stat(sock,&junk) == 0) unlink(sock);
		}

		openlog("php-milter", LOG_PID, LOG_MAIL);
		
		if ((exit_status = mlfi_init())) {
			syslog(1, "mlfi_init failed.");
			closelog();
			goto err;
		}

		smfi_setconn(sock);
		if (smfi_register(smfilter) == MI_FAILURE) {
			syslog(1, "smfi_register failed.");
			fprintf(stderr, "smfi_register failed\n");
			closelog();
			goto err;
		} else {
			exit_status = smfi_main();
		}			

		closelog();

		if (milter_sapi_module.php_ini_path_override) {
			free(milter_sapi_module.php_ini_path_override);
		}

	} zend_catch {
		exit_status = EG(exit_status);
	} zend_end_try();

err:
	php_module_shutdown(TSRMLS_C);
	sapi_shutdown();
	tsrm_shutdown();

	exit(exit_status);
}
/* }}} */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: sw=4 ts=4 fdm=marker
 * vim<600: sw=4 ts=4
 */