12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273(*
* Copyright (c) 2015-2022 Christiano F. Haesbaert <haesbaert@haesbaert.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)[@@@warning"-32-37"]openLwt.Infixtypet={fd:Lwt_unix.file_descr;packets:Cstruct.tlistref;buffer:Cstruct.t;}typedriver=|AF_PACKET|BPFexternalopensock:?filter:string->?promisc:bool->string->Unix.file_descr="caml_rawlink_open"externaldhcp_server_filter:unit->string="caml_dhcp_server_filter"externaldhcp_client_filter:unit->string="caml_dhcp_client_filter"externaldriver:unit->driver="caml_driver"externalbpf_align:int->int->int="caml_bpf_align"letopen_link?filter?(promisc=false)ifname=letfd=Lwt_unix.of_unix_file_descr(opensock?filter:filter~promiscifname)inlet()=Lwt_unix.set_blockingfdfalsein{fd;packets=ref[];buffer=(Cstruct.create65536)}letclose_linkt=Lwt_unix.closet.fdletrecread_packett=match!(t.packets)with|hd::tl->t.packets:=tl;Lwt.returnhd|[]->matchdriver()with|BPF->Lwt_bytes.readt.fdt.buffer.Cstruct.buffer0t.buffer.Cstruct.len>>=(funn->ifn=0thenfailwith"Link socket closed";t.packets:=Rawlink.bpf_split_buffert.buffern;read_packett)|AF_PACKET->Lwt_bytes.readt.fdt.buffer.Cstruct.buffer0t.buffer.Cstruct.len>>=(funn->ifn=0thenfailwith"Link socket closed";letbuf=Cstruct.createninCstruct.blitt.buffer0buf0n;Lwt.returnbuf)letsend_packettbuf=letlen=Cstruct.lengthbufinLwt_bytes.writet.fdbuf.Cstruct.buffer0len>>=(funn->ifn=0thenLwt.fail(Unix.Unix_error(Unix.EPIPE,"send_packet: socket closed",""))elseifn<>lenthenLwt.fail(Unix.Unix_error(Unix.ENOBUFS,"send_packet: short write",""))elseLwt.return_unit)