123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146(*
* Copyright (c) 2010-2015 Anil Madhavapeddy <anil@recoil.org>
* Copyright (C) 2015 Thomas Gazagnaire <thomas@gazagnaire.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.
*)openLwt.Infixletsrc=Logs.Src.create"netif"~doc:"Mirage unix network module"moduleLog=(valLogs.src_logsrc:Logs.LOG)typet={id:string;dev:Lwt_unix.file_descr;mutableactive:bool;mac:Macaddr.t;mtu:int;stats:Mirage_net.stats;}letfdt=t.devtypeerror=[|Mirage_net.Net.error|`Partialofstring*int*Cstruct.t|`Exnofexn]letpp_errorppf=function|#Mirage_net.Net.errorase->Mirage_net.Net.pp_errorppfe|`Partial(id,len',buffer)->Fmt.pfppf"netif %s: partial write (%d, expected %d)"idlen'buffer.Cstruct.len|`Exne->Fmt.exnppfeleterr_permission_denieddevname=Printf.sprintf"Permission denied while opening the %s device. Please re-run using sudo."devnameletconnectdevname=tryRandom.self_init();letfd,devname=Tuntap.opentap~pi:false~devname()inletdev=Lwt_unix.of_unix_file_descr~blocking:truefdinletmac=Macaddr.make_local(fun_->Random.int256)inTuntap.set_up_and_runningdevname;letmtu=Tuntap.get_mtudevnameinLog.debug(funm->m"plugging into %s with mac %a and mtu %d"devnameMacaddr.ppmacmtu);letactive=trueinletstats=Mirage_net.Stats.create()inlett={id=devname;dev;active;mac;mtu;stats}inLog.info(funm->m"connect %s with mac %a"devnameMacaddr.ppmac);Lwt.returntwith|Failure"tun[open]: Permission denied"[@warning"-52"]->Lwt.fail_with(err_permission_denieddevname)|exn->Lwt.failexnletdisconnectt=Log.info(funm->m"disconnect %s"t.id);t.active<-false;Lwt_unix.closet.dev>>=fun()->Tuntap.closetapt.id;Lwt.return_unit(* Input a frame, and block if nothing is available *)letrecreadtbuf=letprocess()=Lwt.catch(fun()->Lwt_cstruct.readt.devbuf>|=function|(-1)->Error`Continue(* EAGAIN or EWOULDBLOCK *)|0->Error`Disconnected(* EOF *)|len->Mirage_net.Stats.rxt.stats(Int64.of_intlen);letbuf=Cstruct.subbuf0leninOkbuf)(function|Unix.Unix_error(Unix.ENXIO,_,_)->Log.err(funm->m"[read] device %s is down, stopping"t.id);Lwt.return(Error`Disconnected)|Lwt.Canceled->Log.err(funm->m"[read] user program requested cancellation of listen on %s"t.id);Lwt.return(Error`Canceled)|exn->Log.err(funm->m"[read] error: %s, continuing"(Printexc.to_stringexn));Lwt.return(Error`Continue))inprocess()>>=function|Error`Continue->readtbuf|Error`Canceled->Lwt.return(Error`Canceled)|Error`Disconnected->Lwt.return(Error`Disconnected)|Okbuf->Lwt.return(Okbuf)(* Loop and listen for packets permanently *)(* this function has to be tail recursive, since it is called at the
top level, otherwise memory of received packets and all reachable
data is never claimed. take care when modifying, here be dragons! *)letreclistent~header_sizefn=matcht.activewith|true->letbuf=Cstruct.create(t.mtu+header_size)inletprocess()=readtbuf>|=function|Okbuf->Lwt.async(fun()->fnbuf);Ok()|Error`Canceled->Error`Disconnected|Error`Disconnected->t.active<-false;Error`Disconnectedinprocess()>>=(function|Ok()->(listen[@tailcall])t~header_sizefn|Errore->Lwt.return(Errore))|false->Lwt.return(Ok())(* Transmit a packet from a Cstruct.t *)letwritet~sizefillf=(* This is the interface to the cruel Lwt world with exceptions, we've to guard *)letbuf=Cstruct.createsizeinletlen=fillfbufiniflen>sizethenLwt.return(Error`Invalid_length)elseLwt.catch(fun()->Lwt_bytes.writet.devbuf.Cstruct.buffer0len>|=funlen'->Mirage_net.Stats.txt.stats(Int64.of_intlen);iflen'<>lenthenError(`Partial(t.id,len',buf))elseOk())(funexn->Lwt.return(Error(`Exnexn)))letmact=t.macletmtut=t.mtuletget_stats_counterst=t.statsletreset_stats_counterst=Mirage_net.Stats.resett.stats