Source

oni / mime / mime_lex.ml

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
(*---------------------------------------------------------------------------*
  $Change$
  Copyright (c) 2005-2010, James H. Woodyatt
  All rights reserved.
  
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:
  
    Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
    
    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution
  
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  OF THE POSSIBILITY OF SUCH DAMAGE. 
 *---------------------------------------------------------------------------*)

(*
let jout = Cf_journal.stdout
*)

open Cf_llscan.Op
open Cf_clex.Op

module Expr = struct
    let wsp = !$"[ `t]"
    let crlf = !$"`r`n"
    
    let no_ws_ctl =
        !^ begin function
            | '\001'..'\008' | '\011' | '\012' | '\014'..'\031' | '\127' ->
                true
            | _ ->
                false
        end
        
    let specials_f_ = function
        | '(' | ')' | '<' | '>' | '[' | ']' | ':' | ';' | '@'
        | '\\' | ',' | '.' | '"' -> true
        | _ -> false
    
    let specials = !^specials_f_
    
    let tspecials_f_ = function
        | '(' | ')' | '<' | '>' | '[' | ']' | ':' | ';' | '@'
        | '/' | '\\' | ',' | '?' | '=' | '"' -> true
        | _ -> false
    
    let tspecials = !^tspecials_f_
        
    let utext =
        let printable_ascii_ = !$"[`033-`126]" in
        (* let obs_utext_ = !$"`n*`r*[^`010`013`128-`255]`n*`r*" in *)
        no_ws_ctl $| printable_ascii_ (* $| obs_utext_ *)
    
    let quoted_pair = !$"\\[`000-`127]"
    
    let obs_fws_ = !+wsp $& !*(crlf $& !+wsp)
    
    let fws = (!? (!*wsp $& crlf) $& !+wsp) $| obs_fws_
    
    let optfws = !?fws
    
    let ch_ctext_printable_ =
        !^ begin function
            | '\033'..'\039' | '\042'..'\091' | '\093'..'\126' -> true
            | _ -> false
        end
    
    let ctext = no_ws_ctl $| ch_ctext_printable_
    
    let cbegin = !:'('
    let cend = !:')'
    
    let atext =
        !^ begin function
            | '\000'..'\032' -> false
            | '\128'..'\255' -> false
            | x -> not (specials_f_ x)
        end
    
    let raw_atom = !+atext
    
    let raw_dot_atom = raw_atom $& !*(!:'.' $& raw_atom)
    
    let ttext =
        !^ begin function
            | '\000'..'\032' -> false
            | '\128'..'\255' -> false
            | x -> not (tspecials_f_ x)
        end
    
    let raw_token = !+ttext
    
    let dquote = !:'"'
    
    let qtext =
        no_ws_ctl $|
        !^ begin function
            | '\033' | '\035'..'\091' | '\092'..'\126' -> true
            | _ -> false
        end
    
    let qcontent = qtext $| quoted_pair
    
    let raw_quoted_string =
        dquote $& !*(optfws $& qcontent) $& optfws $& dquote
    
    let dtext =
        no_ws_ctl $|
        !^ begin function
            | '\033' | '\035'..'\091' | '\092'..'\126' -> true
            | _ -> false
        end
    
    let dcontent = dtext $| quoted_pair
    
    let raw_domain_literal =
        !:'[' $& !*(optfws $& dcontent) $& optfws $& !:']'
    
    let ftext =
        !^ begin function
            | '\033'..'\057' | '\059'..'\126' -> true
            | _ -> false
        end
    
    let field_name = !+ftext
    
    let unstructured = !*(optfws $& utext) $& optfws
end

module E = Expr

let identity_ x = x

let cr_ = ?.'\r'
let lf_ = ?.'\n'
let colon_ = ?.':'

module Int_map = Cf_rbtree.Map(Cf_ordered.Int_order)

type comment_token_t = C_push | C_pop | C_run
type parameter_element_t = P_complete of string | P_partial of string Int_map.t

let scan_comment_ =
    let aux = !*(E.optfws $& (E.ctext $| E.quoted_pair)) $& E.optfws in
    let lex =
        Cf_clex.create !@[ aux $= C_run; !:'(' $= C_push; !:')' $= C_pop ]
    in
    let rec loop n =
        lex >>= function
        | C_push -> loop (succ n)
        | C_pop -> if n > 0 then loop (pred n) else Cf_llscan.ret ()
        | C_run -> loop n
    in
    ?.'(' >>= fun _ ->
    loop 0

let optunit_ p z = match p z with None -> Some ((), z) | x -> x

let quoted_pair_normalize_rule_ s =
    assert (String.length s = 2);
    String.unsafe_get s 1

let chx_normalize_rule_ n z =
    assert (n = 1);
    match Lazy.force z with
    | Cf_seq.P (hd, tl) -> Some (hd, tl)
    | _ -> assert (not true); None

let normalize_lexer_ chx =
    Cf_clex.create !@[
        E.fws $= ' ';
        E.quoted_pair $> quoted_pair_normalize_rule_;
        chx $@ chx_normalize_rule_;
    ]

let normalize_ cons p n z =
    let z' = Cf_seq.shift n z in
    let z = Cf_seq.limit (n - 2) (Cf_seq.shift 1 z) in
    let s = Cf_seq.to_string (Cf_llscan.unfold p z) in
    Some (cons s, z')

let scan_field_name =
    let colon = Cf_clex.create (!* E.wsp $& !:':' $= ()) in
    let raw_field_name =
        Cf_regx.llscan (Cf_regx.of_expression E.field_name)
    in
    raw_field_name >>= fun name ->
    colon >>= fun _ ->
    Cf_llscan.ret name

let scan_unstructured = Cf_regx.llscan (Cf_regx.of_expression E.unstructured)

let scan_fws = Cf_clex.create (E.fws $= ())

let scan_optfws = optunit_ scan_fws

let scan_cfws =
    let aux = scan_optfws >>= fun () -> scan_comment_ in
    let rec loop s =
        match aux s with
        | None -> Some ((), s)
        | Some ((), s) -> loop s
    in
    loop >>= fun () ->
    Cf_llscan.alt [ aux; scan_fws ]

let scan_optcfws = optunit_ scan_cfws

let scan_crlf =
    scan_optcfws >>= fun () ->
    cr_ >>= fun _ ->
    lf_ >>= fun _ ->
    Cf_llscan.ret ()

let scan_raw_atom_ = Cf_clex.create (E.raw_atom $> identity_)
let scan_raw_dot_atom_ = Cf_clex.create (E.raw_dot_atom $> identity_)
let scan_raw_token_ = Cf_clex.create (E.raw_token $> identity_)

let eat_cfws_ p = scan_optcfws >>= fun () -> p

let scan_atom = eat_cfws_ scan_raw_atom_
let scan_dot_atom = eat_cfws_ scan_raw_dot_atom_
let scan_token = eat_cfws_ scan_raw_token_

let scan_raw_quoted_string_ =
    Cf_clex.create begin
        E.raw_quoted_string $@
        normalize_ identity_ (normalize_lexer_ E.qtext)
    end

let scan_quoted_string = eat_cfws_ scan_raw_quoted_string_

let scan_domain_literal =
    eat_cfws_ begin
        Cf_clex.create begin
            E.raw_domain_literal $@
            normalize_ identity_ (normalize_lexer_ E.dtext)
        end
    end

let scan_word =
    eat_cfws_ (Cf_llscan.alt [ scan_raw_atom_; scan_raw_quoted_string_ ])

let scan_obs_phrase =
    let obs_phrase_aux =
        ?* begin
            Cf_llscan.alt [
                scan_word;
                Cf_llscan.tok (function '.' -> Some "." | _ -> None);
                scan_cfws >>= fun () -> Cf_llscan.ret " ";
            ]
        end
    in
    scan_word >>= fun hd ->
    obs_phrase_aux >>= fun tl ->
    let wl = List.rev (hd :: tl) in
    let f a w = (w, 0, String.length w) :: a in
    let m = List.fold_left f [] wl in
    Cf_llscan.ret (Cf_message.contents m)

let scan_addr_spec =
    let stop = eat_cfws_ ?.'.' in
    let stop_word_list = ?* (stop >>= fun _ -> scan_word) in
    let stop_atom_list = ?* (stop >>= fun _ -> scan_atom) in
    let obs_local =
        scan_word >>= fun hd ->
        stop_word_list >>= fun tl ->
        let b = Buffer.create 80 in
        Buffer.add_string b hd;
        List.iter begin fun s ->
            Buffer.add_char b '.';
            Buffer.add_string b s
        end tl;
        Cf_llscan.ret (Buffer.contents b)
    in
    let obs_domain =
        scan_atom >>= fun hd ->
        stop_atom_list >>= fun tl ->
        let b = Buffer.create 80 in
        Buffer.add_string b hd;
        List.iter begin fun s ->
            Buffer.add_char b '.';
            Buffer.add_string b s
        end tl;
        Cf_llscan.ret (Buffer.contents b)
    in
    let local =
        Cf_llscan.alt [
            scan_quoted_string;
            scan_dot_atom;
            obs_local;
        ]
    in
    let domain =
        Cf_llscan.alt [
            scan_domain_literal;
            scan_dot_atom;
            obs_domain;
        ]
    in
    let separator = eat_cfws_ ?.'@' in
    local >>= fun loc ->
    separator >>= fun _ ->
    domain >>= fun dom ->
    Cf_llscan.ret (loc, dom)

let scan_date_time =
    let month_names =
        Mime_atom.Map.of_list [
            "jan", 1;
            "feb", 2;
            "mar", 3;
            "apr", 4;
            "may", 5;
            "jun", 6;
            "jul", 7;
            "aug", 8;
            "sep", 9;
            "oct", 10;
            "nov", 11;
            "dec", 12;
        ]
    and weekday_names =
        Mime_atom.Map.of_list [
            "sun", 0;
            "mon", 1;
            "tue", 2;
            "wed", 3;
            "thu", 4;
            "fri", 5;
            "sat", 6;
        ]
    and zone_names =
        Mime_atom.Map.of_list [
            "UT",   0;
            "GMT",  0;
            "EDT",  (-4);
            "EST",  (-5);
            "CDT",  (-5);
            "CST",  (-6);
            "MDT",  (-6);
            "MST",  (-7);
            "PDT",  (-7);
            "PST",  (-8);
            "A",    1;
            "B",    2;
            "C",    3;
            "D",    4;
            "E",    5;
            "F",    6;
            "G",    7;
            "H",    8;
            "I",    9;
            "K",    10;
            "L",    11;
            "M",    12;
            "N",    (-1);
            "O",    (-2);
            "P",    (-3);
            "Q",    (-4);
            "R",    (-5);
            "S",    (-6);
            "T",    (-7);
            "U",    (-8);
            "V",    (-9);
            "W",    (-10);
            "X",    (-11);
            "Y",    (-12);
            "Z",    0;
        ]
    in
    let number = eat_cfws_ (Cf_scan_parser.scanf "%u" identity_) in
    let weekday =
        scan_atom >>= fun wd ->
        if Mime_atom.Map.member wd weekday_names then
            Cf_llscan.ret ()
        else
            Cf_llscan.nil
    in
    let monthname =
        scan_atom >>= fun wd ->
        try Cf_llscan.ret (Mime_atom.Map.search wd month_names) with
        | Not_found -> Cf_llscan.nil
    in
    let sign = eat_cfws_ (Cf_llscan.alt [ ?.'+'; ?.'-' ]) in
    let named_zone =
        scan_atom >>= fun wd ->
        Cf_llscan.ret begin
            try Some (Mime_atom.Map.search wd zone_names) with
            Not_found -> None
        end
    and numbered_zone =
        sign >>= fun d ->
        Cf_scan_parser.scanf "%4u" identity_ >>= fun n ->
        let hr = n / 100 and min = n mod 100 in
        if hr > 99 || min > 59 then
            Cf_llscan.nil
        else
            let n = ((hr * 60) + min) * 60 in
            Cf_llscan.ret begin
                match d with
                | '-' when n = 0 -> None
                | '-' -> Some (-n)
                | _ -> Some n
            end
    in
    let timezone = Cf_llscan.alt [ numbered_zone; named_zone; ] in
    let comma = eat_cfws_ ?.',' and colon = eat_cfws_ ?.':' in
    ?/ (weekday >>= fun () -> comma) >>= fun _ ->
    number >>= fun day ->
    monthname >>= fun month ->
    number >>= fun year ->
    number >>= fun hour ->
    colon >>= fun _ ->
    number >>= fun minute ->
    colon >>= fun _ ->
    number >>= fun second ->
    timezone >>= fun tz ->
    let tm = {
        Cf_stdtime.year = year;
        Cf_stdtime.month = month;
        Cf_stdtime.day = day;
        Cf_stdtime.hour = hour;
        Cf_stdtime.minute = minute;
        Cf_stdtime.second = second;
    } in
    Cf_llscan.ret (tm, tz)

let scan_parameters =
    let eq = eat_cfws_ ?.'=' in
    let semicolon = eat_cfws_ ?.';' in
    let value =
        eat_cfws_ begin
            Cf_llscan.alt [ scan_raw_quoted_string_; scan_raw_token_ ]
        end
    in
    let equation =
        scan_token >>= fun tag ->
        eq >>= fun _ ->
        value >>= fun v ->
        Cf_llscan.ret (String.lowercase tag, v)
    in
    let element = 
        semicolon >>= fun _ ->
        equation >>= fun (a, v) ->
        Cf_llscan.ret begin
            try
                let n = String.index a '*' in
                let len = String.length a in
                if n > 0 && n < len - 1 then begin
                    let a = String.sub a 0 n in
                    let b = String.sub a (n + 1) (len - n - 1) in
                    let n = int_of_string b in
                    a, Some n, v
                end
                else
                    a, None, v
            with
            | Not_found ->
                a, None, v
        end
    in
    let insert_loop r (a, n_opt, v) =
        let p =
            match n_opt with
            | None ->
                P_complete v
            | Some n ->
                let rr =
                    try
                        match Mime_atom.Map.search a r with
                        | P_partial rr -> rr
                        | _ -> Int_map.nil
                    with
                    | Not_found ->
                        Int_map.nil
                in
                P_partial (Int_map.replace (n, v) rr)
        in
        Mime_atom.Map.replace (a, p) r
    in
    let iterate_loop b (_, s) = Buffer.add_string b s in
    let map_loop (a, p) =
        match p with
        | P_complete s -> a, s
        | P_partial rr ->
            let b = Buffer.create 32 in
            let z = Int_map.to_seq_incr rr in
            Cf_seq.iterate (iterate_loop b) z;
            a, Buffer.contents b
    in
    let reconstruct_loop r pair = Mime_atom.Map.replace pair r in
    let element_list = ?* element in
    element_list >>= fun z ->
    let r = List.fold_left insert_loop Mime_atom.Map.nil z in
    let z = Mime_atom.Map.to_seq_incr r in
    let z = Cf_seq.map map_loop z in
    Cf_llscan.ret (Cf_seq.fold reconstruct_loop Mime_atom.Map.nil z)

let crlf_string_ = "\r\n"

type error =
    | X_field_bad_syntax of int * Cf_message.t
    | X_field_duplicated of string

let error_to_string = function
    | X_field_bad_syntax (n, _) ->
        Printf.sprintf "field with bad syntax at line %u" n
    | X_field_duplicated name ->
        Printf.sprintf "duplicate '%s' field" name

exception Error of error

let split_at_body =
    let rec loop pos z =
        match Lazy.force z with
        | Cf_seq.Z ->
            raise End_of_file
        | Cf_seq.P (hd, tl) when hd <> '\013' ->
            loop (succ pos) tl
        | Cf_seq.P (_, tl) ->
            match Lazy.force tl with
            | Cf_seq.Z ->
                raise End_of_file
            | Cf_seq.P (hd, tl) when hd <> '\010' ->
                loop (pos + 2) tl
            | Cf_seq.P (_, tl) ->
                match Lazy.force tl with
                | Cf_seq.Z ->
                    raise End_of_file
                | Cf_seq.P (hd, tl) when hd <> '\013' ->
                    loop (pos + 3) tl
                | Cf_seq.P (_, tl) ->
                    match Lazy.force tl with
                    | Cf_seq.Z ->
                        raise End_of_file
                    | Cf_seq.P (hd, tl) when hd <> '\010' ->
                        loop (pos + 4) tl
                    | Cf_seq.P _ ->
                        pos + 4
    in
    fun m ->
        let pos = loop 0 (Cf_message.to_seq m) in
        Cf_message.split ~pos m

let rec split_into_fields_scan_ pos rows z =
    match Lazy.force z with
    | Cf_seq.Z ->
        raise End_of_file
    | Cf_seq.P (c, z) when c <> '\r' ->
        split_into_fields_scan_ (succ pos) rows z
    | Cf_seq.P (_, z) ->
        match Lazy.force z with
        | Cf_seq.Z ->
            raise End_of_file
        | Cf_seq.P (c, z) when c <> '\n' ->
            split_into_fields_scan_ (pos + 2) rows z
        | Cf_seq.P (_, z) ->
            let rows = succ rows in
            match Lazy.force z with
            | Cf_seq.P (c, z) when c = '\t' || c = ' ' ->
                split_into_fields_scan_ (pos + 3) rows z
            | _ ->
                pos + 2, rows, z

let rec split_into_fields_loop_ f line acc m z =
    let pos, rows, tl = split_into_fields_scan_ 0 0 z in
    let field, m = Cf_message.split ~pos m in
    if pos = 2 then
        (List.rev_map f) acc, m
    else
        match scan_field_name (Cf_message.to_seq field) with
        | None ->
            raise (Error (X_field_bad_syntax (line, field)))
        | Some (name, z) ->
            let acc = (line, name, z) :: acc in
            split_into_fields_loop_ f (line + rows) acc m tl

let split_into_fields_and_map f m =
    split_into_fields_loop_ f 0 [] m (Cf_message.to_seq m)

let split_into_fields =
    let f (_, name, z) = name, z in fun m -> split_into_fields_and_map f m

let err_default_ _ = Cf_llscan.Error

let select_field ?(err = err_default_) name parse =
    let f (hname, _) = Mime_atom.Order.compare hname name = 0 in
    fun headers ->
        let h1, h2 = List.partition f headers in
        let v =
            match h1 with
            | [] ->
                raise Not_found
            | (name, _) :: _ :: _ ->
                raise (Error (X_field_duplicated name))
            | (_, text) :: [] -> 
                lazy begin
                    match parse text with
                    | None -> raise (err text)
                    | Some (v, _) -> v
                end
        in
        v, h2

let select_opt_field ?(err = err_default_) name parse =
    let f (hname, _) = Mime_atom.Order.compare hname name = 0 in
    fun headers ->
        let h1, h2 = List.partition f headers in
        let v =
            match h1 with
            | [] ->
                Lazy.lazy_from_val None
            | (name, _) :: _ :: _ ->
                raise (Error (X_field_duplicated name))
            | (_, text) :: [] -> 
                lazy begin
                    match parse text with
                    | None -> raise (err text)
                    | Some (v, _) -> Some v
                end
        in
        v, h2

let select_all_fields ?(err = err_default_) name parse =
    let f (hname, _) = Mime_atom.Order.compare hname name = 0 in
    let g (_, text) =
        match parse text with
        | None -> raise (err text)
        | Some (v, _) -> v
    in
    fun headers ->
        let h1, h2 = List.partition f headers in
        lazy (List.map g h1), h2

let formatter b =
    let pp = Format.formatter_of_buffer b in
    let out, flush, _, spaces =
        Format.pp_get_all_formatter_output_functions pp ()
    in
    let newline () = out crlf_string_ 0 2 in
    let pp = Format.make_formatter out flush in
    Format.pp_set_all_formatter_output_functions
        pp ~out ~flush ~newline ~spaces;
    Format.pp_set_margin pp 75;
    pp

let emit_folding_char pp = function
    | '\128'..'\255' as c -> Format.fprintf pp "%%%02X" (Char.code c)
    | '\n' ->  Format.pp_force_newline pp ()
    | ' ' -> Format.pp_print_space pp ()
    | '\t' -> Format.pp_print_tab pp ()
    | c -> Format.pp_print_char pp c

let emit_folding_string pp s =
    for i = 0 to String.length s - 1 do
        emit_folding_char pp (String.unsafe_get s i)
    done

let emit_comment pp s =
    Format.pp_print_char pp '(';
    emit_folding_string pp s;
    Format.pp_print_char pp ')'

let print_char_in_quoted_string_ pp = function
    | ('\034' | '\092' as c) ->
        Format.pp_print_char pp '\092';
        Format.pp_print_char pp c
    | c ->
        emit_folding_char pp c

let emit_quoted_string pp s =
    Format.pp_print_char pp '"';
    for i = 0 to String.length s - 1 do
        print_char_in_quoted_string_ pp (String.unsafe_get s i)
    done;
    Format.pp_print_char pp '"'

let atom_lexer_ =
    Cf_clex.create (Expr.raw_atom $= ()) >>= fun () ->
    Cf_llscan.fin

let emit_word pp s =
    match atom_lexer_ (Cf_seq.of_string s) with
    | Some ((), _) -> Format.pp_print_string pp s
    | None -> emit_quoted_string pp s

let token_lexer_ =
    Cf_clex.create (Expr.raw_token $= ()) >>= fun () ->
    Cf_llscan.fin

let emit_token pp s =
    match token_lexer_ (Cf_seq.of_string s) with
    | Some ((), _) -> Format.pp_print_string pp s
    | None -> emit_quoted_string pp s

let print_char_in_domain_literal_ pp = function
    | ('\091'..'\093' as c) ->
        Format.pp_print_char pp '\092';
        Format.pp_print_char pp c
    | c ->
        emit_folding_char pp c

let dot_atom_lexer_ =
    Cf_clex.create (Expr.raw_dot_atom $= ()) >>= fun () ->
    Cf_llscan.fin

let emit_domain_literal pp s =
    Format.pp_print_char pp '[';
    for i = 0 to String.length s - 1 do
        print_char_in_domain_literal_ pp (String.unsafe_get s i)
    done;
    Format.pp_print_char pp ']'

let emit_addr_local pp s =
    match dot_atom_lexer_ (Cf_seq.of_string s) with
    | Some ((), _) -> Format.pp_print_string pp s
    | None -> emit_quoted_string pp s

let emit_addr_domain pp s =
    match dot_atom_lexer_ (Cf_seq.of_string s) with
    | Some ((), _) -> Format.pp_print_string pp s
    | None -> emit_domain_literal pp s

let emit_date_time =
    let err_ = "ERR" in
    let month = function
        | 1 -> "Jan"
        | 2 -> "Feb"
        | 3 -> "Mar"
        | 4 -> "Apr"
        | 5 -> "May"
        | 6 -> "Jun"
        | 7 -> "Jul"
        | 8 -> "Aug"
        | 9 -> "Sep"
        | 10 -> "Oct"
        | 11 -> "Nov"
        | 12 -> "Dec"
        | _ -> assert (not true); err_
    in
    let weekday = function
        | 0 -> "Sun"
        | 1 -> "Mon"
        | 2 -> "Tue"
        | 3 -> "Wed"
        | 4 -> "Thu"
        | 5 -> "Fri"
        | 6 -> "Sat"
        | _ -> assert (not true); err_
    in
    let zone = function
        | None ->
            '-', 0
        | Some dmin ->
            let ch, n = if dmin < 0 then '-', (-dmin) else '+', dmin in
            let hr = n / 60 and min = n mod 60 in
            ch, (hr * 100 + min)
    in
    fun pp (t, zopt) ->
        if not (Cf_gregorian.is_valid
            ~year:t.Cf_stdtime.year ~month:t.Cf_stdtime.month
            ~day:t.Cf_stdtime.day)
        then
            invalid_arg "Mime_emitter.data_time: not valid gregorian date";
        let wday = ref 0 in
        let cjd =
            Cf_gregorian.to_cjd_unsafe
                ~year:t.Cf_stdtime.year ~month:t.Cf_stdtime.month
                ~day:t.Cf_stdtime.day
        in
        let _ = Cf_gregorian.of_cjd ~wday cjd in
        let wday = weekday !wday in
        let month = month t.Cf_stdtime.month in
        let zch, zn = zone zopt in
        Format.fprintf pp "%s, %u %s %02d %02u:%02u:%02u %c%04u"
            wday t.Cf_stdtime.day month t.Cf_stdtime.year t.Cf_stdtime.hour
            t.Cf_stdtime.minute t.Cf_stdtime.second zch zn

let emit_parameters =
    let value pp s =
        match token_lexer_ (Cf_seq.of_string s) with
        | Some ((), _) -> Format.pp_print_string pp s
        | None -> emit_quoted_string pp s
    in
    let rec loop pp (a, v) =
        Format.fprintf pp ";@ %s=" a;
        value pp v
    in
    fun pp map ->
        Mime_atom.Map.iterate (loop pp) map

let emit_field f pp name v =
    Format.pp_open_box pp 1;
    Format.fprintf pp "%s:@ " name;
    f pp v;
    Format.pp_print_newline pp ()

let emit_optional_field f pp name = function
    | Some v -> emit_field f pp name v
    | None -> ()

(*--- $File$ ---*)