123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)(* logging facility to monitor sockets *)moduleEvents=P2p_events.P2p_fd(* This error is not declared in P2p_errors module of lib_p2p_services because
Unix.error_encoding is part of lib_stdlib_unix that cannot be added easily
as a dependency of lib_p2p_services. *)typelistening_socket_open_failure={reason:Unix.error;address:P2p_addr.t;port:int;}typeerror+=Failed_to_open_listening_socketoflistening_socket_open_failurelet()=register_error_kind`Permanent~id:"p2p.welcome.failed_to_open_listening_socket"~title:"Failed to open listening socket"~description:"The p2p listening socket could not be opened."~pp:(funppf(reason,address,port)->lettipsppf()=matchreasonwith|Unix.EADDRINUSE->Format.fprintfppf"Another tezos node is probably running on this address.@;\
Please choose another P2P port using --net-addr."|_->Format.fprintfppf""inFormat.fprintfppf"@[<v 2>An error occured while initializing P2P server on this \
address: %a:%d.@;\
Reason: %s.@;\
%a@]"P2p_addr.ppaddressport(Unix.error_messagereason)tips())Data_encoding.(obj3(req"reason"Unix_error.encoding)(req"address"P2p_addr.encoding)(req"port"uint16))(function|Failed_to_open_listening_socket{reason;address;port}->Some(reason,address,port)|_->None)(fun(reason,address,port)->Failed_to_open_listening_socket{reason;address;port})letis_not_windows=Sys.os_type<>"Win32"let()=(* Otherwise some writes trigger a SIGPIPE instead of raising an
Lwt_unit exception. In the node, this is already done by
Cohttp, so this is only useful when using the P2P layer as a
stand alone library. *)ifis_not_windowsthenSys.(set_signalsigpipeSignal_ignore)typeunexpected_error=[`Unexpected_errorofexn]typeread_write_error=[`Connection_closed_by_peer|`Connection_lostofexn|`Connection_locally_closed|unexpected_error]typeconnect_error=[`Connection_failed|unexpected_error]typeaccept_error=[`System_errorofexn|`Socket_errorofexn|unexpected_error]typet={fd:Lwt_unix.file_descr;id:int;mutablepoint:P2p_point.Id.toption;mutablepeer_id:P2p_peer.Id.toption;mutablenread:int;mutablenwrit:int;mutableclosing_reasons:P2p_disconnection_reason.tlist;}letset_point~pointt=t.point<-Somepointletset_peer_id~peer_idt=t.peer_id<-Somepeer_idletadd_closing_reason~reasont=t.closing_reasons<-reason::t.closing_reasonsletpp_read_write_errorfmt=function|`Connection_closed_by_peer->Format.fprintffmt"connection closed by peer"|`Connection_lostex->Format.fprintffmt"connection to peer was lost with exception %s"(Printexc.to_stringex)|`Connection_locally_closed->Format.fprintffmt"connection closed by us"|`Unexpected_errorex->Format.fprintffmt"connection closed because of an unexpected error %s"(Printexc.to_stringex)letcreate=letcounter=ref0infunfd->letopenLwt_syntaxinincrcounter;lett={fd;id=!counter;point=None;peer_id=None;nread=0;nwrit=0;closing_reasons=[];}inlet*()=Events.(emitcreate_fd)t.idinreturntletstring_of_sockaddraddr=matchaddrwith|Lwt_unix.ADDR_INET(ip,port)->Printf.sprintf"%s:%d"(Unix.string_of_inet_addrip)port|Lwt_unix.ADDR_UNIXfile->Printf.sprintf"@%s"fileletidt=t.idletraw_socket()=Lwt_unix.socket~cloexec:truePF_INET6SOCK_STREAM0letsocket()=create(raw_socket())letcreate_listening_socket?(reuse_port=false)~backlog?(addr=Ipaddr.V6.unspecified)port=letopenLwt_result_syntaxinLwt.catch(fun()->letsock=raw_socket()in(ifreuse_portthenLwt_unix.(setsockoptsockSO_REUSEPORTtrue));Lwt_unix.(setsockoptsockSO_REUSEADDRtrue);let*!()=Lwt_unix.bindsockUnix.(ADDR_INET(Ipaddr_unix.V6.to_inet_addraddr,port))inLwt_unix.listensockbacklog;returnsock)(function|Unix.Unix_error(err,_,_)->tzfail(Failed_to_open_listening_socket{reason=err;address=addr;port})|exn->Lwt.reraiseexn)letclose?reasont=letopenLwt_syntaxinOption.iter(funreason->add_closing_reason~reasont)reason;let*()=Events.(emitclose_fd)(t.id,t.closing_reasons,t.nread,t.nwrit)inlet*()=matcht.closing_reasonswith|[]->Events.(emitclose_fd_unknown_reason)(t.point,t.peer_id)|_->Events.(emitclose_fd_reason)(t.point,t.peer_id,t.closing_reasons)inLwt.catch(fun()->(* Guarantee idempotency. *)ifLwt_unix.statet.fd=Closedthenreturn_unitelseLwt_unix.closet.fd)(function(* From [man 2 close] [close] can fail with [EBADF, EINTR, EIO, ENOSPC,
EDQUOT] Unix errors.
Retrying the [Unix.close] after a failure return is the wrong thing to
do.
[EDQUOT] is not defined in [Unix.error] type.*)|(Unix.Unix_error((EBADF|EIO|ENOSPC),_,_)(* [EINTR] error is a somewhat special case. [Unix.close] should or
should not be called again, depending on the system.
- Retrying [Unix.close] could lead to close a file descriptor that has
been reused and may lead to unpredictable consequences.
- Not retrying [Unix.close] in some Unix implementation (not Linux),
could lead to leak the file descriptor.
Therefore, not retrying [Unix.close] may be safer. *)(* TODO: https://gitlab.com/tezos/tezos/-/issues/5633
Handle the [EINTR] case by system. *)|Unix.Unix_error(EINTR,_,_))aserr->let*()=Events.(emitclose_fd_error)(t.id,Printexc.to_stringerr)inreturn_unit(* Other possible exceptions can come from [Lwt] lifecycle. These exceptions
are rather meant to be fatal, so we let them raise to top level. *)|ex->raiseex)letread_write_error_handler~rwt=letopenLwt_syntaxinfunction(* from Lwt_unix *)|Unix.Unix_error(EBADF,_,_)whenLwt_unix.statet.fd=Closed->Lwt.return_error`Connection_locally_closed(* from [man 7 tcp], [man 3 read], [man 3 write] *)|(Unix.Unix_error(ETIMEDOUT,_,_)|End_of_file)ase->let*()=close~reason:(Connection_lostrw)tinLwt.return_error(`Connection_loste)|Unix.Unix_error((ECONNRESET|EPIPE),_,_)->let*()=close~reason:(Connection_closed_by_peerrw)tinLwt.return_error`Connection_closed_by_peer|ex->let*()=close~reason:(Connection_closed_by_unexpected_error(rw,Printexc.to_stringex))tinLwt.return_error(`Unexpected_errorex)letreadtbufposlen=letopenLwt_result_syntaxinlet*!()=Events.(emittry_read)(t.id,len)inlet*nread=Lwt.catch(fun()->ifLwt_unix.statet.fd=ClosedthenLwt.return_error`Connection_locally_closedelselet*!nread=Lwt_unix.readt.fdbufposleninreturnnread)(read_write_error_handler~rw:Readt)int.nread<-t.nread+nread;let*!()=Events.(emitread_fd)(t.id,nread,t.nread)inifnread=0thenLwt.return_error`Connection_closed_by_peerelsereturnnreadletwritetbuf=letopenLwt_result_syntaxinletlen=Bytes.lengthbufinlet*!()=Events.(emittry_write)(t.id,len)inlet*()=Lwt.catch(fun()->ifLwt_unix.statet.fd=ClosedthenLwt.return_error`Connection_locally_closedelselet*!()=Lwt_utils_unix.write_bytest.fdbufinreturn_unit)(read_write_error_handler~rw:Writet)int.nwrit<-t.nwrit+len;let*!()=Events.(emitwritten_fd)(t.id,len,t.nwrit)inreturn_unitletconnecttsaddr=letopenLwt_result_syntaxinlet*!()=Events.(emitconnect_fd)(t.id,string_of_sockaddrsaddr)inLwt.catch(fun()->Lwt_unix.connectt.fdsaddr|>Lwt.mapResult.ok)(function|Unix.Unix_error(Unix.ECONNREFUSED,_,_)->let*!()=close~reason:TCP_connection_refusedtinLwt.return_error`Connection_failed|Unix.Unix_error(Unix.EHOSTUNREACH,_,_)->let*!()=close~reason:TCP_connection_unreachabletinLwt.return_error`Connection_failed|Lwt.Canceled->let*!()=close~reason:TCP_connection_canceledtinLwt.return_error`Connection_failed|ex->let*!()=close~reason:(TCP_connection_failed_unexpected_error(Printexc.to_stringex))tinLwt.return_error(`Unexpected_errorex))letacceptlistening_socket=letopenLwt_result_syntaxinlet*fd,saddr=Lwt.catch(fun()->Lwt_unix.accept~cloexec:truelistening_socket|>Lwt.mapResult.ok)(function(* Unix errors related to the failure to create one connection,
No reason to abort just now, but we want to stress out that we
have a problem preventing us from accepting new connections. *)|Unix.Unix_error((EMFILE(* Too many open files by the process *)|ENFILE(* Too many open files in the system *)|ENETDOWN(* Network is down *)),_,_)ase->Lwt.return_error@@`System_errore(* These are socket-specific errors. Ignoring. *)|Unix.Unix_error((EAGAIN(* Resource temporarily unavailable; try again *)|EWOULDBLOCK(* Operation would block *)|ENOPROTOOPT(* Protocol not available *)|EOPNOTSUPP(* Operation not supported on socket *)|ENETUNREACH(* Network is unreachable *)|ECONNABORTED(* Software caused connection abort *)|ECONNRESET(* Connection reset by peer *)|ETIMEDOUT(* Connection timed out *)|EHOSTDOWN(* Host is down *)|EHOSTUNREACH(* No route to host *)(* Ugly hack to catch EPROTO and ENONET, Protocol error, which
are not defined in the Unix module (which is 20 years late on
the POSIX standard). A better solution is to use the package
ocaml-unix-errno or redo the work *)|EUNKNOWNERR(71|64)(* On Linux EPROTO is 71, ENONET is 64 On BSD systems, accept
cannot raise EPROTO. 71 is EREMOTE for openBSD, NetBSD,
Darwin, which is irrelevant here 64 is EHOSTDOWN for openBSD,
NetBSD, Darwin, which is already caught *)),_,_)ase->Lwt.return_error@@`Socket_errore|ex->Lwt.return_error@@`Unexpected_errorex)inlet*!t=createfdinlet*!()=Events.(emitaccept_fd)(t.id,string_of_sockaddrsaddr)inreturn(t,saddr)moduleTable=Hashtbl.Make(structtypenonrect=tletequal{id=x;_}{id=y;_}=x=ylethash{id;_}=Hashtbl.hashidend)