Source

oni / beep / beep_session.ml

Full commit
  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
(*---------------------------------------------------------------------------*
  $Change$
  Copyright (c) 2008-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 errj = Cf_journal.stderr
let _ = errj#setlimit `None
(**)

module N32_map = Beep_core.N32_map

module E_profile = struct
    open Cf_llscan.Op
    
    type encoding = E_none | E_base64
    
    type t = {
        uri: string;
        encoding: encoding;
        content: string;
    }
    
    let cons ~uri ?(enc = E_none) content = {
        uri = uri;
        encoding = enc;
        content = content;
    }
    
    let required = "#REQUIRED" and empty = ""
    
    let initial = {
        uri = required;
        encoding = E_none;
        content = empty;
    }
    
    let emit_octets pp v =
        Format.pp_open_vbox pp 2;
        Format.pp_print_string pp "<profile uri='";
        Format.pp_print_string pp v.uri;
        Format.pp_print_char pp '\'';
        let content =
            match v.encoding with
            | E_base64 ->
                Format.pp_print_string pp " encoding='base64'";
                Mime_base64.E.atomic v.content
            | E_none ->
                v.content
        in
        if v.content = "" then begin
            Format.pp_print_string pp "/>";
            Format.pp_close_box pp ()
        end
        else begin
            Format.pp_print_char pp '>';
            Format.pp_print_cut pp ();
            Format.pp_print_string pp content;
            Format.pp_close_box pp ();
            Format.pp_print_cut pp ();
            Format.pp_print_string pp "</profile>"
        end
    
    let scan_xml_entity =
        let invalid pos pair =
            let event = Xml_event.T_element_start ("profile", [pair]), pos in
            raise (Xml_parser.Invalid event)
        in
        let attr pos obj (k, v as pair) =
            match k with
            | "uri" ->
                { obj with uri = v }
            | "encoding" -> begin
                match v with
                | "none" -> { obj with encoding = E_none }
                | "base64" -> { obj with encoding = E_base64 }
                | _ -> invalid pos pair
              end
            | _ ->
                invalid pos pair
        in
        let space = Xml_parser.S_preserve in
        fun greeting ->
            let content obj =
                if obj.uri == required then
                    Xml_parser.invalid
                else begin
                    Xml_parser.accumulated_character_data >>= fun msg ->
                    let data = Cf_message.contents msg in
                    if greeting && String.length data > 1 then
                        Xml_parser.invalid
                    else begin
                        let data =
                            match obj.encoding with
                            | E_none -> data
                            | E_base64 -> Mime_base64.D.atomic data
                        in
                        ~:{ obj with content = data }
                    end
                end
            in
            Xml_parser.validated_element
                ~tag:"profile" ~attr ~content ~space initial
    
    let scan_xml = scan_xml_entity false
end

module E_greeting = struct
    open Cf_llscan.Op
    
    type t = {
        features: string list;
        localize: string list;
        profiles: string list; (* only URI is valid in greeting elements *)
    }
    
    let cons ?(features = []) ?(localize = []) profiles = {
        features = features;
        localize = localize;
        profiles = profiles;
    }
    
    let rec emit_attribute_value_tokens_ pp = function
        | [] ->
            ()
        | hd :: [] ->
            Format.pp_print_string pp hd
        | hd :: tl ->
            Format.pp_print_string pp hd;
            Format.pp_print_space pp ();
            emit_attribute_value_tokens_ pp tl
    
    let emit_octets pp v =
        Format.pp_open_vbox pp 2;
        Format.pp_print_string pp "<greeting";
        if v.features <> [] then begin
            Format.pp_print_string pp " features='";
            emit_attribute_value_tokens_ pp v.features;
            Format.pp_print_char pp '\'';
        end;
        if v.localize <> [] then begin
            Format.pp_print_string pp " localize='";
            emit_attribute_value_tokens_ pp v.localize;
            Format.pp_print_char pp '\'';
        end;
        if v.profiles = [] then begin
            Format.pp_print_string pp "/>";
            Format.pp_close_box pp ()
        end
        else begin
            Format.pp_print_char pp '>';
            List.iter begin fun profile ->
                Format.pp_print_cut pp ();
                Format.pp_print_string pp "<profile uri='";
                Format.pp_print_string pp profile;
                Format.pp_print_string pp "/>";
            end v.profiles;
            Format.pp_close_box pp ();
            Format.pp_print_cut pp ();
            Format.pp_print_string pp "</greeting>"
        end;
        Format.pp_print_cut pp ()
    
    let scan_xml =
        let default = { features = []; localize = []; profiles = [] } in
        let invalid pos pair =
            let event = Xml_event.T_element_start ("greeting", [pair]), pos in
            raise (Xml_parser.Invalid event)
        in
        let split v =
            let vs = (Cf_seq.of_string v) in
            match Xml_parser.split_attribute_value vs with
            | None -> []
            | Some (vs, _) -> vs
        in
        let attr pos obj (k, v as pair) =
            match k with
            | "features" -> { obj with features = split v }
            | "localize" -> { obj with localize = split v }
            | _ -> invalid pos pair
        in
        let content obj =
            ?* begin
                Xml_parser.optional_whitespace >>= fun () ->
                E_profile.scan_xml_entity true >>= fun profile ->
                if profile.E_profile.content <> "" then
                    Xml_parser.invalid
                else
                    ~:(profile.E_profile.uri)
            end >>= fun profiles ->
            Xml_parser.optional_whitespace >>= fun () ->
            ~:{ obj with profiles = profiles }
        in
        Xml_parser.validated_element ~tag:"greeting" ~attr ~content default
end

module E_start = struct
    open Cf_llscan.Op
    
    type t = {
        number: int32;
        serverName: string option;
        profiles: E_profile.t * E_profile.t list;
    }
        
    let number_required = -1l
    
    let initial = {
        number = number_required;
        serverName = None;
        profiles = E_profile.initial, [];
    }
    
    let invalid_ pos pair =
        let event = Xml_event.T_element_start ("start", [pair]), pos in
        raise (Xml_parser.Invalid event)
    
    let scan_xml =
        let attr pos obj (k, v as pair) =
            match k with
            | "number" ->
                let n = Int32.of_string v in
                let v' = Int32.to_string n in
                if not (v = v' && n >= Int32.zero) then invalid_ pos pair;
                { obj with number = n }
            | "serverName" ->
                { obj with serverName = Some v }
            | _ ->
                invalid_ pos pair
        in
        let content obj =
            if obj.number == number_required then
                Xml_parser.invalid
            else begin
                Xml_parser.optional_whitespace >>= fun () ->
                ?+ begin
                    E_profile.scan_xml_entity true >>= fun profile ->
                    Xml_parser.optional_whitespace >>= fun () ->
                    ~:profile
                end >>= fun (hd, tl) ->
                ~:{ obj with profiles = hd, tl }
            end
        in
        Xml_parser.validated_element ~tag:"start" ~attr ~content initial
    
    let emit_octets pp v =
        Format.pp_open_vbox pp 2;
        Format.pp_print_string pp "<start number='";
        Format.pp_print_string pp (Int32.format "%u" v.number);
        Format.pp_print_char pp '\'';
        begin
            match v.serverName with
            | None -> ()
            | Some s ->
                Format.pp_print_string pp " serverName='";
                Format.pp_print_string pp s;
                Format.pp_print_char pp '\'';
        end;
        Format.pp_print_char pp '>';
        List.iter begin fun profile ->
            Format.pp_print_cut pp ();
            E_profile.emit_octets pp profile;
        end (let hd, tl = v.profiles in hd :: tl);
        Format.pp_close_box pp ();
        Format.pp_print_cut pp ();
        Format.pp_print_string pp "</start>";
        Format.pp_print_cut pp ()
end

module E_signal(S: sig val name: string end) = struct
    open Cf_llscan.Op
    
    type parsed = {
        number: int32;
        code: int;
        lang: string option;
        content: string;
    }
    
    let emit_signal pp ?number code lang content =
        Format.pp_print_char pp '<';
        Format.pp_print_string pp S.name;
        begin
            match number with
            | None -> ()
            | Some n ->
                if n <> Int32.zero then begin
                    Format.pp_print_string pp " number='";
                    Format.pp_print_string pp (Int32.format "%u" n);
                    Format.pp_print_char pp '\''
                end
        end;
        Format.pp_print_string pp " code='";
        Format.pp_print_int pp code;
        Format.pp_print_char pp '\'';
        begin
            match lang with
            | None -> ()
            | Some s ->
                Format.pp_print_string pp " xml:lang='";
                Format.pp_print_string pp s;
                Format.pp_print_char pp '\'';
        end;
        if content = "" then
            Format.pp_print_string pp "/>"
        else begin
            Format.pp_print_char pp '>';
            Format.pp_print_string pp content;
            Format.pp_print_string pp "</";
            Format.pp_print_string pp S.name;
            Format.pp_print_string pp "close>"
        end;
        Format.pp_print_cut pp ()
    
    let scan_signal close =
        let empty = "" in
        let initial = {
            number = 0l;
            code = -1;
            lang = None;
            content = empty;
        } in
        let invalid pos pair =
            let event = Xml_event.T_element_start (S.name, [pair]), pos in
            raise (Xml_parser.Invalid event)
        in
        let attr pos obj (k, v as pair) =
            match k with
            | "number" when close ->
                let n = Int32.of_string v in
                let v' = Int32.to_string n in
                if not (v = v' && n >= Int32.zero) then invalid pos pair;
                { obj with number = n }
            | "code" ->
                if String.length v <> 3 then
                    invalid pos pair;
                String.iter begin function
                    | '0'..'9' -> ()
                    | _ -> invalid pos pair
                end v;
                { obj with code = int_of_string v }
            | "xml:lang" ->
                { obj with lang = Some v }
            | _ ->
                invalid pos pair
        in
        let content obj =
            Xml_parser.accumulated_character_data >>= fun msg ->
            ~:{ obj with content = Cf_message.contents msg }
        in
        Xml_parser.validated_element ~tag:S.name ~attr ~content initial
end

module E_close = struct
    open Cf_llscan.Op
    
    module S = E_signal(struct let name = "close" end)        
    
    type t = {
        number: int32;
        code: int;
        lang: string option;
        content: string;
    }
        
    let emit_octets pp v =
        S.emit_signal pp ~number:v.number v.code v.lang v.content
    
    let scan_xml =
        S.scan_signal true >>= fun v ->
        ~:{
            number = v.S.number;
            code = v.S.code;
            lang = v.S.lang;
            content = v.S.content;
        }
end

module E_ok = struct
    open Cf_llscan.Op
    
    type t = unit
    
    let invalid_ pos pair =
        let event = Xml_event.T_element_start ("ok", [pair]), pos in
        raise (Xml_parser.Invalid event)
    
    let scan_xml =
        let attr pos () pair = invalid_ pos pair in
        let content () = Xml_parser.optional_whitespace in
        let space = Xml_parser.S_preserve in
        Xml_parser.validated_element ~tag:"ok" ~attr ~content ~space ()
    
    let emit_octets pp =
        Format.pp_print_string pp "<ok/>";
        Format.pp_print_cut pp ()
end

module M_msg = struct
    open Cf_llscan.Op
    
    type t =
        | Greeting of E_greeting.t
        | Start of E_start.t
        | Close of E_close.t
    
    let limits = Beep_core.default_limits
    
    let emit_octets pp v =
        Beep_core.default_xml_mime_emit_adapter#emit pp;
        match v with
        | Greeting v -> E_greeting.emit_octets pp v
        | Start v -> E_start.emit_octets pp v
        | Close v -> E_close.emit_octets pp v
    
    let scan_xml _ = Cf_llscan.alt [
        (E_greeting.scan_xml >>= fun v -> ~:(Greeting v));
        (E_start.scan_xml >>= fun v -> ~:(Start v));
        (E_close.scan_xml >>= fun v -> ~:(Close v));
    ]
end

module M_rpy = struct
    open Cf_llscan.Op
    
    type t =
        | Greeting of E_greeting.t
        | Profile of E_profile.t
        | Ok
    
    let limits = Beep_core.default_limits
    
    let emit_octets pp v =
        Beep_core.default_xml_mime_emit_adapter#emit pp;
        match v with
        | Greeting v -> E_greeting.emit_octets pp v
        | Profile v -> E_profile.emit_octets pp v
        | Ok -> E_ok.emit_octets pp
    
    let scan_xml _ = Cf_llscan.alt [
        (E_greeting.scan_xml >>= fun v -> ~:(Greeting v));
        (E_profile.scan_xml >>= fun v -> ~:(Profile v));
        (E_ok.scan_xml >>= fun () -> ~:Ok);
    ]
end

module M_err = struct
    open Cf_llscan.Op
    
    module S = E_signal(struct let name = "error" end)        
    
    let limits = Beep_core.default_limits
    
    type t = {
        code: int;
        lang: string option;
        content: string;
    }
        
    let emit_octets pp v = S.emit_signal pp v.code v.lang v.content
    
    let scan_xml _ =
        S.scan_signal false >>= fun v ->
        ~:{
            code = v.S.code;
            lang = v.S.lang;
            content = v.S.content;
        }
end

module P = struct
    type tag = Beep_core.tag
    
    module MSG = Beep_simple.Xml_entity(M_msg)
    module RPY = Beep_simple.Xml_entity(M_rpy)
    module ERR = Beep_simple.Xml_entity(M_err)
    module ANS = Beep_simple.No_entity
end

module C = Beep_simple.Channel_form(P)

open Cf_cmonad.Op

let wrong_xml =
    let pos = {
        Xml_event.pos_byte_count = 0n;
        pos_line_number = 0n;
        pos_column_number = 0n;
    } in
    Beep_simple.Error (Beep_simple.X_invalid_xml pos)

class cxdrv ?cx msg rspTx cxf = object(self)
    inherit C.cxdrv ?cx msg cxf as super
    
    method private err_complete err = rspTx#put (`Error err)
    
    method private rpy_complete rpy =
        match msg, rpy with
        | M_msg.Greeting _, M_rpy.Greeting v -> rspTx#put (`Greeting v)
        | M_msg.Start _, M_rpy.Profile v -> rspTx#put (`Profile v)
        | M_msg.Close _, M_rpy.Ok -> rspTx#put `Ok
        | _, _ -> super#failed Beep_core.general_syntax_error wrong_xml
    
    method start =
        match msg with
        | M_msg.Greeting _ -> Iom_gadget.start (self#continue core_)
        | _ -> super#start
end

class sxdrv ?sx msgTx rspRx sxf = object(self)
    inherit C.sxdrv ?sx sxf as super
    
    method private msg_complete msg sx =
        begin
            match msg with
            | M_msg.Start v -> msgTx#put (`Start v)
            | M_msg.Close v -> msgTx#put (`Close v)
            | M_msg.Greeting _ -> assert (not true); Cf_cmonad.nil
        end >>= fun () ->
        self#continue sx
    
    method private response = function
        | `Greeting v ->
            super#rpy_complete (M_rpy.Greeting v) core_ >>= self#continue
        | `Profile v ->
            super#rpy_complete (M_rpy.Profile v) core_ >>= self#continue
        | `Ok ->
            super#rpy_complete M_rpy.Ok core_ >>= self#continue
        | `Error v ->
            super#err_complete v core_ >>= self#continue
    
    method private guard =
        rspRx#get self#response >>= fun () ->
        super#guard
end

class drv ?loc ?(feat = []) ~uri cp =
    let loc =
        match loc with
        | Some loc -> (loc :> Beep_core.localizer)
        | None -> new Beep_core.localizer []
    in
    object(self)
        inherit Beep_core.ch0drv cp as super
        
        val greet_ = Some {
            E_greeting.features = feat;
            localize = loc#greeting_lang;
            profiles = uri;
        }
        
        val nextchanno_ =
            match Beep_core.ch0_role cp with
            | Beep_core.R_initiator -> 1l
            | Beep_core.R_listener -> 2l
        
        val mxq_ = Cf_deque.nil
                
        method private ch_stop n =
            if Int32.compare n Int32.zero = 0 then
                Iom_gadget.abort
            else
                self#next
        
        method private up_close n code =
            let v = M_msg.Close {
                E_close.number = n;
                code = code;
                lang = loc#reply_lang;
                content = loc#reply_content code;
            } in
            super#cx_start begin fun core cxf ->
                Iom_gadget.simplex >>= fun (upRx, upTx) ->
                let mxq = Cf_deque.A.push (`Cx upRx) mxq_ in
                let drv = new cxdrv v upTx cxf in
                let drv = (drv :> Beep_core.tag Beep_core.cxdrv) in
                let next = {< core_ = core; mxq_ = mxq >} in
                Cf_cmonad.return (next, drv)
            end >>= fun next ->
            next#next
        
        method private up_ok n =
            errj#fail "Beep_transport.driver#up_ok"
        
        method private up_error n code =
            errj#fail "Beep_transport.driver#up_error"
        
        method private dn_greeting tl _ _ _ = {< mxq_ = tl >}#next
        
        method private dn_error tl code lang content =
            errj#fail "Beep_transport.driver#dn_error"
        
        method private dn_start number serverName profiles =
            errj#fail "Beep_transport.driver#dn_start"
        
        method private dn_profile tl uri encoding content =
            errj#fail "Beep_transport.driver#dn_profile"
        
        method private dn_close number code lang content =
            errj#fail "Beep_transport.driver#dn_start"
        
        method private dn_ok tl =
            errj#fail "Beep_transport.driver#dn_ok"
        
        method private sx_start sxf =
            match greet_ with
            | Some v ->
                Iom_gadget.null >>= fun upWire ->
                let upTx = new Iom_gadget.tx upWire in
                Iom_gadget.simplex >>= fun (dnRx, dnTx) ->
                dnTx#put (`Greeting v) >>= fun () ->
                let sx = super#sxgreeting sxf in
                let drv = new sxdrv ~sx upTx dnRx sxf in
                let drv = (drv :> Beep_core.tag Beep_core.sxdrv) in
                let next = {< greet_ = None >} in
                Cf_cmonad.return (next, drv)
            | None ->
                Iom_gadget.duplex >>= fun ((upRx, dnTx), (dnRx, upTx)) ->
                let drv = new sxdrv upTx dnRx sxf in
                let drv = (drv :> Beep_core.tag Beep_core.sxdrv) in
                let mxq = Cf_deque.A.push (`Sx (upRx, dnTx)) mxq_ in
                let next = {< mxq_ = mxq >} in
                Cf_cmonad.return (next, drv)
        
        method private sx_msg = function
            | `Start v ->
                self#dn_start v.E_start.number v.E_start.serverName
                    v.E_start.profiles
            | `Close v ->
                self#dn_close v.E_close.number v.E_close.code v.E_close.lang
                    v.E_close.content
        
        method private cx_rsp tl = function
            | `Greeting v ->
                self#dn_greeting tl v.E_greeting.features v.E_greeting.localize
                    v.E_greeting.profiles
            | `Profile v ->
                self#dn_profile tl v.E_profile.uri v.E_profile.encoding
                    v.E_profile.content
            | `Ok ->
                self#dn_ok tl
            | `Error v ->
                self#dn_error tl v.M_err.code v.M_err.lang v.M_err.content
        
        method private guard =
            super#guard >>= fun () ->
            match Cf_deque.B.pop mxq_ with
            | None -> Cf_cmonad.nil
            | Some (`Sx (upRx, _), tl) -> upRx#get self#sx_msg
            | Some (`Cx upRx, tl) -> upRx#get (self#cx_rsp tl)
    end

let pad role = Beep_core.ch0_load role C.chform

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