wip
[users/jgh/exim.git] / src / src / pdkim / pdkim.c
1 /* $Cambridge: exim/src/src/pdkim/pdkim.c,v 1.1.2.5 2009/02/27 17:04:20 tom Exp $ */
2 /* pdkim.c */
3
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <string.h>
7 #include <strings.h>
8 #include <ctype.h>
9 #include <unistd.h>
10 #include "pdkim.h"
11
12
13 /* -------------------------------------------------------------------------- */
14 /* A bunch of list constants */
15 char *pdkim_querymethods[] = {
16   "dns/txt",
17   NULL
18 };
19 char *pdkim_algos[] = {
20   "rsa-sha256",
21   "rsa-sha1",
22   NULL
23 };
24 char *pdkim_canons[] = {
25   "simple",
26   "relaxed",
27   NULL
28 };
29
30 typedef struct pdkim_combined_canon_entry {
31   char *str;
32   int canon_headers;
33   int canon_body;
34 } pdkim_combined_canon_entry;
35 pdkim_combined_canon_entry pdkim_combined_canons[] = {
36   { "simple/simple",    PDKIM_CANON_SIMPLE,   PDKIM_CANON_SIMPLE },
37   { "simple/relaxed",   PDKIM_CANON_SIMPLE,   PDKIM_CANON_RELAXED },
38   { "relaxed/simple",   PDKIM_CANON_RELAXED,  PDKIM_CANON_SIMPLE },
39   { "relaxed/relaxed",  PDKIM_CANON_RELAXED,  PDKIM_CANON_RELAXED },
40   { "simple",           PDKIM_CANON_SIMPLE,   PDKIM_CANON_SIMPLE },
41   { "relaxed",          PDKIM_CANON_RELAXED,  PDKIM_CANON_SIMPLE },
42   { NULL,               0,                    0 }
43 };
44
45
46 /* -------------------------------------------------------------------------- */
47 /* Various debugging functions */
48 #ifdef PDKIM_DEBUG
49 void pdkim_quoteprint(FILE *stream, char *data, int len, int lf) {
50   int i;
51   unsigned char *p = (unsigned char *)data;
52
53   for (i=0;i<len;i++) {
54     int c = p[i];
55     switch (c) {
56       case ' ' : fprintf(stream,"{SP}"); break;
57       case '\t': fprintf(stream,"{TB}"); break;
58       case '\r': fprintf(stream,"{CR}"); break;
59       case '\n': fprintf(stream,"{LF}"); break;
60       case '{' : fprintf(stream,"{BO}"); break;
61       case '}' : fprintf(stream,"{BC}"); break;
62       default:
63         if ( (c < 32) || (c > 127) )
64           fprintf(stream,"{%02x}",c);
65         else
66           fputc(c,stream);
67       break;
68     }
69   }
70   if (lf)
71     fputc('\n',stream);
72 }
73 void pdkim_hexprint(FILE *stream, char *data, int len, int lf) {
74   int i;
75   unsigned char *p = (unsigned char *)data;
76
77   for (i=0;i<len;i++) {
78     int c = p[i];
79     fprintf(stream,"%02x ",c);
80   }
81   if (lf)
82     fputc('\n',stream);
83 }
84 #endif
85
86
87 /* -------------------------------------------------------------------------- */
88 /* Simple string list implementation for convinience */
89 pdkim_stringlist *pdkim_append_stringlist(pdkim_stringlist *base, char *str) {
90   pdkim_stringlist *new_entry = malloc(sizeof(pdkim_stringlist));
91   if (new_entry == NULL) return NULL;
92   memset(new_entry,0,sizeof(pdkim_stringlist));
93   new_entry->value = malloc(strlen(str)+1);
94   if (new_entry->value == NULL) return NULL;
95   strcpy(new_entry->value,str);
96   if (base != NULL) {
97     pdkim_stringlist *last = base;
98     while (last->next != NULL) { last = last->next; };
99     last->next = new_entry;
100     return base;
101   }
102   else return new_entry;
103 };
104
105
106 /* -------------------------------------------------------------------------- */
107 /* A small "growing string" implementation to escape malloc/realloc hell */
108 pdkim_str *pdkim_strnew (char *cstr) {
109   unsigned int len = cstr?strlen(cstr):0;
110   pdkim_str *p = malloc(sizeof(pdkim_str));
111   if (p == NULL) return NULL;
112   memset(p,0,sizeof(pdkim_str));
113   p->str = malloc(len+1);
114   if (p->str == NULL) {
115     free(p);
116     return NULL;
117   }
118   p->allocated=(len+1);
119   p->len=len;
120   if (cstr) strcpy(p->str,cstr);
121   return p;
122 };
123 char *pdkim_strcat(pdkim_str *str, char *cstr) {
124   return pdkim_strncat(str, cstr, strlen(cstr));
125 };
126 char *pdkim_strncat(pdkim_str *str, char *data, int len) {
127   if ((str->allocated - str->len) < (len+1)) {
128     /* Extend the buffer */
129     int num_frags = ((len+1)/PDKIM_STR_ALLOC_FRAG)+1;
130     char *n = realloc(str->str,
131                       (str->allocated+(num_frags*PDKIM_STR_ALLOC_FRAG)));
132     if (n == NULL) return NULL;
133     str->str = n;
134     str->allocated += (num_frags*PDKIM_STR_ALLOC_FRAG);
135   }
136   strncpy(&(str->str[str->len]),data,len);
137   str->len+=len;
138   str->str[str->len] = '\0';
139   return str->str;
140 };
141 char *pdkim_numcat(pdkim_str *str, unsigned long num) {
142   char minibuf[20];
143   snprintf(minibuf,20,"%lu",num);
144   return pdkim_strcat(str,minibuf);
145 };
146 char *pdkim_strtrim(pdkim_str *str) {
147   char *p = str->str;
148   char *q = str->str;
149   while ( (*p != '\0') && ((*p == '\t') || (*p == ' ')) ) p++;
150   while (*p != '\0') {*q = *p; q++; p++;};
151   *q = '\0';
152   while ( (q != str->str) && ( (*q == '\0') || (*q == '\t') || (*q == ' ') ) ) {
153     *q = '\0';
154     q--;
155   }
156   str->len = strlen(str->str);
157   return str->str;
158 };
159 char *pdkim_strclear(pdkim_str *str) {
160   str->str[0] = '\0';
161   str->len = 0;
162   return str->str;
163 };
164 void pdkim_strfree(pdkim_str *str) {
165   if (str == NULL) return;
166   if (str->str != NULL) free(str->str);
167   free(str);
168 };
169
170
171 /* -------------------------------------------------------------------------- */
172 /* Matches the name of the passed raw "header" against
173    the passed colon-separated "list", starting at entry
174    "start". Returns the position of the header name in
175    the list. */
176 int header_name_match(char *header,
177                       char *list,
178                       int   start) {
179   char *hname;
180   char *lcopy;
181   char *p;
182   char *q;
183   int pos = 0;
184   int rc = PDKIM_FAIL;
185   char *hcolon = strchr(header,':');
186   if (hcolon == NULL) return rc; /* This isn't a header */
187   hname = malloc((hcolon-header)+1);
188   if (hname == NULL) return PDKIM_ERR_OOM;
189   memset(hname,0,(hcolon-header)+1);
190   strncpy(hname,header,(hcolon-header));
191   lcopy = malloc(strlen(list)+1);
192   if (lcopy == NULL) {
193     free(hname);
194     return PDKIM_ERR_OOM;
195   }
196   strcpy(lcopy,list);
197   p = lcopy;
198   q = strchr(p,':');
199   while (q != NULL) {
200     *q = '\0';
201     if (pos >= start) {
202       if (strcasecmp(p,hname) == 0) {
203         rc = pos;
204         goto BAIL;
205       }
206     }
207     p = q+1;
208     q = strchr(p,':');
209     pos++;
210   }
211   if (pos >= start) {
212     if (strcasecmp(p,hname) == 0)
213       rc = pos;
214   }
215   BAIL:
216   free(hname);
217   free(lcopy);
218   return rc;
219 }
220
221
222 /* -------------------------------------------------------------------------- */
223 /* Performs "relaxed" canonicalization of a header. The returned pointer needs
224    to be free()d. */
225 char *pdkim_relax_header (char *header, int crlf) {
226   int past_field_name = 0;
227   int seen_wsp = 0;
228   char *p = header;
229   char *q;
230   char *relaxed = malloc(strlen(header));
231   if (relaxed == NULL) return NULL;
232   q = relaxed;
233   while (*p != '\0') {
234     int c = *p;
235     /* Ignore CR & LF */
236     if ( (c == '\r') || (c == '\n') ) {
237       p++;
238       continue;
239     }
240     if ( (c == '\t') || (c == ' ') ) {
241       c = ' '; /* Turns WSP into SP */
242       if (seen_wsp) {
243         p++;
244         continue;
245       }
246       else seen_wsp = 1;
247     }
248     else {
249       if ( (!past_field_name) && (c == ':') ) {
250         if (seen_wsp) q--;   /* This removes WSP before the colon */
251         seen_wsp = 1;        /* This removes WSP after the colon */
252         past_field_name = 1;
253       }
254       else seen_wsp = 0;
255     }
256     /* Lowercase header name */
257     if (!past_field_name) c = tolower(c);
258     *q = c;
259     p++;
260     q++;
261   }
262   *q = '\0';
263   if (crlf) strcat(relaxed,"\r\n");
264   return relaxed;
265 };
266
267
268 /* -------------------------------------------------------------------------- */
269 #define PDKIM_QP_ERROR_DECODE -1
270 char *pdkim_decode_qp_char(char *qp_p, int *c) {
271   char *initial_pos = qp_p;
272
273   /* Advance one char */
274   qp_p++;
275
276   /* Check for two hex digits and decode them */
277   if (isxdigit(*qp_p) && isxdigit(qp_p[1])) {
278     /* Do hex conversion */
279     if (isdigit(*qp_p)) {*c = *qp_p - '0';}
280     else {*c = toupper(*qp_p) - 'A' + 10;};
281     *c <<= 4;
282     if (isdigit(qp_p[1])) {*c |= qp_p[1] - '0';}
283     else {*c |= toupper(qp_p[1]) - 'A' + 10;};
284     return qp_p + 2;
285   };
286
287   /* Illegal char here */
288   *c = PDKIM_QP_ERROR_DECODE;
289   return initial_pos;
290 }
291
292
293 /* -------------------------------------------------------------------------- */
294 char *pdkim_decode_qp(char *str) {
295   int nchar = 0;
296   char *q;
297   char *p = str;
298   char *n = malloc(strlen(p)+1);
299   if (n == NULL) return NULL;
300   *n = '\0';
301   q = n;
302   while (*p != '\0') {
303     if (*p == '=') {
304       p = pdkim_decode_qp_char(p,&nchar);
305       if (nchar >= 0) {
306         *q = nchar;
307         q++;
308         continue;
309       }
310     }
311     else {
312       *q = *p;
313       q++;
314     }
315     p++;
316   }
317   return n;
318 }
319
320
321 /* -------------------------------------------------------------------------- */
322 char *pdkim_decode_base64(char *str, int *num_decoded) {
323   int dlen = 0;
324   char *res;
325
326   base64_decode(NULL, &dlen, (unsigned char *)str, strlen(str));
327   res = malloc(dlen+1);
328   if (res == NULL) return NULL;
329   if (base64_decode((unsigned char *)res,&dlen,(unsigned char *)str,strlen(str)) != 0) {
330     free(res);
331     return NULL;
332   }
333   if (num_decoded != NULL) *num_decoded = dlen;
334   return res;
335 }
336
337 /* -------------------------------------------------------------------------- */
338 char *pdkim_encode_base64(char *str, int num) {
339   int dlen = 0;
340   char *res;
341
342   base64_encode(NULL, &dlen, (unsigned char *)str, num);
343   res = malloc(dlen+1);
344   if (res == NULL) return NULL;
345   if (base64_encode((unsigned char *)res,&dlen,(unsigned char *)str,num) != 0) {
346     free(res);
347     return NULL;
348   }
349   return res;
350 }
351
352
353 /* -------------------------------------------------------------------------- */
354 #define PDKIM_HDR_LIMBO 0
355 #define PDKIM_HDR_TAG   1
356 #define PDKIM_HDR_VALUE 2
357 pdkim_signature *pdkim_parse_sig_header(pdkim_ctx *ctx, char *raw_hdr) {
358   pdkim_signature *sig ;
359   char *p,*q;
360   pdkim_str *cur_tag = NULL;
361   pdkim_str *cur_val = NULL;
362   int past_hname = 0;
363   int in_b_val = 0;
364   int where = PDKIM_HDR_LIMBO;
365   int i;
366
367   sig = malloc(sizeof(pdkim_signature));
368   if (sig == NULL) return NULL;
369   memset(sig,0,sizeof(pdkim_signature));
370
371   sig->rawsig_no_b_val = malloc(strlen(raw_hdr)+1);
372   if (sig->rawsig_no_b_val == NULL) {
373     free(sig);
374     return NULL;
375   }
376
377   p = raw_hdr;
378   q = sig->rawsig_no_b_val;
379
380   while (*p != '\0') {
381
382     /* Ignore FWS */
383     if ( (*p == '\r') || (*p == '\n') )
384       goto NEXT_CHAR;
385
386     /* Fast-forward through header name */
387     if (!past_hname) {
388       if (*p == ':') past_hname = 1;
389       goto NEXT_CHAR;
390     }
391
392     if (where == PDKIM_HDR_LIMBO) {
393       /* In limbo, just wait for a tag-char to appear */
394       if (!((*p >= 'a') && (*p <= 'z')))
395         goto NEXT_CHAR;
396
397       where = PDKIM_HDR_TAG;
398     }
399
400     if (where == PDKIM_HDR_TAG) {
401       if (cur_tag == NULL)
402         cur_tag = pdkim_strnew(NULL);
403
404       if ((*p >= 'a') && (*p <= 'z'))
405         pdkim_strncat(cur_tag,p,1);
406
407       if (*p == '=') {
408         if (strcmp(cur_tag->str,"b") == 0) {
409           *q = '='; q++;
410           in_b_val = 1;
411         }
412         where = PDKIM_HDR_VALUE;
413         goto NEXT_CHAR;
414       }
415     }
416
417     if (where == PDKIM_HDR_VALUE) {
418       if (cur_val == NULL)
419         cur_val = pdkim_strnew(NULL);
420
421       if ( (*p == '\r') || (*p == '\n') )
422         goto NEXT_CHAR;
423
424       if (*p == ';') {
425         if (cur_tag->len > 0) {
426           pdkim_strtrim(cur_val);
427           #ifdef PDKIM_DEBUG
428           if (ctx->debug_stream)
429             fprintf(ctx->debug_stream, "%s=%s\n", cur_tag->str, cur_val->str);
430           #endif
431           switch (cur_tag->str[0]) {
432             case 'b':
433               switch (cur_tag->str[1]) {
434                 case 'h':
435                   sig->bodyhash = pdkim_decode_base64(cur_val->str,&(sig->bodyhash_len));
436                 break;
437                 default:
438                   sig->sigdata = pdkim_decode_base64(cur_val->str,&(sig->sigdata_len));
439                 break;
440               }
441             break;
442             case 'v':
443               if (strcmp(cur_val->str,PDKIM_SIGNATURE_VERSION) == 0) {
444                 /* We only support version 1, and that is currently the
445                    only version there is. */
446                 sig->version = 1;
447               }
448             break;
449             case 'a':
450               i = 0;
451               while (pdkim_algos[i] != NULL) {
452                 if (strcmp(cur_val->str,pdkim_algos[i]) == 0 ) {
453                   sig->algo = i;
454                   break;
455                 }
456                 i++;
457               }
458             break;
459             case 'c':
460               i = 0;
461               while (pdkim_combined_canons[i].str != NULL) {
462                 if (strcmp(cur_val->str,pdkim_combined_canons[i].str) == 0 ) {
463                   sig->canon_headers = pdkim_combined_canons[i].canon_headers;
464                   sig->canon_body    = pdkim_combined_canons[i].canon_body;
465                   break;
466                 }
467                 i++;
468               }
469             break;
470             case 'q':
471               i = 0;
472               while (pdkim_querymethods[i] != NULL) {
473                 if (strcmp(cur_val->str,pdkim_querymethods[i]) == 0 ) {
474                   sig->querymethod = i;
475                   break;
476                 }
477                 i++;
478               }
479             break;
480             case 's':
481               sig->selector = malloc(strlen(cur_val->str)+1);
482               if (sig->selector == NULL) break;
483               strcpy(sig->selector, cur_val->str);
484             break;
485             case 'd':
486               sig->domain = malloc(strlen(cur_val->str)+1);
487               if (sig->domain == NULL) break;
488               strcpy(sig->domain, cur_val->str);
489             break;
490             case 'i':
491               sig->identity = pdkim_decode_qp(cur_val->str);
492             break;
493             case 't':
494               sig->created = strtoul(cur_val->str,NULL,10);
495             break;
496             case 'x':
497               sig->expires = strtoul(cur_val->str,NULL,10);
498             break;
499             case 'l':
500               sig->bodylength = strtoul(cur_val->str,NULL,10);
501             break;
502             case 'h':
503               sig->headernames = malloc(strlen(cur_val->str)+1);
504               if (sig->headernames == NULL) break;
505               strcpy(sig->headernames, cur_val->str);
506             break;
507             case 'z':
508               sig->copiedheaders = pdkim_decode_qp(cur_val->str);
509             break;
510             default:
511               #ifdef PDKIM_DEBUG
512               if (ctx->debug_stream)
513                 fprintf(ctx->debug_stream, "Unknown tag encountered\n");
514               #endif
515             break;
516           }
517         }
518         pdkim_strclear(cur_tag);
519         pdkim_strclear(cur_val);
520         in_b_val = 0;
521         where = PDKIM_HDR_LIMBO;
522         goto NEXT_CHAR;
523       }
524       else pdkim_strncat(cur_val,p,1);
525     }
526
527     NEXT_CHAR:
528
529     if (!in_b_val) {
530       *q = *p;
531       q++;
532     }
533     p++;
534   }
535
536   /* Make sure the most important bits are there. */
537   if (!(sig->domain      && (*(sig->domain)      != '\0') &&
538         sig->selector    && (*(sig->selector)    != '\0') &&
539         sig->headernames && (*(sig->headernames) != '\0') &&
540         sig->bodyhash    && (*(sig->bodyhash)    != '\0') &&
541         sig->sigdata     && (*(sig->sigdata)     != '\0') &&
542         sig->version)) {
543     pdkim_free_sig(sig);
544     return NULL;
545   }
546
547   *q = '\0';
548   #ifdef PDKIM_DEBUG
549   if (ctx->debug_stream) {
550     fprintf(ctx->debug_stream,
551             "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
552     pdkim_quoteprint(ctx->debug_stream,
553                      sig->rawsig_no_b_val,
554                      strlen(sig->rawsig_no_b_val), 1);
555     fprintf(ctx->debug_stream,
556             "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
557   }
558   #endif
559
560   sha1_starts(&(sig->sha1_body));
561   sha2_starts(&(sig->sha2_body),0);
562
563   return sig;
564 }
565
566
567
568 /* -------------------------------------------------------------------------- */
569 int pdkim_update_bodyhash(pdkim_ctx *ctx, char *data, int len) {
570   pdkim_signature *sig = ctx->sig;
571   /* Cache relaxed version of data */
572   char *relaxed_data = NULL;
573   int   relaxed_len  = 0;
574
575   /* Traverse all signatures, updating their hashes. */
576   while (sig != NULL) {
577     /* Defaults to simple canon (no further treatment necessary) */
578     char *canon_data = data;
579     int   canon_len = len;
580
581     if (sig->canon_body == PDKIM_CANON_RELAXED) {
582       /* Relax the line if not done already */
583       if (relaxed_data == NULL) {
584         int seen_wsp = 0;
585         char *p = data;
586         int q = 0;
587         relaxed_data = malloc(len+1);
588         if (relaxed_data == NULL) return PDKIM_ERR_OOM;
589         while (*p != '\0') {
590           char c = *p;
591           if ( (c == '\t') || (c == ' ') ) {
592             c = ' '; /* Turns WSP into SP */
593             if (seen_wsp) {
594               p++;
595               continue;
596             }
597             else seen_wsp = 1;
598           }
599           else seen_wsp = 0;
600           relaxed_data[q++] = c;
601           p++;
602         }
603         relaxed_data[q] = '\0';
604         relaxed_len = q;
605       }
606       canon_data = relaxed_data;
607       canon_len  = relaxed_len;
608     }
609
610     /* Make sure we don't exceed the to-be-signed body length */
611     if (sig->bodylength &&
612         ((sig->signed_body_bytes+(unsigned long)canon_len) > sig->bodylength))
613       canon_len = (sig->bodylength - sig->signed_body_bytes);
614
615     if (canon_len > 0) {
616       if (sig->algo == PDKIM_ALGO_RSA_SHA1)
617         sha1_update(&(sig->sha1_body),(unsigned char *)canon_data,canon_len);
618       else
619         sha2_update(&(sig->sha2_body),(unsigned char *)canon_data,canon_len);
620       sig->signed_body_bytes += canon_len;
621 #ifdef PDKIM_DEBUG
622       if (ctx->debug_stream!=NULL)
623         pdkim_quoteprint(ctx->debug_stream,canon_data,canon_len,0);
624 #endif
625     }
626
627     sig = sig->next;
628   }
629
630   if (relaxed_data != NULL) free(relaxed_data);
631   return PDKIM_OK;
632 };
633
634
635 /* -------------------------------------------------------------------------- */
636 int pdkim_finish_bodyhash(pdkim_ctx *ctx) {
637   pdkim_signature *sig = ctx->sig;
638
639   /* Traverse all signatures */
640   while (sig != NULL) {
641
642     /* Finish hashes */
643     unsigned char bh[32]; /* SHA-256 = 32 Bytes,  SHA-1 = 20 Bytes */
644     if (sig->algo == PDKIM_ALGO_RSA_SHA1)
645       sha1_finish(&(sig->sha1_body),bh);
646     else
647       sha2_finish(&(sig->sha2_body),bh);
648
649     #ifdef PDKIM_DEBUG
650     if (ctx->debug_stream) {
651       fprintf(ctx->debug_stream, "PDKIM [%s] Body bytes hashed: %lu\n",
652         sig->domain, sig->signed_body_bytes);
653       fprintf(ctx->debug_stream, "PDKIM [%s] bh  computed: ", sig->domain);
654       pdkim_hexprint(ctx->debug_stream, (char *)bh,
655                      (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32,1);
656     }
657     #endif
658
659     /* SIGNING -------------------------------------------------------------- */
660     if (ctx->mode == PDKIM_MODE_SIGN) {
661       sig->bodyhash_len = (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32;
662       sig->bodyhash = malloc(sig->bodyhash_len);
663       if (sig->bodyhash == NULL) return PDKIM_ERR_OOM;
664       memcpy(sig->bodyhash,bh,sig->bodyhash_len);
665
666       /* If bodylength limit is set, and we have received less bytes
667          than the requested amount, effectively remove the limit tag. */
668       if (sig->signed_body_bytes < sig->bodylength) sig->bodylength = 0;
669     }
670     /* VERIFICATION --------------------------------------------------------- */
671     else {
672       /* Compare bodyhash */
673       if (memcmp(bh,sig->bodyhash,
674                  (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32) == 0) {
675         #ifdef PDKIM_DEBUG
676         if (ctx->debug_stream)
677           fprintf(ctx->debug_stream, "PDKIM [%s] Body hash verified OK\n",
678                   sig->domain);
679         #endif
680       }
681       else {
682         #ifdef PDKIM_DEBUG
683         if (ctx->debug_stream) {
684           fprintf(ctx->debug_stream, "PDKIM [%s] Body hash did NOT verify\n",
685                   sig->domain);
686           fprintf(ctx->debug_stream, "PDKIM [%s] bh signature: ", sig->domain);
687           pdkim_hexprint(ctx->debug_stream, sig->bodyhash,
688                            (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32,1);
689         }
690         #endif
691         sig->verify_status     = PDKIM_VERIFY_FAIL;
692         sig->verify_ext_status = PDKIM_VERIFY_FAIL_BODY;
693       }
694     }
695
696     sig = sig->next;
697   }
698
699   return PDKIM_OK;
700 };
701
702
703
704 /* -------------------------------------------------------------------------- */
705 /* Callback from pdkim_feed below for processing complete body lines */
706 int pdkim_bodyline_complete(pdkim_ctx *ctx) {
707   char *p = ctx->linebuf;
708   int   n = ctx->linebuf_offset;
709
710   /* Ignore extra data if we've seen the end-of-data marker */
711   if (ctx->seen_eod) goto BAIL;
712
713   /* We've always got one extra byte to stuff a zero ... */
714   ctx->linebuf[(ctx->linebuf_offset)] = '\0';
715
716   if (ctx->input_mode == PDKIM_INPUT_SMTP) {
717     /* Terminate on EOD marker */
718     if (memcmp(p,".\r\n",3) == 0) {
719       ctx->seen_eod = 1;
720       goto BAIL;
721     }
722     /* Unstuff dots */
723     if (memcmp(p,"..",2) == 0) {
724       p++;
725       n--;
726     }
727   }
728
729   /* Empty lines need to be buffered until we find a non-empty line */
730   if (memcmp(p,"\r\n",2) == 0) {
731     ctx->num_buffered_crlf++;
732     goto BAIL;
733   }
734
735   /* At this point, we have a non-empty line, so release the buffered ones. */
736   while (ctx->num_buffered_crlf) {
737     pdkim_update_bodyhash(ctx,"\r\n",2);
738     ctx->num_buffered_crlf--;
739   }
740
741   pdkim_update_bodyhash(ctx,p,n);
742
743   BAIL:
744   ctx->linebuf_offset = 0;
745   return PDKIM_OK;
746 }
747
748
749 /* -------------------------------------------------------------------------- */
750 /* Callback from pdkim_feed below for processing complete headers */
751 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
752 int pdkim_header_complete(pdkim_ctx *ctx) {
753   pdkim_signature *sig = ctx->sig;
754
755   /* Special case: The last header can have an extra \r appended */
756   if ( (ctx->cur_header->len > 1) &&
757        (ctx->cur_header->str[(ctx->cur_header->len)-1] == '\r') ) {
758     ctx->cur_header->str[(ctx->cur_header->len)-1] = '\0';
759     ctx->cur_header->len--;
760   }
761
762   /* Traverse all signatures */
763   while (sig != NULL) {
764
765     /* SIGNING -------------------------------------------------------------- */
766     if (ctx->mode == PDKIM_MODE_SIGN) {
767       if (header_name_match(ctx->cur_header->str,
768                             sig->sign_headers?
769                               sig->sign_headers:
770                               PDKIM_DEFAULT_SIGN_HEADERS, 0) < 0) goto NEXT_SIG;
771     }
772     /* VERIFICATION --------------------------------------------------------- */
773     else {
774       int rc = header_name_match(ctx->cur_header->str,
775                                  sig->headernames,
776                                  sig->headernames_pos);
777       /* Header is not included or out-of-sequence */
778       if (rc < 0) goto NEXT_SIG;
779       sig->headernames_pos = rc;
780     }
781
782     /* Add header to the signed headers list */
783     pdkim_stringlist *list = pdkim_append_stringlist(sig->headers,
784                                                      ctx->cur_header->str);
785     if (list == NULL) return PDKIM_ERR_OOM;
786     sig->headers = list;
787
788     NEXT_SIG:
789     sig = sig->next;
790   }
791
792   /* DKIM-Signature: headers are added to the verification list */
793   if ( (ctx->mode == PDKIM_MODE_VERIFY) &&
794        (strncasecmp(ctx->cur_header->str,
795                     DKIM_SIGNATURE_HEADERNAME,
796                     strlen(DKIM_SIGNATURE_HEADERNAME)) == 0) ) {
797     /* Create and chain new signature block */
798     #ifdef PDKIM_DEBUG
799     if (ctx->debug_stream)
800       fprintf(ctx->debug_stream,
801         "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
802     #endif
803     pdkim_signature *new_sig = pdkim_parse_sig_header(ctx, ctx->cur_header->str);
804     if (new_sig != NULL) {
805       pdkim_signature *last_sig = ctx->sig;
806       if (last_sig == NULL) {
807         ctx->sig = new_sig;
808       }
809       else {
810         while (last_sig->next != NULL) { last_sig = last_sig->next; };
811         last_sig->next = new_sig;
812       }
813     }
814     else {
815       #ifdef PDKIM_DEBUG
816       if (ctx->debug_stream) {
817         fprintf(ctx->debug_stream,"Error while parsing signature header\n");
818         fprintf(ctx->debug_stream,
819           "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
820       }
821       #endif
822     }
823   }
824
825   pdkim_strclear(ctx->cur_header); /* Re-use existing pdkim_str */
826   return PDKIM_OK;
827 };
828
829
830
831 /* -------------------------------------------------------------------------- */
832 #define HEADER_BUFFER_FRAG_SIZE 256
833 int pdkim_feed (pdkim_ctx *ctx,
834                 char *data,
835                 int   len) {
836   int p;
837   for (p=0;p<len;p++) {
838     char c = data[p];
839     if (ctx->past_headers) {
840       /* Processing body byte */
841       ctx->linebuf[(ctx->linebuf_offset)++] = c;
842       if (c == '\n') {
843         int rc = pdkim_bodyline_complete(ctx); /* End of line */
844         if (rc != PDKIM_OK) return rc;
845       }
846       if (ctx->linebuf_offset == (PDKIM_MAX_BODY_LINE_LEN-1))
847         return PDKIM_ERR_LONG_LINE;
848     }
849     else {
850       /* Processing header byte */
851       if (c != '\r') {
852         if (c == '\n') {
853           if (ctx->seen_lf) {
854             int rc = pdkim_header_complete(ctx); /* Seen last header line */
855             if (rc != PDKIM_OK) return rc;
856             ctx->past_headers = 1;
857             ctx->seen_lf = 0;
858 #ifdef PDKIM_DEBUG
859             if (ctx->debug_stream)
860               fprintf(ctx->debug_stream,
861                 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
862 #endif
863             continue;
864           }
865           else ctx->seen_lf = 1;
866         }
867         else if (ctx->seen_lf) {
868           if (! ((c == '\t') || (c == ' '))) {
869             int rc = pdkim_header_complete(ctx); /* End of header */
870             if (rc != PDKIM_OK) return rc;
871           }
872           ctx->seen_lf = 0;
873         }
874       }
875       if (ctx->cur_header == NULL) {
876         ctx->cur_header = pdkim_strnew(NULL);
877         if (ctx->cur_header == NULL) return PDKIM_ERR_OOM;
878       }
879       if (pdkim_strncat(ctx->cur_header,&data[p],1) == NULL)
880         return PDKIM_ERR_OOM;
881     }
882   }
883   return PDKIM_OK;
884 };
885
886
887 /* -------------------------------------------------------------------------- */
888 char *pdkim_create_header(pdkim_signature *sig, int final) {
889   char *rc = NULL;
890   char *base64_bh = NULL;
891   char *base64_b  = NULL;
892   pdkim_str *hdr = pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION);
893   if (hdr == NULL) return NULL;
894
895   base64_bh = pdkim_encode_base64(sig->bodyhash, sig->bodyhash_len);
896   if (base64_bh == NULL) goto BAIL;
897
898   /* Required and static bits */
899   if (
900         pdkim_strcat(hdr,"; a=")                                &&
901         pdkim_strcat(hdr,pdkim_algos[sig->algo])                &&
902         pdkim_strcat(hdr,"; q=")                                &&
903         pdkim_strcat(hdr,pdkim_querymethods[sig->querymethod])  &&
904         pdkim_strcat(hdr,"; c=")                                &&
905         pdkim_strcat(hdr,pdkim_canons[sig->canon_headers])      &&
906         pdkim_strcat(hdr,"/")                                   &&
907         pdkim_strcat(hdr,pdkim_canons[sig->canon_body])         &&
908         pdkim_strcat(hdr,"; d=")                                &&
909         pdkim_strcat(hdr,sig->domain)                           &&
910         pdkim_strcat(hdr,"; s=")                                &&
911         pdkim_strcat(hdr,sig->selector)                         &&
912         pdkim_strcat(hdr,";\r\n\th=")                           &&
913         pdkim_strcat(hdr,sig->headernames)                      &&
914         pdkim_strcat(hdr,"; bh=")                               &&
915         pdkim_strcat(hdr,base64_bh)                             &&
916         pdkim_strcat(hdr,";\r\n\t")
917      ) {
918     /* Optional bits */
919     if (sig->identity != NULL) {
920       if (!( pdkim_strcat(hdr,"i=")                             &&
921              pdkim_strcat(hdr,sig->identity)                    &&
922              pdkim_strcat(hdr,";") ) ) {
923         goto BAIL;
924       }
925     }
926     if (sig->created > 0) {
927       if (!( pdkim_strcat(hdr,"t=")                             &&
928              pdkim_numcat(hdr,sig->created)                     &&
929              pdkim_strcat(hdr,";") ) ) {
930         goto BAIL;
931       }
932     }
933     if (sig->expires > 0) {
934       if (!( pdkim_strcat(hdr,"x=")                             &&
935              pdkim_numcat(hdr,sig->expires)                     &&
936              pdkim_strcat(hdr,";") ) ) {
937         goto BAIL;
938       }
939     }
940     if (sig->bodylength > 0) {
941       if (!( pdkim_strcat(hdr,"l=")                             &&
942              pdkim_numcat(hdr,sig->bodylength)                  &&
943              pdkim_strcat(hdr,";") ) ) {
944         goto BAIL;
945       }
946     }
947     /* Extra linebreak */
948     if (hdr->str[(hdr->len)-1] == ';') {
949       if (!pdkim_strcat(hdr," \r\n\t")) goto BAIL;
950     }
951     /* Preliminary or final version? */
952     if (final) {
953       base64_b = pdkim_encode_base64(sig->sigdata, sig->sigdata_len);
954       if (base64_b == NULL) goto BAIL;
955       if (
956             pdkim_strcat(hdr,"b=")                              &&
957             pdkim_strcat(hdr,base64_b)                          &&
958             pdkim_strcat(hdr,";")
959          ) goto DONE;
960     }
961     else {
962       if (pdkim_strcat(hdr,"b=;")) goto DONE;
963     }
964
965     goto BAIL;
966   }
967
968   DONE:
969   rc = strdup(hdr->str);
970
971   BAIL:
972   pdkim_strfree(hdr);
973   if (base64_bh != NULL) free(base64_bh);
974   if (base64_b  != NULL) free(base64_b);
975   return rc;
976 }
977
978
979 /* -------------------------------------------------------------------------- */
980 int pdkim_feed_finish(pdkim_ctx *ctx, char **signature) {
981   pdkim_signature *sig = ctx->sig;
982   pdkim_str *headernames = NULL;             /* Collected signed header names */
983
984   /* Check if we must still flush a (partial) header. If that is the
985      case, the message has no body, and we must compute a body hash
986      out of '<CR><LF>' */
987   if (ctx->cur_header->len) {
988     int rc = pdkim_header_complete(ctx);
989     if (rc != PDKIM_OK) return rc;
990     pdkim_update_bodyhash(ctx,"\r\n",2);
991   }
992   else {
993     /* For non-smtp input, check if there's an unfinished line in the
994        body line buffer. If that is the case, we must add a CRLF to the
995        hash to properly terminate the message. */
996     if ((ctx->input_mode == PDKIM_INPUT_NORMAL) && ctx->linebuf_offset) {
997       pdkim_update_bodyhash(ctx, ctx->linebuf, ctx->linebuf_offset);
998       pdkim_update_bodyhash(ctx,"\r\n",2);
999     }
1000     #ifdef PDKIM_DEBUG
1001     if (ctx->debug_stream)
1002       fprintf(ctx->debug_stream,
1003         "\nPDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1004     #endif
1005   }
1006
1007   /* Build (and/or evaluate) body hash */
1008   if (pdkim_finish_bodyhash(ctx) != PDKIM_OK) return PDKIM_ERR_OOM;
1009
1010   /* SIGNING -------------------------------------------------------------- */
1011   if (ctx->mode == PDKIM_MODE_SIGN) {
1012     headernames = pdkim_strnew(NULL);
1013     if (headernames == NULL) return PDKIM_ERR_OOM;
1014   }
1015   /* ---------------------------------------------------------------------- */
1016
1017   while (sig != NULL) {
1018     sha1_context sha1_headers;
1019     sha2_context sha2_headers;
1020     pdkim_stringlist *p = sig->headers;
1021     char *sig_hdr;
1022     char headerhash[32];
1023
1024     if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1025       sha1_starts(&sha1_headers);
1026     else
1027       sha2_starts(&sha2_headers,0);
1028
1029     #ifdef PDKIM_DEBUG
1030     if (ctx->debug_stream)
1031       fprintf(ctx->debug_stream,
1032               "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
1033     #endif
1034
1035     while (p != NULL) {
1036       char *rh;
1037
1038       /* SIGNING -------------------------------------------------------------- */
1039       if (ctx->mode == PDKIM_MODE_SIGN) {
1040         /* Collect header names (Note: colon presence is guaranteed here) */
1041         char *q = strchr(p->value,':');
1042         if (pdkim_strncat(headernames, p->value,
1043                           (q-(p->value))+((p->next==NULL)?0:1)) == NULL)
1044           return PDKIM_ERR_OOM;
1045       }
1046       /* ---------------------------------------------------------------------- */
1047
1048       if (sig->canon_body == PDKIM_CANON_RELAXED)
1049         rh = pdkim_relax_header(p->value,1); /* cook header for relaxed canon */
1050       else
1051         rh = strdup(p->value);             /* just copy it for simple canon */
1052
1053       if (rh == NULL) return PDKIM_ERR_OOM;
1054
1055       /* Feed header to the hash algorithm */
1056       if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1057         sha1_update(&(sha1_headers),(unsigned char *)rh,strlen(rh));
1058       else
1059         sha2_update(&(sha2_headers),(unsigned char *)rh,strlen(rh));
1060       #ifdef PDKIM_DEBUG
1061       if (ctx->debug_stream)
1062         pdkim_quoteprint(ctx->debug_stream, rh, strlen(rh), 1);
1063       #endif
1064       free(rh);
1065       p = p->next;
1066     }
1067
1068     #ifdef PDKIM_DEBUG
1069     if (ctx->debug_stream)
1070       fprintf(ctx->debug_stream,
1071               "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1072     #endif
1073
1074
1075     /* SIGNING ---------------------------------------------------------------- */
1076     if (ctx->mode == PDKIM_MODE_SIGN) {
1077       /* Copy headernames to signature struct */
1078       sig->headernames = strdup(headernames->str);
1079       pdkim_strfree(headernames);
1080
1081       /* Create signature header with b= omitted */
1082       sig_hdr = pdkim_create_header(ctx->sig,0);
1083     }
1084     /* VERIFICATION ----------------------------------------------------------- */
1085     else {
1086       sig_hdr = strdup(sig->rawsig_no_b_val);
1087     }
1088     /* ------------------------------------------------------------------------ */
1089
1090     if (sig_hdr == NULL) return PDKIM_ERR_OOM;
1091
1092     /* Relax header if necessary */
1093     if (sig->canon_headers == PDKIM_CANON_RELAXED) {
1094       char *relaxed_hdr = pdkim_relax_header(sig_hdr,0);
1095       free(sig_hdr);
1096       if (relaxed_hdr == NULL) return PDKIM_ERR_OOM;
1097       sig_hdr = relaxed_hdr;
1098     }
1099
1100     #ifdef PDKIM_DEBUG
1101     if (ctx->debug_stream) {
1102       fprintf(ctx->debug_stream,
1103               "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1104       pdkim_quoteprint(ctx->debug_stream, sig_hdr, strlen(sig_hdr), 1);
1105       fprintf(ctx->debug_stream,
1106               "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1107     }
1108     #endif
1109
1110     /* Finalize header hash */
1111     if (sig->algo == PDKIM_ALGO_RSA_SHA1) {
1112       sha1_update(&(sha1_headers),(unsigned char *)sig_hdr,strlen(sig_hdr));
1113       sha1_finish(&(sha1_headers),(unsigned char *)headerhash);
1114     }
1115     else {
1116       sha2_update(&(sha2_headers),(unsigned char *)sig_hdr,strlen(sig_hdr));
1117       sha2_finish(&(sha2_headers),(unsigned char *)headerhash);
1118     }
1119
1120     free(sig_hdr);
1121
1122     /* SIGNING ---------------------------------------------------------------- */
1123     if (ctx->mode == PDKIM_MODE_SIGN) {
1124       rsa_context rsa;
1125
1126       /* Perform private key operation */
1127       if (rsa_parse_key(&rsa, (unsigned char *)sig->rsa_privkey,
1128                         strlen(sig->rsa_privkey), NULL, 0) != 0) {
1129         return PDKIM_ERR_RSA_PRIVKEY;
1130       }
1131
1132       sig->sigdata_len = mpi_size(&(rsa.N));
1133       sig->sigdata = malloc(sig->sigdata_len);
1134       if (sig->sigdata == NULL) return PDKIM_ERR_OOM;
1135
1136       if (rsa_pkcs1_sign( &rsa, RSA_PRIVATE,
1137                           ((sig->algo == PDKIM_ALGO_RSA_SHA1)?
1138                              RSA_SHA1:RSA_SHA256),
1139                           0,
1140                           (unsigned char *)headerhash,
1141                           (unsigned char *)sig->sigdata ) != 0) {
1142         return PDKIM_ERR_RSA_SIGNING;
1143       }
1144
1145       rsa_free(&rsa);
1146
1147       #ifdef PDKIM_DEBUG
1148       if (ctx->debug_stream) {
1149         fprintf(ctx->debug_stream, "PDKIM [%s] b computed: ",
1150                 sig->domain);
1151         pdkim_hexprint(ctx->debug_stream, sig->sigdata, sig->sigdata_len, 1);
1152       }
1153       #endif
1154
1155       /* Recreate signature header with b= included, return it to the caller */
1156       if (signature != NULL) {
1157         *signature = pdkim_create_header(ctx->sig,1);
1158         if (*signature == NULL) return PDKIM_ERR_OOM;
1159       }
1160     }
1161     /* VERIFICATION ----------------------------------------------------------- */
1162     else {
1163
1164     }
1165
1166     sig = sig->next;
1167   }
1168
1169   return PDKIM_OK;
1170 }
1171
1172
1173 /* -------------------------------------------------------------------------- */
1174 pdkim_ctx *pdkim_init_verify(void) {
1175   pdkim_ctx *ctx = malloc(sizeof(pdkim_ctx));
1176   if (ctx == NULL) return NULL;
1177   memset(ctx,0,sizeof(pdkim_ctx));
1178   ctx->mode = PDKIM_MODE_VERIFY;
1179   return ctx;
1180 }
1181
1182
1183 /* -------------------------------------------------------------------------- */
1184 pdkim_ctx *pdkim_init_sign(char *domain,
1185                            char *selector,
1186                            char *rsa_privkey) {
1187   pdkim_ctx *ctx;
1188
1189   if (!domain || !selector || !rsa_privkey) return NULL;
1190
1191   ctx = malloc(sizeof(pdkim_ctx));
1192   if (ctx == NULL) return NULL;
1193   memset(ctx,0,sizeof(pdkim_ctx));
1194   pdkim_signature *sig = malloc(sizeof(pdkim_signature));
1195   if (sig == NULL) {
1196     free(ctx);
1197     return NULL;
1198   }
1199   memset(sig,0,sizeof(pdkim_signature));
1200
1201   ctx->mode = PDKIM_MODE_SIGN;
1202   ctx->sig = sig;
1203
1204   ctx->sig->domain = malloc(strlen(domain)+1);
1205   ctx->sig->selector = malloc(strlen(selector)+1);
1206   ctx->sig->rsa_privkey = malloc(strlen(rsa_privkey)+1);
1207
1208   if (!ctx->sig->domain || !ctx->sig->selector || !ctx->sig->rsa_privkey) {
1209     pdkim_free_ctx(ctx);
1210     return NULL;
1211   }
1212
1213   strcpy(ctx->sig->domain, domain);
1214   strcpy(ctx->sig->selector, selector);
1215   strcpy(ctx->sig->rsa_privkey, rsa_privkey);
1216
1217   sha1_starts(&(ctx->sig->sha1_body));
1218   sha2_starts(&(ctx->sig->sha2_body),0);
1219
1220   return ctx;
1221 };
1222
1223 #ifdef PDKIM_DEBUG
1224 /* -------------------------------------------------------------------------- */
1225 void pdkim_set_debug_stream(pdkim_ctx *ctx,
1226                             FILE *debug_stream) {
1227   ctx->debug_stream = debug_stream;
1228 };
1229 #endif
1230
1231 /* -------------------------------------------------------------------------- */
1232 int pdkim_set_optional(pdkim_ctx *ctx,
1233                        int input_mode,
1234                        char *sign_headers,
1235                        char *identity,
1236                        int canon_headers,
1237                        int canon_body,
1238                        unsigned long bodylength,
1239                        int algo,
1240                        unsigned long created,
1241                        unsigned long expires) {
1242
1243   if (identity != NULL) {
1244     ctx->sig->identity = malloc(strlen(identity)+1);
1245     if (!ctx->sig->identity) {
1246       return PDKIM_ERR_OOM;
1247     }
1248     strcpy(ctx->sig->identity, identity);
1249   }
1250
1251   if (sign_headers != NULL) {
1252     ctx->sig->sign_headers = malloc(strlen(sign_headers)+1);
1253     if (!ctx->sig->sign_headers) {
1254       return PDKIM_ERR_OOM;
1255     }
1256     strcpy(ctx->sig->sign_headers, sign_headers);
1257   }
1258
1259   ctx->input_mode = input_mode;
1260   ctx->sig->canon_headers = canon_headers;
1261   ctx->sig->canon_body = canon_body;
1262   ctx->sig->bodylength = bodylength;
1263   ctx->sig->algo = algo;
1264   ctx->sig->created = created;
1265   ctx->sig->expires = expires;
1266
1267   return PDKIM_OK;
1268 };
1269
1270
1271
1272
1273 /* -------------------------------------------------------------------------- */
1274 void pdkim_free_sig(pdkim_signature *sig) {
1275   if (sig) {
1276     pdkim_signature *next = (pdkim_signature *)sig->next;
1277
1278     pdkim_stringlist *e = sig->headers;
1279     while(e != NULL) {
1280       pdkim_stringlist *c = e;
1281       if (e->value != NULL) free(e->value);
1282       e = e->next;
1283       free(c);
1284     }
1285
1286     if (sig->sigdata        != NULL) free(sig->sigdata);
1287     if (sig->bodyhash       != NULL) free(sig->bodyhash);
1288     if (sig->selector       != NULL) free(sig->selector);
1289     if (sig->domain         != NULL) free(sig->domain);
1290     if (sig->identity       != NULL) free(sig->identity);
1291     if (sig->headernames    != NULL) free(sig->headernames);
1292     if (sig->copiedheaders  != NULL) free(sig->copiedheaders);
1293     if (sig->rsa_privkey    != NULL) free(sig->rsa_privkey);
1294     if (sig->sign_headers   != NULL) free(sig->sign_headers);
1295
1296     free(sig);
1297     if (next != NULL) pdkim_free_sig(next);
1298   }
1299 };
1300
1301
1302 /* -------------------------------------------------------------------------- */
1303 void pdkim_free_ctx(pdkim_ctx *ctx) {
1304   if (ctx) {
1305     pdkim_free_sig(ctx->sig);
1306     pdkim_strfree(ctx->cur_header);
1307     free(ctx);
1308   }
1309 };