amall / src / amall_http_server.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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
open Amall_types;
open Am_Ops;
open Printf;
open Amall_http;
open Cd_All;

type port = int;
type addr_string = string;

type listen_addr =
  [= `Inet_any of port
  |  `Inet_loopback of port
  |  `Inet_str of (addr_string * port)
  |  `Inet_addr of (Unix.inet_addr * port)
  ]
;

module Http_server
  (IO : IO_Type)
  (I : It_type.IT with
        type It_IO.m 'a = IO.m 'a
    and type It_IO.input_channel = IO.input_channel
  )
 :
  sig

    value post_form : request ->
      I.iteratee char (request * list (string * string))
    ;

    value it_post_vars : I.iteratee char (list (string * string))
    ;

    value run :
      listen_addr ->
      (request -> (segpath * (Amall_http.Make(IO)(I)).service_desc)) ->
      IO.server
    ;

  end
=
struct

module H = Amall_http.Make(IO)(I);

value it_post_vars = H.it_post_vars
;

open I.Ops;


value (runA : IO.m (I.iteratee 'el 'a) -> It_Types.res 'a) i =
  IO.runIO (i >>% I.run)
;

value rec printexc e =
  match e with
  [ I.Iteratees_err_msg e -> printexc e
  | _ -> Printexc.to_string e
  ]
;

value rec dump_chars_chunks title =
  I.ie_cont step
  where rec step s =
  match s with
  [ I.EOF oe ->
      let err =
        match oe with
        [ None -> "eof"
        | Some e -> printexc e
        ]
      in
        IO.printf "dump_chars_chunks: %s: EOF: %s.\n" title err >>% fun () ->
        I.ie_doneM () s
  | I.Chunk c ->
      IO.printf "dump_chars_chunks: %s: Chunk: %S\n"
        title (I.Subarray.to_string c) >>% fun () ->
      I.ie_contM step
  ]
;



value (post_form : request ->
  I.iteratee char (request * list (string * string))
) request =
  I.printf "request headers was read ok, request_uri: %S, uri: %S.\n\
            headers:\n%s\n===\n%!"
       (Uri.dump_uri request.rq_request_uri__)
       ( (* Uri.dump_uri request.rq_uri *) "<todo>")
       (String.concat "\n" & List.map (fun (k,v) -> sprintf "%S = %S" k v)
         request.rq_headers.rq_all
       )
  >>= fun () ->
(*
  dump_chars_chunks "header"
*)
  H.request_with_post_vars request
;



(*
value _ () =
  let fn = "post-req" in
  match
    runA & I.enum_file fn &
      ((H.it_http & post_form)
       >>= fun r -> dump_chars_chunks "after body" >>= fun () ->
       I.return r
      )
  with
  [ `Ok _ -> ()
  | `Error e -> eprintf "exception: %s\n%!" & printexc e
  ]
;
*)


value () = ignore & I.limit;

(**********************************************************)

value can't_switch_ws_resp =
  { rs_status_code = 400
  ; rs_reason_phrase = "Bad request"
  ; rs_headers = { rs_all = [] }
  ; rs_body = Body_string "Can't switch to Websockets after HTTP requests"
  }
;


value ws_guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
;

open Am_Common
;

value (continue_ws_resp : string -> response) =
  let accept handshake =
    let open Cryptokit in
    transform_string
      (Base64.encode_compact_pad ())
      (hash_string
         (Hash.sha1 ())
         (handshake ^ ws_guid)
      )
  and other_headers =
    [ ("Upgrade", "websocket")
    ; ("Connection", "Upgrade")
    ]
  in
    fun handshake ->
      { rs_status_code = 101
      ; rs_reason_phrase = "Switching Protocols"
      ; rs_body = No_body
      ; rs_headers =
          { rs_all =
              [    ("Sec-WebSocket-Accept", accept handshake)
                :: other_headers
              ]
          }
      }
;


(* TODO: переписать с прямым доступом к массиву. *)
value it_uint16_as_64_netord =
  I.head >>= fun b0 ->
  I.head >>= fun b1 ->
  I.return & Int64.of_int (((Char.code b0) lsl 8) lor (Char.code b1))
;

(* TODO: переписать с прямым доступом к массиву. *)
value ws_it_close_code ~masking_key =
  I.head >>= fun b0 ->
  I.head >>= fun b1 ->
  I.return
    (
         (((Char.code b0) lxor (Char.code masking_key.[0])) lsl 8)
     lor ((Char.code b1) lxor (Char.code masking_key.[1]))
    )
;


exception Ws_error of string
;

value ws_error msg = I.throw_err (Ws_error msg)
;

exception Ws_service_error of exn
;


(* TODO: переписать с прямым доступом к массиву и _прямо_. *)
value ws_len64 =
  let h = I.head >>= fun c -> I.return & Int64.of_int (Char.code c) in
  h >>= fun i0 ->
  let open Int64 in
  let ( lor ) = Int64.logor
  and ( land ) = Int64.logand
  and ( lsl ) = Int64.shift_left in
  if (i0 land 0x80L) == 0x80L
  then ws_error "ws_len64: 'the most significant bit MUST be 0' [rfc6455]"
  else
    h >>= fun i1 ->
    h >>= fun i2 ->
    h >>= fun i3 ->
    h >>= fun i4 ->
    h >>= fun i5 ->
    h >>= fun i6 ->
    h >>= fun i7 ->
    I.return
      (      i7
        lor (i6 lsl  8)
        lor (i5 lsl 16)
        lor (i4 lsl 24)
        lor (i3 lsl 32)
        lor (i2 lsl 40)
        lor (i1 lsl 48)
        lor (i0 lsl 56)
      )
;

value ws_it_masking_key () =
  I.head >>= fun a0 ->
  I.head >>= fun a1 ->
  I.head >>= fun a2 ->
  I.head >>= fun a3 ->
  let module String = Bytes in
  let k = String.make 4 '\x00' in
  ( k.[0] := a0
  ; k.[1] := a1
  ; k.[2] := a2
  ; k.[3] := a3
  ; I.return k
  )
;


value ws_it_frame_header =
  let no_masking_key = Bytes.make 4 '\x00' in
  I.head >>= fun b0 ->
  I.head >>= fun b1 ->
  let fin = ((Char.code b0) land 0x80) == 0x80 in
  let opcode_int = (Char.code b0) land 0x0F in
  let mask = ((Char.code b1) land 0x80) == 0x80 in
  let len1 = ((Char.code b1) land 0x7F) in
  (if len1 = 126
   then it_uint16_as_64_netord
   else if len1 = 127
   then ws_len64
   else I.return (Int64.of_int len1)
  ) >>= fun len ->
  (if mask
  then
    ws_it_masking_key ()
  else
    I.return no_masking_key
  ) >>= fun masking_key ->
  (if opcode_int >= 0x8
   then
     if not fin
     then
       ws_error "All control frames MUST NOT be fragmented."
     else if len > 125L
     then
       ws_error "All control frames MUST have a payload length \
                 of 125 bytes or less."
     else
       match opcode_int with
       [ 0x8 ->
           if len = 0L
           then I.return & `Close None
           else if len = 1L
           then ws_error "Close: 'If there is a body, the first two bytes of \
                          the body MUST be a 2-byte unsigned integer', \
                          but body has only 1 byte."
           else
             ws_it_close_code ~masking_key >>= fun status_code ->
             let () = dbg "ws_it_frame_header: Close: status_code = %i"
               status_code
             in
             let () =
               let m0 = masking_key.[0]
               and m1 = masking_key.[1]
               and m2 = masking_key.[2]
               and m3 = masking_key.[3]
               in
                 ( masking_key.[0] := m2
                 ; masking_key.[1] := m3
                 ; masking_key.[2] := m0
                 ; masking_key.[3] := m1
                 )
             in
             I.return & `Close (Some status_code)
       | 0x9 -> I.return `Ping
       | 0xA -> I.return `Pong
       | x -> I.return & `Ctrl x
       ]
   else
     I.return (match opcode_int with
     [ 0x0 -> `Cont
     | 0x1 -> `Text
     | 0x2 -> `Binary
     | x -> `Nonctrl x
     ])
  )
  >>= fun opcode ->
  let len =
    match opcode with
    [ `Close (Some _) -> Int64.sub len 2L
    | _ -> len
    ]
  in
  let open H in
  I.return &
    { fin = fin
    ; opcode = opcode
    ; len = len
    ; masking_key = masking_key
    }
;

type ws_it_feed_resp =
  [= `Frame_going of
       (  I.iteratee char unit
       * [= `Finished
         |  `Continues
         ]
       )
  |  `Closed of int
  ]
;

type ws_it_loop_data_state =
  [= `Frame_going of I.iteratee char unit
  |  `Frame_done
  ]
;

type ws_it_loop_resp =
  [= ws_it_feed_resp
  |  `Closed of int (* status code *)
  |  `Ping of (I.iteratee char string (* body *) * ws_it_loop_data_state)
  |  `Proto_error of (int * string)  (* (code, reason) *)
  |  `Frame_done
  ]
;


value enee_unmask ~masking_key ~growing_array
  : I.enumeratee Byte.t Byte.t 'a
  = fun it ->
      let mlen = String.length masking_key in
      if mlen = 0
      then
        I.throw_err & Invalid_argument "enum_unmask: masking_key is empty"
      else
        let rec unmask ~mi it =
          match it with
          [ I.IE_done _ | I.IE_cont (Some _) _ -> I.return it
          | I.IE_cont None k -> I.ie_cont (step ~mi it k)
          ]
        and step ~mi it k s =
          match s with
          [ I.EOF _ -> I.ie_doneM it s
          | I.Chunk c ->
              let open I.S.C in
              let clen = c.len in
              let tarr = Array.GrowingArray.request_array clen growing_array in
              let carr = c.arr
              and cofs = c.ofs in
              let cmaxi = cofs + clen in
              let rec loop ~mi ~ci ~ti =
                if ci = cmaxi
                then mi
                else
                  ( tarr.(ti) := Char.chr
                      (     (Char.code carr.(ci))
                       lxor (Char.code masking_key.[mi])
                      )
                  ; loop ~mi:((mi + 1) mod mlen) ~ci:(ci + 1) ~ti:(ti + 1)
                  )
              in
              let mi = loop ~mi ~ci:cofs ~ti:0 in
              let new_chunk = mk ~arr:tarr ~ofs:0 ~len:clen in
              (k (I.Chunk new_chunk)) >>% fun (it, _s) ->
              IO.return (unmask ~mi it, I.Sl.empty)
          ]
        in
          unmask ~mi:0 it
;



value wrap_feeding it_f =
  I.catch
    it_f
    (fun e ->
       match e with
       [ Ws_service_error e -> I.throw_err e
       | e -> I.throw_err & Ws_service_error e
       ]
    )
;


value feed_going_it ~growing_array ~fh it
 =
  let len_int = Int64.to_int fh.len in
  let () = assert (fh.len = Int64.of_int len_int) in
  (wrap_feeding
    (fun () ->
       (I.take_exact
          len_int
          (I.joinI & enee_unmask ~growing_array ~masking_key:fh.masking_key it)
       )
    )
  )
  >>= fun (ex, it) ->
  match ex with
  [ `Done ->
      I.return &
      `Frame_going it (if fh.fin then `Finished else `Continues)
  | `Eof (has_read, opt_err_msg) ->
      let () = dbg "ws: it_loop: feed_going_it: got %i bytes \
                    instead of %i because of %s; closing."
                   (len_int - has_read)
                   len_int
                   (match opt_err_msg with
                    [ None -> "normal EOF"
                    | Some e -> sprintf "error %s"
                                  (Printexc.to_string e)
                    ]
                   )
      in
      (wrap_feeding (fun () ->
        I.feed_it it (I.EOF (Some (H.Ws.Close_received 1006)))
      )) >>= fun _it ->
      I.return &
      `Closed 1006
  ]
;        


value do_websocket
  outsock
  (sl_l : Lazy.t (I.sl char))
  enum_part
  (ws_worker : H.websocket_service_func_worker)
 :
  IO.m unit
 =
  let worker_got_close = ref False
  and growing_array = Array.GrowingArray.make 100 '\x00' in
  (
    let rec it_loop (data_state : ws_it_loop_data_state)
     : I.iteratee char ws_it_loop_resp
     =
        let () = dbg "ws: it_loop" in

        (I.ie_cont & fun s ->
           match s with
           [ I.EOF _ ->
               let () = dbg "it_loop: stream: EOF" in
               I.ie_doneM () s
           | I.Chunk c ->
               let str = I.S.to_string c in
               let () = dbg "it_loop: stream: Chunk \"%s\""
                 (Bytes.hexdump ~style:`Line str) in
               I.ie_doneM () s
           ]
        ) >>= fun () ->
        let () = dbg "ws: it_loop: after dump" in

        I.peek >>= fun p ->
        let () = dbg "ws: it_loop: peek = %s"
          (match p with [None -> "None" | Some c -> sprintf "Some %C" c ]) in

        ws_it_frame_header >>= fun fh ->
        let () = dbg "ws: it_loop: fh" in

        let rec ret_closed ~opc ~code =
          let () = worker_got_close.val := True in
          (wrap_feeding (fun () -> feed_new_worker ~opc))
          >>= fun () ->
          I.return & `Closed code
        
        and feed : ~data_state : ws_it_loop_data_state -> ~opc : _ ->
                   I.iteratee char ws_it_feed_resp
         = fun ~data_state ~opc ->
          let it =
            match data_state with
            [ `Frame_done ->
                wrap_feeding (fun () -> ws_worker opc)
            | `Frame_going it ->
                it
            ]
          in
            feed_going_it ~growing_array ~fh it
        
        and feed_new_worker ~opc : I.iteratee char unit =
          feed ~data_state:`Frame_done ~opc >>= fun fr ->
          match fr with
          [ `Frame_going it _ ->
              wrap_feeding (fun () -> I.feed_it it (I.EOF None))
              >>= fun _it ->
              I.return ()
          | `Closed _code ->
              I.return ()
          ]

        and ret_data_state () =
          I.return &
          match data_state with
          [ `Frame_done as x -> x
          | `Frame_going it -> `Frame_going it `Continues
          ]
        in

        match fh.opcode with
        [ (`Close opt_code) as opc ->
            let code =
              match opt_code with
              [ Some x -> x
              | None -> 1005
              ]
            in
            match data_state with
            [ `Frame_done ->
                ret_closed ~opc ~code
            | `Frame_going it ->
                (wrap_feeding (fun () ->
                  I.feed_it it (I.EOF (Some (H.Ws.Close_received code)))
                )) >>= fun _it ->
                (* итерат, получив EOF, должен перейти в
                   "готовое состояние", а оно неинтересно. *)
                ret_closed ~opc ~code
            ]
        | `Ping ->
            feed_going_it ~growing_array ~fh I.gather_to_string >>= fun fr ->
            match fr with
            [ (`Closed _) as c -> I.return c
            | `Frame_going gath_it _cont_fin -> I.return &
                `Ping gath_it data_state
            ]
        | `Pong ->
            ret_data_state ()
        | (`Ctrl _) as opc ->
            feed_new_worker ~opc >>= fun () ->
            ret_data_state ()
        | (`Text | `Binary | `Nonctrl _) as opc ->
            let () = dbg "ws: it_loop: text/binary/nonctrl" in
            match data_state with
            [ `Frame_going it ->
                let msg = "data frame without previous fin" in
                (wrap_feeding (fun () ->
                  I.feed_it it (I.EOF (Some (Ws_error msg)))
                ))
                (* ошибка, так как при фрейме с fin=true состояние станет
                   _done, а при исходном _going должен быть fin=true перед
                   другими фреймами. *)
                >>= fun _it ->
                I.return & `Proto_error 1002 msg
            | `Frame_done ->
                ( (feed ~data_state ~opc)
                  :> I.iteratee char ws_it_loop_resp
                )
            ]
        | `Cont ->
            match data_state with
            [ `Frame_done ->
                I.return & `Proto_error 1003 "continuation frame without \
                                              previous beginning frame"
                (* продолжение без предыдущего начала *)
            | `Frame_going it ->
                ( (feed_going_it it ~growing_array ~fh)
                  :> I.iteratee char ws_it_loop_resp
                )
            ]
        ]

    and io_loop (enum_part : I.enumpart char ws_it_loop_resp) sl_l data_state =
      let () = dbg "ws: io_loop" in
      if H.Ws.is_close_sent outsock
      then
        IO.return ()
      else
        let sl = Lazy.force sl_l in
        enum_part sl (it_loop data_state)
        >>% fun (loop_it, sl_l, enp_opt) ->
        let () = dbg "ws: io_loop: enum_part returned" in

        (let proc_error e =
           let () = dbg "ws: io_loop: error: %s"
             (Printexc.to_string &
              (loop e
               where rec loop e =
                 match e with
                 [ Ws_service_error e | I.Iteratees_err_msg e -> loop e
                 | _ -> e
                 ]
              )
             )
           in
           let () = dbg "ws: io_loop: proc_error: 1: is_close_sent = %b"
             (H.Ws.is_close_sent outsock)
           in
           (if H.Ws.is_close_sent outsock
            then
              IO.return ()
            else
              match e with
              [ Ws_service_error e ->
                  let msg = Printexc.to_string e in
                  let msg =
                    if String.length msg > 125
                    then
                      (String.sub msg 0 122) ^ "..."
                    else
                      msg
                  in
                    let () = dbg "ws: io_loop: service error: %S" msg in
                    H.Ws.close outsock (Some (1011, msg))
              | _ ->
                  H.Ws.close outsock None
              ]
           ) >>% fun () ->
           let () = dbg "ws: it_loop: proc_error: 2: is_close_sent = %b"
             (H.Ws.is_close_sent outsock)
           in
           IO.return & `Closed 1005
         in
         IO.catch
           (fun () ->
              I.run loop_it
           )
           (fun e ->
              proc_error e
           )
        )
        >>% fun loop_resp ->
        let () = dbg "io_loop: analyzing loop_resp" in
        (match loop_resp with
         [ `Frame_going it `Finished ->
             I.run it >>% fun () ->
             let () = dbg "ws: io_loop: finished service iteratee" in
             IO.return `Frame_done
         | `Frame_going it `Continues ->
             IO.return & `Frame_going it
         | `Frame_done ->
             IO.return `Frame_done
         | `Closed code ->
             (if not worker_got_close.val
              then
                let () = worker_got_close.val := True in
                I.run (ws_worker (`Close (Some code)))
              else
                IO.return ()
             )
             >>% fun () ->
             if H.Ws.is_close_sent outsock
             then
               IO.return `Frame_done
             else
               H.Ws.close outsock (Some (code, "")) >>% fun () ->
               IO.return `Frame_done
               (* will exit after entering io_loop *)
         | `Ping it_body old_state ->
             I.run it_body >>% fun body ->
             H.Ws.send outsock `Pong body >>% fun () ->
             IO.return old_state
         | `Proto_error (code : int) (msg : string) ->
             let () = worker_got_close.val := True in
             I.run (ws_worker (`Close (Some code)))
             >>% fun () ->
             if H.Ws.is_close_sent outsock
             then
               IO.return `Frame_done
             else
               H.Ws.close outsock (Some (code, msg)) >>% fun () ->
               IO.return `Frame_done
         ]
        ) >>% fun data_state ->
        (match enp_opt with
         [ I.EP_None ->
             let () = dbg "ws: io_loop: ep_none" in
             (match data_state with
              [ `Frame_done -> IO.return ()
              | `Frame_going it ->
                  I.run &
                  I.feed_it it (I.EOF (Some (H.Ws.Close_received 1006)))
              ]
             ) >>% fun () ->
             let () = dbg "ws: io_loop: ep_none: worker_got_close = %b"
               worker_got_close.val
             in
             if not worker_got_close.val
             then
               let () = worker_got_close.val := True in
               I.run (ws_worker (`Close (Some 1006)))
             else
               IO.return ()  (* just exit *)
         | I.EP_Some enum_part ->
             let () = dbg "ws: io_loop: ep_some" in
             io_loop enum_part.I.enumpart_poly sl_l data_state
         ]
        )

    in
    io_loop enum_part sl_l `Frame_done
  )
;


(**********************************************************)


value dbg fmt = Printf.ksprintf (Printf.printf "hs: %s\n%!") fmt;


value http_server_func
 (userfunc : request -> (segpath * H.service_desc))
 (inch, outch)
: unit
= IO.run_and_ignore_result
   (let closed = ref False in
    let do_close () =
      if closed.val
      then
        IO.return ()
      else
        IO.catch
          (fun () ->
             let () = closed.val := True in
             IO.close_in inch >>% fun () ->
             IO.close_out outch
          )
          (fun e ->
            let () = dbg "http_server_func: close error: %s"
              (Printexc.to_string e)
            in
              IO.return ()
          )
    in
    IO.catch
      (fun () ->
         let it_req = H.it_http userfunc in
         I.enumpart_readchars
           ~buffer_size:4096
           ~read_func:IO.read_into
           inch
           I.Sl.empty
           it_req
         >>% loop True
         where rec loop can_switch_to_ws (it, sl_l, opt_enp) =
           let () = dbg "hs: entered loop" in
           match opt_enp with
           [ I.EP_None -> do_close ()
           | I.EP_Some cont ->
               let () = dbg "got cont" in

               match it with
               [ I.IE_cont (Some e) _ ->
                   let () = dbg "cont: error %S" (Printexc.to_string e) in
                   do_close ()
               | I.IE_cont None _ ->
                   let () = dbg "cont: cont" in
                   failwith "cont-cont1111"
               | I.IE_done http_or_ws_resp ->
                   let () = dbg "hsf: got req/resp" in
                   match http_or_ws_resp with
                   [ (request, `Http it) ->
                       I.run it >>% fun resp ->
                       let is_head = (request.rq_method = `HEAD) in
                       H.output_response ~is_head outch resp >>% fun () ->

                       let need_to_close =
                         (List.mem `Close request.rq_headers.connection) ||
                         (List.exists
                            (fun (hk, hv) -> hk = "Connection" && hv = "close")
                            resp.rs_headers.rs_all
                         )
                       in
                         if need_to_close
                         then
                           do_close ()
                         else
                           IO.flush outch >>% fun () ->
                           let sl = Lazy.force sl_l in
                           cont.I.enumpart_poly sl it_req >>% loop False

                   | (request, `Ws handshake ws_service segpath) ->
                       if can_switch_to_ws
                       then
                         H.output_response ~is_head:False outch
                           (continue_ws_resp handshake)
                         >>% fun () ->
                         let ws_out_socket = H.Ws.of_out_channel outch in
                         let worker = Partapp3.apply
                           ws_service segpath request ws_out_socket
                         in
                         IO.catch
                           (fun () ->
                              do_websocket
                                ws_out_socket
                                sl_l
                                cont.I.enumpart_poly
                                worker
                              >>% fun () ->
                              IO.return & `Ok ()
                           )
                           (fun e -> IO.return & `Error e)
                         >>% fun res ->
                         match res with
                         [ `Ok () -> IO.return ()
                         | `Error e -> IO.error e
                         ]
                       else
                         H.output_response
                           ~is_head:False outch can't_switch_ws_resp
                         >>% fun () ->
                         do_close ()
                   ]
               ]
           ]
      )
      (fun e ->
        ( Printf.eprintf "amall http: exception: %s\n%!" &
            (loop e
             where rec loop e =
               match e with
               [ I.Iteratees_err_msg e -> "it/" ^ loop e
               | Ws_service_error e -> "wssrv/" ^ loop e
               | _ -> Printexc.to_string e
               ]
            )
        ; do_close ()
        )
      )
   )
;


value run_addr listen_addr (userfunc : request -> (segpath * H.service_desc)) =
  IO.establish_server listen_addr (http_server_func userfunc)
;


value run listen_addr userfunc =
  let a =
    match listen_addr with
    [ `Inet_any port -> Unix.ADDR_INET (Unix.inet_addr_any, port)
    | `Inet_loopback port -> Unix.ADDR_INET (Unix.inet_addr_loopback, port)
    | `Inet_str str port -> Unix.ADDR_INET (Unix.inet_addr_of_string str, port)
    | `Inet_addr a p -> Unix.ADDR_INET (a, p)
    ]
  in
    run_addr a userfunc
;


end;
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.