pax_global_header00006660000000000000000000000064136375120330014515gustar00rootroot0000000000000052 comment=2e9bfae6eca65c37afc1aa1086cd48fa77188d87 ocaml-cry-0.6.5/000077500000000000000000000000001363751203300134135ustar00rootroot00000000000000ocaml-cry-0.6.5/.github/000077500000000000000000000000001363751203300147535ustar00rootroot00000000000000ocaml-cry-0.6.5/.github/workflows/000077500000000000000000000000001363751203300170105ustar00rootroot00000000000000ocaml-cry-0.6.5/.github/workflows/ci.yml000066400000000000000000000013301363751203300201230ustar00rootroot00000000000000name: CI on: [push] jobs: build: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest] https: ['', ssl, osx-secure-transport] exclude: - os: ubuntu-latest https: osx-secure-transport steps: - uses: actions/checkout@v1 - name: Setup OCaml uses: avsm/setup-ocaml@v1.0 - name: Install depext module run: opam install -y depext - name: Pin locally run: opam pin -y add --no-action . - name: Install locally run: opam depext -y -i ${{ matrix.https }} cry - name: Build locally run: eval $(opam env) && dune build - name: Run tests locally run: eval $(opam env) && dune runtest ocaml-cry-0.6.5/.gitignore000066400000000000000000000000631363751203300154020ustar00rootroot00000000000000*~ _build *.byte *.native _tests .merlin *.install ocaml-cry-0.6.5/.merlin000066400000000000000000000000301363751203300146730ustar00rootroot00000000000000S src/* B src/* PKG ssl ocaml-cry-0.6.5/.ocamlformat000066400000000000000000000003201363751203300157130ustar00rootroot00000000000000profile = 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-0.6.5/.travis-ci.sh000077500000000000000000000004251363751203300157320ustar00rootroot00000000000000# Hacking the build into Travis-CI "C" environment # See http://anil.recoil.org/2013/09/30/travis-and-ocaml.html export OPAMYES=1 opam init if [ -n "${OPAM_SWITCH}" ]; then opam switch ${OPAM_SWITCH} fi eval `opam config env` opam install -q -y dune # compile dune build ocaml-cry-0.6.5/.travis.yml000066400000000000000000000001701363751203300155220ustar00rootroot00000000000000language: c sudo: false addons: apt: sources: - avsm packages: - opam script: bash -ex .travis-ci.sh ocaml-cry-0.6.5/CHANGES000066400000000000000000000051461363751203300144140ustar00rootroot000000000000000.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-0.6.5/COPYING000066400000000000000000000431311363751203300144500ustar00rootroot00000000000000 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-0.6.5/README.md000066400000000000000000000013701363751203300146730ustar00rootroot00000000000000ocaml-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-0.6.5/cry.opam000066400000000000000000000015711363751203300150720ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "0.6.5" 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" homepage: "https://github.com/savonet/ocaml-cry" bug-reports: "https://github.com/savonet/ocaml-cry/issues" depends: [ "dune" {> "2.0"} ] depopts: [ "ssl" {>= "0.5.9"} "osx-secure-transport" ] build: [ ["dune" "subst"] {pinned} [ "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-0.6.5/dune-project000066400000000000000000000011021363751203300157270ustar00rootroot00000000000000(lang dune 2.0) (version 0.6.5) (name cry) (source (github savonet/ocaml-cry)) (license GPL-2.0) (authors "Romain Beauxis ") (maintainers "The Savonet Team ") (generate_opam_files true) (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 (dune (> 2.0))) (depopts (ssl (>= 0.5.9)) osx-secure-transport) ) ocaml-cry-0.6.5/examples/000077500000000000000000000000001363751203300152315ustar00rootroot00000000000000ocaml-cry-0.6.5/examples/connect.ml000066400000000000000000000012431363751203300172140ustar00rootroot00000000000000open 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 = Https 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-0.6.5/examples/dune000066400000000000000000000000561363751203300161100ustar00rootroot00000000000000(executable (name connect) (libraries cry)) ocaml-cry-0.6.5/src/000077500000000000000000000000001363751203300142025ustar00rootroot00000000000000ocaml-cry-0.6.5/src/cry.ml000066400000000000000000000527321363751203300153420ustar00rootroot00000000000000(* * 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. *) include Cry_common let ssl = ref None let register_https fn = ssl := Some fn let () = let callback fn = register_https (fun ?timeout ?bind ~host sockaddr -> fn ?timeout ?bind ~host sockaddr) in Cry_https.register callback let get_ssl () = match !ssl with Some fn -> fn | None -> raise (Error Ssl_unavailable) let gethostbyname h = try Unix.gethostbyname h with Not_found -> raise (Error (Unknown_host h)) let unix_transport ?bind ?timeout sockaddr = let domain = Unix.domain_of_sockaddr sockaddr in let socket = try Unix.socket domain Unix.SOCK_STREAM 0 with e -> raise (Error (Create e)) in begin try match bind with | None -> () | Some s -> let bind_addr_inet = (gethostbyname s).Unix.h_addr_list.(0) in (* Seems like you need to bind on port 0 *) let bind_addr = Unix.ADDR_INET (bind_addr_inet, 0) in Unix.bind socket bind_addr with e -> begin try Unix.close socket with _ -> () end; raise (Error (Create e)) end; let wait_for operation delay = let events () = match operation with | `Read -> Unix.select [socket] [] [] delay | `Write -> Unix.select [] [socket] [] delay | `Both -> Unix.select [socket] [socket] [] delay in let r, w, _ = events () in match operation with | `Read -> r <> [] | `Write -> w <> [] | `Both -> r <> [] || w <> [] in let transport = { write = Unix.write socket; read = Unix.read socket; wait_for; close = (fun () -> Unix.close socket); } in let do_timeout = timeout <> None in let check_timeout () = match timeout with | Some timeout -> (* Block in a select call for [timeout] seconds. *) let _, w, _ = Unix.select [] [socket] [] timeout in if w = [] then raise (Error (Connect Timeout)); Unix.clear_nonblock socket; transport | None -> assert false in let finish () = try if do_timeout then Unix.set_nonblock socket; Unix.connect socket sockaddr; if do_timeout then Unix.clear_nonblock socket; transport with | Unix.Unix_error (Unix.EINPROGRESS, _, _) -> check_timeout () | Unix.Unix_error (Unix.EWOULDBLOCK, _, _) when Sys.os_type = "Win32" -> check_timeout () | e -> raise (Error (Connect e)) in try finish () with e -> begin try Unix.close socket with _ -> () end; raise e 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 | Https of verb let string_of_protocol = function | Icy -> "icy" | Http v -> Printf.sprintf "http(%s)" (string_of_verb v) | Https v -> Printf.sprintf "https(%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; transport : transport } type status_priv = PrivConnected of connection_data | PrivDisconnected type status = Connected of connection_data | Disconnected type t = { timeout : float; connection_timeout : float option; bind : string option; 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 ?connection_timeout ?(timeout = 30.) () = { timeout; connection_timeout; bind; icy_cap = false; status = PrivDisconnected; chunked = false; } let write_data ~timeout ?(offset = 0) ?length transport 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 = if not (transport.wait_for `Write timeout) then raise Timeout; let rem = len - ofs in if rem > 0 then ( let ret = transport.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 if x.chunked then write_data ~timeout:x.timeout c.transport "0\r\n\r\n"; c.transport.close (); 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 _ | Https _ -> 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 transport = if not (transport.wait_for `Read timeout) then raise Timeout; try let ret = transport.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 resolve_host host = (Unix.gethostbyname host).Unix.h_addr_list.(0) let add_host_header ?(force = false) headers host port = try ignore (resolve_host host); if force then Hashtbl.replace headers "Host" "" with Not_found -> let host = if port = 80 then host else Printf.sprintf "%s:%d" host port in Hashtbl.replace headers "Host" host let http_path_of_mount = function | Icecast_mount mount -> mount | _ -> raise (Error Invalid_usage) let connect_http c transport 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; add_host_header ~force:(http_version = 1) headers 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 transport request; (* Read input from socket. *) let ret = read_data ~timeout:c.timeout transport 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; transport } with e -> begin try close c with _ -> () end; raise e let icy_id_of_mount = function | Icy_id id -> id | _ -> raise (Error Invalid_usage) let connect_icy c transport 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 transport request; (* Read input from socket. *) let ret = read_data ~timeout:c.timeout transport 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 transport) 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 transport request; c.status <- PrivConnected { connection = source; transport } with e -> begin try close c with _ -> () end; raise e 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 sockaddr = Unix.ADDR_INET (resolve_host source.host, port) in let transport = match source.protocol with | Icy | Http _ -> unix_transport ?bind:c.bind sockaddr | Https _ -> (get_ssl ()) ~host:source.host sockaddr in try (* We do not know icy capabilities so far.. *) c.icy_cap <- false; match source.protocol with | Http verb | Https verb -> connect_http c transport source verb | Icy -> connect_icy c transport source with e -> begin try transport.close () with _ -> () end; raise e 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 ?charset m = let mount = normalize_mount mount in let headers = match headers with Some x -> Hashtbl.copy x | None -> Hashtbl.create 0 in let sockaddr = Unix.ADDR_INET (resolve_host host, port) in let transport = match protocol with | Icy | Http _ -> unix_transport ?bind ~timeout:connection_timeout sockaddr | Https _ -> (get_ssl ()) ~timeout:connection_timeout ~host sockaddr in let close () = try transport.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 _ | Https _ -> let mount = match mount with | Icecast_mount mount -> mount | _ -> raise (Error Invalid_usage) in Hashtbl.replace headers "Authorization" (get_auth user password); add_host_header headers 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 transport request; (* Read input from socket. *) let ret = read_data ~timeout transport 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 -> begin try close () with _ -> () end; raise e 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 connection_timeout = c.connection_timeout in manual_update_metadata ~host ~port ~protocol ~user ~password ~timeout ~mount ?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.transport x ) end else write_data ~offset ~length ~timeout:c.timeout d.transport x ocaml-cry-0.6.5/src/cry.mli000066400000000000000000000174221363751203300155100ustar00rootroot00000000000000(* * 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 operation = [ `Read | `Write | `Both ] type transport = { write : Bytes.t -> int -> int -> int; read : Bytes.t -> int -> int -> int; wait_for : operation -> float -> bool; close : unit -> unit; } (** 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 (** Optional ssl module *) (** Register a transport module to be used for SSL connections. *) val register_https : (?timeout:float -> ?bind:string -> host:string -> Unix.sockaddr -> transport) -> unit (** 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. * [Https] is the icecast2 source protocol with TLS connection. * * 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 | Https 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; transport : transport } (** 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:string -> ?connection_timeout:float -> ?timeout:float -> 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:string -> ?charset:string -> 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-0.6.5/src/cry_common.ml000066400000000000000000000025421363751203300167040ustar00rootroot00000000000000(* * 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. *) 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 operation = [ `Read | `Write | `Both ] type transport = { write : Bytes.t -> int -> int -> int; read : Bytes.t -> int -> int -> int; wait_for : operation -> float -> bool; close : unit -> unit; } ocaml-cry-0.6.5/src/cry_https.noop.ml000066400000000000000000000000241363751203300175210ustar00rootroot00000000000000let register _ = () ocaml-cry-0.6.5/src/cry_https.osx_secure_transport.ml000066400000000000000000000062511363751203300230510ustar00rootroot00000000000000(* * 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 *) open Cry_common let register fn = let connect_ssl ?timeout ?bind ~host sockaddr = let domain = match sockaddr with | Unix.ADDR_UNIX _ -> Unix.PF_UNIX | Unix.ADDR_INET (_, _) -> Unix.PF_INET in let sock = Unix.socket domain Unix.SOCK_STREAM 0 in let do_timeout = timeout <> None in let check_timeout () = match timeout with | Some timeout -> (* Block in a select call for [timeout] seconds. *) let _, w, _ = Unix.select [] [sock] [] timeout in if w = [] then raise (Error (Connect Timeout)); Unix.clear_nonblock sock | None -> assert false in begin try if do_timeout then Unix.set_nonblock sock; Unix.connect sock sockaddr; if do_timeout then Unix.clear_nonblock sock with | Unix.Unix_error (Unix.EINPROGRESS, _, _) -> check_timeout () | Unix.Unix_error (Unix.EWOULDBLOCK, _, _) when Sys.os_type = "Win32" -> check_timeout () | exn -> begin try Unix.close sock with _ -> () end; raise exn end; begin match bind with | None -> () | Some s -> ( try let bind_addr_inet = (Unix.gethostbyname s).Unix.h_addr_list.(0) in (* Seems like you need to bind on port 0 *) let bind_addr = Unix.ADDR_INET (bind_addr_inet, 0) in Unix.bind sock bind_addr with exn -> begin try Unix.close sock with _ -> () end; raise exn ) end; let ctx = SecureTransport.init SecureTransport.Client SecureTransport.Stream in SecureTransport.set_connection ctx sock; SecureTransport.set_peer_domain_name ctx host; SecureTransport.handshake ctx; let close () = SecureTransport.close ctx; Unix.close sock in let wait_for operation delay = let events () = match operation with | `Read -> Unix.select [sock] [] [] delay | `Write -> Unix.select [] [sock] [] delay | `Both -> Unix.select [sock] [sock] [] delay in let r, w, _ = events () in match operation with | `Read -> r <> [] | `Write -> w <> [] | `Both -> r <> [] || w <> [] in { write = SecureTransport.write ctx; read = SecureTransport.read ctx; wait_for; close; } in fn connect_ssl ocaml-cry-0.6.5/src/cry_https.ssl.ml000066400000000000000000000046531363751203300173630ustar00rootroot00000000000000(* * 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 *) open Cry_common let () = Ssl_threads.init (); Ssl.init () let register fn = let connect_ssl ?timeout:_ ?bind ~host:_ socketaddr = let ctx = Ssl.create_context Ssl.SSLv23 Ssl.Client_context in (* SSL_VERIFY_NONE is default in shout. TODO: add option.. *) Ssl.set_verify ctx [] (Some Ssl.client_verify_callback); Ssl.set_verify_depth ctx 3; ignore (Ssl.set_default_verify_paths ctx); let ssl = Ssl.open_connection_with_context ctx socketaddr in let shutdown () = Ssl.shutdown ssl; Unix.close (Ssl.file_descr_of_socket ssl) in begin try match bind with | None -> () | Some s -> let socket = Ssl.file_descr_of_socket ssl in let bind_addr_inet = (Unix.gethostbyname s).Unix.h_addr_list.(0) in (* Seems like you need to bind on port 0 *) let bind_addr = Unix.ADDR_INET (bind_addr_inet, 0) in Unix.bind socket bind_addr with e -> begin try shutdown () with _ -> () end; raise e end; let wait_for operation delay = let socket = Ssl.file_descr_of_socket ssl in let events () = match operation with | `Read -> Unix.select [socket] [] [] delay | `Write -> Unix.select [] [socket] [] delay | `Both -> Unix.select [socket] [socket] [] delay in let r, w, _ = events () in match operation with | `Read -> r <> [] | `Write -> w <> [] | `Both -> r <> [] || w <> [] in { write = Ssl.write ssl; read = Ssl.read ssl; wait_for; close = shutdown } in fn connect_ssl ocaml-cry-0.6.5/src/dune000066400000000000000000000004611363751203300150610ustar00rootroot00000000000000(library (name cry) (public_name cry) (libraries bytes unix (select cry_https.ml from (ssl -> cry_https.ssl.ml) (osx-secure-transport -> cry_https.osx_secure_transport.ml) (-> cry_https.noop.ml))) (synopsis "OCaml client for the various icecast & shoutcast source protocols"))