1 /* $Cambridge: exim/src/src/sieve.c,v 1.26 2007/03/21 15:15:12 ph10 Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 /* Copyright (c) Michael Haardt 2003-2006 */
8 /* See the file NOTICE for conditions of use and distribution. */
10 /* This code was contributed by Michael Haardt. */
13 /* Sieve mail filter. */
27 /* Define this for RFC compliant \r\n end-of-line terminators. */
28 /* Undefine it for UNIX-style \n end-of-line terminators (default). */
31 /* Define this for development of the Sieve extension "encoded-character". */
32 #undef ENCODED_CHARACTER
34 /* Define this for development of the Sieve extension "envelope-auth". */
37 /* Define this for development of the Sieve extension "enotify". */
40 /* Define this for the Sieve extension "subaddress". */
43 /* Define this for the Sieve extension "vacation". */
47 #define VACATION_MIN_DAYS 1
48 /* Must be >= VACATION_MIN_DAYS, must be > 7, should be > 30 */
49 #define VACATION_MAX_DAYS 31
51 /* Keep this at 75 to accept only RFC compliant MIME words. */
52 /* Increase it if you want to match headers from buggy MUAs. */
53 #define MIMEWORD_LENGTH 75
64 #ifdef ENCODED_CHARACTER
65 int require_encoded_character;
68 int require_envelope_auth;
72 struct Notification *notified;
75 int require_subaddress;
81 uschar *vacation_directory;
82 const uschar *subaddress;
83 const uschar *useraddress;
85 int require_iascii_numeric;
88 enum Comparator { COMP_OCTET, COMP_EN_ASCII_CASEMAP, COMP_ASCII_NUMERIC };
89 enum MatchType { MATCH_IS, MATCH_CONTAINS, MATCH_MATCHES };
91 enum AddressPart { ADDRPART_USER, ADDRPART_DETAIL, ADDRPART_LOCALPART, ADDRPART_DOMAIN, ADDRPART_ALL };
93 enum AddressPart { ADDRPART_LOCALPART, ADDRPART_DOMAIN, ADDRPART_ALL };
95 enum RelOp { LT, LE, EQ, GE, GT, NE };
105 struct String method;
106 struct String importance;
107 struct String message;
108 struct Notification *next;
111 static int eq_asciicase(const struct String *needle, const struct String *haystack, int match_prefix);
112 static int parse_test(struct Sieve *filter, int *cond, int exec);
113 static int parse_commands(struct Sieve *filter, int exec, address_item **generated);
115 static uschar str_from_c[]="From";
116 static const struct String str_from={ str_from_c, 4 };
117 static uschar str_to_c[]="To";
118 static const struct String str_to={ str_to_c, 2 };
119 static uschar str_cc_c[]="Cc";
120 static const struct String str_cc={ str_cc_c, 2 };
121 static uschar str_bcc_c[]="Bcc";
122 static const struct String str_bcc={ str_bcc_c, 3 };
123 static uschar str_auth_c[]="auth";
124 static const struct String str_auth={ str_auth_c, 4 };
125 static uschar str_sender_c[]="Sender";
126 static const struct String str_sender={ str_sender_c, 6 };
127 static uschar str_resent_from_c[]="Resent-From";
128 static const struct String str_resent_from={ str_resent_from_c, 11 };
129 static uschar str_resent_to_c[]="Resent-To";
130 static const struct String str_resent_to={ str_resent_to_c, 9 };
131 static uschar str_fileinto_c[]="fileinto";
132 static const struct String str_fileinto={ str_fileinto_c, 8 };
133 static uschar str_envelope_c[]="envelope";
134 static const struct String str_envelope={ str_envelope_c, 8 };
135 #ifdef ENCODED_CHARACTER
136 static uschar str_encoded_character_c[]="encoded-character";
137 static const struct String str_encoded_character={ str_encoded_character_c, 17 };
140 static uschar str_envelope_auth_c[]="envelope-auth";
141 static const struct String str_envelope_auth={ str_envelope_auth_c, 13 };
144 static uschar str_enotify_c[]="enotify";
145 static const struct String str_enotify={ str_enotify_c, 7 };
148 static uschar str_subaddress_c[]="subaddress";
149 static const struct String str_subaddress={ str_subaddress_c, 10 };
152 static uschar str_vacation_c[]="vacation";
153 static const struct String str_vacation={ str_vacation_c, 8 };
154 static uschar str_subject_c[]="Subject";
155 static const struct String str_subject={ str_subject_c, 7 };
157 static uschar str_copy_c[]="copy";
158 static const struct String str_copy={ str_copy_c, 4 };
159 static uschar str_iascii_casemap_c[]="i;ascii-casemap";
160 static const struct String str_iascii_casemap={ str_iascii_casemap_c, 15 };
161 static uschar str_enascii_casemap_c[]="en;ascii-casemap";
162 static const struct String str_enascii_casemap={ str_enascii_casemap_c, 16 };
163 static uschar str_ioctet_c[]="i;octet";
164 static const struct String str_ioctet={ str_ioctet_c, 7 };
165 static uschar str_iascii_numeric_c[]="i;ascii-numeric";
166 static const struct String str_iascii_numeric={ str_iascii_numeric_c, 15 };
167 static uschar str_comparator_iascii_casemap_c[]="comparator-i;ascii-casemap";
168 static const struct String str_comparator_iascii_casemap={ str_comparator_iascii_casemap_c, 26 };
169 static uschar str_comparator_enascii_casemap_c[]="comparator-en;ascii-casemap";
170 static const struct String str_comparator_enascii_casemap={ str_comparator_enascii_casemap_c, 27 };
171 static uschar str_comparator_ioctet_c[]="comparator-i;octet";
172 static const struct String str_comparator_ioctet={ str_comparator_ioctet_c, 18 };
173 static uschar str_comparator_iascii_numeric_c[]="comparator-i;ascii-numeric";
174 static const struct String str_comparator_iascii_numeric={ str_comparator_iascii_numeric_c, 26 };
177 /*************************************************
178 * Encode to quoted-printable *
179 *************************************************/
190 static struct String *quoted_printable_encode(const struct String *src, struct String *dst)
193 const uschar *start,*end;
198 for (pass=0; pass<=1; ++pass)
205 dst->character=store_get(dst->length+1); /* plus one for \0 */
208 for (start=src->character,end=start+src->length; start<end; ++start)
225 || (ch>=62 && ch<=126)
230 && (*(start+1)!='\r' || *(start+2)!='\n')
240 else if (ch=='\r' && start+1<end && *(start+1)=='\n')
258 sprintf(CS new,"=%02X",ch);
265 *new='\0'; /* not included in length, but nice */
270 /*************************************************
271 * Check mail address for correct syntax *
272 *************************************************/
275 Check mail address for being syntactically correct.
278 filter points to the Sieve filter including its state
279 address String containing one address
282 1 Mail address is syntactically OK
286 int check_mail_address(struct Sieve *filter, const struct String *address)
288 int start, end, domain;
291 if (address->length>0)
293 ss = parse_extract_address(address->character, &error, &start, &end, &domain,
297 filter->errmsg=string_sprintf("malformed address \"%s\" (%s)",
298 address->character, error);
306 filter->errmsg=CUS "empty address";
312 /*************************************************
313 * Decode URI encoded string *
314 *************************************************/
318 str URI encoded string
321 0 Decoding successful
326 static int uri_decode(struct String *str)
330 if (str->length==0) return 0;
331 for (s=str->character,t=s,e=s+str->length; s<e; )
335 if (s+2<e && isxdigit(*(s+1)) && isxdigit(*(s+2)))
337 *t++=((isdigit(*(s+1)) ? *(s+1)-'0' : tolower(*(s+1))-'a'+10)<<4)
338 | (isdigit(*(s+2)) ? *(s+2)-'0' : tolower(*(s+2))-'a'+10);
347 str->length=t-str->character;
352 /*************************************************
354 *************************************************/
359 mailtoURI = "mailto:" [ to ] [ headers ]
360 to = [ addr-spec *("%2C" addr-spec ) ]
361 headers = "?" header *( "&" header )
362 header = hname "=" hvalue
367 filter points to the Sieve filter including its state
368 uri URI, excluding scheme
373 1 URI is syntactically OK
378 static int parse_mailto_uri(struct Sieve *filter, const uschar *uri, string_item **recipient, struct String *header, struct String *body)
381 struct String to,hname,hvalue;
385 if (Ustrncmp(uri,"mailto:",7))
387 filter->errmsg=US "Unknown URI scheme";
391 if (*uri && *uri!='?')
395 for (start=uri; *uri && *uri!='?' && (*uri!='%' || *(uri+1)!='2' || tolower(*(uri+2))!='c'); ++uri);
399 to.character=(uschar*)0;
401 to.character=string_cat(to.character,&capacity,&to.length,start,uri-start);
402 to.character[to.length]='\0';
403 if (uri_decode(&to)==-1)
405 filter->errmsg=US"Invalid URI encoding";
408 new=store_get(sizeof(string_item));
409 new->text=store_get(to.length+1);
410 if (to.length) memcpy(new->text,to.character,to.length);
411 new->text[to.length]='\0';
412 new->next=*recipient;
417 filter->errmsg=US"Missing addr-spec in URI";
420 if (*uri=='%') uri+=3;
429 for (start=uri; *uri && (isalnum(*uri) || strchr("$-_.+!*'(),%",*uri)); ++uri);
433 hname.character=(uschar*)0;
435 hname.character=string_cat(hname.character,&capacity,&hname.length,start,uri-start);
436 hname.character[hname.length]='\0';
437 if (uri_decode(&hname)==-1)
439 filter->errmsg=US"Invalid URI encoding";
448 filter->errmsg=US"Missing equal after hname";
452 for (start=uri; *uri && (isalnum(*uri) || strchr("$-_.+!*'(),%",*uri)); ++uri);
456 hvalue.character=(uschar*)0;
458 hvalue.character=string_cat(hvalue.character,&capacity,&hvalue.length,start,uri-start);
459 hvalue.character[hvalue.length]='\0';
460 if (uri_decode(&hvalue)==-1)
462 filter->errmsg=US"Invalid URI encoding";
466 if (hname.length==2 && strcmpic(hname.character, US"to")==0)
468 new=store_get(sizeof(string_item));
469 new->text=store_get(hvalue.length+1);
470 if (hvalue.length) memcpy(new->text,hvalue.character,hvalue.length);
471 new->text[hvalue.length]='\0';
472 new->next=*recipient;
475 else if (hname.length==4 && strcmpic(hname.character, US"body")==0)
479 static struct String ignore[]=
485 static struct String *end=ignore+sizeof(ignore)/sizeof(ignore[0]);
488 for (i=ignore; i<end && !eq_asciicase(&hname,i,0); ++i);
491 if (header->length==-1) header->length=0;
492 capacity=header->length;
493 header->character=string_cat(header->character,&capacity,&header->length,hname.character,hname.length);
494 header->character=string_cat(header->character,&capacity,&header->length,CUS ": ",2);
495 header->character=string_cat(header->character,&capacity,&header->length,hvalue.character,hvalue.length);
496 header->character=string_cat(header->character,&capacity,&header->length,CUS "\n",1);
497 header->character[header->length]='\0';
500 if (*uri=='&') ++uri;
506 filter->errmsg=US"Syntactically invalid URI";
514 /*************************************************
515 * Octet-wise string comparison *
516 *************************************************/
520 needle UTF-8 string to search ...
521 haystack ... inside the haystack
522 match_prefix 1 to compare if needle is a prefix of haystack
524 Returns: 0 needle not found in haystack
528 static int eq_octet(const struct String *needle,
529 const struct String *haystack, int match_prefix)
537 h=haystack->character;
541 if (*n&0x80) return 0;
542 if (*h&0x80) return 0;
544 if (*n!=*h) return 0;
550 return (match_prefix ? nl==0 : nl==0 && hl==0);
554 /*************************************************
555 * ASCII case-insensitive string comparison *
556 *************************************************/
560 needle UTF-8 string to search ...
561 haystack ... inside the haystack
562 match_prefix 1 to compare if needle is a prefix of haystack
564 Returns: 0 needle not found in haystack
568 static int eq_asciicase(const struct String *needle,
569 const struct String *haystack, int match_prefix)
578 h=haystack->character;
584 if (nc&0x80) return 0;
585 if (hc&0x80) return 0;
587 /* tolower depends on the locale and only ASCII case must be insensitive */
588 if ((nc>='A' && nc<='Z' ? nc|0x20 : nc) != (hc>='A' && hc<='Z' ? hc|0x20 : hc)) return 0;
594 return (match_prefix ? nl==0 : nl==0 && hl==0);
598 /*************************************************
599 * Glob pattern search *
600 *************************************************/
604 needle pattern to search ...
605 haystack ... inside the haystack
607 Returns: 0 needle not found in haystack
612 static int eq_glob(const struct String *needle,
613 const struct String *haystack, int ascii_caseless, int match_octet)
615 const uschar *n,*h,*nend,*hend;
619 h=haystack->character;
620 nend=n+needle->length;
621 hend=h+haystack->length;
631 const uschar *npart,*hpart;
633 /* Try to match a non-star part of the needle at the current */
634 /* position in the haystack. */
638 while (npart<nend && *npart!='*') switch (*npart)
642 if (hpart==hend) return 0;
647 /* Match one UTF8 encoded character */
648 if ((*hpart&0xc0)==0xc0)
651 while (hpart<hend && ((*hpart&0xc0)==0x80)) ++hpart;
662 if (npart==nend) return -1;
667 if (hpart==hend) return 0;
668 /* tolower depends on the locale, but we need ASCII */
672 (*hpart&0x80) || (*npart&0x80) ||
675 ? ((*npart>='A' && *npart<='Z' ? *npart|0x20 : *npart) != (*hpart>='A' && *hpart<='Z' ? *hpart|0x20 : *hpart))
680 /* string match after a star failed, advance and try again */
694 /* at this point, a part was matched successfully */
695 if (may_advance && npart==nend && hpart<hend)
696 /* needle ends, but haystack does not: if there was a star before, advance and try again */
706 return (h==hend ? 1 : may_advance);
710 /*************************************************
711 * ASCII numeric comparison *
712 *************************************************/
716 a first numeric string
717 b second numeric string
718 relop relational operator
720 Returns: 0 not (a relop b)
724 static int eq_asciinumeric(const struct String *a,
725 const struct String *b, enum RelOp relop)
728 const uschar *as,*aend,*bs,*bend;
732 aend=a->character+a->length;
734 bend=b->character+b->length;
736 while (*as>='0' && *as<='9' && as<aend) ++as;
738 while (*bs>='0' && *bs<='9' && bs<bend) ++bs;
741 if (al && bl==0) cmp=-1;
742 else if (al==0 && bl==0) cmp=0;
743 else if (al==0 && bl) cmp=1;
747 if (cmp==0) cmp=memcmp(a->character,b->character,al);
751 case LT: return cmp<0;
752 case LE: return cmp<=0;
753 case EQ: return cmp==0;
754 case GE: return cmp>=0;
755 case GT: return cmp>0;
756 case NE: return cmp!=0;
763 /*************************************************
765 *************************************************/
769 filter points to the Sieve filter including its state
770 needle UTF-8 pattern or string to search ...
771 haystack ... inside the haystack
775 Returns: 0 needle not found in haystack
777 -1 comparator does not offer matchtype
780 static int compare(struct Sieve *filter, const struct String *needle, const struct String *haystack,
781 enum Comparator co, enum MatchType mt)
785 if ((filter_test != FTEST_NONE && debug_selector != 0) ||
786 (debug_selector & D_filter) != 0)
788 debug_printf("String comparison (match ");
791 case MATCH_IS: debug_printf(":is"); break;
792 case MATCH_CONTAINS: debug_printf(":contains"); break;
793 case MATCH_MATCHES: debug_printf(":matches"); break;
795 debug_printf(", comparison \"");
798 case COMP_OCTET: debug_printf("i;octet"); break;
799 case COMP_EN_ASCII_CASEMAP: debug_printf("en;ascii-casemap"); break;
800 case COMP_ASCII_NUMERIC: debug_printf("i;ascii-numeric"); break;
802 debug_printf("\"):\n");
803 debug_printf(" Search = %s (%d chars)\n", needle->character,needle->length);
804 debug_printf(" Inside = %s (%d chars)\n", haystack->character,haystack->length);
814 if (eq_octet(needle,haystack,0)) r=1;
817 case COMP_EN_ASCII_CASEMAP:
819 if (eq_asciicase(needle,haystack,0)) r=1;
822 case COMP_ASCII_NUMERIC:
824 if (!filter->require_iascii_numeric)
826 filter->errmsg=CUS "missing previous require \"comparator-i;ascii-numeric\";";
829 if (eq_asciinumeric(needle,haystack,EQ)) r=1;
843 for (h=*haystack; h.length; ++h.character,--h.length) if (eq_octet(needle,&h,1)) { r=1; break; }
846 case COMP_EN_ASCII_CASEMAP:
848 for (h=*haystack; h.length; ++h.character,--h.length) if (eq_asciicase(needle,&h,1)) { r=1; break; }
853 filter->errmsg=CUS "comparator does not offer specified matchtype";
865 if ((r=eq_glob(needle,haystack,0,1))==-1)
867 filter->errmsg=CUS "syntactically invalid pattern";
872 case COMP_EN_ASCII_CASEMAP:
874 if ((r=eq_glob(needle,haystack,1,1))==-1)
876 filter->errmsg=CUS "syntactically invalid pattern";
883 filter->errmsg=CUS "comparator does not offer specified matchtype";
890 if ((filter_test != FTEST_NONE && debug_selector != 0) ||
891 (debug_selector & D_filter) != 0)
892 debug_printf(" Result %s\n",r?"true":"false");
897 /*************************************************
898 * Check header field syntax *
899 *************************************************/
902 RFC 2822, section 3.6.8 says:
906 ftext = %d33-57 / ; Any character except
907 %d59-126 ; controls, SP, and
910 That forbids 8-bit header fields. This implementation accepts them, since
911 all of Exim is 8-bit clean, so it adds %d128-%d255.
914 header header field to quote for suitable use in Exim expansions
916 Returns: 0 string is not a valid header field
917 1 string is a value header field
920 static int is_header(const struct String *header)
930 if (((unsigned char)*h)<33 || ((unsigned char)*h)==':' || ((unsigned char)*h)==127) return 0;
941 /*************************************************
942 * Quote special characters string *
943 *************************************************/
947 header header field to quote for suitable use in Exim expansions
950 Returns: quoted string
953 static const uschar *quote(const struct String *header)
968 quoted=string_cat(quoted,&size,&ptr,CUS "\\0",2);
975 quoted=string_cat(quoted,&size,&ptr,CUS "\\",1);
979 quoted=string_cat(quoted,&size,&ptr,h,1);
985 quoted=string_cat(quoted,&size,&ptr,CUS "",1);
990 /*************************************************
991 * Add address to list of generated addresses *
992 *************************************************/
995 According to RFC 3028, duplicate delivery to the same address must
996 not happen, so the list is first searched for the address.
999 generated list of generated addresses
1000 addr new address to add
1001 file address denotes a file
1006 static void add_addr(address_item **generated, uschar *addr, int file, int maxage, int maxmessages, int maxstorage)
1008 address_item *new_addr;
1010 for (new_addr=*generated; new_addr; new_addr=new_addr->next)
1012 if (Ustrcmp(new_addr->address,addr)==0 && (file ? testflag(new_addr, af_pfr|af_file) : 1))
1014 if ((filter_test != FTEST_NONE && debug_selector != 0) || (debug_selector & D_filter) != 0)
1016 debug_printf("Repeated %s `%s' ignored.\n",file ? "fileinto" : "redirect", addr);
1022 if ((filter_test != FTEST_NONE && debug_selector != 0) || (debug_selector & D_filter) != 0)
1024 debug_printf("%s `%s'\n",file ? "fileinto" : "redirect", addr);
1026 new_addr=deliver_make_addr(addr,TRUE);
1029 setflag(new_addr, af_pfr|af_file);
1032 new_addr->p.errors_address = NULL;
1033 new_addr->next = *generated;
1034 *generated = new_addr;
1038 /*************************************************
1039 * Return decoded header field *
1040 *************************************************/
1043 Unfold the header field as described in RFC 2822 and remove all
1044 leading and trailing white space, then perform MIME decoding and
1045 translate the header field to UTF-8.
1048 value returned value of the field
1049 header name of the header field
1051 Returns: nothing The expanded string is empty
1052 in case there is no such header
1055 static void expand_header(struct String *value, const struct String *header)
1061 value->character=(uschar*)0;
1063 t=r=s=expand_string(string_sprintf("$rheader_%s",quote(header)));
1064 while (*r==' ' || *r=='\t') ++r;
1072 while (t>s && (*(t-1)==' ' || *(t-1)=='\t')) --t;
1074 value->character=rfc2047_decode(s,check_rfc2047_length,US"utf-8",'\0',&value->length,&errmsg);
1078 /*************************************************
1079 * Parse remaining hash comment *
1080 *************************************************/
1084 Comment up to terminating CRLF
1087 filter points to the Sieve filter including its state
1093 static int parse_hashcomment(struct Sieve *filter)
1099 if (*filter->pc=='\r' && *(filter->pc+1)=='\n')
1101 if (*filter->pc=='\n')
1114 filter->errmsg=CUS "missing end of comment";
1119 /*************************************************
1120 * Parse remaining C-style comment *
1121 *************************************************/
1125 Everything up to star slash
1128 filter points to the Sieve filter including its state
1134 static int parse_comment(struct Sieve *filter)
1139 if (*filter->pc=='*' && *(filter->pc+1)=='/')
1146 filter->errmsg=CUS "missing end of comment";
1151 /*************************************************
1152 * Parse optional white space *
1153 *************************************************/
1157 Spaces, tabs, CRLFs, hash comments or C-style comments
1160 filter points to the Sieve filter including its state
1166 static int parse_white(struct Sieve *filter)
1170 if (*filter->pc==' ' || *filter->pc=='\t') ++filter->pc;
1172 else if (*filter->pc=='\r' && *(filter->pc+1)=='\n')
1174 else if (*filter->pc=='\n')
1184 else if (*filter->pc=='#')
1186 if (parse_hashcomment(filter)==-1) return -1;
1188 else if (*filter->pc=='/' && *(filter->pc+1)=='*')
1190 if (parse_comment(filter)==-1) return -1;
1198 /*************************************************
1199 * Parse a optional string *
1200 *************************************************/
1204 quoted-string = DQUOTE *CHAR DQUOTE
1205 ;; in general, \ CHAR inside a string maps to CHAR
1206 ;; so \" maps to " and \\ maps to \
1207 ;; note that newlines and other characters are all allowed
1210 multi-line = "text:" *(SP / HTAB) (hash-comment / CRLF)
1211 *(multi-line-literal / multi-line-dotstuff)
1213 multi-line-literal = [CHAR-NOT-DOT *CHAR-NOT-CRLF] CRLF
1214 multi-line-dotstuff = "." 1*CHAR-NOT-CRLF CRLF
1215 ;; A line containing only "." ends the multi-line.
1216 ;; Remove a leading '.' if followed by another '.'.
1217 string = quoted-string / multi-line
1220 filter points to the Sieve filter including its state
1221 id specifies identifier to match
1225 0 identifier not matched
1228 static int parse_string(struct Sieve *filter, struct String *data)
1233 data->character=(uschar*)0;
1234 if (*filter->pc=='"') /* quoted string */
1239 if (*filter->pc=='"') /* end of string */
1241 int foo=data->length;
1244 /* that way, there will be at least one character allocated */
1245 data->character=string_cat(data->character,&dataCapacity,&foo,CUS "",1);
1248 else if (*filter->pc=='\\' && *(filter->pc+1)) /* quoted character */
1250 if (*(filter->pc+1)=='0') data->character=string_cat(data->character,&dataCapacity,&data->length,CUS "",1);
1251 else data->character=string_cat(data->character,&dataCapacity,&data->length,filter->pc+1,1);
1254 else /* regular character */
1257 if (*filter->pc=='\r' && *(filter->pc+1)=='\n') ++filter->line;
1259 if (*filter->pc=='\n')
1261 data->character=string_cat(data->character,&dataCapacity,&data->length,US"\r",1);
1265 data->character=string_cat(data->character,&dataCapacity,&data->length,filter->pc,1);
1269 filter->errmsg=CUS "missing end of string";
1272 else if (Ustrncmp(filter->pc,CUS "text:",5)==0) /* multiline string */
1275 /* skip optional white space followed by hashed comment or CRLF */
1276 while (*filter->pc==' ' || *filter->pc=='\t') ++filter->pc;
1277 if (*filter->pc=='#')
1279 if (parse_hashcomment(filter)==-1) return -1;
1282 else if (*filter->pc=='\r' && *(filter->pc+1)=='\n')
1284 else if (*filter->pc=='\n')
1296 filter->errmsg=CUS "syntax error";
1302 if (*filter->pc=='\r' && *(filter->pc+1)=='\n') /* end of line */
1304 if (*filter->pc=='\n') /* end of line */
1307 data->character=string_cat(data->character,&dataCapacity,&data->length,CUS "\r\n",2);
1315 if (*filter->pc=='.' && *(filter->pc+1)=='\r' && *(filter->pc+2)=='\n') /* end of string */
1317 if (*filter->pc=='.' && *(filter->pc+1)=='\n') /* end of string */
1320 int foo=data->length;
1322 /* that way, there will be at least one character allocated */
1323 data->character=string_cat(data->character,&dataCapacity,&foo,CUS "",1);
1332 else if (*filter->pc=='.' && *(filter->pc+1)=='.') /* remove dot stuffing */
1334 data->character=string_cat(data->character,&dataCapacity,&data->length,CUS ".",1);
1338 else /* regular character */
1340 data->character=string_cat(data->character,&dataCapacity,&data->length,filter->pc,1);
1344 filter->errmsg=CUS "missing end of multi line string";
1351 /*************************************************
1352 * Parse a specific identifier *
1353 *************************************************/
1357 identifier = (ALPHA / "_") *(ALPHA DIGIT "_")
1360 filter points to the Sieve filter including its state
1361 id specifies identifier to match
1364 0 identifier not matched
1367 static int parse_identifier(struct Sieve *filter, const uschar *id)
1369 size_t idlen=Ustrlen(id);
1371 if (Ustrncmp(filter->pc,id,idlen)==0)
1373 uschar next=filter->pc[idlen];
1375 if ((next>='A' && next<='Z') || (next>='a' && next<='z') || next=='_' || (next>='0' && next<='9')) return 0;
1383 /*************************************************
1385 *************************************************/
1389 number = 1*DIGIT [QUANTIFIER]
1390 QUANTIFIER = "K" / "M" / "G"
1393 filter points to the Sieve filter including its state
1397 -1 no string list found
1400 static int parse_number(struct Sieve *filter, unsigned long *data)
1404 if (*filter->pc>='0' && *filter->pc<='9')
1409 d=Ustrtoul(filter->pc,&e,10);
1412 filter->errmsg=CUstrerror(ERANGE);
1417 if (*filter->pc=='K') { u=1024; ++filter->pc; }
1418 else if (*filter->pc=='M') { u=1024*1024; ++filter->pc; }
1419 else if (*filter->pc=='G') { u=1024*1024*1024; ++filter->pc; }
1420 if (d>(ULONG_MAX/u))
1422 filter->errmsg=CUstrerror(ERANGE);
1431 filter->errmsg=CUS "missing number";
1437 /*************************************************
1438 * Parse a string list *
1439 *************************************************/
1443 string-list = "[" string *("," string) "]" / string
1446 filter points to the Sieve filter including its state
1447 data returns string list
1450 -1 no string list found
1453 static int parse_stringlist(struct Sieve *filter, struct String **data)
1455 const uschar *orig=filter->pc;
1458 struct String *d=(struct String*)0;
1461 if (*filter->pc=='[') /* string list */
1466 if (parse_white(filter)==-1) goto error;
1467 if ((dataLength+1)>=dataCapacity) /* increase buffer */
1470 int newCapacity; /* Don't amalgamate with next line; some compilers grumble */
1471 newCapacity=dataCapacity?(dataCapacity*=2):(dataCapacity=4);
1472 if ((new=(struct String*)store_get(sizeof(struct String)*newCapacity))==(struct String*)0)
1474 filter->errmsg=CUstrerror(errno);
1477 if (d) memcpy(new,d,sizeof(struct String)*dataLength);
1479 dataCapacity=newCapacity;
1481 m=parse_string(filter,&d[dataLength]);
1484 if (dataLength==0) break;
1487 filter->errmsg=CUS "missing string";
1491 else if (m==-1) goto error;
1493 if (parse_white(filter)==-1) goto error;
1494 if (*filter->pc==',') ++filter->pc;
1497 if (*filter->pc==']')
1499 d[dataLength].character=(uschar*)0;
1500 d[dataLength].length=-1;
1507 filter->errmsg=CUS "missing closing bracket";
1511 else /* single string */
1513 if ((d=store_get(sizeof(struct String)*2))==(struct String*)0)
1517 m=parse_string(filter,&d[0]);
1529 d[1].character=(uschar*)0;
1536 filter->errmsg=CUS "missing string list";
1541 /*************************************************
1542 * Parse an optional address part specifier *
1543 *************************************************/
1547 address-part = ":localpart" / ":domain" / ":all"
1548 address-part =/ ":user" / ":detail"
1551 filter points to the Sieve filter including its state
1552 a returns address part specified
1555 0 no comparator found
1559 static int parse_addresspart(struct Sieve *filter, enum AddressPart *a)
1562 if (parse_identifier(filter,CUS ":user")==1)
1564 if (!filter->require_subaddress)
1566 filter->errmsg=CUS "missing previous require \"subaddress\";";
1572 else if (parse_identifier(filter,CUS ":detail")==1)
1574 if (!filter->require_subaddress)
1576 filter->errmsg=CUS "missing previous require \"subaddress\";";
1584 if (parse_identifier(filter,CUS ":localpart")==1)
1586 *a=ADDRPART_LOCALPART;
1589 else if (parse_identifier(filter,CUS ":domain")==1)
1594 else if (parse_identifier(filter,CUS ":all")==1)
1603 /*************************************************
1604 * Parse an optional comparator *
1605 *************************************************/
1609 comparator = ":comparator" <comparator-name: string>
1612 filter points to the Sieve filter including its state
1613 c returns comparator
1616 0 no comparator found
1617 -1 incomplete comparator found
1620 static int parse_comparator(struct Sieve *filter, enum Comparator *c)
1622 struct String comparator_name;
1624 if (parse_identifier(filter,CUS ":comparator")==0) return 0;
1625 if (parse_white(filter)==-1) return -1;
1626 switch (parse_string(filter,&comparator_name))
1631 filter->errmsg=CUS "missing comparator";
1638 if (eq_asciicase(&comparator_name,&str_ioctet,0))
1643 else if (eq_asciicase(&comparator_name,&str_iascii_casemap,0))
1645 *c=COMP_EN_ASCII_CASEMAP;
1648 else if (eq_asciicase(&comparator_name,&str_enascii_casemap,0))
1650 *c=COMP_EN_ASCII_CASEMAP;
1653 else if (eq_asciicase(&comparator_name,&str_iascii_numeric,0))
1655 *c=COMP_ASCII_NUMERIC;
1660 filter->errmsg=CUS "invalid comparator";
1669 /*************************************************
1670 * Parse an optional match type *
1671 *************************************************/
1675 match-type = ":is" / ":contains" / ":matches"
1678 filter points to the Sieve filter including its state
1679 m returns match type
1682 0 no match type found
1685 static int parse_matchtype(struct Sieve *filter, enum MatchType *m)
1687 if (parse_identifier(filter,CUS ":is")==1)
1692 else if (parse_identifier(filter,CUS ":contains")==1)
1697 else if (parse_identifier(filter,CUS ":matches")==1)
1706 /*************************************************
1707 * Parse and interpret an optional test list *
1708 *************************************************/
1712 test-list = "(" test *("," test) ")"
1715 filter points to the Sieve filter including its state
1716 n total number of tests
1717 true number of passed tests
1718 exec Execute parsed statements
1721 0 no test list found
1722 -1 syntax or execution error
1725 static int parse_testlist(struct Sieve *filter, int *n, int *true, int exec)
1727 if (parse_white(filter)==-1) return -1;
1728 if (*filter->pc=='(')
1737 switch (parse_test(filter,&cond,exec))
1740 case 0: filter->errmsg=CUS "missing test"; return -1;
1741 default: ++*n; if (cond) ++*true; break;
1743 if (parse_white(filter)==-1) return -1;
1744 if (*filter->pc==',') ++filter->pc;
1747 if (*filter->pc==')')
1754 filter->errmsg=CUS "missing closing paren";
1762 /*************************************************
1763 * Parse and interpret an optional test *
1764 *************************************************/
1768 filter points to the Sieve filter including its state
1769 cond returned condition status
1770 exec Execute parsed statements
1774 -1 syntax or execution error
1777 static int parse_test(struct Sieve *filter, int *cond, int exec)
1779 if (parse_white(filter)==-1) return -1;
1780 if (parse_identifier(filter,CUS "address"))
1783 address-test = "address" { [address-part] [comparator] [match-type] }
1784 <header-list: string-list> <key-list: string-list>
1786 header-list From, To, Cc, Bcc, Sender, Resent-From, Resent-To
1789 enum AddressPart addressPart=ADDRPART_ALL;
1790 enum Comparator comparator=COMP_EN_ASCII_CASEMAP;
1791 enum MatchType matchType=MATCH_IS;
1792 struct String *hdr,*h,*key,*k;
1798 if (parse_white(filter)==-1) return -1;
1799 if ((m=parse_addresspart(filter,&addressPart))!=0)
1801 if (m==-1) return -1;
1804 filter->errmsg=CUS "address part already specified";
1809 else if ((m=parse_comparator(filter,&comparator))!=0)
1811 if (m==-1) return -1;
1814 filter->errmsg=CUS "comparator already specified";
1819 else if ((m=parse_matchtype(filter,&matchType))!=0)
1821 if (m==-1) return -1;
1824 filter->errmsg=CUS "match type already specified";
1831 if (parse_white(filter)==-1) return -1;
1832 if ((m=parse_stringlist(filter,&hdr))!=1)
1834 if (m==0) filter->errmsg=CUS "header string list expected";
1837 if (parse_white(filter)==-1) return -1;
1838 if ((m=parse_stringlist(filter,&key))!=1)
1840 if (m==0) filter->errmsg=CUS "key string list expected";
1844 for (h=hdr; h->length!=-1 && !*cond; ++h)
1846 uschar *header_value=(uschar*)0,*extracted_addr,*end_addr;
1850 !eq_asciicase(h,&str_from,0)
1851 && !eq_asciicase(h,&str_to,0)
1852 && !eq_asciicase(h,&str_cc,0)
1853 && !eq_asciicase(h,&str_bcc,0)
1854 && !eq_asciicase(h,&str_sender,0)
1855 && !eq_asciicase(h,&str_resent_from,0)
1856 && !eq_asciicase(h,&str_resent_to,0)
1859 filter->errmsg=CUS "invalid header field";
1864 /* We are only interested in addresses below, so no MIME decoding */
1865 header_value=expand_string(string_sprintf("$rheader_%s",quote(h)));
1866 if (header_value == NULL)
1868 filter->errmsg=CUS "header string expansion failed";
1871 parse_allow_group = TRUE;
1872 while (*header_value && !*cond)
1875 int start, end, domain;
1879 end_addr = parse_find_address_end(header_value, FALSE);
1880 saveend = *end_addr;
1882 extracted_addr = parse_extract_address(header_value, &error, &start, &end, &domain, FALSE);
1884 if (extracted_addr) switch (addressPart)
1886 case ADDRPART_ALL: part=extracted_addr; break;
1890 case ADDRPART_LOCALPART: part=extracted_addr; part[domain-1]='\0'; break;
1891 case ADDRPART_DOMAIN: part=extracted_addr+domain; break;
1893 case ADDRPART_DETAIL: part=NULL; break;
1897 *end_addr = saveend;
1900 for (k=key; k->length!=-1; ++k)
1902 struct String partStr;
1904 partStr.character=part;
1905 partStr.length=Ustrlen(part);
1908 *cond=compare(filter,k,&partStr,comparator,matchType);
1909 if (*cond==-1) return -1;
1914 if (saveend == 0) break;
1915 header_value = end_addr + 1;
1917 parse_allow_group = FALSE;
1918 parse_found_group = FALSE;
1923 else if (parse_identifier(filter,CUS "allof"))
1926 allof-test = "allof" <tests: test-list>
1931 switch (parse_testlist(filter,&n,&true,exec))
1934 case 0: filter->errmsg=CUS "missing test list"; return -1;
1935 default: *cond=(n==true); return 1;
1938 else if (parse_identifier(filter,CUS "anyof"))
1941 anyof-test = "anyof" <tests: test-list>
1946 switch (parse_testlist(filter,&n,&true,exec))
1949 case 0: filter->errmsg=CUS "missing test list"; return -1;
1950 default: *cond=(true>0); return 1;
1953 else if (parse_identifier(filter,CUS "exists"))
1956 exists-test = "exists" <header-names: string-list>
1959 struct String *hdr,*h;
1962 if (parse_white(filter)==-1) return -1;
1963 if ((m=parse_stringlist(filter,&hdr))!=1)
1965 if (m==0) filter->errmsg=CUS "header string list expected";
1971 for (h=hdr; h->length!=-1 && *cond; ++h)
1975 header_def=expand_string(string_sprintf("${if def:header_%s {true}{false}}",quote(h)));
1976 if (header_def == NULL)
1978 filter->errmsg=CUS "header string expansion failed";
1981 if (Ustrcmp(header_def,"false")==0) *cond=0;
1986 else if (parse_identifier(filter,CUS "false"))
1989 false-test = "false"
1995 else if (parse_identifier(filter,CUS "header"))
1998 header-test = "header" { [comparator] [match-type] }
1999 <header-names: string-list> <key-list: string-list>
2002 enum Comparator comparator=COMP_EN_ASCII_CASEMAP;
2003 enum MatchType matchType=MATCH_IS;
2004 struct String *hdr,*h,*key,*k;
2010 if (parse_white(filter)==-1) return -1;
2011 if ((m=parse_comparator(filter,&comparator))!=0)
2013 if (m==-1) return -1;
2016 filter->errmsg=CUS "comparator already specified";
2021 else if ((m=parse_matchtype(filter,&matchType))!=0)
2023 if (m==-1) return -1;
2026 filter->errmsg=CUS "match type already specified";
2033 if (parse_white(filter)==-1) return -1;
2034 if ((m=parse_stringlist(filter,&hdr))!=1)
2036 if (m==0) filter->errmsg=CUS "header string list expected";
2039 if (parse_white(filter)==-1) return -1;
2040 if ((m=parse_stringlist(filter,&key))!=1)
2042 if (m==0) filter->errmsg=CUS "key string list expected";
2046 for (h=hdr; h->length!=-1 && !*cond; ++h)
2050 filter->errmsg=CUS "invalid header field";
2055 struct String header_value;
2058 expand_header(&header_value,h);
2059 header_def=expand_string(string_sprintf("${if def:header_%s {true}{false}}",quote(h)));
2060 if (header_value.character == NULL || header_def == NULL)
2062 filter->errmsg=CUS "header string expansion failed";
2065 for (k=key; k->length!=-1; ++k)
2067 if (Ustrcmp(header_def,"true")==0)
2069 *cond=compare(filter,k,&header_value,comparator,matchType);
2070 if (*cond==-1) return -1;
2078 else if (parse_identifier(filter,CUS "not"))
2080 if (parse_white(filter)==-1) return -1;
2081 switch (parse_test(filter,cond,exec))
2084 case 0: filter->errmsg=CUS "missing test"; return -1;
2085 default: *cond=!*cond; return 1;
2088 else if (parse_identifier(filter,CUS "size"))
2091 relop = ":over" / ":under"
2092 size-test = "size" relop <limit: number>
2095 unsigned long limit;
2098 if (parse_white(filter)==-1) return -1;
2099 if (parse_identifier(filter,CUS ":over")) overNotUnder=1;
2100 else if (parse_identifier(filter,CUS ":under")) overNotUnder=0;
2103 filter->errmsg=CUS "missing :over or :under";
2106 if (parse_white(filter)==-1) return -1;
2107 if (parse_number(filter,&limit)==-1) return -1;
2108 *cond=(overNotUnder ? (message_size>limit) : (message_size<limit));
2111 else if (parse_identifier(filter,CUS "true"))
2116 else if (parse_identifier(filter,CUS "envelope"))
2119 envelope-test = "envelope" { [comparator] [address-part] [match-type] }
2120 <envelope-part: string-list> <key-list: string-list>
2122 envelope-part is case insensitive "from" or "to"
2123 #ifdef ENVELOPE_AUTH
2124 envelope-part =/ "auth"
2128 enum Comparator comparator=COMP_EN_ASCII_CASEMAP;
2129 enum AddressPart addressPart=ADDRPART_ALL;
2130 enum MatchType matchType=MATCH_IS;
2131 struct String *env,*e,*key,*k;
2135 if (!filter->require_envelope)
2137 filter->errmsg=CUS "missing previous require \"envelope\";";
2142 if (parse_white(filter)==-1) return -1;
2143 if ((m=parse_comparator(filter,&comparator))!=0)
2145 if (m==-1) return -1;
2148 filter->errmsg=CUS "comparator already specified";
2153 else if ((m=parse_addresspart(filter,&addressPart))!=0)
2155 if (m==-1) return -1;
2158 filter->errmsg=CUS "address part already specified";
2163 else if ((m=parse_matchtype(filter,&matchType))!=0)
2165 if (m==-1) return -1;
2168 filter->errmsg=CUS "match type already specified";
2175 if (parse_white(filter)==-1) return -1;
2176 if ((m=parse_stringlist(filter,&env))!=1)
2178 if (m==0) filter->errmsg=CUS "envelope string list expected";
2181 if (parse_white(filter)==-1) return -1;
2182 if ((m=parse_stringlist(filter,&key))!=1)
2184 if (m==0) filter->errmsg=CUS "key string list expected";
2188 for (e=env; e->length!=-1 && !*cond; ++e)
2190 const uschar *envelopeExpr=CUS 0;
2191 uschar *envelope=US 0;
2193 if (eq_asciicase(e,&str_from,0))
2195 switch (addressPart)
2197 case ADDRPART_ALL: envelopeExpr=CUS "$sender_address"; break;
2201 case ADDRPART_LOCALPART: envelopeExpr=CUS "${local_part:$sender_address}"; break;
2202 case ADDRPART_DOMAIN: envelopeExpr=CUS "${domain:$sender_address}"; break;
2204 case ADDRPART_DETAIL: envelopeExpr=CUS 0; break;
2208 else if (eq_asciicase(e,&str_to,0))
2210 switch (addressPart)
2212 case ADDRPART_ALL: envelopeExpr=CUS "$local_part_prefix$local_part$local_part_suffix@$domain"; break;
2214 case ADDRPART_USER: envelopeExpr=filter->useraddress; break;
2215 case ADDRPART_DETAIL: envelopeExpr=filter->subaddress; break;
2217 case ADDRPART_LOCALPART: envelopeExpr=CUS "$local_part_prefix$local_part$local_part_suffix"; break;
2218 case ADDRPART_DOMAIN: envelopeExpr=CUS "$domain"; break;
2221 #ifdef ENVELOPE_AUTH
2222 else if (eq_asciicase(e,&str_auth,0))
2224 switch (addressPart)
2226 case ADDRPART_ALL: envelopeExpr=CUS "$authenticated_sender"; break;
2230 case ADDRPART_LOCALPART: envelopeExpr=CUS "${local_part:$authenticated_sender}"; break;
2231 case ADDRPART_DOMAIN: envelopeExpr=CUS "${domain:$authenticated_sender}"; break;
2233 case ADDRPART_DETAIL: envelopeExpr=CUS 0; break;
2240 filter->errmsg=CUS "invalid envelope string";
2243 if (exec && envelopeExpr)
2245 if ((envelope=expand_string(US envelopeExpr)) == NULL)
2247 filter->errmsg=CUS "header string expansion failed";
2250 for (k=key; k->length!=-1; ++k)
2252 struct String envelopeStr;
2254 envelopeStr.character=envelope;
2255 envelopeStr.length=Ustrlen(envelope);
2256 *cond=compare(filter,k,&envelopeStr,comparator,matchType);
2257 if (*cond==-1) return -1;
2265 else if (parse_identifier(filter,CUS "valid_notif_method"))
2268 valid_notif_method = "valid_notif_method"
2269 <notification-uris: string-list>
2272 struct String *uris,*u;
2275 if (!filter->require_enotify)
2277 filter->errmsg=CUS "missing previous require \"enotify\";";
2280 if (parse_white(filter)==-1) return -1;
2281 if ((m=parse_stringlist(filter,&uris))!=1)
2283 if (m==0) filter->errmsg=CUS "URI string list expected";
2289 for (u=uris; u->length!=-1 && *cond; ++u)
2291 string_item *recipient;
2292 struct String header,body;
2296 header.character=(uschar*)0;
2298 body.character=(uschar*)0;
2299 if (parse_mailto_uri(filter,u->character,&recipient,&header,&body)!=1)
2310 /*************************************************
2311 * Parse and interpret an optional block *
2312 *************************************************/
2316 filter points to the Sieve filter including its state
2317 exec Execute parsed statements
2318 generated where to hang newly-generated addresses
2320 Returns: 2 success by stop
2322 0 no block command found
2323 -1 syntax or execution error
2326 static int parse_block(struct Sieve *filter, int exec,
2327 address_item **generated)
2331 if (parse_white(filter)==-1) return -1;
2332 if (*filter->pc=='{')
2335 if ((r=parse_commands(filter,exec,generated))==-1 || r==2) return r;
2336 if (*filter->pc=='}')
2343 filter->errmsg=CUS "expecting command or closing brace";
2351 /*************************************************
2352 * Match a semicolon *
2353 *************************************************/
2357 filter points to the Sieve filter including its state
2363 static int parse_semicolon(struct Sieve *filter)
2365 if (parse_white(filter)==-1) return -1;
2366 if (*filter->pc==';')
2373 filter->errmsg=CUS "missing semicolon";
2379 /*************************************************
2380 * Parse and interpret a Sieve command *
2381 *************************************************/
2385 filter points to the Sieve filter including its state
2386 exec Execute parsed statements
2387 generated where to hang newly-generated addresses
2389 Returns: 2 success by stop
2391 -1 syntax or execution error
2393 static int parse_commands(struct Sieve *filter, int exec,
2394 address_item **generated)
2398 if (parse_white(filter)==-1) return -1;
2399 if (parse_identifier(filter,CUS "if"))
2402 if-command = "if" test block *( "elsif" test block ) [ else block ]
2405 int cond,m,unsuccessful;
2408 if (parse_white(filter)==-1) return -1;
2409 if ((m=parse_test(filter,&cond,exec))==-1) return -1;
2412 filter->errmsg=CUS "missing test";
2415 if ((filter_test != FTEST_NONE && debug_selector != 0) ||
2416 (debug_selector & D_filter) != 0)
2418 if (exec) debug_printf("if %s\n",cond?"true":"false");
2420 m=parse_block(filter,exec ? cond : 0, generated);
2421 if (m==-1 || m==2) return m;
2424 filter->errmsg=CUS "missing block";
2427 unsuccessful = !cond;
2428 for (;;) /* elsif test block */
2430 if (parse_white(filter)==-1) return -1;
2431 if (parse_identifier(filter,CUS "elsif"))
2433 if (parse_white(filter)==-1) return -1;
2434 m=parse_test(filter,&cond,exec && unsuccessful);
2435 if (m==-1 || m==2) return m;
2438 filter->errmsg=CUS "missing test";
2441 if ((filter_test != FTEST_NONE && debug_selector != 0) ||
2442 (debug_selector & D_filter) != 0)
2444 if (exec) debug_printf("elsif %s\n",cond?"true":"false");
2446 m=parse_block(filter,exec && unsuccessful ? cond : 0, generated);
2447 if (m==-1 || m==2) return m;
2450 filter->errmsg=CUS "missing block";
2453 if (exec && unsuccessful && cond) unsuccessful = 0;
2458 if (parse_white(filter)==-1) return -1;
2459 if (parse_identifier(filter,CUS "else"))
2461 m=parse_block(filter,exec && unsuccessful, generated);
2462 if (m==-1 || m==2) return m;
2465 filter->errmsg=CUS "missing block";
2470 else if (parse_identifier(filter,CUS "stop"))
2473 stop-command = "stop" { stop-options } ";"
2477 if (parse_semicolon(filter)==-1) return -1;
2480 filter->pc+=Ustrlen(filter->pc);
2484 else if (parse_identifier(filter,CUS "keep"))
2487 keep-command = "keep" { keep-options } ";"
2491 if (parse_semicolon(filter)==-1) return -1;
2494 add_addr(generated,US"inbox",1,0,0,0);
2498 else if (parse_identifier(filter,CUS "discard"))
2501 discard-command = "discard" { discard-options } ";"
2505 if (parse_semicolon(filter)==-1) return -1;
2506 if (exec) filter->keep=0;
2508 else if (parse_identifier(filter,CUS "redirect"))
2511 redirect-command = "redirect" redirect-options "string" ";"
2513 redirect-options =) ":copy"
2516 struct String recipient;
2522 if (parse_white(filter)==-1) return -1;
2523 if (parse_identifier(filter,CUS ":copy")==1)
2525 if (!filter->require_copy)
2527 filter->errmsg=CUS "missing previous require \"copy\";";
2534 if (parse_white(filter)==-1) return -1;
2535 if ((m=parse_string(filter,&recipient))!=1)
2537 if (m==0) filter->errmsg=CUS "missing redirect recipient string";
2540 if (strchr(CCS recipient.character,'@')==(char*)0)
2542 filter->errmsg=CUS "unqualified recipient address";
2547 add_addr(generated,recipient.character,0,0,0,0);
2548 if (!copy) filter->keep = 0;
2550 if (parse_semicolon(filter)==-1) return -1;
2552 else if (parse_identifier(filter,CUS "fileinto"))
2555 fileinto-command = "fileinto" { fileinto-options } string ";"
2557 fileinto-options =) [ ":copy" ]
2560 struct String folder;
2563 unsigned long maxage, maxmessages, maxstorage;
2566 maxage = maxmessages = maxstorage = 0;
2567 if (!filter->require_fileinto)
2569 filter->errmsg=CUS "missing previous require \"fileinto\";";
2574 if (parse_white(filter)==-1) return -1;
2575 if (parse_identifier(filter,CUS ":copy")==1)
2577 if (!filter->require_copy)
2579 filter->errmsg=CUS "missing previous require \"copy\";";
2586 if (parse_white(filter)==-1) return -1;
2587 if ((m=parse_string(filter,&folder))!=1)
2589 if (m==0) filter->errmsg=CUS "missing fileinto folder string";
2592 m=0; s=folder.character;
2593 if (folder.length==0) m=1;
2594 if (Ustrcmp(s,"..")==0 || Ustrncmp(s,"../",3)==0) m=1;
2597 if (Ustrcmp(s,"/..")==0 || Ustrncmp(s,"/../",4)==0) { m=1; break; }
2602 filter->errmsg=CUS "invalid folder";
2607 add_addr(generated, folder.character, 1, maxage, maxmessages, maxstorage);
2608 if (!copy) filter->keep = 0;
2610 if (parse_semicolon(filter)==-1) return -1;
2613 else if (parse_identifier(filter,CUS "notify"))
2616 notify-command = "notify" { notify-options } <method: string> ";"
2617 notify-options = [":from" string]
2618 [":importance" <"1" / "2" / "3">]
2619 [":options" 1*(string-list / number)]
2625 struct String importance;
2626 struct String *options;
2627 struct String message;
2628 struct String method;
2629 struct Notification *already;
2630 string_item *recipient;
2631 struct String header;
2633 uschar *envelope_from,*envelope_to;
2635 if (!filter->require_enotify)
2637 filter->errmsg=CUS "missing previous require \"enotify\";";
2640 from.character=(uschar*)0;
2642 importance.character=(uschar*)0;
2643 importance.length=-1;
2644 options=(struct String*)0;
2645 message.character=(uschar*)0;
2649 header.character=(uschar*)0;
2651 body.character=(uschar*)0;
2652 envelope_from=expand_string("$sender_address");
2653 envelope_to=expand_string("$local_part_prefix$local_part$local_part_suffix@$domain");
2656 if (parse_white(filter)==-1) return -1;
2657 if (parse_identifier(filter,CUS ":from")==1)
2659 if (parse_white(filter)==-1) return -1;
2660 if ((m=parse_string(filter,&from))!=1)
2662 if (m==0) filter->errmsg=CUS "from string expected";
2666 else if (parse_identifier(filter,CUS ":importance")==1)
2668 if (parse_white(filter)==-1) return -1;
2669 if ((m=parse_string(filter,&importance))!=1)
2671 if (m==0) filter->errmsg=CUS "importance string expected";
2674 if (importance.length!=1 || importance.character[0]<'1' || importance.character[0]>'3')
2676 filter->errmsg=CUS "invalid importance";
2680 else if (parse_identifier(filter,CUS ":options")==1)
2682 if (parse_white(filter)==-1) return -1;
2684 else if (parse_identifier(filter,CUS ":message")==1)
2686 if (parse_white(filter)==-1) return -1;
2687 if ((m=parse_string(filter,&message))!=1)
2689 if (m==0) filter->errmsg=CUS "message string expected";
2695 if (parse_white(filter)==-1) return -1;
2696 if ((m=parse_string(filter,&method))!=1)
2698 if (m==0) filter->errmsg=CUS "missing method string";
2701 if (parse_semicolon(filter)==-1) return -1;
2703 for (already=filter->notified; already; already=already->next)
2705 if (already->method.length==method.length
2706 && (method.length==-1 || strcmp(already->method.character,method.character)==0)
2707 && already->importance.length==importance.length
2708 && (importance.length==-1 || strcmp(already->importance.character,importance.character)==0)
2709 && already->message.length==message.length
2710 && (message.length==-1 || strcmp(already->message.character,message.character)==0))
2713 if (already==(struct Notification*)0)
2714 /* New notification, process it */
2716 if (parse_mailto_uri(filter,method.character,&recipient,&header,&body)!=1)
2718 struct Notification *sent;
2719 sent=store_get(sizeof(struct Notification));
2720 sent->method=method;
2721 sent->importance=importance;
2722 sent->message=message;
2723 sent->next=filter->notified;
2724 filter->notified=sent;
2725 if ((filter_test != FTEST_NONE && debug_selector != 0) || (debug_selector & D_filter) != 0)
2727 debug_printf("Notification to `%s'.\n",method.character);
2729 #ifndef COMPILE_SYNTAX_CHECKER
2730 if (exec && filter_test == FTEST_NONE)
2736 if ((pid = child_open_exim2(&fd,envelope_to,envelope_to))>=1)
2740 int buffer_capacity;
2742 f = fdopen(fd, "wb");
2743 for (h = header_list; h != NULL; h = h->next)
2744 if (h->type == htype_received) fprintf(f,"%s",h->text);
2745 fprintf(f,"From: %s\n",from.length==-1 ? envelope_to : from.character);
2746 for (p=recipient; p; p=p->next) fprintf(f,"To: %s\n",p->text);
2747 if (header.length>0) fprintf(f,"%s",header.character);
2748 if (message.length==-1)
2750 message.character=US"Notification";
2751 message.length=Ustrlen(message.character);
2753 /* Allocation is larger than neccessary, but enough even for split MIME words */
2754 buffer_capacity=32+4*message.length;
2755 buffer=store_get(buffer_capacity);
2756 fprintf(f,"Subject: %s\n\n",parse_quote_2047(message.character, message.length, US"utf-8", buffer, buffer_capacity, TRUE));
2757 if (body.length>0) fprintf(f,"%s\n",body.character);
2760 (void)child_close(pid, 0);
2767 if ((filter_test != FTEST_NONE && debug_selector != 0) || (debug_selector & D_filter) != 0)
2769 debug_printf("Repeated notification to `%s' ignored.\n",method.character);
2775 else if (parse_identifier(filter,CUS "vacation"))
2778 vacation-command = "vacation" { vacation-options } <reason: string> ";"
2779 vacation-options = [":days" number]
2782 [":addresses" string-list]
2789 struct String subject;
2791 struct String *addresses;
2793 string_item *aliases;
2794 struct String handle;
2795 struct String reason;
2797 if (!filter->require_vacation)
2799 filter->errmsg=CUS "missing previous require \"vacation\";";
2804 if (filter->vacation_ran)
2806 filter->errmsg=CUS "trying to execute vacation more than once";
2809 filter->vacation_ran=1;
2811 days=VACATION_MIN_DAYS>7 ? VACATION_MIN_DAYS : 7;
2812 subject.character=(uschar*)0;
2814 from.character=(uschar*)0;
2816 addresses=(struct String*)0;
2819 handle.character=(uschar*)0;
2823 if (parse_white(filter)==-1) return -1;
2824 if (parse_identifier(filter,CUS ":days")==1)
2826 if (parse_white(filter)==-1) return -1;
2827 if (parse_number(filter,&days)==-1) return -1;
2828 if (days<VACATION_MIN_DAYS) days=VACATION_MIN_DAYS;
2829 else if (days>VACATION_MAX_DAYS) days=VACATION_MAX_DAYS;
2831 else if (parse_identifier(filter,CUS ":subject")==1)
2833 if (parse_white(filter)==-1) return -1;
2834 if ((m=parse_string(filter,&subject))!=1)
2836 if (m==0) filter->errmsg=CUS "subject string expected";
2840 else if (parse_identifier(filter,CUS ":from")==1)
2842 if (parse_white(filter)==-1) return -1;
2843 if ((m=parse_string(filter,&from))!=1)
2845 if (m==0) filter->errmsg=CUS "from string expected";
2848 if (check_mail_address(filter,&from)!=1)
2851 else if (parse_identifier(filter,CUS ":addresses")==1)
2855 if (parse_white(filter)==-1) return -1;
2856 if ((m=parse_stringlist(filter,&addresses))!=1)
2858 if (m==0) filter->errmsg=CUS "addresses string list expected";
2861 for (a=addresses; a->length!=-1; ++a)
2865 new=store_get(sizeof(string_item));
2866 new->text=store_get(a->length+1);
2867 if (a->length) memcpy(new->text,a->character,a->length);
2868 new->text[a->length]='\0';
2873 else if (parse_identifier(filter,CUS ":mime")==1)
2875 else if (parse_identifier(filter,CUS ":handle")==1)
2877 if (parse_white(filter)==-1) return -1;
2878 if ((m=parse_string(filter,&from))!=1)
2880 if (m==0) filter->errmsg=CUS "handle string expected";
2886 if (parse_white(filter)==-1) return -1;
2887 if ((m=parse_string(filter,&reason))!=1)
2889 if (m==0) filter->errmsg=CUS "missing reason string";
2896 for (s=reason.character,end=reason.character+reason.length; s<end && (*s&0x80)==0; ++s);
2899 filter->errmsg=CUS "MIME reason string contains 8bit text";
2903 if (parse_semicolon(filter)==-1) return -1;
2910 int buffer_capacity;
2914 uschar hexdigest[33];
2918 if (filter_personal(aliases,TRUE))
2920 if (filter_test == FTEST_NONE)
2922 /* ensure oncelog directory exists; failure will be detected later */
2924 (void)directory_make(NULL, filter->vacation_directory, 0700, FALSE);
2926 /* build oncelog filename */
2928 key.character=(uschar*)0;
2931 if (handle.length==-1)
2933 if (subject.length!=-1) key.character=string_cat(key.character,&capacity,&key.length,subject.character,subject.length);
2934 if (from.length!=-1) key.character=string_cat(key.character,&capacity,&key.length,from.character,from.length);
2935 key.character=string_cat(key.character,&capacity,&key.length,reason_is_mime?US"1":US"0",1);
2936 key.character=string_cat(key.character,&capacity,&key.length,reason.character,reason.length);
2941 md5_end(&base, key.character, key.length, digest);
2942 for (i = 0; i < 16; i++) sprintf(CS (hexdigest+2*i), "%02X", digest[i]);
2943 if ((filter_test != FTEST_NONE && debug_selector != 0) || (debug_selector & D_filter) != 0)
2945 debug_printf("Sieve: mail was personal, vacation file basename: %s\n", hexdigest);
2947 if (filter_test == FTEST_NONE)
2949 capacity=Ustrlen(filter->vacation_directory);
2951 once=string_cat(filter->vacation_directory,&capacity,&start,US"/",1);
2952 once=string_cat(once,&capacity,&start,hexdigest,33);
2955 /* process subject */
2957 if (subject.length==-1)
2959 uschar *subject_def;
2961 subject_def=expand_string(US"${if def:header_subject {true}{false}}");
2962 if (Ustrcmp(subject_def,"true")==0)
2964 expand_header(&subject,&str_subject);
2967 subject.character=string_cat(US"Auto: ",&capacity,&start,subject.character,subject.length);
2968 subject.length=start;
2972 subject.character=US"Automated reply";
2973 subject.length=Ustrlen(subject.character);
2977 /* add address to list of generated addresses */
2979 addr = deliver_make_addr(string_sprintf(">%.256s", sender_address), FALSE);
2980 setflag(addr, af_pfr);
2981 setflag(addr, af_ignore_error);
2982 addr->next = *generated;
2984 addr->reply = store_get(sizeof(reply_item));
2985 memset(addr->reply,0,sizeof(reply_item)); /* XXX */
2986 addr->reply->to = string_copy(sender_address);
2987 if (from.length==-1)
2988 addr->reply->from = expand_string(US"$local_part@$domain");
2990 addr->reply->from = from.character;
2991 /* Allocation is larger than neccessary, but enough even for split MIME words */
2992 buffer_capacity=32+4*subject.length;
2993 buffer=store_get(buffer_capacity);
2994 addr->reply->subject=parse_quote_2047(subject.character, subject.length, US"utf-8", buffer, buffer_capacity, TRUE);
2995 addr->reply->oncelog=once;
2996 addr->reply->once_repeat=days*86400;
2998 /* build body and MIME headers */
3002 uschar *mime_body,*reason_end;
3003 static const uschar nlnl[]="\r\n\r\n";
3007 mime_body=reason.character,reason_end=reason.character+reason.length;
3008 mime_body<(reason_end-(sizeof(nlnl)-1)) && memcmp(mime_body,nlnl,(sizeof(nlnl)-1));
3013 addr->reply->headers = string_cat(NULL,&capacity,&start,reason.character,mime_body-reason.character);
3014 addr->reply->headers[start] = '\0';
3017 if (mime_body+(sizeof(nlnl)-1)<reason_end) mime_body+=(sizeof(nlnl)-1);
3018 else mime_body=reason_end-1;
3019 addr->reply->text = string_cat(NULL,&capacity,&start,mime_body,reason_end-mime_body);
3020 addr->reply->text[start] = '\0';
3024 struct String qp = { NULL, 0 }; /* Keep compiler happy (PH) */
3027 start = reason.length;
3028 addr->reply->headers = US"MIME-Version: 1.0\n"
3029 "Content-Type: text/plain;\n"
3030 "\tcharset=\"utf-8\"\n"
3031 "Content-Transfer-Encoding: quoted-printable";
3032 addr->reply->text = quoted_printable_encode(&reason,&qp)->character;
3036 else if ((filter_test != FTEST_NONE && debug_selector != 0) || (debug_selector & D_filter) != 0)
3038 debug_printf("Sieve: mail was not personal, vacation would ignore it\n");
3049 /*************************************************
3050 * Parse and interpret a sieve filter *
3051 *************************************************/
3055 filter points to the Sieve filter including its state
3056 exec Execute parsed statements
3057 generated where to hang newly-generated addresses
3060 -1 syntax or execution error
3063 static int parse_start(struct Sieve *filter, int exec,
3064 address_item **generated)
3066 filter->pc=filter->filter;
3069 filter->require_envelope=0;
3070 filter->require_fileinto=0;
3071 #ifdef ENCODED_CHARACTER
3072 filter->require_encoded_character=0;
3074 #ifdef ENVELOPE_AUTH
3075 filter->require_envelope_auth=0;
3078 filter->require_enotify=0;
3079 filter->notified=(struct Notification*)0;
3082 filter->require_subaddress=0;
3085 filter->require_vacation=0;
3086 filter->vacation_ran=0;
3088 filter->require_copy=0;
3089 filter->require_iascii_numeric=0;
3091 if (parse_white(filter)==-1) return -1;
3093 if (exec && filter->vacation_directory != NULL && filter_test == FTEST_NONE)
3096 struct dirent *oncelog;
3097 struct stat properties;
3100 /* clean up old vacation log databases */
3102 oncelogdir=opendir(CS filter->vacation_directory);
3104 if (oncelogdir ==(DIR*)0 && errno != ENOENT)
3106 filter->errmsg=CUS "unable to open vacation directory";
3110 if (oncelogdir != NULL)
3114 while ((oncelog=readdir(oncelogdir))!=(struct dirent*)0)
3116 if (strlen(oncelog->d_name)==32)
3118 uschar *s=string_sprintf("%s/%s",filter->vacation_directory,oncelog->d_name);
3119 if (Ustat(s,&properties)==0 && (properties.st_mtime+VACATION_MAX_DAYS*86400)<now)
3123 closedir(oncelogdir);
3127 while (parse_identifier(filter,CUS "require"))
3130 require-command = "require" <capabilities: string-list>
3133 struct String *cap,*check;
3136 if (parse_white(filter)==-1) return -1;
3137 if ((m=parse_stringlist(filter,&cap))!=1)
3139 if (m==0) filter->errmsg=CUS "capability string list expected";
3142 for (check=cap; check->character; ++check)
3144 if (eq_octet(check,&str_envelope,0)) filter->require_envelope=1;
3145 else if (eq_octet(check,&str_fileinto,0)) filter->require_fileinto=1;
3146 #ifdef ENCODED_CHARACTER
3147 else if (eq_octet(check,&str_encoded_character,0)) filter->require_encoded_character=1;
3149 #ifdef ENVELOPE_AUTH
3150 else if (eq_octet(check,&str_envelope_auth,0)) filter->require_envelope_auth=1;
3153 else if (eq_octet(check,&str_enotify,0)) filter->require_enotify=1;
3156 else if (eq_octet(check,&str_subaddress,0)) filter->require_subaddress=1;
3159 else if (eq_octet(check,&str_vacation,0))
3161 if (filter_test == FTEST_NONE && filter->vacation_directory == NULL)
3163 filter->errmsg=CUS "vacation disabled";
3166 filter->require_vacation=1;
3169 else if (eq_octet(check,&str_copy,0)) filter->require_copy=1;
3170 else if (eq_octet(check,&str_comparator_ioctet,0)) ;
3171 else if (eq_octet(check,&str_comparator_iascii_casemap,0)) ;
3172 else if (eq_octet(check,&str_comparator_enascii_casemap,0)) ;
3173 else if (eq_octet(check,&str_comparator_iascii_numeric,0)) filter->require_iascii_numeric=1;
3176 filter->errmsg=CUS "unknown capability";
3180 if (parse_semicolon(filter)==-1) return -1;
3182 if (parse_commands(filter,exec,generated)==-1) return -1;
3185 filter->errmsg=CUS "syntax error";
3192 /*************************************************
3193 * Interpret a sieve filter file *
3194 *************************************************/
3198 filter points to the entire file, read into store as a single string
3199 options controls whether various special things are allowed, and requests
3200 special actions (not currently used)
3201 sieve_vacation_directory where to store vacation "once" files
3202 useraddress string expression for :user part of address
3203 subaddress string expression for :subaddress part of address
3204 generated where to hang newly-generated addresses
3205 error where to pass back an error text
3207 Returns: FF_DELIVERED success, a significant action was taken
3208 FF_NOTDELIVERED success, no significant action
3209 FF_DEFER defer requested
3210 FF_FAIL fail requested
3211 FF_FREEZE freeze requested
3212 FF_ERROR there was a problem
3216 sieve_interpret(uschar *filter, int options, uschar *vacation_directory,
3217 uschar *useraddress, uschar *subaddress, address_item **generated, uschar **error)
3223 options = options; /* Keep picky compilers happy */
3226 DEBUG(D_route) debug_printf("Sieve: start of processing\n");
3227 sieve.filter=filter;
3229 if (vacation_directory == NULL)
3230 sieve.vacation_directory = NULL;
3233 sieve.vacation_directory=expand_string(vacation_directory);
3234 if (sieve.vacation_directory == NULL)
3236 *error = string_sprintf("failed to expand \"%s\" "
3237 "(sieve_vacation_directory): %s", vacation_directory,
3238 expand_string_message);
3243 sieve.useraddress = useraddress == NULL ? CUS "$local_part_prefix$local_part$local_part_suffix" : useraddress;
3244 sieve.subaddress = subaddress;
3246 #ifdef COMPILE_SYNTAX_CHECKER
3247 if (parse_start(&sieve,0,generated)==1)
3249 if (parse_start(&sieve,1,generated)==1)
3254 add_addr(generated,US"inbox",1,0,0,0);
3255 msg = string_sprintf("Implicit keep");
3260 msg = string_sprintf("No implicit keep");
3266 msg = string_sprintf("Sieve error: %s in line %d",sieve.errmsg,sieve.line);
3267 #ifdef COMPILE_SYNTAX_CHECKER
3271 add_addr(generated,US"inbox",1,0,0,0);
3276 #ifndef COMPILE_SYNTAX_CHECKER
3277 if (filter_test != FTEST_NONE) printf("%s\n", (const char*) msg);
3278 else debug_printf("%s\n", msg);
3281 DEBUG(D_route) debug_printf("Sieve: end of processing\n");