package cohttp

  1. Overview
  2. Docs

Source file link.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
(*{{{ Copyright (c) 2015 David Sheets <sheets@alum.mit.edu>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
  }}}*)

open Sexplib0.Sexp_conv

(* From <https://tools.ietf.org/html/rfc5988> *)
module Rel = struct
  type t =
    | Extension of Uri_sexp.t
    | Alternate
    | Appendix
    | Bookmark
    | Chapter
    | Contents
    | Copyright
    | Current
    | Described_by
    | Edit
    | Edit_media
    | Enclosure
    | First
    | Glossary
    | Help
    | Hub
    | Index
    | Last
    | Latest_version
    | License
    | Next
    | Next_archive
    | Payment
    | Predecessor_version
    | Prev
    | Prev_archive
    | Related
    | Replies
    | Section
    | Self
    | Service
    | Start
    | Stylesheet
    | Subsection
    | Successor_version
    | Up
    | Version_history
    | Via
    | Working_copy
    | Working_copy_of
  [@@deriving sexp]

  let extension uri = Extension uri
  let alternate = Alternate
  let appendix = Appendix
  let bookmark = Bookmark
  let chapter = Chapter
  let contents = Contents
  let copyright = Copyright
  let current = Current
  let described_by = Described_by
  let edit = Edit
  let edit_media = Edit_media
  let enclosure = Enclosure
  let first = First
  let glossary = Glossary
  let help = Help
  let hub = Hub
  let index = Index
  let last = Last
  let latest_version = Latest_version
  let license = License
  let next = Next
  let next_archive = Next_archive
  let payment = Payment
  let predecessor_version = Predecessor_version
  let prev = Prev
  let prev_archive = Prev_archive
  let related = Related
  let replies = Replies
  let section = Section
  let self = Self
  let service = Service
  let start = Start
  let stylesheet = Stylesheet
  let subsection = Subsection
  let successor_version = Successor_version
  let up = Up
  let version_history = Version_history
  let via = Via
  let working_copy = Working_copy
  let working_copy_of = Working_copy_of
end

module Language = struct
  type t = string [@@deriving sexp]

  let to_string x = x
  let of_string x = x
end

module Charset = struct
  type t = string [@@deriving sexp]

  let to_string x = x
  let of_string x = x
end

module Ext = struct
  type 'a t = { charset : Charset.t; language : Language.t; value : 'a }
  [@@deriving sexp]

  let charset t = t.charset
  let language t = t.language
  let value t = t.value
  let make ?(charset = "") ?(language = "") value = { charset; language; value }
  let map f x = { x with value = f x.value }
end

module Arc = struct
  type t = {
    reverse : bool;
    relation : Rel.t list;
    hreflang : string option;
    media : string option;
    title : string option;
    title_ext : string Ext.t option;
    media_type : (string * string) option;
    extensions : (string * string) list;
    extension_exts : (string * string Ext.t) list;
  }
  [@@deriving sexp]

  let empty =
    {
      reverse = false;
      relation = [];
      hreflang = None;
      media = None;
      title = None;
      title_ext = None;
      media_type = None;
      extensions = [];
      extension_exts = [];
    }
end

type t = { context : Uri_sexp.t; arc : Arc.t; target : Uri_sexp.t }
[@@deriving sexp]

(* TODO: this could be replaced with empty t/arc fupdate *)
type param =
  | Rel of Rel.t list
  | Anchor of Uri.t
  | Rev of Rel.t list
  | Hreflang of Language.t
  | Media of string
  | Title of string
  | Star of param Ext.t
  | Type of (string * string)
  | Link_extension of string * string

let until s start cl =
  let nextl =
    List.map
      (fun c ->
        let pattern = String.make 1 c in
        Stringext.find_from ~start s ~pattern)
      cl
  in
  let min =
    List.fold_left
      (fun min_opt i_opt ->
        match (min_opt, i_opt) with
        | None, None -> None
        | Some i, None | None, Some i -> Some i
        | Some i, Some j -> Some (min i j))
      None nextl
  in
  match min with
  | None -> (Stringext.string_after s start, String.length s)
  | Some i -> (String.sub s start (i - start), i)

let string_of_rel =
  Rel.(
    function
    | Alternate -> "alternate"
    | Appendix -> "appendix"
    | Bookmark -> "bookmark"
    | Chapter -> "chapter"
    | Contents -> "contents"
    | Copyright -> "copyright"
    | Current -> "current"
    | Described_by -> "describedby"
    | Edit -> "edit"
    | Edit_media -> "edit-media"
    | Enclosure -> "enclosure"
    | First -> "first"
    | Glossary -> "glossary"
    | Help -> "help"
    | Hub -> "hub"
    | Index -> "index"
    | Last -> "last"
    | Latest_version -> "latest-version"
    | License -> "license"
    | Next -> "next"
    | Next_archive -> "next-archive"
    | Payment -> "payment"
    | Predecessor_version -> "predecessor-version"
    | Prev -> "prev"
    | Prev_archive -> "prev-archive"
    | Related -> "related"
    | Replies -> "replies"
    | Section -> "section"
    | Self -> "self"
    | Service -> "service"
    | Start -> "start"
    | Stylesheet -> "stylesheet"
    | Subsection -> "subsection"
    | Successor_version -> "successor-version"
    | Up -> "up"
    | Version_history -> "version-history"
    | Via -> "via"
    | Working_copy -> "working-copy"
    | Working_copy_of -> "working-copy-of"
    | Extension uri -> Uri.to_string uri)

let rel_of_string s =
  Rel.(
    try
      ignore (String.index s ':');
      Extension (Uri.of_string s)
    with Not_found -> (
      match s with
      | "alternate" -> Alternate
      | "appendix" -> Appendix
      | "bookmark" -> Bookmark
      | "chapter" -> Chapter
      | "contents" -> Contents
      | "copyright" -> Copyright
      | "current" -> Current
      | "describedby" -> Described_by
      | "edit" -> Edit
      | "edit-media" -> Edit_media
      | "enclosure" -> Enclosure
      | "first" -> First
      | "glossary" -> Glossary
      | "help" -> Help
      | "hub" -> Hub
      | "index" -> Index
      | "last" -> Last
      | "latest-version" -> Latest_version
      | "license" -> License
      | "next" -> Next
      | "next-archive" -> Next_archive
      | "payment" -> Payment
      | "predecessor-version" -> Predecessor_version
      | "prev" | "previous" -> Prev
      | "prev-archive" -> Prev_archive
      | "related" -> Related
      | "replies" -> Replies
      | "section" -> Section
      | "self" -> Self
      | "service" -> Service
      | "start" -> Start
      | "stylesheet" -> Stylesheet
      | "subsection" -> Subsection
      | "successor-version" -> Successor_version
      | "up" -> Up
      | "version-history" -> Version_history
      | "via" -> Via
      | "working-copy" -> Working_copy
      | "working-copy-of" -> Working_copy_of
      | _ -> Extension (Uri.of_string s)))

let quoted_string_of_string s q =
  let rec first_quote q =
    match s.[q] with
    | ' ' -> first_quote (q + 1)
    | '"' -> (
        let q = q + 1 in
        match Stringext.find_from ~start:q s ~pattern:"\"" with
        | None -> (Stringext.string_after s q, String.length s)
        | Some q' -> (String.sub s q (q' - q), q' + 1))
    | _ -> until s q [ ';'; ',' ]
  in
  first_quote q

let rels_of_string_ s q =
  let qs, i = quoted_string_of_string s q in
  let rels = String.split_on_char ' ' qs in
  (List.map rel_of_string (List.filter (fun s -> String.length s > 0) rels), i)

let rels_of_string s i =
  match
    (Stringext.find_from ~start:i s ~pattern:"\"", until s i [ ';'; ',' ])
  with
  | Some q, (_, d) when q < d -> rels_of_string_ s q
  | _, (s, d) -> ([ rel_of_string s ], d)

let anchor_of_string s i =
  let qs, i = quoted_string_of_string s i in
  (Uri.of_string qs, i)

let star_of_string s i =
  match Stringext.find_from ~start:i s ~pattern:"'" with
  | None ->
      let s, i = quoted_string_of_string s i in
      ("", "", s, i)
  | Some a -> (
      let charset = String.sub s i (a - i) in
      let i = a + 1 in
      match Stringext.find_from ~start:i s ~pattern:"'" with
      | None ->
          let s, i = quoted_string_of_string s i in
          (charset, "", s, i)
      | Some a ->
          let language = String.sub s i (a - i) in
          let i = a + 1 in
          let s, i = quoted_string_of_string s i in
          (charset, language, s, i))

let media_type_of_string s i =
  let mt, i = quoted_string_of_string s i in
  match Stringext.split ~max:2 mt ~on:'/' with
  | [] -> (("", ""), i)
  | [ t ] -> ((t, ""), i)
  | t :: st :: _ -> ((t, st), i)

let rec params_of_string s i ps =
  let _, d = until s i [ ';'; ',' ] in
  if d = String.length s then (ps, None)
  else if s.[d] = ',' then (ps, Some d)
  else
    let i = d + 1 in
    let param, i = until s i [ '=' ] in
    let i = i + 1 in
    match String.trim param with
    | "rel" ->
        let rels, i = rels_of_string s i in
        params_of_string s i (Rel rels :: ps)
    | "anchor" ->
        let uri, i = anchor_of_string s i in
        params_of_string s i (Anchor uri :: ps)
    | "rev" ->
        let rels, i = rels_of_string s i in
        params_of_string s i (Rev rels :: ps)
    | "hreflang" ->
        let hreflang, i = until s i [ ','; ';' ] in
        params_of_string s i (Hreflang hreflang :: ps)
    | "media" ->
        let media, i = quoted_string_of_string s i in
        params_of_string s i (Media media :: ps)
    | "title" ->
        let title, i = quoted_string_of_string s i in
        params_of_string s i (Title title :: ps)
    | "title*" ->
        let charset, language, v, i = star_of_string s i in
        params_of_string s i
          (Star { Ext.charset; language; value = Title v } :: ps)
    | "type" ->
        let media_type, i = media_type_of_string s i in
        params_of_string s i (Type media_type :: ps)
    | other when String.length other = 0 ->
        let s, i = quoted_string_of_string s i in
        params_of_string s i (Link_extension ("", s) :: ps)
    | other ->
        let last = String.length other - 1 in
        if other.[last] = '*' then
          let main = String.sub other 0 last in
          let charset, language, v, i = star_of_string s i in
          params_of_string s i
            (Star { Ext.charset; language; value = Link_extension (main, v) }
            :: ps)
        else
          let v, i = quoted_string_of_string s i in
          params_of_string s i (Link_extension (other, v) :: ps)

let rec find_or_default f d = function
  | [] -> d
  | h :: t -> ( match f h with None -> find_or_default f d t | Some v -> v)

let arc_of_relation_params ?(reverse = false) relation params =
  let extensions, extension_exts =
    List.fold_left
      (fun (x, xx) -> function
        | Link_extension (k, v) -> ((k, v) :: x, xx)
        | Star { Ext.charset; language; value = Link_extension (k, value) } ->
            (x, (k, { Ext.charset; language; value }) :: xx)
        | _ -> (x, xx))
      ([], []) params
  in
  {
    Arc.reverse;
    relation;
    hreflang =
      find_or_default
        (function Hreflang l -> Some (Some l) | _ -> None)
        None params;
    media =
      find_or_default
        (function Media m -> Some (Some m) | _ -> None)
        None params;
    title =
      find_or_default
        (function Title t -> Some (Some t) | _ -> None)
        None params;
    title_ext =
      find_or_default
        (function
          | Star { Ext.charset; language; value = Title t } ->
              Some (Some { Ext.charset; language; value = t })
          | _ -> None)
        None params;
    media_type =
      find_or_default
        (function Type mt -> Some (Some mt) | _ -> None)
        None params;
    extensions;
    extension_exts;
  }

let empty =
  { context = Uri.of_string ""; arc = Arc.empty; target = Uri.of_string "" }

let rec unfold s list start =
  match Stringext.find_from ~start s ~pattern:"<" with
  | None -> list
  | Some i -> (
      let uri_ref, i = until s (i + 1) [ '>' ] in
      let i = i + 1 in
      let target = Uri.of_string uri_ref in
      let params, c_opt = params_of_string s i [] in
      let params = List.rev params in
      let context =
        find_or_default
          (function Anchor uri -> Some uri | _ -> None)
          (Uri.of_string "") params
      in
      let link =
        match
          find_or_default
            (function Rel rels -> Some rels | _ -> None)
            [] params
        with
        | _ :: _ as relation ->
            let arc = arc_of_relation_params relation params in
            { context; arc; target }
        | [] -> (
            match
              find_or_default
                (function Rev rels -> Some rels | _ -> None)
                [] params
            with
            | [] ->
                let arc = arc_of_relation_params [] params in
                { context; arc; target }
            | rev ->
                let arc = arc_of_relation_params ~reverse:true rev params in
                { context = target; arc; target = context })
      in
      let list = link :: list in
      match c_opt with None -> list | Some c -> unfold s list c)

let of_string s = List.rev (unfold s [] 0)

open Printf

let arc_to_string context arc =
  Arc.(
    let attrs =
      match arc.relation with
      | [] -> []
      | rels ->
          [
            sprintf "%s=\"%s\""
              (if arc.reverse then "rev" else "rel")
              (String.concat " " (List.map string_of_rel rels));
          ]
    in
    let attrs =
      match arc.hreflang with
      | None -> attrs
      | Some s -> ("hreflang=" ^ s) :: attrs
    in
    let attrs =
      match arc.media with
      | None -> attrs
      | Some s -> sprintf "media=\"%s\"" s :: attrs
    in
    let attrs =
      match arc.title with
      | None -> attrs
      | Some s -> sprintf "title=%S" s :: attrs
      (* TODO: this isn't quite right...*)
    in
    let attrs =
      match arc.title_ext with
      | None -> attrs
      | Some { Ext.charset; language; value } ->
          sprintf "title*=%s'%s'%s" charset language value :: attrs
    in
    let attrs =
      match arc.media_type with
      | None -> attrs
      | Some (typ, sub) -> sprintf "type=%s/%s" typ sub :: attrs
    in
    let attrs =
      List.map (fun (k, v) -> sprintf "%s=%S" k v) arc.extensions @ attrs
    in
    let attrs =
      List.map
        (fun (k, { Ext.charset; language; value }) ->
          sprintf "%s=%s'%s'%s" k charset language value)
        arc.extension_exts
      @ attrs
    in
    let attrs =
      if context = Uri.of_string "" then attrs
      else sprintf "anchor=\"%s\"" (Uri.to_string context) :: attrs
    in
    String.concat "; " attrs)

let to_string { context; arc; target } =
  sprintf "<%s>; %s" (Uri.to_string target) (arc_to_string context arc)
OCaml

Innovation. Community. Security.