pax_global_header00006660000000000000000000000064145760672250014530gustar00rootroot0000000000000052 comment=e6f8a26645be88b18ef1ff2c5dc0037b602a0078 ocaml-cry-1.0.3/000077500000000000000000000000001457606722500134175ustar00rootroot00000000000000ocaml-cry-1.0.3/.github/000077500000000000000000000000001457606722500147575ustar00rootroot00000000000000ocaml-cry-1.0.3/.github/workflows/000077500000000000000000000000001457606722500170145ustar00rootroot00000000000000ocaml-cry-1.0.3/.github/workflows/ci.yml000066400000000000000000000013311457606722500201300ustar00rootroot00000000000000name: CI on: pull_request: push: branches: - main jobs: cancel_previous_run: runs-on: ubuntu-latest steps: - name: Cancel Previous Runs uses: styfle/cancel-workflow-action@0.4.0 with: access_token: ${{ github.token }} build: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest] include: - os: macos-latest extra-packages: osx-secure-transport - os: ubuntu-latest extra-packages: ssl steps: - name: Build and test module uses: savonet/build-and-test-ocaml-module@main with: extra-packages: ${{ matrix.extra-packages }} ocaml-cry-1.0.3/.github/workflows/doc.yml000066400000000000000000000011431457606722500203030ustar00rootroot00000000000000name: Documentation on: push: branches: - main jobs: build_doc: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Setup OCaml uses: avsm/setup-ocaml@v2 with: ocaml-compiler: 4.14.0 - name: Pin locally run: opam pin -y add -n . - name: Install locally run: opam install -y odoc cry - name: Build doc run: opam exec dune build @doc - name: Deploy doc uses: JamesIves/github-pages-deploy-action@4.1.6 with: branch: gh-pages folder: _build/default/_doc/_html ocaml-cry-1.0.3/.gitignore000066400000000000000000000000721457606722500154060ustar00rootroot00000000000000*~ _build *.byte *.native _tests .merlin *.install .*.sw* ocaml-cry-1.0.3/.merlin000066400000000000000000000000301457606722500146770ustar00rootroot00000000000000S src/* B src/* PKG ssl ocaml-cry-1.0.3/.ocamlformat000066400000000000000000000003371457606722500157270ustar00rootroot00000000000000version=0.25.1 profile = conventional break-separators = after space-around-lists = false doc-comments = before match-indent = 2 match-indent-nested = always parens-ite exp-grouping = preserve module-item-spacing = compact ocaml-cry-1.0.3/CHANGES000066400000000000000000000065411457606722500144200ustar00rootroot000000000000001.0.3 (2024-03-18) ===== * Raise a proper error when non-blocking connection fails. * Fix poll segfault. 1.0.2 (2024-01-08) ====== * Use `poll` for select when available. * Make sure `close` call always closes the socket. * Add option to prevert ipv4 over ipv6. Defer to system defaults otherwise. 1.0.1 (2023-07-01) ===== * Fix wrong transport being used when updating metadata. 1.0.0 (2023-06-27) ===== * Simplify Host header logic, pass host through SSL SNI. Thanks to @N6UDP! * Rewrote transport logic to be more flexible. Leave SSL implementation to caller. 0.6.7 (2022-03-18) ===== * Default to ipv4 host resolution for backward compatibility. 0.6.6 (2022-01-30) ====== * Add support for ipv6 connection, thanks to @gilou and @jcourreges (#6) 0.6.5 (2020-03-27) ===== * Switched to dune. * Added optional offset and length parameters to send function. * Added support for Expect: 100-continue to PUT requests (savonet/liquidsoap#1078). 0.6.4 (2019-08-22) ===== * Set SSL to use default path for certificate resolution. * Fix fd leak with SSL 0.6.3 (2019-08-04) ===== * Set chunked capability based on request not response HTTP version. 0.6.2 (2018-08-16) ===== * Fix fd leak in unix_transport, make sure it doesn't happen in SSL implementations as well (savonet/liquidsoap#548) 0.6.1 (2017-11-02) ===== * Fix hostname resolution (savonet/liquidsoap#496) 0.6.0 (2017-10-14) ===== * Make IPv6 implicit. * Add debug flag (-g) to OCAMLFLAGS * Fix host resolution. 0.5.0 (2017-04-11) ===== * Add support for OSX's SecureTransport 0.4.1 (2016-06-26) ===== * Revert back to Bytes.t for backward compatibility with old OCaml compilers. 0.4.0 (2016-06-25) ===== * Fixed shoutcast v2 metadata update * Better API * Switch to Bytes.set * Implement Https connection for icecast. 0.3.0 (2015-07-29) ===== * Switch to Bytes API. * Implemented shoutcast v2 protocol extension allowing multiple sources connected to the same shoutcast v2 server. * Added experimental HTTP capabilities: - Use any PUT, POST or SOURCE verb - Use chunked transfer for HTTP 1.1 * Added HTTP Host: header. 0.2.2 (2011-04-10) ===== * Add second timeout parameters for connection attempts. * New optional charset parameter for ICY metadata updates. * Added new functions [string_of_protocol] and [string_of_connection] 0.2.1 (2011-08-04) ===== * Implemented a proper connection timeout mechanism. 0.2.0 (2011-06-26) ===== * Added an exception parameters to propagate original exceptions when raising an internal's exception. * Fixed exception handling in ICY's answer parsing. * Remove buggy timeout option. 0.1.5 (2010-09-06) ===== * Icy connection was broken with previous release, fixed.. 0.1.4 (2010-09-06) ===== * Fixed http headers generation. Before,ocaml-cry was sending one extra \r\n before starting sending the stream.. 0.1.3 (2010-08-19) ===== * Use recursive calls to Unix.write everywhere and make it safer. 0.1.2 (2010-02-08) ===== * Fix the sending code: older versions resulted in a high load and in some cases in loss of stream chunks. * Added manual_update_metadata to update metadata on any source without being necessarily connected/streaming on it. 0.1.1 (2009-10-26) ===== * Fixed ICY source connection; send headers only after receiving "OK2". * Fixed error: Scanf may raise other exceptions, catching any of them now. 0.1.0 (2009-10-12) ===== * Initial release ocaml-cry-1.0.3/COPYING000066400000000000000000000431311457606722500144540ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. ocaml-cry-1.0.3/README.md000066400000000000000000000013701457606722500146770ustar00rootroot00000000000000ocaml-cry This package contains an OCaml implementation of the various icecast & shoutcast source client protocols. Please read the COPYING file before using this software. Prerequisites: ============== - ocaml - dune - findlib Compilation: ============ ```sh dune build ``` This should build both the native and the byte-code version of the extension library. Installation: ============= Using [opam](http://opam.ocaml.org/): ```sh opam install cry ``` Using `dune` and a local copy (dev only): ```sh dune install ``` This should install the library file (using ocamlfind) in the appropriate place. Author: ======= This author of this software may be contacted by electronic mail at the following address: savonet-users@lists.sourceforge.net. ocaml-cry-1.0.3/cry.opam000066400000000000000000000015741457606722500151010ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "1.0.3" synopsis: "OCaml client for the various icecast & shoutcast source protocols" description: "The cry library is an implementation of the various icecast & shoutcast protocols to connect to streaming servers such as icecast" maintainer: ["The Savonet Team "] authors: ["Romain Beauxis "] license: "GPL-2.0-only" homepage: "https://github.com/savonet/ocaml-cry" bug-reports: "https://github.com/savonet/ocaml-cry/issues" depends: [ "ocaml" {>= "4.12.0"} "dune" {>= "2.8"} "base-bytes" "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/savonet/ocaml-cry.git" ocaml-cry-1.0.3/dune-project000066400000000000000000000011121457606722500157340ustar00rootroot00000000000000(lang dune 2.8) (version 1.0.3) (name cry) (source (github savonet/ocaml-cry)) (license GPL-2.0-only) (authors "Romain Beauxis ") (maintainers "The Savonet Team ") (generate_opam_files true) (use_standard_c_and_cxx_flags false) (package (name cry) (synopsis "OCaml client for the various icecast & shoutcast source protocols") (description "The cry library is an implementation of the various icecast & shoutcast protocols to connect to streaming servers such as icecast") (depends (ocaml (>= 4.12.0)) dune base-bytes) ) ocaml-cry-1.0.3/examples/000077500000000000000000000000001457606722500152355ustar00rootroot00000000000000ocaml-cry-1.0.3/examples/connect.ml000066400000000000000000000012421457606722500172170ustar00rootroot00000000000000open Cry let c = create () let connection = let mount = Icecast_mount "" in let content_type = mpeg in let channels = 2 in let samplerate = 44100 in let bitrate = 128 in let protocol = Http Put in let audio_info = audio_info ~channels ~samplerate ~bitrate () in { (connection ~audio_info ~protocol ~mount ~content_type ()) with port = 8443; } let () = try connect c connection; if get_icy_cap c then Printf.printf "Icy enabled !\n%!"; let meta = Hashtbl.create 10 in Hashtbl.add meta "artist" "test"; Hashtbl.add meta "title" "test"; update_metadata c meta with e -> Printf.printf "Error: %s\n%!" (string_of_error e) ocaml-cry-1.0.3/examples/dune000066400000000000000000000000561457606722500161140ustar00rootroot00000000000000(executable (name connect) (libraries cry)) ocaml-cry-1.0.3/src/000077500000000000000000000000001457606722500142065ustar00rootroot00000000000000ocaml-cry-1.0.3/src/cry.ml000066400000000000000000000606421457606722500153450ustar00rootroot00000000000000(* * Copyright 2003-2016 Savonet team * * This file is part of Ocaml-cry. * * Ocaml-cry is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Ocaml-cry is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Ocaml-cry; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** OCaml low level implementation of the shout source protocol. *) external poll : Unix.file_descr array -> Unix.file_descr array -> Unix.file_descr array -> float -> Unix.file_descr array * Unix.file_descr array * Unix.file_descr array = "caml_cry_poll" let poll r w e timeout = let r = Array.of_list r in let w = Array.of_list w in let e = Array.of_list e in let r, w, e = poll r w e timeout in (Array.to_list r, Array.to_list w, Array.to_list e) let select = match Sys.os_type with "Unix" -> poll | _ -> Unix.select type error = | Create of exn | Connect of exn | Close of exn | Write of exn | Read of exn | Busy | Ssl_unavailable | Not_connected | Invalid_usage | Unknown_host of string | Bad_answer of string option | Http_answer of int * string * string exception Error of error exception Timeout type event = [ `Read | `Write | `Both ] type socket = < typ : string ; transport : transport ; file_descr : Unix.file_descr ; wait_for : ?log:(string -> unit) -> event -> float -> unit ; write : Bytes.t -> int -> int -> int ; read : Bytes.t -> int -> int -> int ; close : unit > and transport = < name : string ; protocol : string ; default_port : int ; connect : ?bind_address:string -> ?timeout:float -> ?prefer:[ `System_default | `Ipv4 | `Ipv6 ] -> string -> int -> socket > (* Wait for [`Read socker], [`Write socket] or [`Both socket] for at most * [timeout] seconds on the given [socket]. Raises [Timeout] if timeout * is reached. *) let wait_for ?(log = fun _ -> ()) event timeout = let start_time = Unix.gettimeofday () in let max_time = start_time +. timeout in let r, w = match event with | `Read socket -> ([socket], []) | `Write socket -> ([], [socket]) | `Both socket -> ([socket], [socket]) in let rec wait t = let r, w, _ = try select r w [] t with Unix.Unix_error (Unix.EINTR, _, _) -> ([], [], []) in if r = [] && w = [] then ( let current_time = Unix.gettimeofday () in if current_time >= max_time then ( log "Timeout reached!"; raise Timeout) else wait (min 1. (max_time -. current_time))) in wait (min 1. timeout) let unix_socket transport fd : socket = object method typ = "unix" method file_descr = fd method transport = transport method wait_for ?log (event : event) d = let event = match event with | `Read -> `Read fd | `Write -> `Write fd | `Both -> `Both fd in wait_for ?log event d method write = Unix.write fd method read = Unix.read fd method close = Unix.close fd end let sockaddr_of_address address = match Unix.getaddrinfo address "0" [AI_NUMERICHOST] with | [] -> raise Not_found | addr :: _ -> addr.ai_addr let addrinfo_order = function | _, Unix.ADDR_UNIX _ -> 2 | `Ipv4, Unix.ADDR_INET (s, _) -> if Unix.is_inet6_addr s then 1 else 0 | `Ipv6, Unix.ADDR_INET (s, _) -> if Unix.is_inet6_addr s then 0 else 1 let resolve_host ~prefer host port = match ( prefer, Unix.getaddrinfo host (string_of_int port) [AI_SOCKTYPE SOCK_STREAM] ) with | _, [] -> raise Not_found | `System_default, l -> l | ((`Ipv4, l) as v) | ((`Ipv6, l) as v) -> List.sort (fun { Unix.ai_addr = s; _ } { Unix.ai_addr = s'; _ } -> Stdlib.compare (addrinfo_order (fst v, s)) (addrinfo_order (fst v, s'))) l let connect_sockaddr ?bind_address ?timeout sockaddr = let domain = Unix.domain_of_sockaddr sockaddr in let socket = Unix.socket ~cloexec:true domain Unix.SOCK_STREAM 0 in (try match bind_address with | None -> () | Some s -> Unix.bind socket (sockaddr_of_address s) with exn -> let bt = Printexc.get_raw_backtrace () in begin try Unix.close socket with _ -> () end; Printexc.raise_with_backtrace exn bt); let do_timeout = timeout <> None in let check_timeout () = let timeout = Option.get timeout in (* Block in a select call for [timeout] seconds. *) let _, w, _ = select [] [socket] [] timeout in if w = [] then raise Timeout; match Unix.getsockopt_error socket with | Some err -> raise (Unix.Unix_error (err, "connect", "")) | None -> Unix.clear_nonblock socket; socket in let finish () = try if do_timeout then Unix.set_nonblock socket; Unix.connect socket sockaddr; if do_timeout then Unix.clear_nonblock socket; socket with | Unix.Unix_error (Unix.EINPROGRESS, _, _) -> check_timeout () | Unix.Unix_error (Unix.EWOULDBLOCK, _, _) when Sys.os_type = "Win32" -> check_timeout () in try finish () with e -> let bt = Printexc.get_raw_backtrace () in begin try Unix.close socket with _ -> () end; Printexc.raise_with_backtrace e bt let unix_connect ?bind_address ?timeout ?(prefer = `System_default) host port = let rec connect_any ?bind_address ?timeout (addrs : Unix.addr_info list) = match addrs with | [] -> raise Not_found | [addr] -> (* Let a possible error bubble up *) connect_sockaddr ?bind_address ?timeout addr.ai_addr | addr :: tail -> ( try connect_sockaddr ?bind_address ?timeout addr.ai_addr with _ -> connect_any ?bind_address ?timeout tail) in connect_any ?bind_address ?timeout (resolve_host ~prefer host port) let unix_transport : transport = object (self) method name = "unix" method protocol = "http" method default_port = 80 method connect ?bind_address ?timeout ?prefer host port = let socket = unix_connect ?bind_address ?timeout ?prefer host port in unix_socket self socket end let unix_socket = unix_socket unix_transport let rec string_of_error = function | Error (Create e) -> pp "could not initiate a new handler" e | Error (Connect e) -> pp "could not connect to host" e | Error (Write e) -> pp "could not write data to host" e | Error (Read e) -> pp "could not read data from host" e | Error (Close e) -> pp "could not close connection" e | Error Busy -> "busy" | Error Ssl_unavailable -> "SSL transport is not available" | Error Not_connected -> "not connected" | Error Invalid_usage -> "invalid usage" (* | Unix.unix_error (code,name,param) -> Printf.sprintf "%s in %s(%s)" (Unix.error_message code) name param *) | Error (Unknown_host h) -> Printf.sprintf "Unknown host: %s" h | Timeout -> "connection timeout" | Error (Bad_answer s) -> Printf.sprintf "bad answer%s" (match s with Some s -> Printf.sprintf ": %s" s | None -> "") | Error (Http_answer (c, x, v)) -> Printf.sprintf "%i, %s (HTTP/%s)" c x v | e -> Printexc.to_string e and pp s e = Printf.sprintf "%s: %s" s (string_of_error e) type verb = Put | Post | Source let string_of_verb = function | Put -> "PUT" | Post -> "POST" | Source -> "SOURCE" type protocol = Icy | Http of verb let string_of_protocol = function | Icy -> "icy" | Http v -> Printf.sprintf "http(%s)" (string_of_verb v) type content_type = string let ogg_application = "application/ogg" let ogg_audio = "audio/ogg" let ogg_video = "video/ogg" let mpeg = "audio/mpeg" let content_type_of_string s = s let string_of_content_type x = x type mount = Icy_id of int | Icecast_mount of string type connection = { mount : mount; user : string; password : string; host : string; port : int; chunked : bool; content_type : content_type; protocol : protocol; headers : (string, string) Hashtbl.t; } let string_of_mount = function | Icy_id id -> Printf.sprintf "\"sid\": %d" id | Icecast_mount mount -> Printf.sprintf "\"mount\": %S" mount let string_of_connection c = Printf.sprintf "{ %s,\n\ \"user\": %S,\n\ \"password\": %S,\n\ \"host\": %S,\n\ \"port\": %d,\n\ \"chunked\": %b,\n\ \"content_type\": %S,\n\ \"protocol\": %S,\n\ \"headers\": { %s } }" (string_of_mount c.mount) c.user c.password c.host c.port c.chunked (string_of_content_type c.content_type) (string_of_protocol c.protocol) (Hashtbl.fold (fun x y z -> Printf.sprintf "%S: %S,\n%s" x y z) c.headers "") type audio_info = (string, string) Hashtbl.t type metadata = (string, string) Hashtbl.t (* Metadata socket is only present if icy_cap is true *) type connection_data = { connection : connection; socket : socket } type status_priv = PrivConnected of connection_data | PrivDisconnected type status = Connected of connection_data | Disconnected type t = { timeout : float; connection_timeout : float option; bind_address : string option; transport : transport; mutable icy_cap : bool; mutable status : status_priv; mutable chunked : bool; } let get_connection_data x = match x.status with | PrivConnected d -> d | PrivDisconnected -> raise (Error Not_connected) let create ?bind_address ?connection_timeout ?(timeout = 30.) ?(transport = unix_transport) () = { timeout; connection_timeout; transport; bind_address; icy_cap = false; status = PrivDisconnected; chunked = false; } let write_data ~timeout ?(offset = 0) ?length (socket : socket) request = let request = Bytes.unsafe_of_string request in let len = match length with Some l -> l | None -> Bytes.length request in let rec write ofs = socket#wait_for `Write timeout; let rem = len - ofs in if rem > 0 then ( let ret = socket#write request ofs rem in if ret = 0 then raise (Failure "connection closed."); if ret < rem then write (ofs + ret)) in try write offset with e -> raise (Error (Write e)) let close x = try let c = get_connection_data x in Fun.protect ~finally:(fun () -> c.socket#close) (fun () -> if x.chunked then write_data ~timeout:x.timeout c.socket "0\r\n\r\n"; x.chunked <- false; x.icy_cap <- false; x.status <- PrivDisconnected) with | Error _ as e -> raise e | e -> raise (Error (Close e)) let get_status c = match c.status with | PrivConnected d -> Connected d | PrivDisconnected -> Disconnected let get_icy_cap c = c.icy_cap let audio_info ?samplerate ?channels ?quality ?bitrate () = let infos = Hashtbl.create 10 in let f m x y = match y with Some v -> Hashtbl.replace infos x (m v) | None -> () in f string_of_int "channels" channels; f string_of_int "samplerate" samplerate; f string_of_int "bitrate" bitrate; f string_of_float "quality" quality; infos let normalize_mount mount = match mount with | Icecast_mount mount -> Icecast_mount begin match mount with | "" -> "/" | mount -> if mount.[0] = '/' then mount else Printf.sprintf "/%s" mount end | _ -> mount let connection ?user_agent ?name ?genre ?url ?public ?audio_info ?description ?(host = "localhost") ?(port = 8000) ?(chunked = false) ?(password = "hackme") ?(protocol = Http Source) ?(user = "source") ~mount ~content_type () = let headers = Hashtbl.create 10 in let public = match public with | Some x -> if x then Some "1" else Some "0" | None -> None in let mount = normalize_mount mount in let f (x, y) = match y with Some v -> Hashtbl.replace headers x v | None -> () in let x = match protocol with | Http _ -> let audio_info = match audio_info with | Some x -> let f x y z = let z = if z <> "" then z ^ ";" else z in Printf.sprintf "%s%s=%s" z x y in Some (Hashtbl.fold f x "") | None -> None in [ ("User-Agent", user_agent); ("ice-name", name); ("ice-genre", genre); ("ice-url", url); ("ice-public", public); ("ice-audio-info", audio_info); ("ice-description", description); ] | Icy -> [ ("icy-name", name); ("icy-url", url); ("icy-pub", public); ("icy-genre", genre); ( "icy-br", match audio_info with | None -> None | Some x -> ( try Some (Hashtbl.find x "bitrate") with Not_found -> None) ); ] in List.iter f x; { host; port; user; chunked; password; mount; content_type; protocol; headers; } (** Base 64 encoding. *) let encode64 s = let digit = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" in let extra = String.length s mod 3 in let s = match extra with 1 -> s ^ "\000\000" | 2 -> s ^ "\000" | _ -> s in let n = String.length s in let dst = Bytes.create (4 * (n / 3)) in for i = 0 to (n / 3) - 1 do let ( := ) j v = Bytes.set dst ((i * 4) + j) digit.[v] in let c j = int_of_char s.[(i * 3) + j] in let c0 = c 0 and c1 = c 1 and c2 = c 2 in 0 := c0 lsr 2; 1 := (c0 lsl 4) land 63 lor (c1 lsr 4); 2 := (c1 lsl 2) land 63 lor (c2 lsr 6); 3 := c2 land 63 done; if extra = 1 then begin Bytes.set dst ((4 * (n / 3)) - 2) '='; Bytes.set dst ((4 * (n / 3)) - 1) '=' end else if extra = 2 then Bytes.set dst ((4 * (n / 3)) - 1) '='; Bytes.to_string dst (* URL encoding/decoging according to RFC 1738, RFC 1630. * Borrowed from ocamlnet. *) (** Converts k to a 2-digit hexadecimal string. *) let to_hex2 = let hex_digits = [| '0'; '1'; '2'; '3'; '4'; '5'; '6'; '7'; '8'; '9'; 'A'; 'B'; 'C'; 'D'; 'E'; 'F'; |] in fun k -> let s = Bytes.create 2 in Bytes.set s 0 hex_digits.((k lsr 4) land 15); Bytes.set s 1 hex_digits.(k land 15); Bytes.to_string s let url_encode s = let rec do_url_encode s s' = (* True if x is an acceptable char *) let range x = (* 0-9 *) (x >= 0x30 && x <= 0x39) (* A-Z *) || (x >= 0x41 && x <= 0x5A) || (* a-z *) (x >= 0x61 && x <= 0x7a) in match String.length s with | 0 -> s' | l -> let x = Char.code s.[0] in let s' = if not (range x) then Printf.sprintf "%s%%%s" s' (to_hex2 x) else Printf.sprintf "%s%c" s' s.[0] in do_url_encode (String.sub s 1 (l - 1)) s' in do_url_encode s "" let http_header = Printf.sprintf "%s %s HTTP/1.%d\r\n%s\r\n\r\n" let get_auth user password = Printf.sprintf "Basic %s" (encode64 (user ^ ":" ^ password)) let buf = Bytes.create 1024 (* TODO: review all reading code as this * seems a bit ad-hoc/naive.. *) (** Read and split data. * There should always be at least * one element in the resulting list. * If not, something bad happened. *) let read_data ~timeout (socket : socket) = socket#wait_for `Read timeout; try let ret = socket#read buf 0 1024 in (* split data *) let buf = Bytes.sub buf 0 ret in let rec f pos l = try let x = Bytes.index_from buf pos '\n' in f (x + 1) (Bytes.sub buf pos (x - pos - 1) :: l) with Invalid_argument _ | Not_found -> if pos < ret then Bytes.sub buf pos (ret - pos) :: l else l in let ret = f 0 [] in if List.length ret = 0 then [Bytes.of_string ""] else List.rev (f 0 []) with e -> raise (Error (Read e)) let header_string headers source = let unique_headers = Hashtbl.create 10 in Hashtbl.iter (Hashtbl.replace unique_headers) headers; (* Icy headers are of the form: %s:%s *) let sep = if source.protocol = Icy then "" else " " in (* "content-type" seems to be in lower case * for shoutcast. Also, it seems that * it is good to pass it last, see: * http://forums.winamp.com/showthread.php?threadid=285035 *) let content_label = if source.protocol = Icy then "content-type" else "Content-Type" in let f x y z = Printf.sprintf "%s:%s%s" x sep y :: z in let headers = Hashtbl.fold f unique_headers (f content_label source.content_type []) in String.concat "\r\n" headers let parse_http_answer s = let f v c s = (v, c, s) in try Scanf.sscanf s "HTTP/%s %i %[^\r^\n]" f with | Scanf.Scan_failure s -> raise (Error (Bad_answer (Some s))) | _ -> raise (Error (Bad_answer None)) let http_path_of_mount = function | Icecast_mount mount -> mount | _ -> raise (Error Invalid_usage) let connect_http c (socket : socket) source verb = let auth = get_auth source.user source.password in try let http_version = if source.chunked then 1 else 0 in let headers = Hashtbl.copy source.headers in Hashtbl.replace headers "Authorization" auth; Hashtbl.replace headers "Host" (Printf.sprintf "%s:%d" source.host source.port); if source.chunked then Hashtbl.replace headers "Transfer-Encoding" "chunked"; if verb = Put then Hashtbl.add headers "Expect" "100-continue"; let headers = header_string headers source in let request = http_header (string_of_verb verb) (http_path_of_mount source.mount) http_version headers in write_data ~timeout:c.timeout socket request; (* Read input from socket. *) let ret = read_data ~timeout:c.timeout socket in let v, code, s = parse_http_answer (Bytes.to_string (List.hd ret)) in let err = Error (Http_answer (code, s, v)) in begin match verb with | Put when code <> 100 -> raise err | v when v <> Put && (code < 200 || code >= 300) -> raise err | _ -> () end; c.chunked <- source.chunked; c.icy_cap <- true; c.status <- PrivConnected { connection = source; socket } with e -> let bt = Printexc.get_raw_backtrace () in begin try close c with _ -> () end; Printexc.raise_with_backtrace e bt let icy_id_of_mount = function | Icy_id id -> id | _ -> raise (Error Invalid_usage) let connect_icy c socket source = let password = let user = match source.user with "" -> "" | user -> Printf.sprintf "%s:" user in let id = match icy_id_of_mount source.mount with | 1 -> "" | id -> Printf.sprintf ":#%d" id in Printf.sprintf "%s%s%s" user source.password id in let request = Printf.sprintf "%s\r\n" password in try write_data ~timeout:c.timeout socket request; (* Read input from socket. *) let ret = read_data ~timeout:c.timeout socket in let f s = if s.[0] <> 'O' && s.[1] <> 'K' then raise (Error (Bad_answer (Some s))) in begin try Scanf.sscanf (Bytes.to_string (List.hd ret)) "%[^\r^\n]" f with | Scanf.Scan_failure s -> raise (Error (Bad_answer (Some s))) | Error _ as e -> raise e | _ -> raise (Error (Bad_answer None)) end; (* Read another line *) let ret = match ret with | _ :: y :: _ -> y | _ -> List.hd (read_data ~timeout:c.timeout socket) in let f _ = c.icy_cap <- true in begin try Scanf.sscanf (Bytes.to_string ret) "icy-caps:%[1]" f with Scanf.Scan_failure _ -> () end; (* Now Write headers *) let headers = header_string source.headers source in let request = Printf.sprintf "%s\r\n\r\n" headers in write_data ~timeout:c.timeout socket request; c.status <- PrivConnected { connection = source; socket } with e -> let bt = Printexc.get_raw_backtrace () in begin try close c with _ -> () end; Printexc.raise_with_backtrace e bt let connect c source = if c.status <> PrivDisconnected then raise (Error Busy); let port = if source.protocol = Icy then source.port + 1 else source.port in let socket = c.transport#connect ?bind_address:c.bind_address ?timeout:c.connection_timeout source.host port in try (* We do not know icy capabilities so far.. *) c.icy_cap <- false; match source.protocol with | Http verb -> connect_http c socket source verb | Icy -> connect_icy c socket source with e -> let bt = Printexc.get_raw_backtrace () in begin try socket#close with _ -> () end; Printexc.raise_with_backtrace e bt let http_meta_request mount charset meta headers = let unique_headers = Hashtbl.create 10 in Hashtbl.iter (Hashtbl.replace unique_headers) headers; let header = Hashtbl.fold (Printf.sprintf "%s: %s\r\n%s") unique_headers "" in Printf.sprintf "GET /admin/metadata?mode=updinfo&mount=%s%s%s HTTP/1.0\r\n%s\r\n" mount charset meta header let icy_meta_request = Printf.sprintf "GET /admin.cgi?mode=updinfo&pass=%s%s HTTP/1.0\r\n%s\r\n" let manual_update_metadata ~host ~port ~protocol ~user ~password ~mount ?(connection_timeout = 5.) ?(timeout = 30.) ?headers ?bind_address ?charset ?(transport = unix_transport) m = let mount = normalize_mount mount in let headers = match headers with Some x -> Hashtbl.copy x | None -> Hashtbl.create 0 in let socket = transport#connect ?bind_address ~timeout:connection_timeout host port in let close () = try socket#close with e -> raise (Error (Close e)) in try let charset = match charset with Some c -> Printf.sprintf "&charset=%s" c | None -> "" in let f x y z = if y <> "" then Printf.sprintf "%s&%s=%s" z (url_encode x) (url_encode y) else z in let meta = Hashtbl.fold f m "" in let request = match protocol with | Http _ -> let mount = match mount with | Icecast_mount mount -> mount | _ -> raise (Error Invalid_usage) in Hashtbl.replace headers "Authorization" (get_auth user password); Hashtbl.replace headers "Host" (Printf.sprintf "%s:%d" host port); http_meta_request mount charset meta headers | Icy -> let sid = match mount with | Icy_id id -> id | _ -> raise (Error Invalid_usage) in let meta = match sid with | 1 -> meta | sid -> Printf.sprintf "%s&sid=%d" meta sid in let user_agent = try Hashtbl.find headers "User-Agent" with Not_found -> "ocaml-cry" in let user_agent = Printf.sprintf "User-Agent: %s (Mozilla compatible)\r\n" user_agent in icy_meta_request password meta user_agent in write_data ~timeout socket request; (* Read input from socket. *) let ret = read_data ~timeout socket in let v, code, s = parse_http_answer (Bytes.to_string (List.hd ret)) in if code <> 200 then raise (Error (Http_answer (code, s, v))); close () with e -> let bt = Printexc.get_raw_backtrace () in begin try close () with _ -> () end; Printexc.raise_with_backtrace e bt let update_metadata ?charset c m = if not c.icy_cap then raise (Error Invalid_usage); let data = get_connection_data c in let source = data.connection in let user = source.user in let port = source.port in let password = source.password in let headers = Some source.headers in let protocol = source.protocol in let mount = source.mount in let host = source.host in let timeout = c.timeout in let transport = c.transport in let connection_timeout = c.connection_timeout in manual_update_metadata ~host ~port ~protocol ~user ~password ~timeout ~mount ~transport ?headers ?connection_timeout ?charset m let send ?(offset = 0) ?length c x = let length = match length with Some l -> l | None -> String.length x in let d = get_connection_data c in if c.chunked then begin if length > 0 then ( let x = Printf.sprintf "%X\r\n%s\r\n" length (String.sub x offset length) in write_data ~timeout:c.timeout d.socket x) end else write_data ~offset ~length ~timeout:c.timeout d.socket x ocaml-cry-1.0.3/src/cry.mli000066400000000000000000000202431457606722500155070ustar00rootroot00000000000000(* * Copyright 2003-2016 Savonet team * * This file is part of Ocaml-cry. * * Ocaml-cry is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Ocaml-cry is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Ocaml-cry; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** Native implementation of the shout source protocols * for icecast and shoutcast. *) (** {2 Description} * * [Cry] implements the protocols used to connect and send source data to * icecast2 and shoutcast servers. * * It is a low-level implementation that minimally manages source * connections. In particular, it does not handle synchronisation, unlike * the main implementation libshout. Hence, the task of sending audio data * to the streaming server at real time rate is left to the application. *) (** {2 Types and errors} *) type event = [ `Read | `Write | `Both ] type socket = < typ : string ; transport : transport ; file_descr : Unix.file_descr ; wait_for : ?log:(string -> unit) -> event -> float -> unit ; write : Bytes.t -> int -> int -> int ; read : Bytes.t -> int -> int -> int ; close : unit > and transport = < name : string ; protocol : string ; default_port : int ; connect : ?bind_address:string -> ?timeout:float -> ?prefer:[ `System_default | `Ipv4 | `Ipv6 ] -> string -> int -> socket > (** Possible errors. *) type error = | Create of exn | Connect of exn | Close of exn | Write of exn | Read of exn | Busy | Ssl_unavailable | Not_connected | Invalid_usage | Unknown_host of string | Bad_answer of string option | Http_answer of int * string * string exception Error of error exception Timeout (** Base unix connect *) val unix_connect : ?bind_address:string -> ?timeout:float -> ?prefer:[ `System_default | `Ipv4 | `Ipv6 ] -> string -> int -> Unix.file_descr (** Unix transport and socket. *) val unix_transport : transport val unix_socket : Unix.file_descr -> socket (** Get a string explaining an error. *) val string_of_error : exn -> string (** Possible verbs for HTTP streaming. Default: [Source] *) type verb = Put | Post | Source (** Possible protocols. [Icy] is the (undocumented) shoutcast source protocol. * [Http] is the icecast2 source protocol. * * Ogg streaming is only possible with [Http]. Any headerless format, * (e.g. mpeg containers), should work with both protocols, * provided you set the correct content-type (mime) for the source. *) type protocol = Icy | Http of verb (** Return a string representation of a protocol. *) val string_of_protocol : protocol -> string (** Special type for content-type (mime) data. *) type content_type (** General mime type for ogg data. *) val ogg_application : content_type (** Mime type for audio data encapsulated using ogg. *) val ogg_audio : content_type (** Mime type for video data encapsulated using ogg. *) val ogg_video : content_type (** Mime type for mpeg audio data (mp3). *) val mpeg : content_type (** Create a mime type from a string (e.g. "audio/aacp") *) val content_type_of_string : string -> content_type (** Get the string representation of a mime type. *) val string_of_content_type : content_type -> string (** Type for a mount point. [Icy_id] are for Shoutcast v2 * sid. For Shoutcast v1, use [Icy_id 1]. *) type mount = Icy_id of int | Icecast_mount of string (** Type for a source connection. * * [headers] is a hash table containing the headers. * See [connection] function for more details. *) type connection = { mount : mount; user : string; password : string; host : string; port : int; chunked : bool; content_type : content_type; protocol : protocol; headers : (string, string) Hashtbl.t; } (** Returns a JSON string representation of a connection. *) val string_of_connection : connection -> string (** Type for audio informations. Used for connection headers. * See [audio_info] function for more details. *) type audio_info = (string, string) Hashtbl.t (** Type for metadata values. *) type metadata = (string, string) Hashtbl.t (* Type for connection data *) type connection_data = { connection : connection; socket : socket } (** Type for the status of a handler. *) type status = Connected of connection_data | Disconnected (** Type for the main handler. *) type t (** {2 API} *) (** Create a new handler. * * [bind] is not used by default (system default). * [timeout] is [30.] by default. *) val create : ?bind_address:string -> ?connection_timeout:float -> ?timeout:float -> ?transport:transport -> unit -> t (** Get a handler's status *) val get_status : t -> status (** Get a handler's ICY capabilities. * For the [Http] protocol, this is always true. * For the [Icy] protocol, this is detected upon connecting. *) val get_icy_cap : t -> bool (** Get data associated with a connection. Use it only if you know * what you are doing. * * Raises: [Error Not_connected] if not connected. *) val get_connection_data : t -> connection_data (** Create a new [audio_info] value, * filed with given values. *) val audio_info : ?samplerate:int -> ?channels:int -> ?quality:float -> ?bitrate:int -> unit -> audio_info (** Create a new [connection] value * with default values. * * [mount] is mandatory when using the [Http] protocol. * [icy_id] is mandatory to support multiple shoutcast sources * on shoutcast v2. * * [host] is ["localhost"] by default. * [password] is ["hackme"] by default. * [user] is ["source"] by default. Change [user] only if you know * what your are doing. * [protocol] is [Http] by default. * [port] is [8000] by default. * [chunked] is [false] by default and only works with HTTP/1.1-capable * servers. * * The list of preset headers for [Http] connections is: * ["User-Agent"], ["ice-name"], ["ice-genre"], * ["ice-url"], ["ice-public"], ["ice-audio-info"], * ["ice-description"]. * * The list of preset headers for [Icy] connections is: * ["User-Agent"], ["icy-name"], ["icy-url"], ["icy-pub"], * ["icy-genre"], ["icy-br"]. * * Additionally, you can also add: * ["icy-irc"], ["icy-icq"] and ["icy-aim"] but these are not added * by this function. *) val connection : ?user_agent:string -> ?name:string -> ?genre:string -> ?url:string -> ?public:bool -> ?audio_info:audio_info -> ?description:string -> ?host:string -> ?port:int -> ?chunked:bool -> ?password:string -> ?protocol:protocol -> ?user:string -> mount:mount -> content_type:content_type -> unit -> connection (** Connect a handler. *) val connect : t -> connection -> unit (** Update metadata on a handler. Useful only for non-ogg data format, * and if [icy_cap] is [true] for [Icy] connections. * * For [Icy] protocol, the relevant metadata are only ["song"] * and ["url"]. * * Raises: [Error Not_connected] * if not connected. *) val update_metadata : ?charset:string -> t -> metadata -> unit (** Manually update metadata on any source without necessarily * being connected to it for streaming. * * Optional [timeout] is [30.] by default. * * Use it only if you know what you are doing ! *) val manual_update_metadata : host:string -> port:int -> protocol:protocol -> user:string -> password:string -> mount:mount -> ?connection_timeout:float -> ?timeout:float -> ?headers:(string, string) Hashtbl.t -> ?bind_address:string -> ?charset:string -> ?transport:transport -> metadata -> unit (** Send data to a source connection. * * Raises: [Error Not_connected] * if not connected. *) val send : ?offset:int -> ?length:int -> t -> string -> unit (** Close a source connection. * * Raises: [Error Not_connected] * if not connected. *) val close : t -> unit ocaml-cry-1.0.3/src/cry_stubs.c000066400000000000000000000055071457606722500163760ustar00rootroot00000000000000#include #include #include #include #include #include #include #include /* On native Windows platforms, many macros are not defined. */ #if (defined _WIN32 || defined __WIN32__) && !defined __CYGWIN__ #ifndef EWOULDBLOCK #define EWOULDBLOCK EAGAIN #endif #endif #ifdef WIN32 #define Fd_val(fd) win_CRT_fd_of_filedescr(fd) #define Val_fd(fd) caml_failwith("Val_fd") #else #define Fd_val(fd) Int_val(fd) #define Val_fd(fd) Val_int(fd) #endif #ifndef WIN32 #include CAMLprim value caml_cry_poll(value _read, value _write, value _err, value _timeout) { CAMLparam3(_read, _write, _err); CAMLlocal4(_pread, _pwrite, _perr, _ret); struct pollfd *fds; nfds_t nfds = 0; nfds_t nread = 0; nfds_t nwrite = 0; nfds_t nerr = 0; int timeout; size_t last = 0; int n, ret; if (Double_val(_timeout) == -1) timeout = -1; else timeout = Double_val(_timeout) * 1000; nfds += Wosize_val(_read); nfds += Wosize_val(_write); nfds += Wosize_val(_err); fds = calloc(nfds, sizeof(struct pollfd)); if (fds == NULL) caml_raise_out_of_memory(); for (n = 0; n < Wosize_val(_read); n++) { fds[last + n].fd = Fd_val(Field(_read, n)); fds[last + n].events = POLLIN; } last += Wosize_val(_read); for (n = 0; n < Wosize_val(_write); n++) { fds[last + n].fd = Fd_val(Field(_write, n)); fds[last + n].events = POLLOUT; } last += Wosize_val(_write); for (n = 0; n < Wosize_val(_err); n++) { fds[last + n].fd = Fd_val(Field(_err, n)); fds[last + n].events = POLLERR; } caml_release_runtime_system(); ret = poll(fds, nfds, timeout); caml_acquire_runtime_system(); if (ret == -1) { free(fds); uerror("poll", Nothing); } for (n = 0; n < nfds; n++) { if (fds[n].revents & POLLIN) nread++; if (fds[n].revents & POLLOUT) nwrite++; if (fds[n].revents & POLLERR) nerr++; } _pread = caml_alloc_tuple(nread); nread = 0; _pwrite = caml_alloc_tuple(nwrite); nwrite = 0; _perr = caml_alloc_tuple(nerr); nerr = 0; for (n = 0; n < nfds; n++) { if (fds[n].revents & POLLIN) { Store_field(_pread, nread, Val_fd(fds[n].fd)); nread++; } if (fds[n].revents & POLLOUT) { Store_field(_pwrite, nwrite, Val_fd(fds[n].fd)); nwrite++; } if (fds[n].revents & POLLERR) { Store_field(_perr, nerr, Val_fd(fds[n].fd)); nerr++; } } free(fds); _ret = caml_alloc_tuple(3); Store_field(_ret, 0, _pread); Store_field(_ret, 1, _pwrite); Store_field(_ret, 2, _perr); CAMLreturn(_ret); } #else CAMLprim value caml_cry_poll(value _read, value _write, value _err, value _timeout) { caml_failwith("caml_poll"); } #endif ocaml-cry-1.0.3/src/dune000066400000000000000000000003071457606722500150640ustar00rootroot00000000000000(library (name cry) (public_name cry) (libraries bytes unix) (foreign_stubs (language c) (names cry_stubs)) (synopsis "OCaml client for the various icecast & shoutcast source protocols"))