diff --git a/embuilder.py b/embuilder.py index a25afb47e9ad0..0f9b5b02d8273 100755 --- a/embuilder.py +++ b/embuilder.py @@ -35,6 +35,7 @@ build libc libc-mt libc-extras + libc-sockets struct_info emmalloc emmalloc_debug @@ -47,6 +48,7 @@ dlmalloc_threadsafe_noerrno dlmalloc_threadsafe_debug_noerrno pthreads + posix_proxy libc++ libc++_noexcept libc++abi @@ -110,11 +112,11 @@ SYSTEM_TASKS = [ 'al', 'compiler-rt', 'gl', 'gl-mt', 'libc', 'libc-mt', 'libc-extras', - 'emmalloc', 'emmalloc_debug', 'dlmalloc', 'dlmalloc_threadsafe', 'pthreads', - 'dlmalloc_debug', 'dlmalloc_threadsafe_debug', 'libc++', 'libc++_noexcept', + 'libc-sockets', 'emmalloc', 'emmalloc_debug', 'dlmalloc', + 'dlmalloc_threadsafe', 'pthreads', 'posix_proxy', 'dlmalloc_debug', + 'dlmalloc_threadsafe_debug', 'libc++', 'libc++_noexcept', 'dlmalloc_debug_noerrno', 'dlmalloc_threadsafe_debug_noerrno', - 'dlmalloc_noerrno', 'dlmalloc_threadsafe_noerrno', - 'libc++abi', 'html5' + 'dlmalloc_noerrno', 'dlmalloc_threadsafe_noerrno', 'libc++abi', 'html5' ] USER_TASKS = [ 'binaryen', 'bullet', 'freetype', 'icu', 'libpng', 'ogg', 'sdl2', @@ -303,6 +305,20 @@ def main(): build_port('cocos2d', None, ['-s', 'USE_COCOS2D=3', '-s', 'USE_ZLIB=1', '-s', 'USE_LIBPNG=1', '-s', 'ERROR_ON_UNDEFINED_SYMBOLS=0']) elif what == 'regal': build_port('regal', 'libregal.bc', ['-s', 'USE_REGAL=1']) + elif what == 'libc-sockets': + build(''' + #include + int main() { + return socket(0,0,0); + } + ''', ['libc-sockets.bc']) + elif what == 'posix_proxy': + build(''' + #include + int main() { + return socket(0,0,0); + } + ''', ['libposix-sockets-proxy.bc'], ['-s', 'PROXY_POSIX_SOCKETS=1', '-s', 'USE_PTHREADS=1', '-s', 'PROXY_TO_PTHREAD=1']) else: logger.error('unfamiliar build target: ' + what) sys.exit(1) diff --git a/site/source/docs/porting/index.rst b/site/source/docs/porting/index.rst index f9538de78d977..1a2d7e2adde8f 100644 --- a/site/source/docs/porting/index.rst +++ b/site/source/docs/porting/index.rst @@ -17,6 +17,7 @@ The topics in this section cover the main integration points that you need to co Audio Debugging pthreads + networking simd asyncify emterpreter diff --git a/site/source/docs/porting/networking.rst b/site/source/docs/porting/networking.rst new file mode 100644 index 0000000000000..cd4ab6351f1e6 --- /dev/null +++ b/site/source/docs/porting/networking.rst @@ -0,0 +1,38 @@ +.. Networking: + +============================== +Networking +============================== + +Emscripten compiled applications have a number of ways to connect with online servers. Check the subtopics here to learn about the different strategies that are available. + +If you are familiar with networking concepts provided by different web APIs, such as XmlHttpRequest, Fetch, WebSockets and WebRTC, you can quickly get started by leveraging what you already know: by calling out from C/C++ code to JavaScript (see the "Connecting C++ and JavaScript" section), you can establish networked connections by writing regular JavaScript. For C/C++ developers, Emscripten provides a few approaches, described here. + +Emscripten WebSockets API +========================= + +WebSockets API provides connection-oriented message-framed bidirectional asynchronous networking communication to the browser. It is the closest to TCP on the web that web sites can access, direct access to TCP sockets is not possible from web browsers. + +Emscripten provides a passthrough API for accessing the WebSockets API from C/C++ code. This is useful for developers who would prefer not to write any JavaScript code, or deal with the C/C++ and JavaScript language interop. See the system include file for details. One benefit that the Emscripten WebSockets API provides over manual WebSockets access in JavaScript is the ability to share access to a WebSocket handle across multiple threads, something that can be time consuming to develop from scratch. + +Emulated POSIX TCP Sockets over WebSockets +========================================== + +If you have existing TCP networking code written in C/C++ that utilizes the Posix Sockets API, by default Emscripten attempts to emulate such connections to take place over the WebSocket protocol instead. For this to work, you will need to use something like WebSockify on the server side to enable the TCP server stack to receive incoming WebSocket connections. This emulation is not very complete at the moment, it is likely that you will run into problems out of the box and need to adapt the code to work within the limitations that this emulation provides. + +Full POSIX Sockets over WebSocket Proxy Server +============================================== + +Emscripten provides a native POSIX Sockets proxy server program, located in directory tools/websocket_to_posix_proxy/, that allows full POSIX Sockets API access from a web browser. This support works by proxying all POSIX Sockets API calls from the browser to the Emscripten POSIX Sockets proxy server (via transparent use of WebSockets API), and the proxy server then performs the native TCP/UDP calls on behalf of the page. This allows a web browser page to run full TCP & UDP connections, act as a server to accept incoming connections, and perform host name lookups and reverse lookups. Because all API calls are individually proxied, this support can be slow. This support is mostly useful for developing testing infrastructure and debugging. + +For an example of how the POSIX Sockets proxy server works in an Emscripten client program, see the file tests/websocket/tcp_echo_client.cpp. + +XmlHttpRequests and Fetch API +============================= + +For HTTP transfers, one can use the browser built-in XmlHttpRequest (XHR) API and the newer Fetch API. These can be accessed directly from JavaScript. Emscripten also provides passthrough APIs to perform HTTP requests. For more information, see the emscripten_async_wget*() C API and the Emscripten Fetch API. + +WebRTC and UDP +============== + +Direct UDP communication is not available in browsers, but as a close alternative, the WebRTC specification provides a mechanism to perform UDP-like communication with WebRTC Data Channels. Currently Emscripten does not provide a C/C++ API for interacting with WebRTC. diff --git a/src/library.js b/src/library.js index 7965cb00c5baa..0294bc1f6e1ad 100644 --- a/src/library.js +++ b/src/library.js @@ -3459,6 +3459,7 @@ LibraryManager.library = { // arpa/inet.h // ========================================================================== +#if PROXY_POSIX_SOCKETS == 0 // old ipv4 only functions inet_addr__deps: ['_inet_pton4_raw'], inet_addr: function(ptr) { @@ -4201,6 +4202,8 @@ LibraryManager.library = { 0x0b00000a, 0x0c00000a, 0x0d00000a, 0x0e00000a] /* 0x0100000a is reserved */ }, +#endif // PROXY_POSIX_SOCKETS == 0 + // pwd.h getpwnam: function() { throw 'getpwnam: TODO' }, diff --git a/src/library_syscall.js b/src/library_syscall.js index 5f8fb5ed7a633..0bcc2335412d2 100644 --- a/src/library_syscall.js +++ b/src/library_syscall.js @@ -476,6 +476,7 @@ var SyscallsLibrary = { __syscall97: function(which, varargs) { // setpriority return -ERRNO_CODES.EPERM; }, +#if PROXY_POSIX_SOCKETS == 0 __syscall102__deps: ['$SOCKFS', '$DNS', '_read_sockaddr', '_write_sockaddr'], __syscall102: function(which, varargs) { // socketcall var call = SYSCALLS.get(), socketvararg = SYSCALLS.get(); @@ -654,6 +655,7 @@ var SyscallsLibrary = { default: abort('unsupported socketcall syscall ' + call); } }, +#endif // ~PROXY_POSIX_SOCKETS==0 __syscall104: function(which, varargs) { // setitimer return -ERRNO_CODES.ENOSYS; // unsupported feature }, diff --git a/src/library_websocket.js b/src/library_websocket.js index 91e4e0d8e81d6..c9c4fbbbe7e4a 100644 --- a/src/library_websocket.js +++ b/src/library_websocket.js @@ -109,6 +109,7 @@ var LibraryWebSocket = { #endif return {{{ cDefine('EMSCRIPTEN_RESULT_INVALID_TARGET') }}}; } + HEAPU32[urlLength>>2] = lengthBytesUTF8(socket.url); return {{{ cDefine('EMSCRIPTEN_RESULT_SUCCESS') }}}; }, diff --git a/src/settings.js b/src/settings.js index de832f31b3a0e..f42ca45701525 100644 --- a/src/settings.js +++ b/src/settings.js @@ -364,6 +364,9 @@ var SOCKET_WEBRTC = 0; // where addr and port are derived from the socket connect/bind/accept calls. var WEBSOCKET_URL = 'ws://'; +// If 1, the POSIX sockets API uses a proxy bridge to proxy sockets calls +var PROXY_POSIX_SOCKETS = 0; + // A string containing a comma separated list of WebSocket subprotocols // as would be present in the Sec-WebSocket-Protocol header. var WEBSOCKET_SUBPROTOCOL = 'binary'; diff --git a/system/include/emscripten/posix_socket.h b/system/include/emscripten/posix_socket.h new file mode 100644 index 0000000000000..c07c7999213ab --- /dev/null +++ b/system/include/emscripten/posix_socket.h @@ -0,0 +1,13 @@ +#pragma once + +#include "websocket.h" + +#ifdef __cplusplus +extern "C" { +#endif + +extern EMSCRIPTEN_RESULT emscripten_init_websocket_to_posix_socket_bridge(const char *bridgeUrl); + +#ifdef __cplusplus +} +#endif diff --git a/system/lib/libc-sockets.symbols b/system/lib/libc-sockets.symbols new file mode 100644 index 0000000000000..9f495e01005db --- /dev/null +++ b/system/lib/libc-sockets.symbols @@ -0,0 +1,23 @@ + U __errno_location + U __syscall102 + U __syscall221 + U __syscall_ret +-------- T accept +-------- T bind +-------- T connect + U free +-------- T freeaddrinfo +-------- T getpeername +-------- T getsockname +-------- T getsockopt +-------- T listen +-------- T recv +-------- T recvfrom +-------- T recvmsg +-------- T send +-------- T sendmsg +-------- T sendto +-------- T setsockopt +-------- T shutdown +-------- T socket +-------- T socketpair diff --git a/system/lib/libc.symbols b/system/lib/libc.symbols index 3d9d7c2cecad3..e9cb63f4aae68 100644 --- a/system/lib/libc.symbols +++ b/system/lib/libc.symbols @@ -1,263 +1,488 @@ --------- C h_errno --------- C __hwcap --------- C __libc --------- C optarg --------- C optopt --------- C __optpos --------- C __sysinfo --------- d ascii64 --------- d b64 --------- d b64.802 --------- d b64.812 -------- d BF_atoi64 +-------- t BF_crypt -------- d BF_crypt.flags_by_subtype +-------- t BF_decode +-------- t BF_encode +-------- t BF_encrypt -------- d BF_init_state -------- d BF_itoa64 -------- d BF_magic_w --------- d big5 --------- d bindings --------- d bindtextdomain.lock --------- d buf --------- d buf.462 --------- d buf.582 --------- d buf.598 --------- d c16rtomb.internal_state --------- d casemaps --------- d catlens --------- d catnames +-------- t BF_set_key +-------- t BF_swap +-------- d K +-------- d K.65 +-------- d PIo2 +-------- t S +-------- d Sden +-------- d Snum +-------- W _IO_feof_unlocked +-------- W _IO_ferror_unlocked +-------- W _IO_getc +-------- W _IO_getc_unlocked +-------- W _IO_putc +-------- W _IO_putc_unlocked +-------- t __DOUBLE_BITS +-------- t __DOUBLE_BITS.19 +-------- t __DOUBLE_BITS.25 +-------- t __DOUBLE_BITS.261 +-------- t __DOUBLE_BITS.264 +-------- t __DOUBLE_BITS.266 +-------- t __DOUBLE_BITS.268 +-------- t __DOUBLE_BITS.269 +-------- t __DOUBLE_BITS.271 +-------- t __DOUBLE_BITS.273 +-------- t __DOUBLE_BITS.325 +-------- t __DOUBLE_BITS.327 +-------- t __DOUBLE_BITS.334 +-------- t __DOUBLE_BITS.337 +-------- t __DOUBLE_BITS.340 +-------- t __DOUBLE_BITS.348 +-------- t __DOUBLE_BITS.648 +-------- t __FLOAT_BITS +-------- t __FLOAT_BITS.22 +-------- t __FLOAT_BITS.265 +-------- t __FLOAT_BITS.267 +-------- t __FLOAT_BITS.270 +-------- t __FLOAT_BITS.272 +-------- t __FLOAT_BITS.274 +-------- t __FLOAT_BITS.28 +-------- t __FLOAT_BITS.326 +-------- t __FLOAT_BITS.335 +-------- t __FLOAT_BITS.336 +-------- t __FLOAT_BITS.343 +-------- t __FLOAT_BITS.349 +-------- W __aio_close +-------- t __bswap_16 +-------- t __bswap_16.484 +-------- t __bswap_32 +-------- t __bswap_32.483 -------- D __c_dot_utf8 -------- D __c_dot_utf8_locale --------- d charmaps -------- D __c_locale --------- d c_messages --------- d c_numeric --------- d comp_maskl0 --------- d comp_maskl1 --------- d comp_maskr0 --------- d comp_maskr1 + U __clock_gettime +-------- T __cos +-------- T __cosdf +-------- T __crypt_blowfish -------- d __crypt_blowfish.test_hash --------- d crypt.buf +-------- T __crypt_des +-------- T __crypt_md5 -------- d __crypt_md5.testhash -------- d __crypt_md5.testkey -------- d __crypt_md5.testsetting +-------- T __crypt_r +-------- T __crypt_sha256 -------- d __crypt_sha256.testhash -------- d __crypt_sha256.testkey -------- d __crypt_sha256.testsetting +-------- T __crypt_sha512 -------- d __crypt_sha512.testhash -------- d __crypt_sha512.testkey -------- d __crypt_sha512.testsetting --------- d c_time --------- d current_domain --------- d dcngettext.cats --------- d decfloat.p10s --------- d decfloat.th --------- d defpolicy --------- d digits +-------- T __ctype_b_loc +-------- T __ctype_get_mb_cur_max +-------- T __ctype_tolower_loc +-------- T __ctype_toupper_loc +-------- T __des_setkey +-------- T __dn_comp +-------- T __dn_expand +-------- T __dns_count_addrs -------- d __dns_count_addrs.p --------- d dummy --------- d dummy_file --------- d ecvt.buf --------- d empty_mo +-------- T __dns_doqueries +-------- T __dns_get_rr +-------- T __dns_parse +-------- T __dns_query +-------- T __do_des +-------- T __do_orphaned_stdio_locks +-------- T __dup3 +-------- T __duplocale +-------- T __emscripten_pthread_data_constructor -------- d __encrypt_key --------- d envvars --------- d errid --------- d errmsg +-------- T __errno_location -------- d __errno_storage --------- d errors --------- d ether_aton.a --------- d ether_ntoa.x --------- d evalbinop.prec --------- d exp10f.p10 --------- d exp10.p10 --------- d exp2ft --------- d f --------- d f.581 --------- d f.597 --------- d fact --------- d fmtmsg.msgs --------- d fp_maskl +-------- T __expo2 +-------- T __expo2f +-------- T __fbufsize +-------- T __fclose_ca +-------- T __fdopen +-------- T __fesetround +-------- t __fflush_unlocked +-------- T __fgetwc_unlocked +-------- t __fgetwc_unlocked_internal +-------- T __flbf +-------- T __floatscan +-------- T __flt_rounds +-------- T __fmodeflags +-------- T __fopen_rb_ca +-------- T __fpclassify +-------- T __fpclassifyf +-------- T __fpclassifyl +-------- T __fpending +-------- T __fpurge +-------- T __fputwc_unlocked +-------- T __freadable +-------- T __freadahead +-------- T __freading +-------- T __freadptr +-------- T __freadptrinc +-------- W __freelocale +-------- t __frexp_exp +-------- t __frexp_expf +-------- T __fseeko +-------- T __fseeko_unlocked +-------- T __fseterr +-------- T __fsetlocking -------- D __fsmu8 --------- d gb18030 +-------- T __fstatfs +-------- T __ftello +-------- T __ftello_unlocked +-------- T __futimesat +-------- T __fwritable +-------- T __fwritex +-------- T __fwriting +-------- T __fxstat +-------- W __fxstat64 +-------- T __fxstatat +-------- W __fxstatat64 +-------- T __get_locale -------- d __get_locale.loc_head -------- d __get_locale.lock --------- d getmntent.linebuf --------- d getmntent.mnt --------- d getservbyname.buf --------- d getservbyname.se --------- d getservbyport.buf --------- d getservbyport.se --------- d hkscs --------- d i --------- D in6addr_any --------- D in6addr_loopback --------- d inet_ntoa.buf --------- d init --------- d init_jk --------- d ipio2 --------- d ip_maskl --------- d ip_maskr --------- d iswspace.spaces --------- d j --------- d jis0208 --------- d K --------- d K.816 --------- d key_perm_maskl --------- d key_perm_maskr --------- d key_shifts --------- d ksc --------- d l64a.s --------- d legacy_chars --------- d lock --------- d lock.606 --------- d log_addr --------- d log_facility --------- d log_fd --------- d log_ident --------- d log_mask --------- d log_opt +-------- T __get_resolv_conf +-------- W __getdelim +-------- T __getdents +-------- t __getopt_long +-------- t __getopt_long_core +-------- T __getopt_msg +-------- T __gettextdomain +-------- T __h_errno_location +-------- C __hwcap +-------- T __inet_aton +-------- T __intscan +-------- T __ipparse +-------- T __isalnum_l +-------- T __isalpha_l +-------- T __isblank_l +-------- T __iscntrl_l +-------- T __isdigit_l +-------- T __isgraph_l +-------- T __islower_l +-------- W __isoc99_fscanf +-------- W __isoc99_fwscanf +-------- W __isoc99_scanf +-------- W __isoc99_sscanf +-------- W __isoc99_swscanf +-------- W __isoc99_vfscanf +-------- W __isoc99_vfwscanf +-------- W __isoc99_vscanf +-------- W __isoc99_vsscanf +-------- W __isoc99_vswscanf +-------- W __isoc99_vwscanf +-------- W __isoc99_wscanf +-------- T __isprint_l +-------- T __ispunct_l +-------- T __isspace_l +-------- T __isupper_l +-------- T __iswalnum_l +-------- T __iswalpha_l +-------- T __iswblank_l +-------- T __iswcntrl_l +-------- T __iswctype_l +-------- T __iswdigit_l +-------- T __iswgraph_l +-------- T __iswlower_l +-------- T __iswprint_l +-------- T __iswpunct_l +-------- T __iswspace_l +-------- T __iswupper_l +-------- T __iswxdigit_l +-------- T __isxdigit_l +-------- T __lctrans +-------- T __lctrans_cur +-------- T __lctrans_impl +-------- T __ldexp_cexp +-------- T __ldexp_cexpf +-------- T __lgamma_r +-------- T __lgammaf_r +-------- T __lgammal_r +-------- C __libc +-------- T __libc_get_version +-------- T __loc_is_allocated + U __lock +-------- T __lockfile +-------- T __lookup_ipliteral +-------- T __lookup_name +-------- T __lookup_serv +-------- T __lxstat +-------- W __lxstat64 +-------- T __madvise -------- d __main_pthread --------- d mbrlen.internal --------- d mbrtoc16.internal_state --------- d mbrtoc32.internal_state --------- d mbrtowc.internal_state --------- d md5crypt.perm --------- d messages --------- d mkptr6.xdigits --------- d msgs --------- d n --------- d name_from_dns.afrr --------- D _ns_flagdata --------- d ofl_head --------- d ofl_lock --------- D opterr --------- D optind + U __map_file +-------- T __memrchr +-------- T __mkostemps +-------- T __mmap +-------- T __mo_lookup +-------- T __mprotect +-------- T __mremap + U __muldc3 + U __mulsc3 +-------- T __munmap +-------- t __netlink_enumerate +-------- T __newlocale +-------- T __nl_langinfo +-------- T __nl_langinfo_l +-------- T __ofl_add +-------- T __ofl_lock +-------- T __ofl_unlock +-------- t __openlog +-------- C __optpos -------- D __optreset --------- d pairs --------- d parseop.opch --------- d parseop.opch2 --------- d PIo2 --------- d posix_lconv --------- d pr2 --------- d pR2 --------- d pR2.180 --------- d pr2.209 --------- d pr3 --------- d pR3 --------- d pR3.179 --------- d pr3.208 --------- d pr5 --------- d pR5 --------- d pR5.186 --------- d pr5.215 --------- d pr8 --------- d pR8 --------- d pR8.185 --------- d pr8.214 +-------- T __overflow +-------- T __pleval +-------- W __posix_getopt +-------- T __procfdname -------- D __progname -------- D __progname_full --------- d ps2 --------- d pS2 --------- d pS2.182 --------- d ps2.211 --------- d ps3 --------- d pS3 --------- d pS3.181 --------- d ps3.210 --------- d ps5 --------- d pS5 --------- d pS5.184 --------- d ps5.213 --------- d ps8 --------- d pS8 --------- d pS8.183 --------- d ps8.212 --------- d psbox --------- d ptable --------- d ptable.105 --------- d ptable.107 --------- d ptsname.buf --------- d qr2 --------- d qR2 --------- d qR2.172 --------- d qr2.207 --------- d qr3 --------- d qR3 --------- d qR3.171 --------- d qr5 --------- d qR5 --------- d qR5.178 --------- d qr8 --------- d qR8 --------- d qR8.177 --------- d qr8.206 --------- d qs2 --------- d qS2 --------- d qS2.174 --------- d qs2.205 --------- d qs3 --------- d qS3 --------- d qS3.173 --------- d qs5 --------- d qS5 --------- d qS5.176 --------- d qs8 --------- d qS8 --------- d qS8.175 --------- d qs8.204 +-------- t __pthread_self +-------- t __pthread_self.107 +-------- t __pthread_self.132 +-------- t __pthread_self.139 +-------- t __pthread_self.192 +-------- t __pthread_self.212 +-------- t __pthread_self.216 +-------- t __pthread_self.217 +-------- t __pthread_self.231 +-------- t __pthread_self.232 +-------- t __pthread_self.233 +-------- t __pthread_self.240 +-------- t __pthread_self.426 +-------- t __pthread_self.431 +-------- t __pthread_self.434 +-------- t __pthread_self.437 +-------- t __pthread_self.440 +-------- t __pthread_self.443 +-------- t __pthread_self.514 +-------- t __pthread_self.566 +-------- t __pthread_self.577 +-------- t __pthread_self.578 +-------- t __pthread_self.585 +-------- t __pthread_self.595 +-------- t __pthread_self.638 +-------- T __ptsname_r +-------- T __rand48_step +-------- T __randname +-------- T __rem_pio2 +-------- T __rem_pio2_large +-------- T __rem_pio2f +-------- T __res_mkquery +-------- T __res_msend +-------- T __res_msend_rc +-------- T __res_send +-------- T __res_state -------- d __res_state.res --------- d Sden --------- d seed +-------- T __rtnetlink_enumerate -------- D __seed48 --------- d seed48.p --------- d setlocale.lock --------- d sha256crypt.perm --------- d sha512crypt.perm +-------- T __setrlimit +-------- T __setxid +-------- T __shgetc +-------- T __shlim +-------- T __shm_mapname +-------- T __signbit +-------- T __signbitf +-------- T __signbitl -------- D __signgam --------- d sizeprefix --------- d Snum --------- d states --------- d states.543 --------- D stderr +-------- T __sin +-------- T __sindf +-------- t __srandom +-------- T __statfs -------- D __stderr_used --------- D stdin -------- D __stdin_used --------- D stdout --------- D __stdout_used --------- d strings --------- d strtok.p --------- d tab --------- d table --------- d table.101 --------- d table.104 --------- d table.106 --------- d table.108 --------- d table.115 --------- d table.403 --------- d tbl --------- d tmpnam.internal --------- d tre_macros --------- d ttyname.buf --------- d version --------- d vfwscanf.size_pfx --------- d wctype.names --------- d wtable --------- d x --------- d xdigits +-------- T __stdio_close +-------- T __stdio_exit +-------- W __stdio_exit_needed +-------- T __stdio_read +-------- T __stdio_seek +-------- T __stdio_write +-------- D __stdout_used +-------- T __stdout_write +-------- T __stpcpy +-------- T __stpncpy +-------- T __strcasecmp_l +-------- T __strchrnul +-------- T __strcoll_l +-------- T __strdup +-------- T __strerror_l +-------- T __string_read +-------- T __strncasecmp_l +-------- W __strtoimax_internal +-------- W __strtol_internal +-------- W __strtoll_internal +-------- W __strtoul_internal +-------- W __strtoull_internal +-------- W __strtoumax_internal +-------- T __strxfrm_l +-------- T __synccall + U __syscall10 + U __syscall102 + U __syscall114 + U __syscall118 + U __syscall12 + U __syscall121 + U __syscall122 + U __syscall125 + U __syscall132 + U __syscall133 + U __syscall14 + U __syscall140 + U __syscall142 + U __syscall144 + U __syscall145 + U __syscall146 + U __syscall147 + U __syscall148 + U __syscall15 + U __syscall150 + U __syscall151 + U __syscall152 + U __syscall153 + U __syscall163 + U __syscall168 + U __syscall180 + U __syscall181 + U __syscall183 + U __syscall191 + U __syscall192 + U __syscall193 + U __syscall194 + U __syscall195 + U __syscall196 + U __syscall197 + U __syscall198 + U __syscall199 + U __syscall20 + U __syscall200 + U __syscall201 + U __syscall202 + U __syscall205 + U __syscall207 + U __syscall209 + U __syscall211 + U __syscall212 + U __syscall218 + U __syscall219 + U __syscall220 + U __syscall221 + U __syscall268 + U __syscall269 + U __syscall272 + U __syscall29 + U __syscall295 + U __syscall296 + U __syscall297 + U __syscall298 + U __syscall3 + U __syscall300 + U __syscall301 + U __syscall302 + U __syscall303 + U __syscall304 + U __syscall305 + U __syscall306 + U __syscall308 + U __syscall320 + U __syscall324 + U __syscall33 + U __syscall330 + U __syscall331 + U __syscall333 + U __syscall334 + U __syscall337 + U __syscall34 + U __syscall340 + U __syscall345 + U __syscall36 + U __syscall38 + U __syscall39 + U __syscall4 + U __syscall40 + U __syscall41 + U __syscall42 + U __syscall5 + U __syscall51 + U __syscall54 + U __syscall57 + U __syscall6 + U __syscall60 + U __syscall63 + U __syscall64 + U __syscall66 + U __syscall75 + U __syscall77 + U __syscall83 + U __syscall85 + U __syscall9 + U __syscall91 + U __syscall94 + U __syscall96 + U __syscall97 +-------- T __syscall_ret +-------- C __sysinfo +-------- T __tan +-------- T __tandf +-------- T __tolower_l +-------- T __toread +-------- T __toread_needs_stdio_exit +-------- T __toupper_l +-------- t __towcase +-------- T __towctrans_l +-------- T __towlower_l +-------- T __towrite +-------- T __towrite_needs_stdio_exit +-------- T __towupper_l +-------- T __tre_mem_alloc_impl +-------- T __tre_mem_destroy +-------- T __tre_mem_new_impl +-------- T __uflow +-------- T __unlist_locked_file + U __unlock +-------- T __unlockfile +-------- T __uselocale +-------- W __vm_wait +-------- T __vsyslog + U __wait +-------- T __wcscoll_l +-------- T __wcsxfrm_l +-------- T __wctrans_l +-------- T __wctype_l +-------- T __xmknod +-------- T __xmknodat +-------- W __xpg_basename +-------- W __xpg_strerror_r +-------- T __xstat +-------- W __xstat64 +-------- t _crypt_extended_r_uut + U _exit +-------- T _flushlbf +-------- D _ns_flagdata +-------- t _redupi +-------- t _redupif +-------- t _strcolcmp +-------- t _vsyslog -------- T a64l -------- t a_cas -------- t a_cas_p --------- T accept +-------- t a_ctz_64 +-------- t a_ctz_l +-------- t a_ctz_l.385 +-------- t a_ctz_l.386 +-------- t a_ctz_l.734 +-------- t a_store +-------- t a_store.586 + U accept -------- T accept4 -------- T access -------- T acct -------- T acosh -------- T acoshf -------- T acoshl --------- t a_ctz_64 --------- t a_ctz_l --------- t a_ctz_l.430 --------- t a_ctz_l.44 --------- t a_ctz_l.8 -------- t add_adjusted -------- t add_and_denormalize -------- t add_icase_literals @@ -265,17 +490,19 @@ -------- t addrcmp -------- T aligned_alloc -------- T alphasort +-------- W alphasort64 -------- t append -------- t arg_n --------- t arg_n.448 +-------- t arg_n.675 +-------- d ascii64 -------- t ascii_is_unsafe -------- t ascii_to_bin -------- T asinh -------- T asinhf -------- T asinhl -------- T asprintf --------- t a_store --------- t a_store.531 + U atan2 + U atan2f -------- T atanh -------- T atanhf -------- T atanhl @@ -283,28 +510,32 @@ -------- T atoi -------- T atol -------- T atoll +-------- d b64 +-------- d b64.49 +-------- d b64.61 -------- T basename -------- T bcmp -------- T bcopy --------- t BF_crypt --------- t BF_decode --------- t BF_encode --------- t BF_encrypt --------- t BF_set_key --------- t BF_swap --------- T bind --------- T bindtextdomain +-------- d big5 + U bind -------- T bind_textdomain_codeset +-------- d bindings +-------- T bindtextdomain +-------- d bindtextdomain.lock -------- t binop -------- T bsearch --------- t __bswap_16 --------- t __bswap_16.684 --------- t __bswap_32 --------- t __bswap_32.656 -------- T btowc +-------- d buf +-------- d buf.622 +-------- d buf.626 +-------- d buf.630 -------- T bzero -------- T c16rtomb +-------- d c16rtomb.internal_state -------- T c32rtomb +-------- d c_messages +-------- d c_numeric +-------- d c_time -------- T cabs -------- T cabsf -------- T cabsl @@ -314,10 +545,12 @@ -------- T cacoshf -------- T cacoshl -------- T cacosl + U calloc -------- T carg -------- T cargf -------- T cargl -------- t casefold +-------- d casemaps -------- T casin -------- T casinf -------- T casinh @@ -332,6 +565,8 @@ -------- T catanl -------- T catclose -------- T catgets +-------- d catlens +-------- d catnames -------- T catopen -------- T cbrt -------- T cbrtf @@ -350,38 +585,45 @@ -------- T cfmakeraw -------- T cfsetispeed -------- T cfsetospeed +-------- W cfsetspeed +-------- d charmaps -------- T chdir --------- t checker -------- T chmod -------- T chown -------- T cimag -------- T cimagf -------- T cimagl -------- t cleanup --------- t cleanup.691 +-------- t cleanup.504 -------- T clearerr +-------- W clearerr_unlocked + U clock_gettime -------- T clog -------- T clogf -------- T clogl -------- T close --------- T closedir -------- t close_file +-------- T closedir -------- T closelog -------- t common --------- t common.142 --------- t common.170 --------- t common.203 +-------- t common.285 +-------- t common.302 +-------- t common.303 +-------- d comp_maskl0 +-------- d comp_maskl1 +-------- d comp_maskr0 +-------- d comp_maskr1 -------- T conj -------- T conjf -------- T conjl --------- T connect + U connect -------- t copy_addr -------- t copy_lladdr -------- T copysign -------- T copysignf -------- T copysignl --------- T __cos --------- T __cosdf + U cos + U cosf -------- T cosh -------- T coshf -------- T coshl @@ -395,14 +637,10 @@ -------- T crealf -------- T creall -------- T creat +-------- W creat64 -------- T crypt --------- T __crypt_blowfish --------- T __crypt_des --------- t _crypt_extended_r_uut --------- T __crypt_md5 --------- T __crypt_r --------- T __crypt_sha256 --------- T __crypt_sha512 +-------- d crypt.buf +-------- W crypt_r -------- T csin -------- T csinf -------- T csinh @@ -419,122 +657,115 @@ -------- T ctanhl -------- T ctanl -------- T ctermid --------- T __ctype_b_loc --------- T __ctype_get_mb_cur_max --------- T __ctype_tolower_loc --------- T __ctype_toupper_loc +-------- d current_domain -------- t cycle -------- T dcgettext -------- T dcngettext +-------- d dcngettext.cats -------- t dd_add -------- t dd_mul -------- t decfloat +-------- d decfloat.p10s +-------- d decfloat.th +-------- d defpolicy -------- t des_cipher --------- T __des_setkey -------- T dgettext +-------- d digits -------- T dirfd -------- T dirname -------- T div --------- T __dn_comp --------- T __dn_expand --------- T dngettext --------- T __dns_count_addrs --------- T __dns_doqueries --------- T __dns_get_rr +-------- W dn_comp +-------- W dn_expand -------- T dn_skipname --------- T __dns_parse +-------- T dngettext -------- t dns_parse_callback --------- T __dns_query --------- T __do_des -------- t do_nftw --------- T __do_orphaned_stdio_locks -------- t do_read --------- t do_read.432 --------- t do_read.445 +-------- t do_read.746 +-------- t do_read.749 -------- t do_setrlimit -------- t do_setxid --------- t __DOUBLE_BITS --------- t __DOUBLE_BITS.147 --------- t __DOUBLE_BITS.148 --------- t __DOUBLE_BITS.150 --------- t __DOUBLE_BITS.153 --------- t __DOUBLE_BITS.156 --------- t __DOUBLE_BITS.169 --------- t __DOUBLE_BITS.190 --------- t __DOUBLE_BITS.193 --------- t __DOUBLE_BITS.224 --------- t __DOUBLE_BITS.234 --------- t __DOUBLE_BITS.261 --------- t __DOUBLE_BITS.268 --------- t __DOUBLE_BITS.547 --------- t __DOUBLE_BITS.728 --------- t __DOUBLE_BITS.729 --------- t __DOUBLE_BITS.754 --------- t do_wordexp -------- T dprintf -------- T drand48 --------- t dummy.450 --------- t dummy.721 +-------- W drem +-------- W dremf +-------- t dummy +-------- t dummy.556 +-------- d dummy.563 +-------- t dummy.709 -------- t dummy_gettextdomain -------- T dup -------- T dup2 --------- T __dup3 --------- T __duplocale +-------- W dup3 +-------- W duplocale -------- T ecvt --------- T __emscripten_pthread_data_constructor +-------- d ecvt.buf +-------- d empty_mo -------- T encrypt -------- T endhostent -------- T endmntent +-------- W endnetent -------- T endservent +-------- d envvars -------- T erand48 -------- T erf -------- T erfc -------- t erfc1 --------- t erfc1.238 +-------- t erfc1.254 -------- t erfc2 --------- t erfc2.237 +-------- t erfc2.253 -------- T erfcf -------- T erfcl -------- T erff -------- T erfl --------- T __errno_location +-------- d errid +-------- d errmsg -------- T ether_aton +-------- d ether_aton.a -------- T ether_aton_r -------- T ether_hostton -------- T ether_line -------- T ether_ntoa +-------- d ether_ntoa.x -------- T ether_ntoa_r -------- T ether_ntohost -------- t evalbinop +-------- d evalbinop.prec -------- t evalexpr -------- t evalprim + U exp -------- T exp10 +-------- d exp10.p10 -------- T exp10f +-------- d exp10f.p10 -------- T exp10l -------- T exp2 -------- T exp2f +-------- d exp2ft -------- T exp2l + U expf -------- T expm1 -------- T expm1f -------- T expm1l --------- T __expo2 --------- T __expo2f --------- T faccessat --------- T __fbufsize +-------- d f +-------- d f.625 +-------- d f.629 + U fabs + U fabsf +-------- d fact -------- T fchdir -------- T fchmod -------- T fchmodat -------- T fchown -------- T fchownat -------- T fclose --------- T __fclose_ca -------- T fcntl -------- T fcvt -------- T fdatasync -------- T fdim -------- T fdimf -------- T fdiml --------- T __fdopen +-------- W fdopen -------- T fdopendir -------- T feclearexcept -------- T fegetenv @@ -542,50 +773,40 @@ -------- T fegetround -------- T feholdexcept -------- T feof +-------- W feof_unlocked -------- T feraiseexcept -------- T ferror +-------- W ferror_unlocked -------- T fesetenv -------- T fesetexceptflag -------- T fesetround --------- T __fesetround -------- T fetestexcept -------- T feupdateenv -------- T fflush --------- t __fflush_unlocked +-------- W fflush_unlocked -------- T ffs -------- T ffsl -------- T ffsll -------- T fgetc +-------- W fgetc_unlocked -------- T fgetln -------- T fgetpos +-------- W fgetpos64 -------- T fgets +-------- W fgets_unlocked -------- T fgetwc --------- T __fgetwc_unlocked --------- t __fgetwc_unlocked_internal +-------- W fgetwc_unlocked -------- T fgetws +-------- W fgetws_unlocked -------- T fileno +-------- W fileno_unlocked -------- t find_charmap -------- T finite -------- T finitef -------- t fixup --------- T __flbf --------- t __FLOAT_BITS --------- t __FLOAT_BITS.149 --------- t __FLOAT_BITS.158 --------- t __FLOAT_BITS.161 --------- t __FLOAT_BITS.164 --------- t __FLOAT_BITS.189 --------- t __FLOAT_BITS.196 --------- t __FLOAT_BITS.225 --------- t __FLOAT_BITS.241 --------- t __FLOAT_BITS.244 --------- t __FLOAT_BITS.727 --------- t __FLOAT_BITS.734 --------- t __FLOAT_BITS.747 --------- T __floatscan -------- T flockfile --------- T __flt_rounds --------- T _flushlbf + U floor + U floorf -------- T fma -------- T fmaf -------- T fmal @@ -597,165 +818,170 @@ -------- T fminf -------- T fminl -------- T fmod --------- T __fmodeflags -------- T fmodf -------- T fmodl -------- t fmt_fp --------- T fmtmsg -------- t fmt_o -------- t fmt_u -------- t fmt_x +-------- T fmtmsg +-------- d fmtmsg.msgs -------- T fnmatch -------- t fnmatch_internal -------- T fopen --------- T __fopen_rb_ca +-------- W fopen64 + U fork -------- T forkpty -------- t fourbyte_memmem -------- t fourbyte_strstr --------- T __fpclassify --------- T __fpclassifyf --------- T __fpclassifyl --------- T __fpending +-------- d fp_maskl -------- T fprintf --------- T __fpurge +-------- W fpurge -------- T fputc +-------- W fputc_unlocked -------- T fputs +-------- W fputs_unlocked -------- T fputwc --------- T __fputwc_unlocked +-------- W fputwc_unlocked -------- T fputws +-------- W fputws_unlocked -------- T fread --------- T __freadable --------- T __freadahead --------- T __freading --------- T __freadptr --------- T __freadptrinc --------- T freeaddrinfo +-------- W fread_unlocked + U free -------- T freeifaddrs -------- t freelist -------- T freelocale -------- T freopen +-------- W freopen64 -------- T frexp --------- t __frexp_exp --------- t __frexp_expf -------- T frexpf -------- T frexpl -------- T fscanf -------- T fseek --------- T __fseeko --------- T __fseeko_unlocked --------- T __fseterr --------- T __fsetlocking +-------- W fseeko +-------- W fseeko64 -------- T fsetpos +-------- W fsetpos64 -------- T fstat +-------- W fstat64 -------- T fstatat --------- T __fstatfs +-------- W fstatat64 +-------- W fstatfs +-------- W fstatfs64 -------- T fstatvfs +-------- W fstatvfs64 -------- T fsync -------- T ftell --------- T __ftello --------- T __ftello_unlocked +-------- W ftello +-------- W ftello64 -------- T ftruncate +-------- W ftruncate64 -------- T ftrylockfile -------- T funlockfile -------- T futimens --------- T __futimesat +-------- W futimesat -------- t fuzzycmp -------- T fwide -------- T fwprintf --------- T __fwritable -------- T fwrite --------- T __fwritex --------- T __fwriting +-------- W fwrite_unlocked -------- T fwscanf --------- T __fxstat --------- T __fxstatat +-------- d gb18030 -------- T gcvt -------- t gen_netmask -------- t get_16 -------- t get_32 +-------- T get_current_dir_name -------- T getauxval -------- T getc +-------- T getc_unlocked -------- T getchar -------- T getchar_unlocked --------- T getc_unlocked --------- T get_current_dir_name -------- T getcwd -------- T getdelim --------- T __getdents +-------- W getdents +-------- W getdents64 -------- T getdomainname -------- T getegid + U getenv -------- T geteuid -------- T getgid --------- T getgrouplist -------- T getgroups -------- T gethostent -------- T gethostid -------- T gethostname -------- T getifaddrs -------- t getint --------- t getint.542 +-------- t getint.661 -------- t getlens -------- T getline --------- T __get_locale -------- T getlogin -------- T getlogin_r -------- T getmntent +-------- d getmntent.linebuf +-------- d getmntent.mnt -------- T getmntent_r + U getnameinfo -------- T getnetbyaddr -------- T getnetbyname +-------- W getnetent -------- t getoffs -------- T getopt --------- t __getopt_long -------- T getopt_long --------- t __getopt_long_core -------- T getopt_long_only --------- T __getopt_msg --------- T getpeername -------- T getpgid -------- T getpgrp -------- T getpid -------- T getppid -------- T getpriority -------- T getresgid --------- T __get_resolv_conf -------- T getresuid -------- T getrlimit +-------- W getrlimit64 -------- T getrusage -------- T gets -------- T getservbyname +-------- d getservbyname.buf +-------- d getservbyname.se -------- T getservbyname_r -------- T getservbyport +-------- d getservbyport.buf +-------- d getservbyport.se -------- T getservbyport_r -------- T getservent -------- T getsid --------- T getsockname --------- T getsockopt + U getsockname -------- T getsubopt -------- T gettext -------- t gettextdir --------- T __gettextdomain -------- T getuid -------- T getw -------- T getwc +-------- W getwc_unlocked -------- T getwchar --------- t getword +-------- W getwchar_unlocked -------- T glob +-------- W glob64 -------- T globfree +-------- W globfree64 + U gmtime_r -------- T grantpt +-------- C h_errno -------- t hashmd --------- t hashmd.809 +-------- t hashmd.58 -------- T hasmntopt --------- T __h_errno_location -------- T herror -------- t hexfloat -------- t hexval --------- t hexval.772 +-------- t hexval.518 +-------- d hkscs -------- T hstrerror -------- T htonl -------- T htons -------- T hypot -------- T hypotf -------- T hypotl +-------- d i -------- T iconv -------- T iconv_close -------- T iconv_open @@ -769,110 +995,99 @@ -------- T ilogbl -------- T imaxabs -------- T imaxdiv +-------- D in6addr_any +-------- D in6addr_loopback +-------- t in_set -------- T index --------- T __inet_aton + U inet_addr +-------- W inet_aton -------- T inet_lnaof -------- T inet_makeaddr -------- T inet_netof -------- T inet_network -------- T inet_ntoa +-------- d inet_ntoa.buf -------- T inet_ntop -------- T inet_pton --------- T initgroups +-------- d init +-------- d init_jk -------- T initstate --------- t in_set --------- T __intscan -------- T ioctl --------- T __ipparse +-------- d ip_maskl +-------- d ip_maskr +-------- d ipio2 +-------- t is_literal +-------- t is_lost_conn +-------- t is_valid_hostname -------- T isalnum --------- T __isalnum_l -------- T isalnum_l -------- T isalpha --------- T __isalpha_l -------- T isalpha_l -------- T isascii -------- T isatty -------- T isblank --------- T __isblank_l -------- T isblank_l -------- T iscntrl --------- T __iscntrl_l -------- T iscntrl_l -------- T isdigit --------- T __isdigit_l -------- T isdigit_l -------- T isgraph --------- T __isgraph_l -------- T isgraph_l --------- t is_literal --------- t is_lost_conn -------- T islower --------- T __islower_l -------- T islower_l -------- T isprint --------- T __isprint_l -------- T isprint_l -------- T ispunct --------- T __ispunct_l -------- T ispunct_l -------- T issetugid -------- T isspace --------- T __isspace_l -------- T isspace_l -------- T isupper --------- T __isupper_l -------- T isupper_l --------- t is_valid_hostname -------- T iswalnum --------- T __iswalnum_l -------- T iswalnum_l -------- T iswalpha --------- T __iswalpha_l -------- T iswalpha_l -------- T iswblank --------- T __iswblank_l -------- T iswblank_l -------- T iswcntrl --------- T __iswcntrl_l -------- T iswcntrl_l -------- T iswctype --------- T __iswctype_l -------- T iswctype_l -------- T iswdigit --------- T __iswdigit_l -------- T iswdigit_l -------- T iswgraph --------- T __iswgraph_l -------- T iswgraph_l -------- T iswlower --------- T __iswlower_l -------- T iswlower_l -------- T iswprint --------- T __iswprint_l -------- T iswprint_l -------- T iswpunct --------- T __iswpunct_l -------- T iswpunct_l -------- T iswspace --------- T __iswspace_l +-------- d iswspace.spaces -------- T iswspace_l -------- T iswupper --------- T __iswupper_l -------- T iswupper_l -------- T iswxdigit --------- T __iswxdigit_l -------- T iswxdigit_l -------- T isxdigit --------- T __isxdigit_l -------- T isxdigit_l +-------- d j -------- T j0 -------- T j0f -------- T j1 -------- T j1f +-------- d jis0208 -------- T jn -------- T jnf -------- T jrand48 +-------- d key_perm_maskl +-------- d key_perm_maskr +-------- d key_shifts +-------- d ksc -------- T l64a +-------- d l64a.s -------- t labelof -------- T labs -------- t lcg31 @@ -880,25 +1095,19 @@ -------- T lchmod -------- T lchown -------- T lcong48 --------- T __lctrans --------- T __lctrans_cur --------- T __lctrans_impl -------- T ldexp --------- T __ldexp_cexp --------- T __ldexp_cexpf -------- T ldexpf -------- T ldexpl -------- T ldiv +-------- d legacy_chars -------- T lgamma +-------- W lgamma_r -------- T lgammaf --------- T __lgammaf_r +-------- W lgammaf_r -------- T lgammal --------- T __lgammal_r --------- T __lgamma_r --------- T __libc_get_version +-------- W lgammal_r -------- T link -------- T linkat --------- T listen -------- T llabs -------- T lldiv -------- T llrint @@ -909,9 +1118,11 @@ -------- T llroundl -------- t loadstate -------- T localeconv --------- T __loc_is_allocated +-------- d lock +-------- d lock.509 -------- T lockf --------- T __lockfile +-------- W lockf64 + U log -------- T log10 -------- T log10f -------- T log10l @@ -921,13 +1132,17 @@ -------- T log2 -------- T log2f -------- T log2l +-------- d log_addr +-------- d log_facility +-------- d log_fd +-------- d log_ident +-------- d log_mask +-------- d log_opt -------- T logb -------- T logbf -------- T logbl + U logf -------- T login_tty --------- T __lookup_ipliteral --------- T __lookup_name --------- T __lookup_serv -------- T lrand48 -------- T lrint -------- T lrintf @@ -936,34 +1151,45 @@ -------- T lroundf -------- T lroundl -------- T lseek +-------- W lseek64 -------- T lstat --------- T __lxstat --------- T __madvise +-------- W lstat64 +-------- W madvise + U malloc -------- t marksub -------- t match -------- t match_bracket -------- t match_in_dir -------- T mblen -------- T mbrlen +-------- d mbrlen.internal -------- T mbrtoc16 +-------- d mbrtoc16.internal_state -------- T mbrtoc32 +-------- d mbrtoc32.internal_state -------- T mbrtowc +-------- d mbrtowc.internal_state -------- T mbsinit -------- T mbsnrtowcs -------- T mbsrtowcs -------- T mbstowcs -------- T mbtowc -------- t mclose --------- t md5crypt -------- t md5_init -------- t md5_sum -------- t md5_update +-------- t md5crypt +-------- d md5crypt.perm -------- T memccpy -------- T memchr -------- T memcmp + U memcpy -------- T memmem + U memmove -------- T mempcpy --------- T __memrchr +-------- W memrchr + U memset +-------- d messages -------- T mincore -------- T mkdir -------- T mkdirat @@ -973,34 +1199,42 @@ -------- T mknod -------- T mknodat -------- T mkostemp --------- T __mkostemps +-------- W mkostemp64 +-------- W mkostemps +-------- W mkostemps64 -------- t mkptr4 -------- t mkptr6 +-------- d mkptr6.xdigits -------- T mkstemp +-------- W mkstemp64 -------- T mkstemps +-------- W mkstemps64 -------- T mktemp -------- T mlock -------- T mlockall --------- T __mmap +-------- W mmap +-------- W mmap64 -------- T modf -------- T modff -------- T modfl --------- T __mo_lookup --------- T __mprotect +-------- W mprotect -------- T mrand48 -------- t mread --------- T __mremap +-------- W mremap -------- t ms_close --------- t mseek -------- t ms_seek -------- t ms_write +-------- t mseek +-------- d msgs -------- T msync -------- t mtime -------- T munlock -------- T munlockall --------- T __munmap +-------- W munmap -------- t mwrite +-------- d n -------- t name_from_dns +-------- d name_from_dns.afrr -------- t name_from_dns_search -------- t name_from_hosts -------- t name_from_null @@ -1008,13 +1242,13 @@ -------- T nan -------- T nanf -------- T nanl + U nanosleep -------- T nearbyint -------- T nearbyintf -------- T nearbyintl --------- t __netlink_enumerate -------- t netlink_msg_to_ifaddr -------- t netlink_msg_to_nameindex --------- T __newlocale +-------- W newlocale -------- T nextafter -------- T nextafterf -------- T nextafterl @@ -1022,10 +1256,11 @@ -------- T nexttowardf -------- T nexttowardl -------- T nftw +-------- W nftw64 -------- T ngettext -------- T nice --------- T __nl_langinfo --------- T __nl_langinfo_l +-------- W nl_langinfo +-------- W nl_langinfo_l -------- T nrand48 -------- T ns_get16 -------- T ns_get32 @@ -1037,30 +1272,53 @@ -------- T ns_skiprr -------- T ntohl -------- T ntohs --------- T __ofl_add --------- T __ofl_lock --------- T __ofl_unlock +-------- d ofl_head +-------- d ofl_lock -------- T open +-------- W open64 +-------- T open_memstream +-------- T open_wmemstream -------- T openat +-------- W openat64 -------- T opendir --------- t __openlog -------- T openlog --------- T open_memstream -------- T openpty --------- T open_wmemstream +-------- C optarg +-------- D opterr +-------- D optind +-------- C optopt +-------- W optreset -------- t out --------- t out.541 --------- T __overflow +-------- t out.660 +-------- d pR2 +-------- d pR2.295 +-------- d pR3 +-------- d pR3.294 +-------- d pR5 +-------- d pR5.301 +-------- d pR8 +-------- d pR8.300 +-------- d pS2 +-------- d pS2.297 +-------- d pS3 +-------- d pS3.296 +-------- d pS5 +-------- d pS5.299 +-------- d pS8 +-------- d pS8.298 -------- t pad --------- t pad.795 --------- t pad.803 --------- t pad.813 +-------- t pad.50 +-------- t pad.62 +-------- t pad.647 +-------- d pairs -------- t parse_atom -------- t parse_bracket -------- t parse_bracket_terms -------- t parse_dup -------- t parse_dup_count -------- t parseop +-------- d parseop.opch +-------- d parseop.opch2 -------- t pat_next -------- T pause -------- T pclose @@ -1068,96 +1326,134 @@ -------- T perror -------- T pipe -------- T pipe2 --------- T __pleval -------- t pntz -------- t policyof -------- T poll -------- t pone -------- t ponef -------- t pop_arg --------- t pop_arg.544 --------- T popen +-------- t pop_arg.663 -------- T posix_close -------- T posix_fadvise +-------- W posix_fadvise64 -------- T posix_fallocate +-------- W posix_fallocate64 +-------- d posix_lconv -------- T posix_madvise + U posix_memalign -------- T posix_openpt + U pow +-------- W pow10 +-------- W pow10f +-------- W pow10l +-------- d pr2 +-------- d pr2.309 +-------- d pr3 +-------- d pr3.308 +-------- d pr5 +-------- d pr5.315 +-------- d pr8 +-------- d pr8.314 -------- T pread +-------- W pread64 -------- T preadv +-------- W preadv64 -------- t prefixmatch -------- T printf -------- t printf_core -------- t processblock --------- t processblock.804 --------- t processblock.814 --------- T __procfdname +-------- t processblock.51 +-------- t processblock.63 +-------- W program_invocation_name +-------- W program_invocation_short_name +-------- d ps2 +-------- d ps2.311 +-------- d ps3 +-------- d ps3.310 +-------- d ps5 +-------- d ps5.313 +-------- d ps8 +-------- d ps8.312 +-------- d psbox -------- T pselect --------- t __pthread_self +-------- d ptable +-------- d ptable.103 +-------- d ptable.105 + U pthread_cleanup_pop + U pthread_cleanup_push -------- T pthread_self --------- t __pthread_self.285 --------- t __pthread_self.300 --------- t __pthread_self.306 --------- t __pthread_self.317 --------- t __pthread_self.321 --------- t __pthread_self.326 --------- t __pthread_self.338 --------- t __pthread_self.360 --------- t __pthread_self.379 --------- t __pthread_self.390 --------- t __pthread_self.455 --------- t __pthread_self.515 --------- t __pthread_self.524 --------- t __pthread_self.530 --------- t __pthread_self.538 --------- t __pthread_self.585 --------- t __pthread_self.617 --------- t __pthread_self.697 --------- t __pthread_self.699 --------- t __pthread_self.704 --------- t __pthread_self.709 --------- t __pthread_self.717 --------- t __pthread_self.720 --------- t __pthread_self.771 + U pthread_setcancelstate + U pthread_sigmask -------- T ptsname --------- T __ptsname_r +-------- d ptsname.buf +-------- W ptsname_r -------- t put_16 -------- t put_32 -------- T putc +-------- T putc_unlocked -------- T putchar -------- T putchar_unlocked --------- T putc_unlocked -------- T puts -------- T putw -------- T putwc +-------- W putwc_unlocked -------- T putwchar +-------- W putwchar_unlocked -------- T pwrite +-------- W pwrite64 -------- T pwritev +-------- W pwritev64 -------- t pzero -------- t pzerof +-------- d qR2 +-------- d qR2.287 +-------- d qR3 +-------- d qR3.286 +-------- d qR5 +-------- d qR5.293 +-------- d qR8 +-------- d qR8.292 +-------- d qS2 +-------- d qS2.289 +-------- d qS3 +-------- d qS3.288 +-------- d qS5 +-------- d qS5.291 +-------- d qS8 +-------- d qS8.290 -------- t qone -------- t qonef +-------- d qr2 +-------- d qr2.307 +-------- d qr3 +-------- d qr5 +-------- d qr8 +-------- d qr8.306 +-------- d qs2 +-------- d qs2.305 +-------- d qs3 +-------- d qs5 +-------- d qs8 +-------- d qs8.304 -------- T qsort -------- t qzero -------- t qzerof -------- T rand --------- T __rand48_step --------- T __randname --------- T random -------- T rand_r +-------- T random -------- T read -------- T readdir +-------- W readdir64 +-------- W readdir64_r -------- T readdir_r -------- T readlink -------- T readlinkat -------- T readv + U realloc -------- T realpath --------- t reap --------- T recv --------- T recvfrom + U recv + U recvfrom -------- T recvmmsg --------- T recvmsg --------- t _redupi --------- t _redupif -------- T regcomp -------- T regerror -------- T regexec @@ -1166,33 +1462,27 @@ -------- T remainderf -------- T remainderl -------- T remove --------- T __rem_pio2 --------- T __rem_pio2f --------- T __rem_pio2_large -------- T remquo -------- T remquof -------- T remquol -------- T rename -------- T renameat -------- T res_init --------- T __res_mkquery --------- T __res_msend --------- T __res_msend_rc --------- T res_querydomain --------- T __res_send --------- T __res_state +-------- W res_mkquery +-------- W res_send -------- T rewind -------- T rewinddir -------- T rindex -------- T rint + U rintf -------- T rintl -------- T rmdir -------- t rol -------- t ror --------- t ror.815 +-------- t ror.64 + U round + U roundf -------- T roundl --------- T __rtnetlink_enumerate --------- t S -------- t savestate -------- T scalb -------- T scalbf @@ -1203,16 +1493,18 @@ -------- T scalbnf -------- T scalbnl -------- T scandir +-------- W scandir64 -------- t scanexp -------- T scanf -------- t scopeof +-------- d seed -------- T seed48 +-------- d seed48.p -------- T seekdir -------- T select --------- T send + U send -------- T sendmmsg --------- T sendmsg --------- T sendto + U sendto -------- T setbuf -------- T setbuffer -------- T setdomainname @@ -1220,12 +1512,15 @@ -------- T seteuid -------- T setgid -------- T sethostent + U setitimer -------- T setkey -------- T setlinebuf -------- T setlocale +-------- d setlocale.lock -------- t setlocale_one_unlocked -------- T setlogmask -------- T setmntent +-------- W setnetent -------- T setpgid -------- T setpgrp -------- T setpriority @@ -1234,109 +1529,105 @@ -------- T setresuid -------- T setreuid -------- T setrlimit --------- T __setrlimit +-------- W setrlimit64 -------- T setservent -------- T setsid --------- T setsockopt + U setsockopt -------- T setstate -------- T setuid -------- t setup_salt -------- T setvbuf --------- T __setxid --------- t sha256crypt -------- t sha256_init -------- t sha256_sum -------- t sha256_update --------- t sha512crypt +-------- t sha256crypt +-------- d sha256crypt.perm -------- t sha512_init -------- t sha512_sum -------- t sha512_update --------- T __shgetc +-------- t sha512crypt +-------- d sha512crypt.perm -------- t shl --------- T __shlim --------- T __shm_mapname -------- T shm_open -------- T shm_unlink -------- t shr --------- T shutdown --------- t sift --------- T __signbit --------- T __signbitf --------- T __signbitl +-------- t sift + U sigfillset +-------- W signgam -------- T significand -------- T significandf --------- T __sin + U sin +-------- t sin_pi +-------- t sin_pi.320 -------- T sincos -------- T sincosf -------- T sincosl --------- T __sindf + U sinf -------- T sinh -------- T sinhf -------- T sinhl -------- t sinpi --------- t sin_pi --------- t sin_pi.157 +-------- d sizeprefix -------- t skipspace -------- T sleep --------- T snprintf -------- t sn_write +-------- T snprintf -------- T sockatmark --------- T socket --------- T socketpair + U socket -------- t sort -------- T sprintf -------- t sq + U sqrt + U sqrtf -------- T srand -------- T srand48 --------- t __srandom -------- T srandom -------- T sscanf -------- T stat --------- T __statfs +-------- W stat64 +-------- d states +-------- d states.662 +-------- W statfs +-------- W statfs64 -------- T statvfs --------- T __stdio_close --------- T __stdio_exit --------- T __stdio_read --------- T __stdio_seek --------- T __stdio_write --------- T __stdout_write +-------- W statvfs64 +-------- D stderr +-------- D stdin +-------- D stdout -------- t store_int --------- t store_int.449 --------- T __stpcpy --------- T __stpncpy +-------- t store_int.676 +-------- W stpcpy +-------- W stpncpy +-------- t str_next -------- T strcasecmp --------- T __strcasecmp_l -------- T strcasecmp_l -------- T strcasestr -------- T strcat -------- T strchr --------- T __strchrnul +-------- W strchrnul -------- T strcmp --------- t _strcolcmp -------- T strcoll --------- T __strcoll_l +-------- W strcoll_l -------- T strcpy -------- T strcspn --------- T __strdup +-------- W strdup -------- T strerror --------- T __strerror_l -------- T strerror_l -------- T strerror_r -------- T strfmon -------- T strfmon_l --------- T __string_read + U strftime +-------- d strings -------- T strlcat -------- T strlcpy -------- T strlen -------- T strlwr -------- T strncasecmp --------- T __strncasecmp_l -------- T strncasecmp_l -------- T strncat -------- T strncmp -------- T strncpy -------- T strndup --------- t str_next -------- T strnlen -------- T strpbrk -------- T strrchr @@ -1350,40 +1641,48 @@ -------- T strtof_l -------- T strtoimax -------- T strtok +-------- d strtok.p -------- T strtok_r -------- T strtol +-------- T strtol_l -------- T strtold -------- T strtold_l -------- T strtoll --------- T strtol_l -------- T strtoll_l -------- T strtoul --------- T strtoull -------- T strtoul_l +-------- T strtoull -------- T strtoull_l -------- T strtoumax -------- t strtox --------- t strtox.423 +-------- t strtox.739 -------- T strupr -------- T strverscmp -------- T strxfrm --------- T __strxfrm_l +-------- W strxfrm_l +-------- t sw_write -------- T swab -------- t swapc -------- T swprintf -------- T swscanf --------- t sw_write -------- T symlink -------- T symlinkat -------- T sync --------- T __synccall --------- T __syscall_ret -------- T syslog --------- T __tan --------- T __tandf +-------- d tab +-------- d table +-------- d table.101 +-------- d table.102 +-------- d table.104 +-------- d table.106 +-------- d table.122 +-------- d table.82 + U tan + U tanf -------- T tanh -------- T tanhf -------- T tanhl +-------- d tbl -------- T tcdrain -------- T tcflow -------- T tcflush @@ -1402,31 +1701,24 @@ -------- T tgammal -------- t threebyte_memmem -------- t threebyte_strstr + U time -------- T tmpfile +-------- W tmpfile64 -------- T tmpnam +-------- d tmpnam.internal -------- t to64 --------- t to64.801 --------- t to64.811 +-------- t to64.48 +-------- t to64.60 -------- T toascii -------- T tolower --------- T __tolower_l -------- T tolower_l --------- T __toread --------- T __toread_needs_stdio_exit -------- T toupper --------- T __toupper_l -------- T toupper_l --------- t __towcase -------- T towctrans --------- T __towctrans_l -------- T towctrans_l -------- T towlower --------- T __towlower_l -------- T towlower_l --------- T __towrite --------- T __towrite_needs_stdio_exit -------- T towupper --------- T __towupper_l -------- T towupper_l -------- t tre_add_tag_left -------- t tre_add_tag_right @@ -1443,11 +1735,9 @@ -------- t tre_expand_ast -------- t tre_expand_macro -------- t tre_fill_pmatch +-------- d tre_macros -------- t tre_make_trans -------- t tre_match_empty --------- T __tre_mem_alloc_impl --------- T __tre_mem_destroy --------- T __tre_mem_new_impl -------- t tre_neg_char_classes_match -------- t tre_new_lit -------- t tre_parse @@ -1469,9 +1759,11 @@ -------- t trinkle -------- T trunc -------- T truncate +-------- W truncate64 -------- T truncf -------- T truncl -------- T ttyname +-------- d ttyname.buf -------- T ttyname_r -------- t twobyte_memmem -------- t twobyte_strstr @@ -1479,25 +1771,25 @@ -------- t twoway_strstr -------- t twoway_wcsstr -------- T ualarm --------- T __uflow -------- T umask -------- T uname -------- T ungetc -------- T ungetwc -------- T unlink -------- T unlinkat --------- T __unlist_locked_file --------- T __unlockfile -------- T unlockpt --------- T __uselocale +-------- W uselocale -------- T utimensat -------- T vasprintf -------- T vdprintf +-------- d version -------- T versionsort +-------- W versionsort64 -------- T vfprintf -------- T vfscanf -------- T vfwprintf -------- T vfwscanf +-------- d vfwscanf.size_pfx -------- T vprintf -------- T vscanf -------- T vsnprintf @@ -1506,10 +1798,10 @@ -------- t vstrfmon_l -------- T vswprintf -------- T vswscanf --------- t _vsyslog --------- T __vsyslog +-------- W vsyslog -------- T vwprintf -------- T vwscanf + U waitpid -------- T wcpcpy -------- T wcpncpy -------- T wcrtomb @@ -1519,7 +1811,7 @@ -------- T wcschr -------- T wcscmp -------- T wcscoll --------- T __wcscoll_l +-------- W wcscoll_l -------- T wcscpy -------- T wcscspn -------- T wcsdup @@ -1548,18 +1840,17 @@ -------- T wcstoull -------- T wcstoumax -------- t wcstox --------- t wcstox.431 +-------- t wcstox.748 -------- T wcswcs -------- T wcswidth -------- T wcsxfrm --------- T __wcsxfrm_l +-------- W wcsxfrm_l -------- T wctob -------- T wctomb -------- T wctrans --------- T __wctrans_l -------- T wctrans_l -------- T wctype --------- T __wctype_l +-------- d wctype.names -------- T wctype_l -------- T wcwidth -------- T wmemchr @@ -1570,8 +1861,6 @@ -------- t wms_close -------- t wms_seek -------- t wms_write --------- T wordexp --------- T wordfree -------- T wprintf -------- t wprintf_core -------- t wrap_write @@ -1579,164 +1868,12 @@ -------- T writev -------- T wscanf -------- t wstring_read --------- T __xmknod --------- T __xmknodat --------- T __xstat +-------- d wtable +-------- d x +-------- d xdigits -------- T y0 -------- T y0f -------- T y1 -------- T y1f -------- T yn -------- T ynf --------- W __aio_close --------- W alphasort64 --------- W cfsetspeed --------- W clearerr_unlocked --------- W creat64 --------- W crypt_r --------- W dn_comp --------- W dn_expand --------- W drem --------- W dremf --------- W dup3 --------- W duplocale --------- W endnetent --------- W fdopen --------- W feof_unlocked --------- W ferror_unlocked --------- W fflush_unlocked --------- W fgetc_unlocked --------- W fgetpos64 --------- W fgets_unlocked --------- W fgetwc_unlocked --------- W fgetws_unlocked --------- W fileno_unlocked --------- W fopen64 --------- W fpurge --------- W fputc_unlocked --------- W fputs_unlocked --------- W fputwc_unlocked --------- W fputws_unlocked --------- W fread_unlocked --------- W __freelocale --------- W freopen64 --------- W fseeko --------- W fseeko64 --------- W fsetpos64 --------- W fstat64 --------- W fstatat64 --------- W fstatfs --------- W fstatfs64 --------- W fstatvfs64 --------- W ftello --------- W ftello64 --------- W ftruncate64 --------- W futimesat --------- W fwrite_unlocked --------- W __fxstat64 --------- W __fxstatat64 --------- W __getdelim --------- W getdents --------- W getdents64 --------- W getnetent --------- W getrlimit64 --------- W getwchar_unlocked --------- W getwc_unlocked --------- W glob64 --------- W globfree64 --------- W inet_aton --------- W _IO_feof_unlocked --------- W _IO_ferror_unlocked --------- W _IO_getc --------- W _IO_getc_unlocked --------- W _IO_putc --------- W _IO_putc_unlocked --------- W __isoc99_fscanf --------- W __isoc99_fwscanf --------- W __isoc99_scanf --------- W __isoc99_sscanf --------- W __isoc99_swscanf --------- W __isoc99_vfscanf --------- W __isoc99_vfwscanf --------- W __isoc99_vscanf --------- W __isoc99_vsscanf --------- W __isoc99_vswscanf --------- W __isoc99_vwscanf --------- W __isoc99_wscanf --------- W lgammaf_r --------- W lgammal_r --------- W lgamma_r --------- W lockf64 --------- W lseek64 --------- W lstat64 --------- W __lxstat64 --------- W madvise --------- W memrchr --------- W mkostemp64 --------- W mkostemps --------- W mkostemps64 --------- W mkstemp64 --------- W mkstemps64 --------- W mmap --------- W mmap64 --------- W mprotect --------- W mremap --------- W munmap --------- W newlocale --------- W nftw64 --------- W nl_langinfo --------- W nl_langinfo_l --------- W open64 --------- W openat64 --------- W optreset --------- W posix_fadvise64 --------- W posix_fallocate64 --------- W __posix_getopt --------- W pow10 --------- W pow10f --------- W pow10l --------- W pread64 --------- W preadv64 --------- W program_invocation_name --------- W program_invocation_short_name --------- W ptsname_r --------- W putwchar_unlocked --------- W putwc_unlocked --------- W pwrite64 --------- W pwritev64 --------- W readdir64 --------- W readdir64_r --------- W res_mkquery --------- W res_send --------- W scandir64 --------- W setnetent --------- W setrlimit64 --------- W signgam --------- W stat64 --------- W statfs --------- W statfs64 --------- W statvfs64 --------- W __stdio_exit_needed --------- W stpcpy --------- W stpncpy --------- W strchrnul --------- W strcoll_l --------- W strdup --------- W __strtoimax_internal --------- W __strtol_internal --------- W __strtoll_internal --------- W __strtoul_internal --------- W __strtoull_internal --------- W __strtoumax_internal --------- W strxfrm_l --------- W tmpfile64 --------- W truncate64 --------- W uselocale --------- W versionsort64 --------- W __vm_wait --------- W vsyslog --------- W wcscoll_l --------- W wcsxfrm_l --------- W __xpg_basename --------- W __xpg_strerror_r --------- W __xstat64 diff --git a/system/lib/wasm-libc.symbols b/system/lib/wasm-libc.symbols index f19c1be17162b..76b1ff5ff606e 100644 --- a/system/lib/wasm-libc.symbols +++ b/system/lib/wasm-libc.symbols @@ -41,9 +41,6 @@ -------- T log -------- T logf -------- T logl --------- T memcpy --------- T memmove --------- T memset -------- T pow -------- T powf -------- T powl diff --git a/system/lib/websocket/websocket_to_posix_socket.cpp b/system/lib/websocket/websocket_to_posix_socket.cpp new file mode 100644 index 0000000000000..10a44b4f128b7 --- /dev/null +++ b/system/lib/websocket/websocket_to_posix_socket.cpp @@ -0,0 +1,965 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +// Uncomment to enable debug printing +// #define POSIX_SOCKET_DEBUG + +// Uncomment to enable more verbose debug printing (in addition to uncommenting POSIX_SOCKET_DEBUG) +// #define POSIX_SOCKET_DEEP_DEBUG + +#define MIN(a,b) (((a)<(b))?(a):(b)) + +extern "C" +{ + +static void *memdup(const void *ptr, size_t sz) +{ + if (!ptr) return 0; + void *dup = malloc(sz); + if (dup) memcpy(dup, ptr, sz); + return dup; +} + +// Each proxied socket call has at least the following data. +struct SocketCallHeader +{ + int callId; + int function; +}; + +// Each socket call returns at least the following data. +struct SocketCallResultHeader +{ + int callId; + int ret; + int errno_; + // Buffer can contain more data here, conceptually: + // uint8_t extraData[]; +}; + +struct PosixSocketCallResult +{ + PosixSocketCallResult *next; + int callId; + int operationCompleted; + + // Before the call has finished, this field represents the minimum expected number of bytes that server will need to report back. + // After the call has finished, this field reports back the number of bytes pointed to by data, >= the expected value. + int bytes; + + // Result data: + SocketCallResultHeader *data; +}; + +// Shield multithreaded accesses to POSIX sockets functions in the program, namely the two variables 'bridgeSocket' and 'callResultHead' below. +static pthread_mutex_t bridgeLock = PTHREAD_MUTEX_INITIALIZER; + +// Socket handle for the connection from browser WebSocket to the sockets bridge proxy server. +static EMSCRIPTEN_WEBSOCKET_T bridgeSocket = (EMSCRIPTEN_WEBSOCKET_T)0; + +// Stores a linked list of all currently pending sockets operations (ones that are waiting for a reply back from the sockets proxy server) +static PosixSocketCallResult *callResultHead = 0; + +static PosixSocketCallResult *allocate_call_result(int expectedBytes) +{ + pthread_mutex_lock(&bridgeLock); // Guard multithreaded access to 'callResultHead' and 'nextId' below + PosixSocketCallResult *b = (PosixSocketCallResult*)(malloc(sizeof(PosixSocketCallResult))); + if (!b) + { +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "allocate_call_result: Failed to allocate call result struct of size %d bytes!\n", (int)sizeof(PosixSocketCallResult)); +#endif + pthread_mutex_unlock(&bridgeLock); + return 0; + } + static int nextId = 1; + b->callId = nextId++; +#ifdef POSIX_SOCKET_DEEP_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "allocate_call_result: allocated call ID %d\n", b->callId); +#endif + b->bytes = expectedBytes; + b->data = 0; + b->operationCompleted = 0; + b->next = 0; + + if (!callResultHead) + callResultHead = b; + else + { + PosixSocketCallResult *t = callResultHead; + while(t->next) t = t->next; + t->next = b; + } + pthread_mutex_unlock(&bridgeLock); + return b; +} + +static void free_call_result(PosixSocketCallResult *buffer) +{ +#ifdef POSIX_SOCKET_DEEP_DEBUG + if (buffer) + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "free_call_result: freed call ID %d\n", buffer->callId); +#endif + + if (buffer->data) free(buffer->data); + free(buffer); +} + +PosixSocketCallResult *pop_call_result(int callId) +{ + pthread_mutex_lock(&bridgeLock); // Guard multithreaded access to 'callResultHead' + PosixSocketCallResult *prev = 0; + PosixSocketCallResult *b = callResultHead; + while(b) + { + if (b->callId == callId) + { + if (prev) prev->next = b->next; + else callResultHead = b->next; + b->next = 0; +#ifdef POSIX_SOCKET_DEEP_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "pop_call_result: Removed call ID %d from pending sockets call queue\n", callId); +#endif + pthread_mutex_unlock(&bridgeLock); + return b; + } + prev = b; + b = b->next; + } + pthread_mutex_unlock(&bridgeLock); +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "pop_call_result: No such call ID %d in pending sockets call queue!\n", callId); +#endif + return 0; +} + +void wait_for_call_result(PosixSocketCallResult *b) +{ +#ifdef POSIX_SOCKET_DEEP_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "wait_for_call_result: Waiting for call ID %d\n", b->callId); +#endif + while(!emscripten_atomic_load_u32(&b->operationCompleted)) + emscripten_futex_wait(&b->operationCompleted, 0, 1e9); +#ifdef POSIX_SOCKET_DEEP_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "wait_for_call_result: Waiting for call ID %d done\n", b->callId); +#endif +} + +static EM_BOOL bridge_socket_on_message(int eventType, const EmscriptenWebSocketMessageEvent *websocketEvent, void *userData) +{ + if (websocketEvent->numBytes < sizeof(SocketCallResultHeader)) + { + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "Received corrupt WebSocket result message with size %d, not enough space for header, at least %d bytes!\n", (int)websocketEvent->numBytes, (int)sizeof(SocketCallResultHeader)); + return EM_TRUE; + } + + SocketCallResultHeader *header = (SocketCallResultHeader *)websocketEvent->data; + +#ifdef POSIX_SOCKET_DEEP_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "POSIX sockets bridge received message on thread %p, size: %d bytes, for call ID %d\n", (void*)pthread_self(), websocketEvent->numBytes, header->callId); +#endif + + PosixSocketCallResult *b = pop_call_result(header->callId); + if (!b) + { + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "Received WebSocket result message to unknown call ID %d!\n", (int)header->callId); + // TODO: Craft a socket result that signifies a failure, and wake the listening thread + return EM_TRUE; + } + + if (websocketEvent->numBytes < b->bytes) + { + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "Received corrupt WebSocket result message with size %d, expected at least %d bytes!\n", (int)websocketEvent->numBytes, b->bytes); + // TODO: Craft a socket result that signifies a failure, and wake the listening thread + return EM_TRUE; + } + + b->bytes = websocketEvent->numBytes; + b->data = (SocketCallResultHeader*)memdup(websocketEvent->data, websocketEvent->numBytes); + + if (!b->data) + { + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "Out of memory, tried to allocate %d bytes!\n", websocketEvent->numBytes); + return EM_TRUE; + } + + if (b->operationCompleted != 0) + { + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "Memory corruption(?): the received result for completed operation at address %p was expected to be in state 0, but it was at state %d!\n", &b->operationCompleted, (int)b->operationCompleted); + } + + emscripten_atomic_store_u32(&b->operationCompleted, 1); + emscripten_futex_wake(&b->operationCompleted, 0x7FFFFFFF); + + return EM_TRUE; +} + +EMSCRIPTEN_WEBSOCKET_T emscripten_init_websocket_to_posix_socket_bridge(const char *bridgeUrl) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_JS_STACK, "emscripten_init_websocket_to_posix_socket_bridge(bridgeUrl=\"%s\")\n", bridgeUrl); +#endif + pthread_mutex_lock(&bridgeLock); // Guard multithreaded access to 'bridgeSocket' + if (bridgeSocket) + { +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_WARN | EM_LOG_JS_STACK, "emscripten_init_websocket_to_posix_socket_bridge(bridgeUrl=\"%s\"): A previous bridge socket connection handle existed! Forcibly tearing old connection down.\n", bridgeUrl); +#endif + emscripten_websocket_close(bridgeSocket, 0, 0); + emscripten_websocket_delete(bridgeSocket); + bridgeSocket = 0; + } + EmscriptenWebSocketCreateAttributes attr; + emscripten_websocket_init_create_attributes(&attr); + attr.url = bridgeUrl; + bridgeSocket = emscripten_websocket_new(&attr); + emscripten_websocket_set_onmessage_callback_on_thread(bridgeSocket, 0, bridge_socket_on_message, EM_CALLBACK_THREAD_CONTEXT_MAIN_BROWSER_THREAD); + + pthread_mutex_unlock(&bridgeLock); + return bridgeSocket; +} + +#define POSIX_SOCKET_MSG_SOCKET 1 +#define POSIX_SOCKET_MSG_SOCKETPAIR 2 +#define POSIX_SOCKET_MSG_SHUTDOWN 3 +#define POSIX_SOCKET_MSG_BIND 4 +#define POSIX_SOCKET_MSG_CONNECT 5 +#define POSIX_SOCKET_MSG_LISTEN 6 +#define POSIX_SOCKET_MSG_ACCEPT 7 +#define POSIX_SOCKET_MSG_GETSOCKNAME 8 +#define POSIX_SOCKET_MSG_GETPEERNAME 9 +#define POSIX_SOCKET_MSG_SEND 10 +#define POSIX_SOCKET_MSG_RECV 11 +#define POSIX_SOCKET_MSG_SENDTO 12 +#define POSIX_SOCKET_MSG_RECVFROM 13 +#define POSIX_SOCKET_MSG_SENDMSG 14 +#define POSIX_SOCKET_MSG_RECVMSG 15 +#define POSIX_SOCKET_MSG_GETSOCKOPT 16 +#define POSIX_SOCKET_MSG_SETSOCKOPT 17 +#define POSIX_SOCKET_MSG_GETADDRINFO 18 +#define POSIX_SOCKET_MSG_GETNAMEINFO 19 + +#define MAX_SOCKADDR_SIZE 256 +#define MAX_OPTIONVALUE_SIZE 16 + +int socket(int domain, int type, int protocol) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "socket(domain=%d,type=%d,protocol=%d) on thread %p\n", domain, type, protocol, (void*)pthread_self()); +#endif + + struct { + SocketCallHeader header; + int domain; + int type; + int protocol; + } d; + + PosixSocketCallResult *b = allocate_call_result(sizeof(SocketCallResultHeader)); + d.header.callId = b->callId; + d.header.function = POSIX_SOCKET_MSG_SOCKET; + d.domain = domain; + d.type = type; + d.protocol = protocol; + emscripten_websocket_send_binary(bridgeSocket, &d, sizeof(d)); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret < 0) errno = b->data->errno_; + free_call_result(b); + return ret; +} + +int socketpair(int domain, int type, int protocol, int socket_vector[2]) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "socketpair(domain=%d,type=%d,protocol=%d, socket_vector=[%d,%d])\n", domain, type, protocol, socket_vector[0], socket_vector[1]); +#endif + + struct { + SocketCallHeader header; + int domain; + int type; + int protocol; + } d; + + struct Result { + SocketCallResultHeader header; + int sv[2]; + }; + + PosixSocketCallResult *b = allocate_call_result(sizeof(Result)); + d.header.callId = b->callId; + d.header.function = POSIX_SOCKET_MSG_SOCKETPAIR; + d.domain = domain; + d.type = type; + d.protocol = protocol; + emscripten_websocket_send_binary(bridgeSocket, &d, sizeof(d)); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret == 0) + { + Result *r = (Result*)b->data; + socket_vector[0] = r->sv[0]; + socket_vector[1] = r->sv[1]; + } + else + { + errno = b->data->errno_; + } + free_call_result(b); + return ret; +} + +int shutdown(int socket, int how) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "shutdown(socket=%d,how=%d)\n", socket, how); +#endif + + struct { + SocketCallHeader header; + int socket; + int how; + } d; + + PosixSocketCallResult *b = allocate_call_result(sizeof(SocketCallResultHeader)); + d.header.callId = b->callId; + d.header.function = POSIX_SOCKET_MSG_SHUTDOWN; + d.socket = socket; + d.how = how; + emscripten_websocket_send_binary(bridgeSocket, &d, sizeof(d)); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret != 0) errno = b->data->errno_; + free_call_result(b); + return ret; +} + +int bind(int socket, const struct sockaddr *address, socklen_t address_len) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "bind(socket=%d,address=%p,address_len=%d)\n", socket, address, address_len); +#endif + + struct Data { + SocketCallHeader header; + int socket; + uint32_t/*socklen_t*/ address_len; + uint8_t address[]; + }; + int numBytes = sizeof(Data) + address_len; + Data *d = (Data*)malloc(numBytes); + + PosixSocketCallResult *b = allocate_call_result(sizeof(SocketCallResultHeader)); + d->header.callId = b->callId; + d->header.function = POSIX_SOCKET_MSG_BIND; + d->socket = socket; + d->address_len = address_len; + if (address) memcpy(d->address, address, address_len); + else memset(d->address, 0, address_len); + emscripten_websocket_send_binary(bridgeSocket, d, numBytes); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret != 0) errno = b->data->errno_; + free_call_result(b); + + free(d); + return ret; +} + +int connect(int socket, const struct sockaddr *address, socklen_t address_len) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "connect(socket=%d,address=%p,address_len=%d)\n", socket, address, address_len); +#endif + + struct Data { + SocketCallHeader header; + int socket; + uint32_t/*socklen_t*/ address_len; + uint8_t address[]; + }; + int numBytes = sizeof(Data) + address_len; + Data *d = (Data*)malloc(numBytes); + + PosixSocketCallResult *b = allocate_call_result(sizeof(SocketCallResultHeader)); + d->header.callId = b->callId; + d->header.function = POSIX_SOCKET_MSG_CONNECT; + d->socket = socket; + d->address_len = address_len; + if (address) memcpy(d->address, address, address_len); + else memset(d->address, 0, address_len); + emscripten_websocket_send_binary(bridgeSocket, d, numBytes); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret != 0) errno = b->data->errno_; + free_call_result(b); + + free(d); + return ret; +} + +int listen(int socket, int backlog) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "listen(socket=%d,backlog=%d)\n", socket, backlog); +#endif + + struct { + SocketCallHeader header; + int socket; + int backlog; + } d; + + PosixSocketCallResult *b = allocate_call_result(sizeof(SocketCallResultHeader)); + d.header.callId = b->callId; + d.header.function = POSIX_SOCKET_MSG_LISTEN; + d.socket = socket; + d.backlog = backlog; + emscripten_websocket_send_binary(bridgeSocket, &d, sizeof(d)); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret != 0) errno = b->data->errno_; + free_call_result(b); + return ret; +} + +int accept(int socket, struct sockaddr *address, socklen_t *address_len) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "accept(socket=%d,address=%p,address_len=%p)\n", socket, address, address_len); +#endif + + struct { + SocketCallHeader header; + int socket; + uint32_t/*socklen_t*/ address_len; + } d; + + PosixSocketCallResult *b = allocate_call_result(sizeof(SocketCallResultHeader)); + d.header.callId = b->callId; + d.header.function = POSIX_SOCKET_MSG_ACCEPT; + d.socket = socket; + d.address_len = address_len ? *address_len : 0; + emscripten_websocket_send_binary(bridgeSocket, &d, sizeof(d)); + + struct Result { + SocketCallResultHeader header; + int address_len; + uint8_t address[]; + }; + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret == 0) + { + Result *r = (Result*)b->data; + int realAddressLen = MIN(b->bytes - sizeof(Result), r->address_len); + int copiedAddressLen = MIN(*address_len, realAddressLen); + if (address) memcpy(address, r->address, copiedAddressLen); + if (address_len) *address_len = realAddressLen; + } + else + { + errno = b->data->errno_; + } + free_call_result(b); + return ret; +} + +int getsockname(int socket, struct sockaddr *address, socklen_t *address_len) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "getsockname(socket=%d,address=%p,address_len=%p)\n", socket, address, address_len); +#endif + + struct { + SocketCallHeader header; + int socket; + uint32_t/*socklen_t*/ address_len; + } d; + + struct Result { + SocketCallResultHeader header; + int address_len; + uint8_t address[]; + }; + + PosixSocketCallResult *b = allocate_call_result(sizeof(Result)); + d.header.callId = b->callId; + d.header.function = POSIX_SOCKET_MSG_GETSOCKNAME; + d.socket = socket; + d.address_len = *address_len; + emscripten_websocket_send_binary(bridgeSocket, &d, sizeof(d) + *address_len - MAX_SOCKADDR_SIZE); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret == 0) + { + Result *r = (Result*)b->data; + int realAddressLen = MIN(b->bytes - sizeof(Result), r->address_len); + int copiedAddressLen = MIN(*address_len, realAddressLen); + if (address) memcpy(address, r->address, copiedAddressLen); + if (address_len) *address_len = realAddressLen; + } + else + { + errno = b->data->errno_; + } + free_call_result(b); + return ret; +} + +int getpeername(int socket, struct sockaddr *address, socklen_t *address_len) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "getpeername(socket=%d,address=%p,address_len=%p)\n", socket, address, address_len); +#endif + + struct { + SocketCallHeader header; + int socket; + uint32_t/*socklen_t*/ address_len; + } d; + + struct Result { + SocketCallResultHeader header; + int address_len; + uint8_t address[]; + }; + + PosixSocketCallResult *b = allocate_call_result(sizeof(Result)); + d.header.callId = b->callId; + d.header.function = POSIX_SOCKET_MSG_GETPEERNAME; + d.socket = socket; + d.address_len = *address_len; + emscripten_websocket_send_binary(bridgeSocket, &d, sizeof(d) + *address_len - MAX_SOCKADDR_SIZE); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret == 0) + { + Result *r = (Result*)b->data; + int realAddressLen = MIN(b->bytes - sizeof(Result), r->address_len); + int copiedAddressLen = MIN(*address_len, realAddressLen); + if (address) memcpy(address, r->address, copiedAddressLen); + if (address_len) *address_len = realAddressLen; + } + else + { + errno = b->data->errno_; + } + free_call_result(b); + return ret; +} + +ssize_t send(int socket, const void *message, size_t length, int flags) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "send(socket=%d,message=%p,length=%zd,flags=%d)\n", socket, message, length, flags); +#endif + + struct MSG { + SocketCallHeader header; + int socket; + uint32_t/*size_t*/ length; + int flags; + uint8_t message[]; + }; + size_t sz = sizeof(MSG)+length; + MSG *d = (MSG*)malloc(sz); + + PosixSocketCallResult *b = allocate_call_result(sizeof(SocketCallResultHeader)); + d->header.callId = b->callId; + d->header.function = POSIX_SOCKET_MSG_SEND; + d->socket = socket; + d->length = length; + d->flags = flags; + if (message) memcpy(d->message, message, length); + else memset(d->message, 0, length); + emscripten_websocket_send_binary(bridgeSocket, d, sz); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret < 0) errno = b->data->errno_; + free_call_result(b); + + free(d); + return ret; +} + +ssize_t recv(int socket, void *buffer, size_t length, int flags) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "recv(socket=%d,buffer=%p,length=%zd,flags=%d)\n", socket, buffer, length, flags); +#endif + + struct { + SocketCallHeader header; + int socket; + uint32_t/*size_t*/ length; + int flags; + } d; + + PosixSocketCallResult *b = allocate_call_result(sizeof(SocketCallResultHeader)); + d.header.callId = b->callId; + d.header.function = POSIX_SOCKET_MSG_RECV; + d.socket = socket; + d.length = length; + d.flags = flags; + emscripten_websocket_send_binary(bridgeSocket, &d, sizeof(d)); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret >= 0) + { + struct Result { + SocketCallResultHeader header; + uint8_t data[]; + }; + Result *r = (Result*)b->data; + if (buffer) memcpy(buffer, r->data, MIN(ret, length)); + } + else + { + errno = b->data->errno_; + } + free_call_result(b); + + return ret; +} + +ssize_t sendto(int socket, const void *message, size_t length, int flags, const struct sockaddr *dest_addr, socklen_t dest_len) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "sendto(socket=%d,message=%p,length=%zd,flags=%d,dest_addr=%p,dest_len=%d)\n", socket, message, length, flags, dest_addr, dest_len); +#endif + + struct MSG { + SocketCallHeader header; + int socket; + uint32_t/*size_t*/ length; + int flags; + uint32_t/*socklen_t*/ dest_len; + uint8_t dest_addr[MAX_SOCKADDR_SIZE]; + uint8_t message[]; + }; + size_t sz = sizeof(MSG)+length; + MSG *d = (MSG*)malloc(sz); + + PosixSocketCallResult *b = allocate_call_result(sizeof(SocketCallResultHeader)); + d->header.callId = b->callId; + d->header.function = POSIX_SOCKET_MSG_SENDTO; + d->socket = socket; + d->length = length; + d->flags = flags; + d->dest_len = dest_len; + memset(d->dest_addr, 0, sizeof(d->dest_addr)); + if (dest_addr) memcpy(d->dest_addr, dest_addr, dest_len); + if (message) memcpy(d->message, message, length); + else memset(d->message, 0, length); + emscripten_websocket_send_binary(bridgeSocket, d, sz); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret < 0) errno = b->data->errno_; + free_call_result(b); + + free(d); + return ret; +} + +ssize_t recvfrom(int socket, void *buffer, size_t length, int flags, struct sockaddr *address, socklen_t *address_len) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "recvfrom(socket=%d,buffer=%p,length=%zd,flags=%d,address=%p,address_len=%p)\n", socket, buffer, length, flags, address, address_len); +#endif + + struct { + SocketCallHeader header; + int socket; + uint32_t/*size_t*/ length; + int flags; + uint32_t/*socklen_t*/ address_len; + } d; + + PosixSocketCallResult *b = allocate_call_result(sizeof(SocketCallResultHeader)); + d.header.callId = b->callId; + d.header.function = POSIX_SOCKET_MSG_RECVFROM; + d.socket = socket; + d.length = length; + d.flags = flags; + d.address_len = *address_len; + emscripten_websocket_send_binary(bridgeSocket, &d, sizeof(d)); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret >= 0) + { + struct Result { + SocketCallResultHeader header; + int data_len; + int address_len; // N.B. this is the reported address length of the sender, that may be larger than what is actually serialized to this message. + uint8_t data_and_address[]; + }; + Result *r = (Result*)b->data; + if (buffer) memcpy(buffer, r->data_and_address, MIN(r->data_len, length)); + int copiedAddressLen = MIN((address_len ? *address_len : 0), r->address_len); + if (address) memcpy(address, r->data_and_address + r->data_len, copiedAddressLen); + if (address_len) *address_len = r->address_len; + } + else + { + errno = b->data->errno_; + } + free_call_result(b); + + return ret; +} + +ssize_t sendmsg(int socket, const struct msghdr *message, int flags) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "sendmsg(socket=%d,message=%p,flags=%d)\n", socket, message, flags); +#endif + + exit(1); // TODO + return 0; +} + +ssize_t recvmsg(int socket, struct msghdr *message, int flags) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "recvmsg(socket=%d,message=%p,flags=%d)\n", socket, message, flags); +#endif + + exit(1); // TODO + return 0; +} + +int getsockopt(int socket, int level, int option_name, void *option_value, socklen_t *option_len) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "getsockopt(socket=%d,level=%d,option_name=%d,option_value=%p,option_len=%p)\n", socket, level, option_name, option_value, option_len); +#endif + + struct { + SocketCallHeader header; + int socket; + int level; + int option_name; + uint32_t/*socklen_t*/ option_len; + } d; + + struct Result { + SocketCallResultHeader header; + uint8_t option_value[]; + }; + + PosixSocketCallResult *b = allocate_call_result(sizeof(Result)); + d.header.callId = b->callId; + d.header.function = POSIX_SOCKET_MSG_GETSOCKOPT; + d.socket = socket; + d.level = level; + d.option_name = option_name; + d.option_len = *option_len; + emscripten_websocket_send_binary(bridgeSocket, &d, sizeof(d)); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret == 0) + { + Result *r = (Result*)b->data; + int optLen = b->bytes - sizeof(Result); + if (option_value) memcpy(option_value, r->option_value, MIN(*option_len, optLen)); + if (option_len) *option_len = optLen; + } + else + { + errno = b->data->errno_; + } + free_call_result(b); + return ret; +} + +int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len) +{ +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "setsockopt(socket=%d,level=%d,option_name=%d,option_value=%p,option_len=%d)\n", socket, level, option_name, option_value, option_len); +#endif + + struct MSG { + SocketCallHeader header; + int socket; + int level; + int option_name; + int option_len; + uint8_t option_value[]; + }; + int messageSize = sizeof(MSG) + option_len; + MSG *d = (MSG*)malloc(messageSize); + + PosixSocketCallResult *b = allocate_call_result(sizeof(SocketCallResultHeader)); + d->header.callId = b->callId; + d->header.function = POSIX_SOCKET_MSG_SETSOCKOPT; + d->socket = socket; + d->level = level; + d->option_name = option_name; + if (option_value) memcpy(d->option_value, option_value, option_len); + else memset(d->option_value, 0, option_len); + d->option_len = option_len; + emscripten_websocket_send_binary(bridgeSocket, d, messageSize); + + wait_for_call_result(b); + int ret = b->data->ret; + if (ret != 0) errno = b->data->errno_; + free_call_result(b); + + free(d); + return ret; +} + +// Host name resolution: + +int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res) +{ +#define MAX_NODE_LEN 2048 +#define MAX_SERVICE_LEN 128 + + struct { + SocketCallHeader header; + char node[MAX_NODE_LEN]; // Arbitrary max length limit + char service[MAX_SERVICE_LEN]; // Arbitrary max length limit + int hasHints; + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + } d; + + struct ResAddrinfo + { + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + int/*socklen_t*/ ai_addrlen; + uint8_t /*sockaddr **/ ai_addr[]; + }; + + struct Result { + SocketCallResultHeader header; + char ai_canonname[MAX_NODE_LEN]; + int addrCount; + uint8_t /*ResAddrinfo[]*/ addr[]; + }; + + memset(&d, 0, sizeof(d)); + PosixSocketCallResult *b = allocate_call_result(sizeof(Result)); + d.header.callId = b->callId; + d.header.function = POSIX_SOCKET_MSG_GETADDRINFO; + if (node) + { + assert(strlen(node) <= MAX_NODE_LEN-1); + strncpy(d.node, node, MAX_NODE_LEN-1); + } + if (service) + { + assert(strlen(service) <= MAX_SERVICE_LEN-1); + strncpy(d.service, service, MAX_SERVICE_LEN-1); + } + d.hasHints = !!hints; + if (hints) + { + d.ai_flags = hints->ai_flags; + d.ai_family = hints->ai_family; + d.ai_socktype = hints->ai_socktype; + d.ai_protocol = hints->ai_protocol; + } + +#ifdef POSIX_SOCKET_DEBUG + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "getaddrinfo(node=%s,service=%s,hasHints=%d,ai_flags=%d,ai_family=%d,ai_socktype=%d,ai_protocol=%d,hintsPtr=%p,resPtr=%p)\n", node, service, d.hasHints, d.ai_flags, d.ai_family, d.ai_socktype, d.ai_protocol, hints, res); +#endif + + emscripten_websocket_send_binary(bridgeSocket, &d, sizeof(d)); + + wait_for_call_result(b); + int ret = b->data->ret; + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "getaddrinfo finished, ret=%d\n", ret); + if (ret == 0) + { + if (res) + { + Result *r = (Result*)b->data; + uint8_t *raiAddr = (uint8_t*)&r->addr[0]; + addrinfo *results = (addrinfo*)malloc(sizeof(addrinfo)*r->addrCount); + emscripten_log(EM_LOG_NO_PATHS | EM_LOG_CONSOLE | EM_LOG_ERROR | EM_LOG_JS_STACK, "%d results\n", r->addrCount); + for(size_t i = 0; i < r->addrCount; ++i) + { + ResAddrinfo *rai = (ResAddrinfo*)raiAddr; + results[i].ai_flags = rai->ai_flags; + results[i].ai_family = rai->ai_family; + results[i].ai_socktype = rai->ai_socktype; + results[i].ai_protocol = rai->ai_protocol; + results[i].ai_addrlen = rai->ai_addrlen; + results[i].ai_addr = (sockaddr *)malloc(results[i].ai_addrlen); + memcpy(results[i].ai_addr, rai->ai_addr, results[i].ai_addrlen); + results[i].ai_canonname = (i == 0) ? strdup(r->ai_canonname) : 0; + results[i].ai_next = i+1 < r->addrCount ? &results[i+1] : 0; + fprintf(stderr, "%d: ai_flags=%d, ai_family=%d, ai_socktype=%d, ai_protocol=%d, ai_addrlen=%d, ai_addr=", (int)i, results[i].ai_flags, results[i].ai_family, results[i].ai_socktype, results[i].ai_protocol, results[i].ai_addrlen); + for(size_t j = 0; j < results[i].ai_addrlen; ++j) + fprintf(stderr, " %02X", ((uint8_t*)results[i].ai_addr)[j]); + fprintf(stderr, ",ai_canonname=%s, ai_next=%p\n", results[i].ai_canonname, results[i].ai_next); + raiAddr += sizeof(ResAddrinfo) + rai->ai_addrlen; + } + *res = results; + } + } + else + { + errno = b->data->errno_; + if (res) *res = 0; + } + free_call_result(b); + + return ret; +} + +void freeaddrinfo(struct addrinfo *res) +{ + for(addrinfo *r = res; r; r = r->ai_next) + { + free(r->ai_canonname); + free(r->ai_addr); + } + free(res); +} + +int getnameinfo(const struct sockaddr *addr, socklen_t addrlen, char *host, socklen_t hostlen, char *serv, socklen_t servlen, int flags) +{ + // TODO + // POSIX_SOCKET_MSG_GETNAMEINFO + return -1; +} + +// TODO: +// const char *gai_strerror(int); + + + +} // ~extern "C" diff --git a/tests/test_other.py b/tests/test_other.py index 4b64e8f8d8454..34b6071a4227b 100644 --- a/tests/test_other.py +++ b/tests/test_other.py @@ -7881,7 +7881,7 @@ def test(filename, expectations, size_slack): 0, [], [], 8, 0, 0, 0), # noqa; totally empty! # we don't metadce with linkable code! other modules may want stuff (['-O3', '-s', 'MAIN_MODULE=1'], - 1556, [], [], 226057, 28, 75, None), # noqa; don't compare the # of functions in a main module, which changes a lot + 1566, [], [], 226057, 28, 75, None), # noqa; don't compare the # of functions in a main module, which changes a lot ], size_slack) # noqa print('test on a minimal pure computational thing') diff --git a/tests/test_sockets.py b/tests/test_sockets.py index b5546829b2ef8..9b06a001efd2f 100644 --- a/tests/test_sockets.py +++ b/tests/test_sockets.py @@ -123,6 +123,29 @@ def __exit__(self, *args, **kwargs): # make sure to use different ports in each one because it takes a while for the processes to be cleaned up +# Executes a native executable server process +class BackgroundServerProcess(object): + def __init__(self, args): + self.processes = [] + self.args = args + + def __enter__(self): + print('Running background server: ' + str(self.args)) + process = Popen(self.args) + self.processes.append(process) + + def __exit__(self, *args, **kwargs): + clean_processes(self.processes) + + +def NodeJsWebSocketEchoServerProcess(): + return BackgroundServerProcess([path_from_root('tests', 'websocket', 'nodejs_websocket_echo_server.js')]) + + +def PythonTcpEchoServerProcess(port): + return BackgroundServerProcess([PYTHON, path_from_root('tests', 'websocket', 'tcp_echo_server.py'), port]) + + class sockets(BrowserCore): emcc_args = [] @@ -433,3 +456,24 @@ def test_nodejs_sockets_echo(self): out = run_js('client.js', engine=NODE_JS, full_output=True) self.assertContained('do_msg_read: read 14 bytes', out) self.assertContained('connect: ws://localhost:59168/testA/testB, text,base64,binary', out) + + # Test Emscripten WebSockets API to send and receive text and binary messages against an echo server. + # N.B. running this test requires 'npm install ws' in Emscripten root directory + def test_websocket_send(self): + with NodeJsWebSocketEchoServerProcess(): + self.btest(os.path.join('websocket', 'test_websocket_send.c'), expected='101', args=['-lwebsocket', '-s', 'NO_EXIT_RUNTIME=1', '-s', 'WEBSOCKET_DEBUG=1']) + + # Test that native POSIX sockets API can be used by proxying calls to an intermediate WebSockets -> POSIX sockets bridge server + def test_posix_proxy_sockets(self): + # Build the websocket bridge server + run_process(['cmake', path_from_root('tools', 'websocket_to_posix_proxy')]) + run_process(['cmake', '--build', '.']) + if os.name == 'nt': # This is not quite exact, instead of "isWindows()" this should be "If CMake defaults to building with Visual Studio", but there is no good check for that, so assume Windows==VS. + proxy_server = os.path.join(self.get_dir(), 'Debug', 'websocket_to_posix_proxy.exe') + else: + proxy_server = os.path.join(self.get_dir(), 'websocket_to_posix_proxy') + + with BackgroundServerProcess([proxy_server, '8080']): + with PythonTcpEchoServerProcess('7777'): + # Build and run the TCP echo client program with Emscripten + self.btest(path_from_root('tests', 'websocket', 'tcp_echo_client.cpp'), expected='101', args=['-lwebsocket', '-s', 'PROXY_POSIX_SOCKETS=1', '-s', 'USE_PTHREADS=1', '-s', 'PROXY_TO_PTHREAD=1']) diff --git a/tests/websocket/nodejs_websocket_echo_server.js b/tests/websocket/nodejs_websocket_echo_server.js new file mode 100644 index 0000000000000..c2923f8d59284 --- /dev/null +++ b/tests/websocket/nodejs_websocket_echo_server.js @@ -0,0 +1,36 @@ +function padHex(number, digits) { + var s = number.toString(16); + return Array(Math.max(digits - s.length + 1, 0)).join(0) + s; +} + +function hexDump(bytes) { + var s = ' '; + for(var i = 0; i < bytes.length; ++i) { + s += ' ' + padHex(bytes[i], 2); + if (i % 16 == 15) { + console.log(s); + s = ' '; + } + else if (i % 8 == 7) s += ' '; + } + console.log(s); +} + +var port = 8088; +var ws = require('ws'); +var wss = new ws.Server({ port: port }); +console.log('WebSocket server listening on ws://localhost:' + port + '/'); +wss.on('connection', function(ws) { + console.log('Client connected!'); + ws.on('message', function(message) { + if (typeof message === 'string') { + console.log('received TEXT: ' + message.length + ' characters:'); + console.log(' "' + message + '"'); + } else { + console.log('received BINARY: ' + message.length + ' bytes:'); + hexDump(message); + } + console.log(''); + ws.send(message); // Echo back the received message + }); +}); diff --git a/tests/websocket/tcp_echo_client.cpp b/tests/websocket/tcp_echo_client.cpp new file mode 100644 index 0000000000000..47a001ef7a46c --- /dev/null +++ b/tests/websocket/tcp_echo_client.cpp @@ -0,0 +1,123 @@ +// TCP client that sends a few messages to a server and prints out the replies +#include +#include +#include +#include +#include +#include +#include + +#ifdef __EMSCRIPTEN__ +#include +#include +#include + +EMSCRIPTEN_WEBSOCKET_T bridgeSocket = 0; + +extern "C" { +EMSCRIPTEN_WEBSOCKET_T emscripten_init_websocket_to_posix_socket_bridge(const char *bridgeUrl); +} +#endif + +int lookup_host(const char *host) +{ + struct addrinfo hints, *res; + int errcode; + char addrstr[100]; + void *ptr; + + memset(&hints, 0, sizeof (hints)); + hints.ai_family = PF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags |= AI_CANONNAME; + + errcode = getaddrinfo(host, NULL, &hints, &res); + if (errcode != 0) + { + printf("getaddrinfo failed!\n"); + return -1; + } + + printf("Host: %s\n", host); + while (res) + { + inet_ntop(res->ai_family, res->ai_addr->sa_data, addrstr, 100); + + switch (res->ai_family) + { + case AF_INET: + ptr = &((struct sockaddr_in *)res->ai_addr)->sin_addr; + break; + case AF_INET6: + ptr = &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr; + break; + } + inet_ntop(res->ai_family, ptr, addrstr, 100); + printf("IPv%d address: %s (%s)\n", res->ai_family == PF_INET6 ? 6 : 4, addrstr, res->ai_canonname); + res = res->ai_next; + } + + return 0; +} + +int main(int argc , char *argv[]) +{ +#ifdef __EMSCRIPTEN__ + bridgeSocket = emscripten_init_websocket_to_posix_socket_bridge("ws://localhost:8080"); + // Synchronously wait until connection has been established. + uint16_t readyState = 0; + do { + emscripten_websocket_get_ready_state(bridgeSocket, &readyState); + emscripten_thread_sleep(100); + } while(readyState == 0); +#endif + + lookup_host("google.com"); + + // Create socket + int sock = socket(AF_INET, SOCK_STREAM, 0); + if (sock == -1) + { + printf("Could not create socket"); + exit(1); + } + printf("Socket created: %d\n", sock); + + struct sockaddr_in server; + server.sin_addr.s_addr = inet_addr("127.0.0.1"); + server.sin_family = AF_INET; + server.sin_port = htons(7777); + + if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) + { + perror("connect failed. Error"); + return 1; + } + + puts("Connected\n"); + for(int i = 0; i < 10; ++i) + { + const char message[] = "hell"; + if (send(sock, message, strlen(message), 0) < 0) + { + puts("Send failed"); + return 1; + } + + char server_reply[256]; + if (recv(sock, server_reply, 256, 0) < 0) + { + puts("recv failed"); + break; + } + + puts("Server reply: "); + puts(server_reply); + } + + close(sock); +#ifdef REPORT_RESULT + REPORT_RESULT(101); +#endif + return 0; +} diff --git a/tests/websocket/tcp_echo_server.py b/tests/websocket/tcp_echo_server.py new file mode 100644 index 0000000000000..fce31bb8ab026 --- /dev/null +++ b/tests/websocket/tcp_echo_server.py @@ -0,0 +1,18 @@ +import socket, sys + +def listen(): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind(('0.0.0.0', int(sys.argv[1]))) + s.listen(10) + while True: + conn, address = s.accept() + while True: + data = conn.recv(2048) + if not data: + break + conn.sendall(data) + conn.close() + +if __name__ == "__main__": + listen() diff --git a/tests/websocket/tcp_in_two_threads.cpp b/tests/websocket/tcp_in_two_threads.cpp new file mode 100644 index 0000000000000..b74378259d9a8 --- /dev/null +++ b/tests/websocket/tcp_in_two_threads.cpp @@ -0,0 +1,162 @@ +// TCP client that operates TCP connection in two threads: one thread that does blocking recv(), +// and another that does send()s +#include +#include +#include +#include +#include +#include +#include + +#ifdef __EMSCRIPTEN__ +#include +#include +#include + +EMSCRIPTEN_WEBSOCKET_T bridgeSocket = 0; + +extern "C" { +EMSCRIPTEN_WEBSOCKET_T emscripten_init_websocket_to_posix_socket_bridge(const char *bridgeUrl); +} +#endif + +int lookup_host(const char *host) +{ + struct addrinfo hints, *res; + int errcode; + char addrstr[100]; + void *ptr; + + memset(&hints, 0, sizeof (hints)); + hints.ai_family = PF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags |= AI_CANONNAME; + + errcode = getaddrinfo(host, NULL, &hints, &res); + if (errcode != 0) + { + printf("getaddrinfo failed!\n"); + return -1; + } + + printf("Host: %s\n", host); + while (res) + { + inet_ntop(res->ai_family, res->ai_addr->sa_data, addrstr, 100); + + switch (res->ai_family) + { + case AF_INET: + ptr = &((struct sockaddr_in *)res->ai_addr)->sin_addr; + break; + case AF_INET6: + ptr = &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr; + break; + } + inet_ntop(res->ai_family, ptr, addrstr, 100); + printf("IPv%d address: %s (%s)\n", res->ai_family == PF_INET6 ? 6 : 4, addrstr, res->ai_canonname); + res = res->ai_next; + } + + return 0; +} + +int pendingMessages = 0; + +void *send_thread(void *arg) +{ + int sock = (int)arg; + + for(int i = 0; i < 10; ++i) + { + char message[] = "hella"; + message[4] += i; + + while(emscripten_atomic_load_u32(&pendingMessages) != 0) + emscripten_thread_sleep(10); + + printf("Send()ing\n"); + if (send(sock, message, strlen(message), 0) < 0) + { + puts("Send failed"); + pthread_exit((void*)1); + } + printf("Send() done\n"); + emscripten_atomic_add_u32(&pendingMessages, 1); + } + pthread_exit(0); +} + +void *recv_thread(void *arg) +{ + int sock = (int)arg; + + for(int i = 0; i < 10; ++i) + { + char server_reply[256] = {}; + printf("Recv()ing\n"); + if (recv(sock, server_reply, 256, 0) < 0) + { + puts("recv failed"); + pthread_exit((void*)1); + } + printf("Recv() done\n"); + + puts("Server reply: "); + puts(server_reply); + emscripten_atomic_sub_u32(&pendingMessages, 1); + } + pthread_exit(0); +} + +int main(int argc , char *argv[]) +{ +#ifdef __EMSCRIPTEN__ + bridgeSocket = emscripten_init_websocket_to_posix_socket_bridge("ws://localhost:8080"); + // Synchronously wait until connection has been established. + uint16_t readyState = 0; + do { + emscripten_websocket_get_ready_state(bridgeSocket, &readyState); + emscripten_thread_sleep(100); + } while(readyState == 0); +#endif + + lookup_host("google.com"); + + // Create socket + int sock = socket(AF_INET, SOCK_STREAM, 0); + if (sock == -1) + { + printf("Could not create socket"); + exit(1); + } + printf("Socket created: %d\n", sock); + + struct sockaddr_in server; + server.sin_addr.s_addr = inet_addr("127.0.0.1"); + server.sin_family = AF_INET; + server.sin_port = htons(8888); + + if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) + { + perror("connect failed. Error"); + return 1; + } + + pthread_t sendThread; + pthread_t recvThread; + pthread_create(&recvThread, 0, &recv_thread, (void*)sock); + emscripten_thread_sleep(1000); // To get a better guarantee that the first recv() precedes the first send(), sleep for a moment between recv+send thread starts + pthread_create(&sendThread, 0, &send_thread, (void*)sock); + void *sendRet; + void *recvRet; + printf("Waiting for send thread to be finished\n"); + pthread_join(sendThread, &sendRet); + printf("Send thread finished, waiting for recv thread to be finished\n"); + pthread_join(recvThread, &recvRet); + printf("Send thread and recv thread finished\n"); + close(sock); + if ((int)sendRet != 0) fprintf(stderr, "pthread send failed!\n"); + if ((int)recvRet != 0) fprintf(stderr, "pthread recv failed!\n"); + return 0; +} diff --git a/tests/websocket/test_websocket_send.c b/tests/websocket/test_websocket_send.c new file mode 100644 index 0000000000000..b72a092d501f0 --- /dev/null +++ b/tests/websocket/test_websocket_send.c @@ -0,0 +1,89 @@ +#include +#include +#include + +EM_BOOL WebSocketOpen(int eventType, const EmscriptenWebSocketOpenEvent *e, void *userData) +{ + printf("open(eventType=%d, userData=%d)\n", eventType, (int)userData); + + emscripten_websocket_send_utf8_text(e->socket, "hello on the other side"); + + char data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + emscripten_websocket_send_binary(e->socket, data, sizeof(data)); + + return 0; +} + +EM_BOOL WebSocketClose(int eventType, const EmscriptenWebSocketCloseEvent *e, void *userData) +{ + printf("close(eventType=%d, wasClean=%d, code=%d, reason=%s, userData=%d)\n", eventType, e->wasClean, e->code, e->reason, (int)userData); + return 0; +} + +EM_BOOL WebSocketError(int eventType, const EmscriptenWebSocketErrorEvent *e, void *userData) +{ + printf("error(eventType=%d, userData=%d)\n", eventType, (int)userData); + return 0; +} + +static int passed = 0; + +EM_BOOL WebSocketMessage(int eventType, const EmscriptenWebSocketMessageEvent *e, void *userData) +{ + printf("message(eventType=%d, userData=%d, data=%p, numBytes=%d, isText=%d)\n", eventType, (int)userData, e->data, e->numBytes, e->isText); + if (e->isText) + { + printf("text data: \"%s\"\n", e->data); +#ifdef REPORT_RESULT + if (!!strcmp((const char*)e->data, "hello on the other side")) REPORT_RESULT(-1); + passed += 1; +#endif + } + else + { + printf("binary data:"); + for(int i = 0; i < e->numBytes; ++i) + { + printf(" %02X", e->data[i]); +#ifdef REPORT_RESULT + if (e->data[i] != i) REPORT_RESULT(-2); +#endif + } + printf("\n"); + passed += 100; + + emscripten_websocket_close(e->socket, 0, 0); + emscripten_websocket_delete(e->socket); +#ifdef REPORT_RESULT + printf("%d\n", passed); + REPORT_RESULT(passed); +#endif + } + return 0; +} + +int main() +{ + if (!emscripten_websocket_is_supported()) + { + printf("WebSockets are not supported, cannot continue!\n"); + exit(1); + } + + EmscriptenWebSocketCreateAttributes attr; + emscripten_websocket_init_create_attributes(&attr); + + attr.url = "ws://localhost:8088"; + + EMSCRIPTEN_WEBSOCKET_T socket = emscripten_websocket_new(&attr); + if (socket <= 0) + { + printf("WebSocket creation failed, error code %d!\n", (EMSCRIPTEN_RESULT)socket); + exit(1); + } + + emscripten_websocket_set_onopen_callback(socket, (void*)42, WebSocketOpen); + emscripten_websocket_set_onclose_callback(socket, (void*)43, WebSocketClose); + emscripten_websocket_set_onerror_callback(socket, (void*)44, WebSocketError); + emscripten_websocket_set_onmessage_callback(socket, (void*)45, WebSocketMessage); +} diff --git a/tools/shared.py b/tools/shared.py index af28499149d7e..ca11fa4f5e558 100644 --- a/tools/shared.py +++ b/tools/shared.py @@ -2714,7 +2714,8 @@ def path_to_system_js_libraries(library_name): 'X11': 'library_xlib.js', 'SDL': 'library_sdl.js', 'stdc++': '', - 'uuid': 'library_uuid.js' + 'uuid': 'library_uuid.js', + 'websocket': 'library_websocket.js' } library_files = [] if library_name in js_system_libraries: diff --git a/tools/system_libs.py b/tools/system_libs.py index 118a7127f1ad2..8e674a44c7a4f 100755 --- a/tools/system_libs.py +++ b/tools/system_libs.py @@ -19,6 +19,11 @@ stdout = None stderr = None +LIBC_SOCKETS = ['socket.c', 'socketpair.c', 'shutdown.c', 'bind.c', 'connect.c', + 'listen.c', 'accept.c', 'getsockname.c', 'getpeername.c', 'send.c', + 'recv.c', 'sendto.c', 'recvfrom.c', 'sendmsg.c', 'recvmsg.c', + 'getsockopt.c', 'setsockopt.c', 'freeaddrinfo.c'] + def call_process(cmd): shared.run_process(cmd, stdout=stdout, stderr=stderr) @@ -87,6 +92,7 @@ def read_symbols(path): # XXX We also need to add libc symbols that use malloc, for example strdup. It's very rare to use just them and not # a normal malloc symbol (like free, after calling strdup), so we haven't hit this yet, but it is possible. libc_symbols = read_symbols(shared.path_from_root('system', 'lib', 'libc.symbols')) + libc_sockets_symbols = read_symbols(shared.path_from_root('system', 'lib', 'libc-sockets.symbols')) libcxx_symbols = read_symbols(shared.path_from_root('system', 'lib', 'libcxx', 'symbols')) libcxxabi_symbols = read_symbols(shared.path_from_root('system', 'lib', 'libcxxabi', 'symbols')) gl_symbols = read_symbols(shared.path_from_root('system', 'lib', 'gl.symbols')) @@ -188,6 +194,8 @@ def create_libc(libname): 'faccessat.c', ] + blacklist += LIBC_SOCKETS + # individual math files blacklist += [ 'abs.c', 'cos.c', 'cosf.c', 'cosl.c', 'sin.c', 'sinf.c', 'sinl.c', @@ -235,6 +243,19 @@ def create_libc(libname): args += threading_flags(libname) return build_libc(libname, libc_files, args) + def create_libc_sockets(libname): + logging.debug('building libc-sockets for cache') + network_dir = shared.path_from_root('system', 'lib', 'libc', 'musl', 'src', 'network') + libc_files = [os.path.join(network_dir, x) for x in LIBC_SOCKETS] + + # Without -fno-builtin, LLVM can optimize away or convert calls to library + # functions to something else based on assumptions that they behave exactly + # like the standard library. This can cause unexpected bugs when we use our + # custom standard library. The same for other libc/libm builds. + args = ['-Os', '-fno-builtin'] + args += threading_flags(libname) + return build_libc(libname, libc_files, args) + def create_pthreads(libname): # Add pthread files. pthreads_files = files_in_path( @@ -385,6 +406,9 @@ def create_html5(libname): files += [os.path.join(src_dir, f) for f in filenames] return build_libc(libname, files, ['-Oz']) + def create_posix_proxy(libname): + return build_libc(libname, [shared.path_from_root('system', 'lib', 'websocket', 'websocket_to_posix_socket.cpp')], ['-Oz']) + def create_compiler_rt(libname): files = files_in_path( path_components=['system', 'lib', 'compiler-rt', 'lib', 'builtins'], @@ -633,6 +657,11 @@ class Dummy(object): system_libs += [Library('libgl', ext, create_gl, gl_symbols, [libc_name], False)] # noqa system_libs.append(Library(libc_name, ext, create_libc, libc_symbols, libc_deps, False)) + if shared.Settings.PROXY_POSIX_SOCKETS: + system_libs.append(Library('libposix-sockets-proxy', ext, create_posix_proxy, [], [], False)) + forced += ['libposix-sockets-proxy'] + else: + system_libs.append(Library(libc_name + '-sockets', ext, create_libc_sockets, libc_sockets_symbols, libc_deps, False)) # if building to wasm, we need more math code, since we have less builtins if shared.Settings.WASM: diff --git a/tools/websocket_to_posix_proxy/CMakeLists.txt b/tools/websocket_to_posix_proxy/CMakeLists.txt new file mode 100644 index 0000000000000..ce06da6c2145f --- /dev/null +++ b/tools/websocket_to_posix_proxy/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 2.8) + +project(websocket_to_posix_proxy) + +file(GLOB sourceFiles src/*.cpp src/*.h) + +add_executable(websocket_to_posix_proxy ${sourceFiles}) + +if (WIN32) + add_definitions(-D_CRT_SECURE_NO_WARNINGS) + add_definitions(/wd4200) # "nonstandard extension used: zero-sized array in struct/union" + target_link_libraries(websocket_to_posix_proxy Ws2_32.lib) +endif() diff --git a/tools/websocket_to_posix_proxy/src/main.cpp b/tools/websocket_to_posix_proxy/src/main.cpp new file mode 100644 index 0000000000000..96b84ffde50cc --- /dev/null +++ b/tools/websocket_to_posix_proxy/src/main.cpp @@ -0,0 +1,382 @@ +#include +#include +#include +#include +#include "posix_sockets.h" +#include "threads.h" +#include +#include + +#include "sha1.h" +#include "websocket_to_posix_proxy.h" +#include "socket_registry.h" + +// #define PROXY_DEBUG + +// #define PROXY_DEEP_DEBUG + +static const unsigned char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static void base64_encode(void *dst, const void *src, size_t len) // thread-safe, re-entrant +{ + assert(dst != src); + unsigned int *d = (unsigned int *)dst; + const unsigned char *s = (const unsigned char*)src; + const unsigned char *end = s + len; + while(s < end) + { + uint32_t e = *s++ << 16; + if (s < end) e |= *s++ << 8; + if (s < end) e |= *s++; + *d++ = b64[e >> 18] | (b64[(e >> 12) & 0x3F] << 8) | (b64[(e >> 6) & 0x3F] << 16) | (b64[e & 0x3F] << 24); + } + for (size_t i = 0; i < (3 - (len % 3)) % 3; i++) ((char *)d)[-1-i] = '='; +} + +#define BUFFER_SIZE 1024 +#define on_error(...) { fprintf(stderr, __VA_ARGS__); fflush(stderr); exit(1); } + +// Given a multiline string of HTTP headers, returns a pointer to the beginning of the value of given header inside the string that was passed in. +static int GetHttpHeader(const char *headers, const char *header, char *out) // thread-safe, re-entrant +{ + const char *pos = strstr(headers, header); + if (!pos) return 0; + pos += strlen(header); + const char *end = pos; + while(*end != '\r') ++end; + memcpy(out, pos, end-pos); + out[end-pos] = '\0'; + return end-pos; +} + +// Sends WebSocket handshake back to the given WebSocket connection. +void SendHandshake(int fd, const char *request) +{ + char key[128]; + GetHttpHeader(request, "Sec-WebSocket-Key: ", key); + const char webSocketGlobalGuid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + strcat(key, webSocketGlobalGuid); + + char sha1[21]; + printf("hashing key: \"%s\"\n", key); + SHA1(sha1, key, strlen(key)); + + char handshakeMsg[] = + "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Accept: 0000000000000000000000000000\r\n" + "\r\n"; + + base64_encode(strstr(handshakeMsg, "Sec-WebSocket-Accept: ") + strlen("Sec-WebSocket-Accept: "), sha1, 20); + + int err = send(fd, handshakeMsg, strlen(handshakeMsg), 0); + if (err < 0) on_error("Client write failed\n"); + printf("Sent handshake:\n%s\n", handshakeMsg); +} + +// Validates if the given, possibly partially received WebSocket message has enough bytes to contain a full WebSocket header. +static bool WebSocketHasFullHeader(uint8_t *data, uint64_t obtainedNumBytes) +{ + if (obtainedNumBytes < 2) return false; + uint64_t expectedNumBytes = 2; + WebSocketMessageHeader *header = (WebSocketMessageHeader *)data; + if (header->mask) expectedNumBytes += 4; + switch(header->payloadLength) + { + case 127: return expectedNumBytes += 8; break; + case 126: return expectedNumBytes += 2; break; + default: break; + } + return obtainedNumBytes >= expectedNumBytes; +} + +// Computes the total number of bytes that the given WebSocket message will take up. +uint64_t WebSocketFullMessageSize(uint8_t *data, uint64_t obtainedNumBytes) +{ + assert(WebSocketHasFullHeader(data, obtainedNumBytes)); + + uint64_t expectedNumBytes = 2; + WebSocketMessageHeader *header = (WebSocketMessageHeader *)data; + if (header->mask) expectedNumBytes += 4; + switch(header->payloadLength) + { + case 127: return expectedNumBytes += 8 + ntoh64(*(uint64_t*)(data+2)); break; + case 126: return expectedNumBytes += 2 + ntohs(*(uint16_t*)(data+2)); break; + default: expectedNumBytes += header->payloadLength; break; + } + return expectedNumBytes; +} + +// Tests the structure integrity of the websocket message length. +bool WebSocketValidateMessageSize(uint8_t *data, uint64_t obtainedNumBytes) +{ + uint64_t expectedNumBytes = WebSocketFullMessageSize(data, obtainedNumBytes); + + if (expectedNumBytes != obtainedNumBytes) + { + printf("Corrupt WebSocket message size! (got %llu bytes, expected %llu bytes)\n", obtainedNumBytes, expectedNumBytes); + printf("Received data:"); + for(size_t i = 0; i < obtainedNumBytes; ++i) + printf(" %02X", data[i]); + printf("\n"); + } + return expectedNumBytes == obtainedNumBytes; +} + +uint64_t WebSocketMessagePayloadLength(uint8_t *data, uint64_t numBytes) +{ + WebSocketMessageHeader *header = (WebSocketMessageHeader *)data; + switch(header->payloadLength) + { + case 127: return ntoh64(*(uint64_t*)(data+2)); + case 126: return ntohs(*(uint16_t*)(data+2)); + default: return header->payloadLength; + } +} + +uint32_t WebSocketMessageMaskingKey(uint8_t *data, uint64_t numBytes) +{ + WebSocketMessageHeader *header = (WebSocketMessageHeader *)data; + if (!header->mask) return 0; + switch(header->payloadLength) + { + case 127: return *(uint32_t*)(data+10); + case 126: return *(uint32_t*)(data+4); + default: return *(uint32_t*)(data+2); + } +} + +uint8_t *WebSocketMessageData(uint8_t *data, uint64_t numBytes) +{ + WebSocketMessageHeader *header = (WebSocketMessageHeader *)data; + data += 2; // Two bytes of fixed size header + if (header->mask) data += 4; // If there is a masking key present in the header, that takes up 4 bytes + switch(header->payloadLength) + { + case 127: return data + 8; // 64-bit length + case 126: return data + 2; // 16-bit length + default: return data; // 7-bit length that was embedded in fixed size header. + } +} + +void CloseWebSocket(int client_fd) +{ + printf("Closing WebSocket connection %d\n", client_fd); + CloseAllSocketsByConnection(client_fd); + shutdown(client_fd, SHUTDOWN_BIDIRECTIONAL); + CLOSE_SOCKET(client_fd); +} + +const char *WebSocketOpcodeToString(int opcode) +{ + static const char *opcodes[] = { "continuation frame (0x0)", "text frame (0x1)", "binary frame (0x2)", "reserved(0x3)", "reserved(0x4)", "reserved(0x5)", + "reserved(0x6)", "reserved(0x7)", "connection close (0x8)", "ping (0x9)", "pong (0xA)", "reserved(0xB)", "reserved(0xC)", "reserved(0xD)", "reserved(0xE)", "reserved(0xF)" }; + return opcodes[opcode]; +} + +void DumpWebSocketMessage(uint8_t *data, uint64_t numBytes) +{ + bool goodMessageSize = WebSocketValidateMessageSize(data, numBytes); + if (!goodMessageSize) + return; + + WebSocketMessageHeader *header = (WebSocketMessageHeader *)data; + uint64_t payloadLength = WebSocketMessagePayloadLength(data, numBytes); + uint8_t *payload = WebSocketMessageData(data, numBytes); + + printf("Received: FIN: %d, opcode: %s, mask: 0x%08X, payload length: %llu bytes, unmasked payload:", header->fin, WebSocketOpcodeToString(header->opcode), + WebSocketMessageMaskingKey(data, numBytes), payloadLength); + for(uint64_t i = 0; i < payloadLength; ++i) + { + if (i%16 == 0) printf("\n"); + if (i%8==0) printf(" "); + printf(" %02X", payload[i]); + if (i >= 63 && payloadLength > 64) + { + printf("\n ... (%llu more bytes)", payloadLength-i); + break; + } + } + printf("\n"); +} + +// connection thread manages a single active proxy connection. +THREAD_RETURN_T connection_thread(void *arg) +{ + int client_fd = (int)(uintptr_t)arg; + printf("Established new proxy connection handler thread for incoming connection, at fd=%d\n", client_fd); // TODO: print out getpeername()+getsockname() for more info + + // Waiting for connection upgrade handshake + char buf[BUFFER_SIZE]; + int read = recv(client_fd, buf, BUFFER_SIZE, 0); + + if (!read) + { + CloseWebSocket(client_fd); + EXIT_THREAD(0); + } + + if (read < 0) + { + fprintf(stderr, "Client read failed\n"); + CloseWebSocket(client_fd); + EXIT_THREAD(0); + } + +#ifdef PROXY_DEEP_DEBUG + printf("Received:"); + for(int i = 0; i < read; ++i) + { + printf(" %02X", buf[i]); + } + printf("\n"); +// printf("In text:\n%s\n", buf); +#endif + SendHandshake(client_fd, buf); + +#ifdef PROXY_DEEP_DEBUG + printf("Handshake received, entering message loop:\n"); +#endif + + std::vector fragmentData; + + bool connectionAlive = true; + while (connectionAlive) + { + int read = recv(client_fd, buf, BUFFER_SIZE, 0); + + if (!read) break; // done reading + if (read < 0) + { + fprintf(stderr, "Client read failed\n"); + EXIT_THREAD(0); + } + +#ifdef PROXY_DEEP_DEBUG + printf("Received:"); + for(int i = 0; i < read; ++i) + { + printf(" %02X", ((unsigned char*)buf)[i]); + } + printf("\n"); +// printf("In text:\n%s\n", buf); +#endif + +#ifdef PROXY_DEEP_DEBUG + printf("Have %d+%d==%d bytes now in queue\n", (int)fragmentData.size(), (int)read, (int)(fragmentData.size()+read)); +#endif + fragmentData.insert(fragmentData.end(), buf, buf+read); + + // Process received fragments until there is not enough data for a full message + while(!fragmentData.empty()) + { + bool hasFullHeader = WebSocketHasFullHeader(&fragmentData[0], fragmentData.size()); + if (!hasFullHeader) + { +#ifdef PROXY_DEEP_DEBUG + printf("(not enough for a full WebSocket header)\n"); +#endif + break; + } + uint64_t neededBytes = WebSocketFullMessageSize(&fragmentData[0], fragmentData.size()); + if (fragmentData.size() < neededBytes) + { +#ifdef PROXY_DEEP_DEBUG + printf("(not enough for a full WebSocket message, needed %d bytes)\n", (int)neededBytes); +#endif + break; + } + + WebSocketMessageHeader *header = (WebSocketMessageHeader *)&fragmentData[0]; + uint64_t payloadLength = WebSocketMessagePayloadLength(&fragmentData[0], neededBytes); + uint8_t *payload = WebSocketMessageData(&fragmentData[0], neededBytes); + + // Unmask payload + if (header->mask) + WebSocketMessageUnmaskPayload(payload, payloadLength, WebSocketMessageMaskingKey(&fragmentData[0], neededBytes)); + +#ifdef PROXY_DEEP_DEBUG + DumpWebSocketMessage(&fragmentData[0], neededBytes); +#endif + + switch(header->opcode) + { + case 0x02: /*binary message*/ ProcessWebSocketMessage(client_fd, payload, payloadLength); break; + case 0x08: connectionAlive = false; break; + default: + fprintf(stderr, "Unknown WebSocket opcode received %x!\n", header->opcode); + connectionAlive = false; // Kill connection + break; + } + + fragmentData.erase(fragmentData.begin(), fragmentData.begin() + (ptrdiff_t)neededBytes); +#ifdef PROXY_DEEP_DEBUG + printf("Cleared used bytes, got %d left in fragment queue.\n", (int)fragmentData.size()); +#endif + } + } + printf("Proxy connection closed\n"); + CloseWebSocket(client_fd); + EXIT_THREAD(0); +} + +int main(int argc, char *argv[]) +{ + if (argc < 2) on_error("websocket_to_posix_proxy creates a bridge that allows WebSocket connections on a web page to proxy out to perform TCP/UDP connections.\nUsage: %s [port]\n", argv[0]); + +#ifdef _WIN32 + WSADATA wsaData; + int failed = WSAStartup(MAKEWORD(2,2), &wsaData); + if (failed) + { + printf("WSAStartup failed: %d\n", failed); + return 1; + } +#else + signal(SIGPIPE, SIG_IGN); +#endif + + const int port = atoi(argv[1]); + int server_fd = socket(AF_INET, SOCK_STREAM, 0); + if (server_fd < 0) on_error("Could not create socket\n"); + + struct sockaddr_in server; + server.sin_family = AF_INET; + server.sin_port = htons(port); + server.sin_addr.s_addr = htonl(INADDR_ANY); + + int opt_val = 1; + setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, (SETSOCKOPT_PTR_TYPE)&opt_val, sizeof opt_val); + + int err = bind(server_fd, (struct sockaddr *) &server, sizeof(server)); + if (err < 0) on_error("Could not bind socket\n"); + + err = listen(server_fd, 128); + if (err < 0) on_error("Could not listen on socket\n"); + + printf("websocket_to_posix_proxy server is now listening for WebSocket connections to ws://localhost:%d/\n", port); + + while (1) + { + int client_fd = accept(server_fd, 0, 0); + if (client_fd < 0) + { + fprintf(stderr, "Could not establish new incoming proxy connection\n"); + continue; // Do not quit here, but keep serving any existing proxy connections. + } + + THREAD_T connection; + CREATE_THREAD_RETURN_T ret = CREATE_THREAD(connection, connection_thread, (void*)(uintptr_t)client_fd); + if (!CREATE_THREAD_SUCCEEDED(ret)) + { + fprintf(stderr, "Failed to create a connection handler thread for incoming proxy connection!\n"); + continue; // Do not quit here, but keep program alive to manage other existing proxy connections. + } + } + +#ifdef _WIN32 + WSACleanup(); +#endif + + return 0; +} diff --git a/tools/websocket_to_posix_proxy/src/posix_sockets.h b/tools/websocket_to_posix_proxy/src/posix_sockets.h new file mode 100644 index 0000000000000..78b433d9f5197 --- /dev/null +++ b/tools/websocket_to_posix_proxy/src/posix_sockets.h @@ -0,0 +1,52 @@ +#pragma once + +#include + +#if defined(__APPLE__) || defined(____linux__) + +#include +#include +#include +#include +#include + +#define SHUTDOWN_READ SHUT_RD +#define SHUTDOWN_WRITE SHUT_WR +#define SHUTDOWN_BIDIRECTIONAL SHUT_RDWR +#define SETSOCKOPT_PTR_TYPE const int* +#define SEND_RET_TYPE ssize_t +#define SEND_FORMATTING_SPECIFIER "%ld" +#define CLOSE_SOCKET(x) close(x) + +#define GET_SOCKET_ERROR() (errno) + +#define PRINT_SOCKET_ERROR(errorCode) do { \ + printf("Call failed! errno: %s(%d)\n", strerror(errorCode), errorCode); \ + } while(0) + +#elif defined(_MSC_VER) + +#include +#include + +#define SHUTDOWN_READ SD_RECEIVE +#define SHUTDOWN_WRITE SD_SEND +#define SHUTDOWN_BIDIRECTIONAL SD_BOTH +#define SETSOCKOPT_PTR_TYPE const char* +#define SEND_RET_TYPE int +#define SEND_FORMATTING_SPECIFIER "%d" +#define CLOSE_SOCKET(x) closesocket(x) + +#define GET_SOCKET_ERROR() (WSAGetLastError()) + +static inline void PRINT_SOCKET_ERROR(int errorCode) +{ + void *lpMsgBuf = 0; + HRESULT hresult = HRESULT_FROM_WIN32(errorCode); + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + 0, hresult, 0 /*Default language*/, (LPTSTR)&lpMsgBuf, 0, 0); + printf("Call failed! WSAGetLastError: %s(%d)\n", (char*)lpMsgBuf, errorCode); + LocalFree(lpMsgBuf); +} + +#endif diff --git a/tools/websocket_to_posix_proxy/src/sha1.cpp b/tools/websocket_to_posix_proxy/src/sha1.cpp new file mode 100644 index 0000000000000..c2c529f529d75 --- /dev/null +++ b/tools/websocket_to_posix_proxy/src/sha1.cpp @@ -0,0 +1,295 @@ +/* +SHA-1 in C +By Steve Reid +100% Public Domain + +Test Vectors (from FIPS PUB 180-1) +"abc" + A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D +"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" + 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 +A million repetitions of "a" + 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F +*/ + +/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */ +/* #define SHA1HANDSOFF * Copies data before messing with it. */ + +#define SHA1HANDSOFF + +#include +#include + +/* for uint32_t */ +#include + +#include "sha1.h" + + +#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) + +/* blk0() and blk() perform the initial expand. */ +/* I got the idea of expanding during the round function from SSLeay */ +#if BYTE_ORDER == LITTLE_ENDIAN +#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ + |(rol(block->l[i],8)&0x00FF00FF)) +#elif BYTE_ORDER == BIG_ENDIAN +#define blk0(i) block->l[i] +#else +#error "Endianness not defined!" +#endif +#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ + ^block->l[(i+2)&15]^block->l[i&15],1)) + +/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ +#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); +#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); +#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); + + +/* Hash a single 512-bit block. This is the core of the algorithm. */ + +void SHA1Transform( + uint32_t state[5], + const unsigned char buffer[64] +) +{ + uint32_t a, b, c, d, e; + + typedef union + { + unsigned char c[64]; + uint32_t l[16]; + } CHAR64LONG16; + +#ifdef SHA1HANDSOFF + CHAR64LONG16 block[1]; /* use array to appear as a pointer */ + + memcpy(block, buffer, 64); +#else + /* The following had better never be used because it causes the + * pointer-to-const buffer to be cast into a pointer to non-const. + * And the result is written through. I threw a "const" in, hoping + * this will cause a diagnostic. + */ + CHAR64LONG16 *block = (const CHAR64LONG16 *) buffer; +#endif + /* Copy context->state[] to working vars */ + a = state[0]; + b = state[1]; + c = state[2]; + d = state[3]; + e = state[4]; + /* 4 rounds of 20 operations each. Loop unrolled. */ + R0(a, b, c, d, e, 0); + R0(e, a, b, c, d, 1); + R0(d, e, a, b, c, 2); + R0(c, d, e, a, b, 3); + R0(b, c, d, e, a, 4); + R0(a, b, c, d, e, 5); + R0(e, a, b, c, d, 6); + R0(d, e, a, b, c, 7); + R0(c, d, e, a, b, 8); + R0(b, c, d, e, a, 9); + R0(a, b, c, d, e, 10); + R0(e, a, b, c, d, 11); + R0(d, e, a, b, c, 12); + R0(c, d, e, a, b, 13); + R0(b, c, d, e, a, 14); + R0(a, b, c, d, e, 15); + R1(e, a, b, c, d, 16); + R1(d, e, a, b, c, 17); + R1(c, d, e, a, b, 18); + R1(b, c, d, e, a, 19); + R2(a, b, c, d, e, 20); + R2(e, a, b, c, d, 21); + R2(d, e, a, b, c, 22); + R2(c, d, e, a, b, 23); + R2(b, c, d, e, a, 24); + R2(a, b, c, d, e, 25); + R2(e, a, b, c, d, 26); + R2(d, e, a, b, c, 27); + R2(c, d, e, a, b, 28); + R2(b, c, d, e, a, 29); + R2(a, b, c, d, e, 30); + R2(e, a, b, c, d, 31); + R2(d, e, a, b, c, 32); + R2(c, d, e, a, b, 33); + R2(b, c, d, e, a, 34); + R2(a, b, c, d, e, 35); + R2(e, a, b, c, d, 36); + R2(d, e, a, b, c, 37); + R2(c, d, e, a, b, 38); + R2(b, c, d, e, a, 39); + R3(a, b, c, d, e, 40); + R3(e, a, b, c, d, 41); + R3(d, e, a, b, c, 42); + R3(c, d, e, a, b, 43); + R3(b, c, d, e, a, 44); + R3(a, b, c, d, e, 45); + R3(e, a, b, c, d, 46); + R3(d, e, a, b, c, 47); + R3(c, d, e, a, b, 48); + R3(b, c, d, e, a, 49); + R3(a, b, c, d, e, 50); + R3(e, a, b, c, d, 51); + R3(d, e, a, b, c, 52); + R3(c, d, e, a, b, 53); + R3(b, c, d, e, a, 54); + R3(a, b, c, d, e, 55); + R3(e, a, b, c, d, 56); + R3(d, e, a, b, c, 57); + R3(c, d, e, a, b, 58); + R3(b, c, d, e, a, 59); + R4(a, b, c, d, e, 60); + R4(e, a, b, c, d, 61); + R4(d, e, a, b, c, 62); + R4(c, d, e, a, b, 63); + R4(b, c, d, e, a, 64); + R4(a, b, c, d, e, 65); + R4(e, a, b, c, d, 66); + R4(d, e, a, b, c, 67); + R4(c, d, e, a, b, 68); + R4(b, c, d, e, a, 69); + R4(a, b, c, d, e, 70); + R4(e, a, b, c, d, 71); + R4(d, e, a, b, c, 72); + R4(c, d, e, a, b, 73); + R4(b, c, d, e, a, 74); + R4(a, b, c, d, e, 75); + R4(e, a, b, c, d, 76); + R4(d, e, a, b, c, 77); + R4(c, d, e, a, b, 78); + R4(b, c, d, e, a, 79); + /* Add the working vars back into context.state[] */ + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + state[4] += e; + /* Wipe variables */ + a = b = c = d = e = 0; +#ifdef SHA1HANDSOFF + memset(block, '\0', sizeof(block)); +#endif +} + + +/* SHA1Init - Initialize new context */ + +void SHA1Init( + SHA1_CTX * context +) +{ + /* SHA1 initialization constants */ + context->state[0] = 0x67452301; + context->state[1] = 0xEFCDAB89; + context->state[2] = 0x98BADCFE; + context->state[3] = 0x10325476; + context->state[4] = 0xC3D2E1F0; + context->count[0] = context->count[1] = 0; +} + + +/* Run your data through this. */ + +void SHA1Update( + SHA1_CTX * context, + const unsigned char *data, + uint32_t len +) +{ + uint32_t i; + + uint32_t j; + + j = context->count[0]; + if ((context->count[0] += len << 3) < j) + context->count[1]++; + context->count[1] += (len >> 29); + j = (j >> 3) & 63; + if ((j + len) > 63) + { + memcpy(&context->buffer[j], data, (i = 64 - j)); + SHA1Transform(context->state, context->buffer); + for (; i + 63 < len; i += 64) + { + SHA1Transform(context->state, &data[i]); + } + j = 0; + } + else + i = 0; + memcpy(&context->buffer[j], &data[i], len - i); +} + + +/* Add padding and return the message digest. */ + +void SHA1Final( + unsigned char digest[20], + SHA1_CTX * context +) +{ + unsigned i; + + unsigned char finalcount[8]; + + unsigned char c; + +#if 0 /* untested "improvement" by DHR */ + /* Convert context->count to a sequence of bytes + * in finalcount. Second element first, but + * big-endian order within element. + * But we do it all backwards. + */ + unsigned char *fcp = &finalcount[8]; + + for (i = 0; i < 2; i++) + { + uint32_t t = context->count[i]; + + int j; + + for (j = 0; j < 4; t >>= 8, j++) + *--fcp = (unsigned char) t} +#else + for (i = 0; i < 8; i++) + { + finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */ + } +#endif + c = 0200; + SHA1Update(context, &c, 1); + while ((context->count[0] & 504) != 448) + { + c = 0000; + SHA1Update(context, &c, 1); + } + SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */ + for (i = 0; i < 20; i++) + { + digest[i] = (unsigned char) + ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); + } + /* Wipe variables */ + memset(context, '\0', sizeof(*context)); + memset(&finalcount, '\0', sizeof(finalcount)); +} + +void SHA1( + char *hash_out, + const char *str, + int len) +{ + SHA1_CTX ctx; + int ii; + + SHA1Init(&ctx); + for (ii=0; ii + 100% Public Domain + */ + +#include "stdint.h" + +typedef struct +{ + uint32_t state[5]; + uint32_t count[2]; + unsigned char buffer[64]; +} SHA1_CTX; + +void SHA1Transform( + uint32_t state[5], + const unsigned char buffer[64] + ); + +void SHA1Init( + SHA1_CTX * context + ); + +void SHA1Update( + SHA1_CTX * context, + const unsigned char *data, + uint32_t len + ); + +void SHA1Final( + unsigned char digest[20], + SHA1_CTX * context + ); + +void SHA1( + char *hash_out, + const char *str, + int len); + +#endif /* SHA1_H */ diff --git a/tools/websocket_to_posix_proxy/src/socket_registry.cpp b/tools/websocket_to_posix_proxy/src/socket_registry.cpp new file mode 100644 index 0000000000000..f9d564d2be7ec --- /dev/null +++ b/tools/websocket_to_posix_proxy/src/socket_registry.cpp @@ -0,0 +1,50 @@ +#include "socket_registry.h" + +#include +#include +#include + +namespace +{ + std::map > socketsPerProxyConnection; +} + +void TrackSocketUsedByConnection(int proxyConnection, int usedSocket) +{ + if (usedSocket == 0) return; + if (IsSocketPartOfConnection(proxyConnection, usedSocket)) + return; + socketsPerProxyConnection[proxyConnection].push_back(usedSocket); +} + +void CloseSocketByConnection(int proxyConnection, int usedSocket) +{ + if (!IsSocketPartOfConnection(proxyConnection, usedSocket)) + return; + printf("Closing socket fd %d used by proxy connection %d\n", usedSocket, proxyConnection); + CLOSE_SOCKET(usedSocket); + std::vector &sockets = socketsPerProxyConnection[proxyConnection]; + sockets.erase(std::remove(sockets.begin(), sockets.end(), usedSocket), sockets.end()); +} + +void CloseAllSocketsByConnection(int proxyConnection) +{ + std::vector &sockets = socketsPerProxyConnection[proxyConnection]; + for(size_t i = 0; i < sockets.size(); ++i) + { + printf("Closing socket fd %d used by proxy connection %d.\n", sockets[i], proxyConnection); + shutdown(sockets[i], SHUTDOWN_BIDIRECTIONAL); + CLOSE_SOCKET(sockets[i]); + } + socketsPerProxyConnection.erase(proxyConnection); +} + +bool IsSocketPartOfConnection(int proxyConnection, int usedSocket) +{ + if (usedSocket == 0) return true; // Allow all proxy connections to access "socket 0" when/if they need to refer to socket that does not exist. + if (socketsPerProxyConnection.find(proxyConnection) == socketsPerProxyConnection.end()) + return false; + + std::vector &sockets = socketsPerProxyConnection[proxyConnection]; + return std::find(sockets.begin(), sockets.end(), usedSocket) != sockets.end(); +} diff --git a/tools/websocket_to_posix_proxy/src/socket_registry.h b/tools/websocket_to_posix_proxy/src/socket_registry.h new file mode 100644 index 0000000000000..ae29104d085a9 --- /dev/null +++ b/tools/websocket_to_posix_proxy/src/socket_registry.h @@ -0,0 +1,21 @@ +#pragma once + +#include "posix_sockets.h" + +// Socket Registry remembers all the sockets created by incoming proxy connections, so that those sockets can be properly +// shut down when an incoming proxy connection disconnects. + +// Tracks that the given socket is part of the specified proxy connection. When proxyConnection disconnects, all sockets +// used by it are shut down. +void TrackSocketUsedByConnection(int proxyConnection, int usedSocket); + +// Untracks the given socket - the proxy connection has shut it down. +void CloseSocketByConnection(int proxyConnection, int usedSocket); + +// Given proxy connection has disconnected - shut down all the sockets it had created. +void CloseAllSocketsByConnection(int proxyConnection); + +// Returns if the given socket is known to be owned by the specified proxy connection. +// This is used to gate socket connections so that two proxy connections can not access +// each others' sockets. +bool IsSocketPartOfConnection(int proxyConnection, int usedSocket); diff --git a/tools/websocket_to_posix_proxy/src/threads.h b/tools/websocket_to_posix_proxy/src/threads.h new file mode 100644 index 0000000000000..52bba0e8f2bc2 --- /dev/null +++ b/tools/websocket_to_posix_proxy/src/threads.h @@ -0,0 +1,39 @@ +#pragma once + +#if defined(__unix__) || defined(__APPLE__) || defined(__linux__) +#include +#define THREAD_T pthread_t +#define CREATE_THREAD(threadPtr, threadFunc, threadArg) pthread_create(&threadPtr, 0, threadFunc, threadArg) +#define CREATE_THREAD_RETURN_T int +#define CREATE_THREAD_SUCCEEDED(x) (x == 0) +#define EXIT_THREAD(code) pthread_exit((void*)(uintptr_t)code) +#define THREAD_RETURN_T void* +#define MUTEX_T pthread_mutex_t +inline MUTEX_T CREATE_MUTEX() +{ + pthread_mutex_t m; + pthread_mutex_init(&m, 0); + return m; +} +#define LOCK_MUTEX(m) pthread_mutex_lock(m) +#define UNLOCK_MUTEX(m) pthread_mutex_unlock(m) +#endif + +#if defined(_WIN32) +#include +#define THREAD_T HANDLE +#define CREATE_THREAD(threadPtr, threadFunc, threadArg) threadPtr = CreateThread(0, 0, threadFunc, threadArg, 0, 0) +#define CREATE_THREAD_RETURN_T HANDLE +#define CREATE_THREAD_SUCCEEDED(x) (x != 0) +#define EXIT_THREAD(code) ExitThread((DWORD)code) +#define THREAD_RETURN_T DWORD WINAPI +#define MUTEX_T CRITICAL_SECTION +inline MUTEX_T CREATE_MUTEX() +{ + CRITICAL_SECTION cs; + InitializeCriticalSectionAndSpinCount(&cs, 0x00000400); + return cs; +} +#define LOCK_MUTEX(m) EnterCriticalSection(m) +#define UNLOCK_MUTEX(m) LeaveCriticalSection(m) +#endif diff --git a/tools/websocket_to_posix_proxy/src/websocket_to_posix_proxy.cpp b/tools/websocket_to_posix_proxy/src/websocket_to_posix_proxy.cpp new file mode 100644 index 0000000000000..c436734d62a9b --- /dev/null +++ b/tools/websocket_to_posix_proxy/src/websocket_to_posix_proxy.cpp @@ -0,0 +1,1672 @@ +#include +#include +#include +#include "posix_sockets.h" +#include "threads.h" +#include +#include +#include + +#include "websocket_to_posix_proxy.h" +#include "socket_registry.h" + +// Uncomment to enable debug printing +// #define POSIX_SOCKET_DEBUG + +// Uncomment to enable more verbose debug printing (in addition to uncommenting POSIX_SOCKET_DEBUG) +// #define POSIX_SOCKET_DEEP_DEBUG + +#define MIN(a,b) (((a)<(b))?(a):(b)) +#define MAX(a,b) (((a)>(b))?(a):(b)) + +uint64_t ntoh64(uint64_t x) // thread-safe, re-entrant +{ + return ntohl(x>>32) | ((uint64_t)ntohl(x&0xFFFFFFFFu) << 32); +} + +#define POSIX_SOCKET_MSG_SOCKET 1 +#define POSIX_SOCKET_MSG_SOCKETPAIR 2 +#define POSIX_SOCKET_MSG_SHUTDOWN 3 +#define POSIX_SOCKET_MSG_BIND 4 +#define POSIX_SOCKET_MSG_CONNECT 5 +#define POSIX_SOCKET_MSG_LISTEN 6 +#define POSIX_SOCKET_MSG_ACCEPT 7 +#define POSIX_SOCKET_MSG_GETSOCKNAME 8 +#define POSIX_SOCKET_MSG_GETPEERNAME 9 +#define POSIX_SOCKET_MSG_SEND 10 +#define POSIX_SOCKET_MSG_RECV 11 +#define POSIX_SOCKET_MSG_SENDTO 12 +#define POSIX_SOCKET_MSG_RECVFROM 13 +#define POSIX_SOCKET_MSG_SENDMSG 14 +#define POSIX_SOCKET_MSG_RECVMSG 15 +#define POSIX_SOCKET_MSG_GETSOCKOPT 16 +#define POSIX_SOCKET_MSG_SETSOCKOPT 17 +#define POSIX_SOCKET_MSG_GETADDRINFO 18 +#define POSIX_SOCKET_MSG_GETNAMEINFO 19 + +#define MAX_SOCKADDR_SIZE 256 +#define MAX_OPTIONVALUE_SIZE 16 + +struct SocketCallHeader +{ + int callId; + int function; +}; + +static char buf_temp_str[2048] = {}; + +static char *BufferToString(const void *buf, size_t len) // not thread-safe, but only used for debug prints, so expected not to cause trouble +{ + uint8_t *b = (uint8_t *)buf; + if (!b) + { + sprintf(buf_temp_str, "(null ptr) (%d bytes)", (int)len); + return buf_temp_str; + } + + for(size_t i = 0; i < len && i*3 + 64 < sizeof(buf_temp_str); ++i) + { + sprintf(buf_temp_str + i*3, "%02X ", b[i]); + } + sprintf(buf_temp_str + len*3, " (%d bytes)", (int)len); + return buf_temp_str; +} + +void WebSocketMessageUnmaskPayload(uint8_t *payload, uint64_t payloadLength, uint32_t maskingKey) // thread-safe, re-entrant +{ + uint8_t maskingKey8[4]; + memcpy(maskingKey8, &maskingKey, 4); + uint32_t *data_u32 = (uint32_t *)payload; + uint32_t *end_u32 = (uint32_t *)((uintptr_t)(payload + (payloadLength & ~3u))); + + while(data_u32 < end_u32) + *data_u32++ ^= maskingKey; + + uint8_t *end = payload + payloadLength; + uint8_t *data = (uint8_t *)data_u32; + while(data < end) + { + *data ^= maskingKey8[(data-payload) % 4]; + ++data; + } +} + +// Technically only would need one lock per connection, but this is now one lock per all connections, which would be +// slightly inefficient if we were handling multiple proxied connections at the same time. (currently that is a rare +// use case, expected to only be proxying one connection at a time - if this proxy bridge is expected to be used +// for hundreds of connections simultaneously, this mutex should be refactored to be per-connection) +static MUTEX_T webSocketLock = CREATE_MUTEX(); + +void SendWebSocketMessage(int client_fd, void *buf, uint64_t numBytes) +{ + LOCK_MUTEX(&webSocketLock); + uint8_t headerData[sizeof(WebSocketMessageHeader) + 8/*possible extended length*/] = {}; + WebSocketMessageHeader *header = (WebSocketMessageHeader *)headerData; + header->opcode = 0x02; + header->fin = 1; + int headerBytes = 2; + + if (numBytes < 126) + header->payloadLength = numBytes; + else if (numBytes <= 65535) + { + header->payloadLength = 126; + *(uint16_t*)(headerData+headerBytes) = htons((unsigned short)numBytes); + headerBytes += 2; + } + else + { + header->payloadLength = 127; + *(uint64_t*)(headerData+headerBytes) = hton64(numBytes); + headerBytes += 8; + } + +#ifdef POSIX_SOCKET_DEEP_DEBUG + printf("Sending %llu bytes message (%llu bytes of payload) to WebSocket\n", headerBytes + numBytes, numBytes); + + printf("Header:"); + for(int i = 0; i < headerBytes; ++i) + printf(" %02X", headerData[i]); + + printf("\nPayload:"); + for(int i = 0; i < numBytes; ++i) + printf(" %02X", ((unsigned char*)buf)[i]); + printf("\n"); +#endif + + send(client_fd, (const char*)headerData, headerBytes, 0); // header + send(client_fd, (const char*)buf, (int)numBytes, 0); // payload + UNLOCK_MUTEX(&webSocketLock); +} + +#define MUSL_PF_UNSPEC 0 +#define MUSL_PF_LOCAL 1 +#define MUSL_PF_UNIX PF_LOCAL +#define MUSL_PF_FILE PF_LOCAL +#define MUSL_PF_INET 2 +#define MUSL_PF_AX25 3 +#define MUSL_PF_IPX 4 +#define MUSL_PF_APPLETALK 5 +#define MUSL_PF_NETROM 6 +#define MUSL_PF_BRIDGE 7 +#define MUSL_PF_ATMPVC 8 +#define MUSL_PF_X25 9 +#define MUSL_PF_INET6 10 +#define MUSL_PF_ROSE 11 +#define MUSL_PF_DECnet 12 +#define MUSL_PF_NETBEUI 13 +#define MUSL_PF_SECURITY 14 +#define MUSL_PF_KEY 15 +#define MUSL_PF_NETLINK 16 +#define MUSL_PF_ROUTE PF_NETLINK +#define MUSL_PF_PACKET 17 +#define MUSL_PF_ASH 18 +#define MUSL_PF_ECONET 19 +#define MUSL_PF_ATMSVC 20 +#define MUSL_PF_RDS 21 +#define MUSL_PF_SNA 22 +#define MUSL_PF_IRDA 23 +#define MUSL_PF_PPPOX 24 +#define MUSL_PF_WANPIPE 25 +#define MUSL_PF_LLC 26 +#define MUSL_PF_IB 27 +#define MUSL_PF_MPLS 28 +#define MUSL_PF_CAN 29 +#define MUSL_PF_TIPC 30 +#define MUSL_PF_BLUETOOTH 31 +#define MUSL_PF_IUCV 32 +#define MUSL_PF_RXRPC 33 +#define MUSL_PF_ISDN 34 +#define MUSL_PF_PHONET 35 +#define MUSL_PF_IEEE802154 36 +#define MUSL_PF_CAIF 37 +#define MUSL_PF_ALG 38 +#define MUSL_PF_NFC 39 +#define MUSL_PF_VSOCK 40 +#define MUSL_PF_KCM 41 +#define MUSL_PF_MAX 42 + +#define MUSL_AF_UNSPEC MUSL_PF_UNSPEC +#define MUSL_AF_LOCAL MUSL_PF_LOCAL +#define MUSL_AF_UNIX MUSL_AF_LOCAL +#define MUSL_AF_FILE MUSL_AF_LOCAL +#define MUSL_AF_INET MUSL_PF_INET +#define MUSL_AF_AX25 MUSL_PF_AX25 +#define MUSL_AF_IPX MUSL_PF_IPX +#define MUSL_AF_APPLETALK MUSL_PF_APPLETALK +#define MUSL_AF_NETROM MUSL_PF_NETROM +#define MUSL_AF_BRIDGE MUSL_PF_BRIDGE +#define MUSL_AF_ATMPVC MUSL_PF_ATMPVC +#define MUSL_AF_X25 MUSL_PF_X25 +#define MUSL_AF_INET6 MUSL_PF_INET6 +#define MUSL_AF_ROSE MUSL_PF_ROSE +#define MUSL_AF_DECnet MUSL_PF_DECnet +#define MUSL_AF_NETBEUI MUSL_PF_NETBEUI +#define MUSL_AF_SECURITY MUSL_PF_SECURITY +#define MUSL_AF_KEY MUSL_PF_KEY +#define MUSL_AF_NETLINK MUSL_PF_NETLINK +#define MUSL_AF_ROUTE MUSL_PF_ROUTE +#define MUSL_AF_PACKET MUSL_PF_PACKET +#define MUSL_AF_ASH MUSL_PF_ASH +#define MUSL_AF_ECONET MUSL_PF_ECONET +#define MUSL_AF_ATMSVC MUSL_PF_ATMSVC +#define MUSL_AF_RDS MUSL_PF_RDS +#define MUSL_AF_SNA MUSL_PF_SNA +#define MUSL_AF_IRDA MUSL_PF_IRDA +#define MUSL_AF_PPPOX MUSL_PF_PPPOX +#define MUSL_AF_WANPIPE MUSL_PF_WANPIPE +#define MUSL_AF_LLC MUSL_PF_LLC +#define MUSL_AF_IB MUSL_PF_IB +#define MUSL_AF_MPLS MUSL_PF_MPLS +#define MUSL_AF_CAN MUSL_PF_CAN +#define MUSL_AF_TIPC MUSL_PF_TIPC +#define MUSL_AF_BLUETOOTH MUSL_PF_BLUETOOTH +#define MUSL_AF_IUCV MUSL_PF_IUCV +#define MUSL_AF_RXRPC MUSL_PF_RXRPC +#define MUSL_AF_ISDN MUSL_PF_ISDN +#define MUSL_AF_PHONET MUSL_PF_PHONET +#define MUSL_AF_IEEE802154 MUSL_PF_IEEE802154 +#define MUSL_AF_CAIF MUSL_PF_CAIF +#define MUSL_AF_ALG MUSL_PF_ALG +#define MUSL_AF_NFC MUSL_PF_NFC +#define MUSL_AF_VSOCK MUSL_PF_VSOCK +#define MUSL_AF_KCM MUSL_PF_KCM +#define MUSL_AF_MAX MUSL_PF_MAX + +static int Translate_Socket_Domain(int domain) +{ + switch(domain) + { +// case MUSL_PF_UNSPEC: return PF_UNSPEC; +// case MUSL_PF_LOCAL: return PF_LOCAL; +// case MUSL_PF_UNIX: return PF_UNIX; +// case MUSL_PF_FILE: return PF_FILE; +// case MUSL_PF_INET: return PF_INET; +// case MUSL_PF_AX25: return PF_AX25; +// case MUSL_PF_IPX: return PF_IPX; +// case MUSL_PF_APPLETALK: return PF_APPLETALK; +// case MUSL_PF_NETROM: return PF_NETROM; +// case MUSL_PF_BRIDGE: return PF_BRIDGE; +// case MUSL_PF_ATMPVC: return PF_ATMPVC; +// case MUSL_PF_X25: return PF_X25; +// case MUSL_PF_INET6: return PF_INET6; +// case MUSL_PF_ROSE: return PF_ROSE; +// case MUSL_PF_DECnet: return PF_DECnet; +// case MUSL_PF_NETBEUI: return PF_NETBEUI; +// case MUSL_PF_SECURITY: return PF_SECURITY; +// case MUSL_PF_KEY: return PF_KEY; +// case MUSL_PF_NETLINK: return PF_NETLINK; +// case MUSL_PF_ROUTE: return PF_ROUTE; +// case MUSL_PF_PACKET: return PF_PACKET; +// case MUSL_PF_ASH: return PF_ASH; +// case MUSL_PF_ECONET: return PF_ECONET; +// case MUSL_PF_ATMSVC: return PF_ATMSVC; +// case MUSL_PF_RDS: return PF_RDS; +// case MUSL_PF_SNA: return PF_SNA; +// case MUSL_PF_IRDA: return PF_IRDA; +// case MUSL_PF_PPPOX: return PF_PPPOX; +// case MUSL_PF_WANPIPE: return PF_WANPIPE; +// case MUSL_PF_LLC: return PF_LLC; +// case MUSL_PF_IB: return PF_IB; +// case MUSL_PF_MPLS: return PF_MPLS; +// case MUSL_PF_CAN: return PF_CAN; +// case MUSL_PF_TIPC: return PF_TIPC; +// case MUSL_PF_BLUETOOTH: return PF_BLUETOOTH; +// case MUSL_PF_IUCV: return PF_IUCV; +// case MUSL_PF_RXRPC: return PF_RXRPC; +// case MUSL_PF_ISDN: return PF_ISDN; +// case MUSL_PF_PHONET: return PF_PHONET; +// case MUSL_PF_IEEE802154: return PF_IEEE802154; +// case MUSL_PF_CAIF: return PF_CAIF; +// case MUSL_PF_ALG: return PF_ALG; +// case MUSL_PF_NFC: return PF_NFC; +// case MUSL_PF_VSOCK: return PF_VSOCK; +// case MUSL_PF_KCM: return PF_KCM; +// case MUSL_PF_MAX: return PF_MAX; + + case MUSL_AF_UNSPEC: return AF_UNSPEC; +#ifdef AF_LOCAL + case MUSL_AF_LOCAL: return AF_LOCAL; +#endif +// case MUSL_AF_UNIX: return AF_UNIX; +// case MUSL_AF_FILE: return AF_FILE; + case MUSL_AF_INET: return AF_INET; +// case MUSL_AF_AX25: return AF_AX25; + case MUSL_AF_IPX: return AF_IPX; + case MUSL_AF_APPLETALK: return AF_APPLETALK; +// case MUSL_AF_NETROM: return AF_NETROM; +// case MUSL_AF_BRIDGE: return AF_BRIDGE; +// case MUSL_AF_ATMPVC: return AF_ATMPVC; +// case MUSL_AF_X25: return AF_X25; + case MUSL_AF_INET6: return AF_INET6; +// case MUSL_AF_ROSE: return AF_ROSE; + case MUSL_AF_DECnet: return AF_DECnet; +// case MUSL_AF_NETBEUI: return AF_NETBEUI; +// case MUSL_AF_SECURITY: return AF_SECURITY; +// case MUSL_AF_KEY: return AF_KEY; +// case MUSL_AF_NETLINK: return AF_NETLINK; +// case MUSL_AF_ROUTE: return AF_ROUTE; +// case MUSL_AF_PACKET: return AF_PACKET; +// case MUSL_AF_ASH: return AF_ASH; +// case MUSL_AF_ECONET: return AF_ECONET; +// case MUSL_AF_ATMSVC: return AF_ATMSVC; +// case MUSL_AF_RDS: return AF_RDS; + case MUSL_AF_SNA: return AF_SNA; +// case MUSL_AF_IRDA: return AF_IRDA; +// case MUSL_AF_PPPOX: return AF_PPPOX; +// case MUSL_AF_WANPIPE: return AF_WANPIPE; +// case MUSL_AF_LLC: return AF_LLC; +// case MUSL_AF_IB: return AF_IB; +// case MUSL_AF_MPLS: return AF_MPLS; +// case MUSL_AF_CAN: return AF_CAN; +// case MUSL_AF_TIPC: return AF_TIPC; +// case MUSL_AF_BLUETOOTH: return AF_BLUETOOTH; +// case MUSL_AF_IUCV: return AF_IUCV; +// case MUSL_AF_RXRPC: return AF_RXRPC; +#ifdef AF_ISDN + case MUSL_AF_ISDN: return AF_ISDN; +#endif +// case MUSL_AF_PHONET: return AF_PHONET; +// case MUSL_AF_IEEE802154: return AF_IEEE802154; +// case MUSL_AF_CAIF: return AF_CAIF; +// case MUSL_AF_ALG: return AF_ALG; +// case MUSL_AF_NFC: return AF_NFC; +// case MUSL_AF_VSOCK: return AF_VSOCK; +// case MUSL_AF_KCM: return AF_KCM; + case MUSL_AF_MAX: return AF_MAX; + default: + fprintf(stderr, "Uncrecognized Socket Domain %d!\n", domain); + return domain; + } +} + +#define MUSL_SOCK_STREAM 1 +#define MUSL_SOCK_DGRAM 2 +#define MUSL_SOCK_RAW 3 +#define MUSL_SOCK_RDM 4 +#define MUSL_SOCK_SEQPACKET 5 +#define MUSL_SOCK_DCCP 6 +#define MUSL_SOCK_PACKET 10 +#define MUSL_SOCK_CLOEXEC 02000000 +#define MUSL_SOCK_NONBLOCK 04000 + +static int Translate_Socket_Type(int type) +{ + if ((type & MUSL_SOCK_CLOEXEC) != 0) + { + fprintf(stderr, "Unsupported MUSL SOCK_CLOEXEC passed!\n"); + type &= ~MUSL_SOCK_CLOEXEC; + } + if ((type & MUSL_SOCK_NONBLOCK) != 0) + { + fprintf(stderr, "Unsupported MUSL SOCK_NONBLOCK passed!\n"); + type &= ~MUSL_SOCK_NONBLOCK; + } + + switch(type) + { + case MUSL_SOCK_STREAM: return SOCK_STREAM; + case MUSL_SOCK_DGRAM: return SOCK_DGRAM; + case MUSL_SOCK_RAW: return SOCK_RAW; + case MUSL_SOCK_RDM: return SOCK_RDM; + case MUSL_SOCK_SEQPACKET: return SOCK_SEQPACKET; +// case MUSL_SOCK_DCCP: return SOCK_DCCP; +// case MUSL_SOCK_PACKET: return SOCK_PACKET; + default: + fprintf(stderr, "Uncrecognized socket type %d!\n", type); + return type; + } +} + +#define MUSL_IPPROTO_IP 0 +#define MUSL_IPPROTO_HOPOPTS 0 +#define MUSL_IPPROTO_ICMP 1 +#define MUSL_IPPROTO_IGMP 2 +#define MUSL_IPPROTO_IPIP 4 +#define MUSL_IPPROTO_TCP 6 +#define MUSL_IPPROTO_EGP 8 +#define MUSL_IPPROTO_PUP 12 +#define MUSL_IPPROTO_UDP 17 +#define MUSL_IPPROTO_IDP 22 +#define MUSL_IPPROTO_TP 29 +#define MUSL_IPPROTO_DCCP 33 +#define MUSL_IPPROTO_IPV6 41 +#define MUSL_IPPROTO_ROUTING 43 +#define MUSL_IPPROTO_FRAGMENT 44 +#define MUSL_IPPROTO_RSVP 46 +#define MUSL_IPPROTO_GRE 47 +#define MUSL_IPPROTO_ESP 50 +#define MUSL_IPPROTO_AH 51 +#define MUSL_IPPROTO_ICMPV6 58 +#define MUSL_IPPROTO_NONE 59 +#define MUSL_IPPROTO_DSTOPTS 60 +#define MUSL_IPPROTO_MTP 92 +#define MUSL_IPPROTO_BEETPH 94 +#define MUSL_IPPROTO_ENCAP 98 +#define MUSL_IPPROTO_PIM 103 +#define MUSL_IPPROTO_COMP 108 +#define MUSL_IPPROTO_SCTP 132 +#define MUSL_IPPROTO_MH 135 +#define MUSL_IPPROTO_UDPLITE 136 +#define MUSL_IPPROTO_MPLS 137 +#define MUSL_IPPROTO_RAW 255 + +static int Translate_Socket_Protocol(int protocol) +{ + switch(protocol) + { + case MUSL_IPPROTO_IP: return IPPROTO_IP; +// case MUSL_IPPROTO_HOPOPTS: return IPPROTO_HOPOPTS; + case MUSL_IPPROTO_ICMP: return IPPROTO_ICMP; + case MUSL_IPPROTO_IGMP: return IPPROTO_IGMP; +#ifdef IPPROTO_IPIP + case MUSL_IPPROTO_IPIP: return IPPROTO_IPIP; +#endif + case MUSL_IPPROTO_TCP: return IPPROTO_TCP; + case MUSL_IPPROTO_EGP: return IPPROTO_EGP; + case MUSL_IPPROTO_PUP: return IPPROTO_PUP; + case MUSL_IPPROTO_UDP: return IPPROTO_UDP; + case MUSL_IPPROTO_IDP: return IPPROTO_IDP; +#ifdef IPPROTO_TP + case MUSL_IPPROTO_TP: return IPPROTO_TP; +#endif +// case MUSL_IPPROTO_DCCP: return IPPROTO_DCCP; + case MUSL_IPPROTO_IPV6: return IPPROTO_IPV6; + case MUSL_IPPROTO_ROUTING: return IPPROTO_ROUTING; + case MUSL_IPPROTO_FRAGMENT: return IPPROTO_FRAGMENT; +#ifdef IPPROTO_RSVP + case MUSL_IPPROTO_RSVP: return IPPROTO_RSVP; +#endif +#ifdef IPPROTO_GRE + case MUSL_IPPROTO_GRE: return IPPROTO_GRE; +#endif + case MUSL_IPPROTO_ESP: return IPPROTO_ESP; + case MUSL_IPPROTO_AH: return IPPROTO_AH; + case MUSL_IPPROTO_ICMPV6: return IPPROTO_ICMPV6; + case MUSL_IPPROTO_NONE: return IPPROTO_NONE; + case MUSL_IPPROTO_DSTOPTS: return IPPROTO_DSTOPTS; +#ifdef IPPROTO_MTP + case MUSL_IPPROTO_MTP: return IPPROTO_MTP; +#endif +// case MUSL_IPPROTO_BEETPH: return IPPROTO_BEETPH; +#ifdef IPPROTO_ENCAP + case MUSL_IPPROTO_ENCAP: return IPPROTO_ENCAP; +#endif + case MUSL_IPPROTO_PIM: return IPPROTO_PIM; +// case MUSL_IPPROTO_COMP: return IPPROTO_COMP; + case MUSL_IPPROTO_SCTP: return IPPROTO_SCTP; +// case MUSL_IPPROTO_MH: return IPPROTO_MH; +// case MUSL_IPPROTO_UDPLITE: return IPPROTO_UDPLITE; +// case MUSL_IPPROTO_MPLS: return IPPROTO_MPLS; + case MUSL_IPPROTO_RAW: return IPPROTO_RAW; + default: + fprintf(stderr, "Unrecognized socket protocol %d!\n", protocol); + return protocol; + } +} + +#define MUSL_SOL_SOCKET 1 +#define MUSL_SOL_IP 0 +#define MUSL_SOL_IPV6 41 +#define MUSL_SOL_ICMPV6 58 +#define MUSL_SOL_RAW 255 +#define MUSL_SOL_DECNET 261 +#define MUSL_SOL_X25 262 +#define MUSL_SOL_PACKET 263 +#define MUSL_SOL_ATM 264 +#define MUSL_SOL_AAL 265 +#define MUSL_SOL_IRDA 266 +#define MUSL_SOL_NETBEUI 267 +#define MUSL_SOL_LLC 268 +#define MUSL_SOL_DCCP 269 +#define MUSL_SOL_NETLINK 270 +#define MUSL_SOL_TIPC 271 +#define MUSL_SOL_RXRPC 272 +#define MUSL_SOL_PPPOL2TP 273 +#define MUSL_SOL_BLUETOOTH 274 +#define MUSL_SOL_PNPIPE 275 +#define MUSL_SOL_RDS 276 +#define MUSL_SOL_IUCV 277 +#define MUSL_SOL_CAIF 278 +#define MUSL_SOL_ALG 279 +#define MUSL_SOL_NFC 280 +#define MUSL_SOL_KCM 281 + +static int Translate_Socket_Level(int level) +{ + switch(level) + { + case MUSL_SOL_SOCKET: return SOL_SOCKET; + case MUSL_IPPROTO_TCP: return IPPROTO_TCP; +// case MUSL_SOL_IP: return SOL_IP; +// case MUSL_SOL_IPV6: return SOL_IPV6; +// case MUSL_SOL_ICMPV6: return SOL_ICMPV6; +// case MUSL_SOL_RAW: return SOL_RAW; +// case MUSL_SOL_DECNET: return SOL_DECNET; +// case MUSL_SOL_X25: return SOL_X25; +// case MUSL_SOL_PACKET: return SOL_PACKET; +// case MUSL_SOL_ATM: return SOL_ATM; +// case MUSL_SOL_AAL: return SOL_AAL; +// case MUSL_SOL_IRDA: return SOL_IRDA; +// case MUSL_SOL_NETBEUI: return SOL_NETBEUI; +// case MUSL_SOL_LLC: return SOL_LLC; +// case MUSL_SOL_DCCP: return SOL_DCCP; +// case MUSL_SOL_NETLINK: return SOL_NETLINK; +// case MUSL_SOL_TIPC: return SOL_TIPC; +// case MUSL_SOL_RXRPC: return SOL_RXRPC; +// case MUSL_SOL_PPPOL2TP: return SOL_PPPOL2TP; +// case MUSL_SOL_BLUETOOTH: return SOL_BLUETOOTH; +// case MUSL_SOL_PNPIPE: return SOL_PNPIPE; +// case MUSL_SOL_RDS: return SOL_RDS; +// case MUSL_SOL_IUCV: return SOL_IUCV; +// case MUSL_SOL_CAIF: return SOL_CAIF; +// case MUSL_SOL_ALG: return SOL_ALG; +// case MUSL_SOL_NFC: return SOL_NFC; +// case MUSL_SOL_KCM: return SOL_KCM; + default: + fprintf(stderr, "Uncrecognized socket level %d!\n", level); + return level; + } +} + +#define MUSL_SO_DEBUG 1 +#define MUSL_SO_REUSEADDR 2 +#define MUSL_SO_TYPE 3 +#define MUSL_SO_ERROR 4 +#define MUSL_SO_DONTROUTE 5 +#define MUSL_SO_BROADCAST 6 +#define MUSL_SO_SNDBUF 7 +#define MUSL_SO_RCVBUF 8 +#define MUSL_SO_KEEPALIVE 9 +#define MUSL_SO_OOBINLINE 10 +#define MUSL_SO_NO_CHECK 11 +#define MUSL_SO_PRIORITY 12 +#define MUSL_SO_LINGER 13 +#define MUSL_SO_BSDCOMPAT 14 +#define MUSL_SO_REUSEPORT 15 +#define MUSL_SO_PASSCRED 16 +#define MUSL_SO_PEERCRED 17 +#define MUSL_SO_RCVLOWAT 18 +#define MUSL_SO_SNDLOWAT 19 +#define MUSL_SO_RCVTIMEO 20 +#define MUSL_SO_SNDTIMEO 21 +#define MUSL_SO_ACCEPTCONN 30 +#define MUSL_SO_SNDBUFFORCE 32 +#define MUSL_SO_RCVBUFFORCE 33 +#define MUSL_SO_PROTOCOL 38 +#define MUSL_SO_DOMAIN 39 +#define MUSL_SO_SECURITY_AUTHENTICATION 22 +#define MUSL_SO_SECURITY_ENCRYPTION_TRANSPORT 23 +#define MUSL_SO_SECURITY_ENCRYPTION_NETWORK 24 +#define MUSL_SO_BINDTODEVICE 25 +#define MUSL_SO_ATTACH_FILTER 26 +#define MUSL_SO_DETACH_FILTER 27 +#define MUSL_SO_PEERNAME 28 +#define MUSL_SO_TIMESTAMP 29 +#define MUSL_SO_PEERSEC 31 +#define MUSL_SO_PASSSEC 34 +#define MUSL_SO_TIMESTAMPNS 35 +#define MUSL_SO_MARK 36 +#define MUSL_SO_TIMESTAMPING 37 +#define MUSL_SO_RXQ_OVFL 40 +#define MUSL_SO_WIFI_STATUS 41 +#define MUSL_SO_PEEK_OFF 42 +#define MUSL_SO_NOFCS 43 +#define MUSL_SO_LOCK_FILTER 44 +#define MUSL_SO_SELECT_ERR_QUEUE 45 +#define MUSL_SO_BUSY_POLL 46 +#define MUSL_SO_MAX_PACING_RATE 47 +#define MUSL_SO_BPF_EXTENSIONS 48 +#define MUSL_SO_INCOMING_CPU 49 +#define MUSL_SO_ATTACH_BPF 50 +#define MUSL_SO_ATTACH_REUSEPORT_CBPF 51 +#define MUSL_SO_ATTACH_REUSEPORT_EBPF 52 +#define MUSL_SO_CNX_ADVICE 53 + +static int Translate_SOL_SOCKET_option(int sockopt) +{ + switch(sockopt) + { + case MUSL_SO_DEBUG: return SO_DEBUG; + case MUSL_SO_REUSEADDR: return SO_REUSEADDR; + case MUSL_SO_TYPE: return SO_TYPE; + case MUSL_SO_ERROR: return SO_ERROR; + case MUSL_SO_DONTROUTE: return SO_DONTROUTE; + case MUSL_SO_BROADCAST: return SO_BROADCAST; + case MUSL_SO_SNDBUF: return SO_SNDBUF; + case MUSL_SO_RCVBUF: return SO_RCVBUF; + case MUSL_SO_KEEPALIVE: return SO_KEEPALIVE; + case MUSL_SO_OOBINLINE: return SO_OOBINLINE; +// case MUSL_SO_NO_CHECK: return SO_NO_CHECK; +// case MUSL_SO_PRIORITY: return SO_PRIORITY; + case MUSL_SO_LINGER: return SO_LINGER; +// case MUSL_SO_BSDCOMPAT: return SO_BSDCOMPAT; +#ifdef SO_REUSEPORT + case MUSL_SO_REUSEPORT: return SO_REUSEPORT; +#endif +// case MUSL_SO_PASSCRED: return SO_PASSCRED; +// case MUSL_SO_PEERCRED: return SO_PEERCRED; + case MUSL_SO_RCVLOWAT: return SO_RCVLOWAT; + case MUSL_SO_SNDLOWAT: return SO_SNDLOWAT; + case MUSL_SO_RCVTIMEO: return SO_RCVTIMEO; + case MUSL_SO_SNDTIMEO: return SO_SNDTIMEO; + case MUSL_SO_ACCEPTCONN: return SO_ACCEPTCONN; +// case MUSL_SO_SNDBUFFORCE: return SO_SNDBUFFORCE; +// case MUSL_SO_RCVBUFFORCE: return SO_RCVBUFFORCE; +// case MUSL_SO_PROTOCOL: return SO_PROTOCOL; +// case MUSL_SO_DOMAIN: return SO_DOMAIN; +// case MUSL_SO_SECURITY_AUTHENTICATION: return SO_SECURITY_AUTHENTICATION; +// case MUSL_SO_SECURITY_ENCRYPTION_TRANSPORT: return SO_SECURITY_ENCRYPTION_TRANSPORT; +// case MUSL_SO_SECURITY_ENCRYPTION_NETWORK: return SO_SECURITY_ENCRYPTION_NETWORK; +// case MUSL_SO_BINDTODEVICE: return SO_BINDTODEVICE; +// case MUSL_SO_ATTACH_FILTER: return SO_ATTACH_FILTER; +// case MUSL_SO_DETACH_FILTER: return SO_DETACH_FILTER; +// case MUSL_SO_PEERNAME: return SO_PEERNAME; +#ifdef SO_TIMESTAMP + case MUSL_SO_TIMESTAMP: return SO_TIMESTAMP; +#endif +// case MUSL_SO_PEERSEC: return SO_PEERSEC; +// case MUSL_SO_PASSSEC: return SO_PASSSEC; +// case MUSL_SO_TIMESTAMPNS: return SO_TIMESTAMPNS; +// case MUSL_SO_MARK: return SO_MARK; +// case MUSL_SO_TIMESTAMPING: return SO_TIMESTAMPING; +// case MUSL_SO_RXQ_OVFL: return SO_RXQ_OVFL; +// case MUSL_SO_WIFI_STATUS: return SO_WIFI_STATUS; +// case MUSL_SO_PEEK_OFF: return SO_PEEK_OFF; +// case MUSL_SO_NOFCS: return SO_NOFCS; +// case MUSL_SO_LOCK_FILTER: return SO_LOCK_FILTER; +// case MUSL_SO_SELECT_ERR_QUEUE: return SO_SELECT_ERR_QUEUE; +// case MUSL_SO_BUSY_POLL: return SO_BUSY_POLL; +// case MUSL_SO_MAX_PACING_RATE: return SO_MAX_PACING_RATE; +// case MUSL_SO_BPF_EXTENSIONS: return SO_BPF_EXTENSIONS; +// case MUSL_SO_INCOMING_CPU: return SO_INCOMING_CPU; +// case MUSL_SO_ATTACH_BPF: return SO_ATTACH_BPF; +// case MUSL_SO_ATTACH_REUSEPORT_CBPF: return SO_ATTACH_REUSEPORT_CBPF; +// case MUSL_SO_ATTACH_REUSEPORT_EBPF: return SO_ATTACH_REUSEPORT_EBPF; +// case MUSL_SO_CNX_ADVICE: return SO_CNX_ADVICE; + default: + fprintf(stderr, "Unrecognized SOL_SOCKET option %d!\n", sockopt); + return sockopt; + } +} + +#define MUSL_TCP_NODELAY 1 +#define MUSL_TCP_MAXSEG 2 +#define MUSL_TCP_CORK 3 +#define MUSL_TCP_KEEPIDLE 4 +#define MUSL_TCP_KEEPINTVL 5 +#define MUSL_TCP_KEEPCNT 6 +#define MUSL_TCP_SYNCNT 7 +#define MUSL_TCP_LINGER2 8 +#define MUSL_TCP_DEFER_ACCEPT 9 +#define MUSL_TCP_WINDOW_CLAMP 10 +#define MUSL_TCP_INFO 11 +#define MUSL_TCP_QUICKACK 12 +#define MUSL_TCP_CONGESTION 13 +#define MUSL_TCP_MD5SIG 14 +#define MUSL_TCP_THIN_LINEAR_TIMEOUTS 16 +#define MUSL_TCP_THIN_DUPACK 17 +#define MUSL_TCP_USER_TIMEOUT 18 +#define MUSL_TCP_REPAIR 19 +#define MUSL_TCP_REPAIR_QUEUE 20 +#define MUSL_TCP_QUEUE_SEQ 21 +#define MUSL_TCP_REPAIR_OPTIONS 22 +#define MUSL_TCP_FASTOPEN 23 +#define MUSL_TCP_TIMESTAMP 24 +#define MUSL_TCP_NOTSENT_LOWAT 25 +#define MUSL_TCP_CC_INFO 26 +#define MUSL_TCP_SAVE_SYN 27 +#define MUSL_TCP_SAVED_SYN 28 + +static int Translate_IPPROTO_TCP_option(int sockopt) +{ + switch(sockopt) + { + case MUSL_TCP_NODELAY: return TCP_NODELAY; + case MUSL_TCP_MAXSEG: return TCP_MAXSEG; +// case MUSL_TCP_CORK: return TCP_CORK; +// case MUSL_TCP_KEEPIDLE: return TCP_KEEPIDLE; + case MUSL_TCP_KEEPINTVL: return TCP_KEEPINTVL; + case MUSL_TCP_KEEPCNT: return TCP_KEEPCNT; +// case MUSL_TCP_SYNCNT: return TCP_SYNCNT; +// case MUSL_TCP_LINGER2: return TCP_LINGER2; +// case MUSL_TCP_DEFER_ACCEPT: return TCP_DEFER_ACCEPT; +// case MUSL_TCP_WINDOW_CLAMP: return TCP_WINDOW_CLAMP; +// case MUSL_TCP_INFO: return TCP_INFO; +// case MUSL_TCP_QUICKACK: return TCP_QUICKACK; +// case MUSL_TCP_CONGESTION: return TCP_CONGESTION; +// case MUSL_TCP_MD5SIG: return TCP_MD5SIG; +// case MUSL_TCP_THIN_LINEAR_TIMEOUTS: return TCP_THIN_LINEAR_TIMEOUTS; +// case MUSL_TCP_THIN_DUPACK: return TCP_THIN_DUPACK; +// case MUSL_TCP_USER_TIMEOUT: return TCP_USER_TIMEOUT; +// case MUSL_TCP_REPAIR: return TCP_REPAIR; +// case MUSL_TCP_REPAIR_QUEUE: return TCP_REPAIR_QUEUE; +// case MUSL_TCP_QUEUE_SEQ: return TCP_QUEUE_SEQ; +// case MUSL_TCP_REPAIR_OPTIONS: return TCP_REPAIR_OPTIONS; + case MUSL_TCP_FASTOPEN: return TCP_FASTOPEN; +// case MUSL_TCP_TIMESTAMP: return TCP_TIMESTAMP; +#ifdef TCP_NOTSENT_LOWAT + case MUSL_TCP_NOTSENT_LOWAT: return TCP_NOTSENT_LOWAT; +#endif +// case MUSL_TCP_CC_INFO: return TCP_CC_INFO; +// case MUSL_TCP_SAVE_SYN: return TCP_SAVE_SYN; +// case MUSL_TCP_SAVED_SYN: return TCP_SAVED_SYN; + default: + fprintf(stderr, "Unrecognized IPPROTO_TCP option %d!\n", sockopt); + return sockopt; + } +} + +void Socket(int client_fd, uint8_t *data, uint64_t numBytes) // int socket(int domain, int type, int protocol); +{ + struct MSG { + SocketCallHeader header; + int domain; + int type; + int protocol; + }; + MSG *d = (MSG*)data; + + d->domain = Translate_Socket_Domain(d->domain); + d->type = Translate_Socket_Type(d->type); + d->protocol = Translate_Socket_Protocol(d->protocol); + int ret = socket(d->domain, d->type, d->protocol); + int errorCode = (ret < 0) ? GET_SOCKET_ERROR() : 0; + +#ifdef POSIX_SOCKET_DEBUG + printf("socket(domain=%d,type=%d,protocol=%d)->%d\n", d->domain, d->type, d->protocol, ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + + if (errorCode == 0) + { + // The proxy client connection created a new socket - track its lifetime and mark the new socket to be part of + // this particular proxy connection so that it will be properly freed when the proxy connection disconnects, + // and that no other proxy connections will be able to access this socket. + TrackSocketUsedByConnection(client_fd, ret); + } + + struct { + int callId; + int ret; + int errno_; + } r; + r.callId = d->header.callId; + r.ret = ret; + r.errno_ = errorCode; + SendWebSocketMessage(client_fd, &r, sizeof(r)); +} + +void Socketpair(int client_fd, uint8_t *data, uint64_t numBytes) // int socketpair(int domain, int type, int protocol, int socket_vector[2]); +{ + struct MSG { + SocketCallHeader header; + int domain; + int type; + int protocol; + }; + MSG *d = (MSG*)data; + + int socket_vector[2]; + +#ifdef _MSC_VER + printf("TODO implement socketpair() on Windows\n"); + int ret = -1; + int errorCode = -1; +#else + d->domain = Translate_Socket_Domain(d->domain); + d->type = Translate_Socket_Type(d->type); + d->protocol = Translate_Socket_Protocol(d->protocol); + int ret = socketpair(d->domain, d->type, d->protocol, socket_vector); + int errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; +#endif + +#ifdef POSIX_SOCKET_DEBUG + printf("socketpair(domain=%d,type=%d,protocol=%d, socket_vector=[%d,%d])->%d\n", d->domain, d->type, d->protocol, socket_vector[0], socket_vector[1], ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + + if (errorCode == 0) + { + // The proxy client connection created two new sockets - track their lifetime and mark the new sockets to be part of + // this particular proxy connection so that they will be properly freed when the proxy connection disconnects, + // and that no other proxy connections will be able to access these sockets. + TrackSocketUsedByConnection(client_fd, socket_vector[0]); + TrackSocketUsedByConnection(client_fd, socket_vector[1]); + } + + struct { + int callId; + int ret; + int errno_; + int sv[2]; + } r; + r.callId = d->header.callId; + r.ret = ret; + r.errno_ = errorCode; + r.sv[0] = socket_vector[0]; + r.sv[1] = socket_vector[1]; + SendWebSocketMessage(client_fd, &r, sizeof(r)); +} + +#define MUSL_SHUT_RD 0 +#define MUSL_SHUT_WR 1 +#define MUSL_SHUT_RDWR 2 + +static int Translate_Shutdown_How(int how) +{ + switch(how) + { + case MUSL_SHUT_RD: return SHUTDOWN_READ; + case MUSL_SHUT_WR: return SHUTDOWN_WRITE; + case MUSL_SHUT_RDWR: return SHUTDOWN_BIDIRECTIONAL; + default: + fprintf(stderr, "Unrecognized shutdown() how option %d!\n", how); + return how; + } +} + +void Shutdown(int client_fd, uint8_t *data, uint64_t numBytes) // int shutdown(int socket, int how); +{ + struct MSG { + SocketCallHeader header; + int socket; + int how; + }; + MSG *d = (MSG*)data; + + d->how = Translate_Shutdown_How(d->how); + + int ret, errorCode; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = shutdown(d->socket, d->how); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; +#ifdef POSIX_SOCKET_DEBUG + printf("shutdown(socket=%d,how=%d)->%d\n", d->socket, d->how, ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + if (errorCode == 0 && d->how == SHUTDOWN_BIDIRECTIONAL) + { + // Proxy client performed bidirectional close, mark this socket as being disconnected, and disallow it + // from accessing this socket again - this close()s the socket. + CloseSocketByConnection(client_fd, d->socket); + } + } + else + { + fprintf(stderr, "shutdown(socket=%d,how=%d): Proxy client connection client_fd=%d attempted to call shutdown() on a socket fd=%d that it did not create (or has already shut down)\n", d->socket, d->how, client_fd, d->socket); + ret = errorCode = -1; + } + + struct { + int callId; + int ret; + int errno_; + } r; + r.callId = d->header.callId; + r.ret = ret; + r.errno_ = (ret != 0) ? errno : 0; + SendWebSocketMessage(client_fd, &r, sizeof(r)); +} + +void Bind(int client_fd, uint8_t *data, uint64_t numBytes) // int bind(int socket, const struct sockaddr *address, socklen_t address_len); +{ + struct MSG { + SocketCallHeader header; + int socket; + uint32_t/*socklen_t*/ address_len; + uint8_t address[]; + }; + MSG *d = (MSG*)data; + + int ret, errorCode; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = bind(d->socket, (sockaddr*)d->address, d->address_len); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; +#ifdef POSIX_SOCKET_DEBUG + printf("bind(socket=%d,address=%p,address_len=%d, address=\"%s\")->%d\n", d->socket, d->address, d->address_len, BufferToString(d->address, d->address_len), ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + } + else + { + fprintf(stderr, "bind(): Proxy client connection client_fd=%d attempted to call bind() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + } + + struct { + int callId; + int ret; + int errno_; + } r; + r.callId = d->header.callId; + r.ret = ret; + r.errno_ = (ret != 0) ? errno : 0; + SendWebSocketMessage(client_fd, &r, sizeof(r)); +} + +void Connect(int client_fd, uint8_t *data, uint64_t numBytes) // int connect(int socket, const struct sockaddr *address, socklen_t address_len); +{ + struct MSG { + SocketCallHeader header; + int socket; + uint32_t/*socklen_t*/ address_len; + uint8_t address[]; + }; + MSG *d = (MSG*)data; + + int actualAddressLen = MIN(d->address_len, (uint32_t)numBytes - sizeof(MSG)); + + int ret, errorCode; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = connect(d->socket, (sockaddr*)d->address, actualAddressLen); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; +#ifdef POSIX_SOCKET_DEBUG + printf("connect(socket=%d,address=%p,address_len=%d, address=\"%s\")->%d\n", d->socket, d->address, d->address_len, BufferToString(d->address, actualAddressLen), ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + } + else + { + fprintf(stderr, "connect(): Proxy client connection client_fd=%d attempted to call connect() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + } + + struct { + int callId; + int ret; + int errno_; + } r; + r.callId = d->header.callId; + r.ret = ret; + r.errno_ = (ret != 0) ? errno : 0; + SendWebSocketMessage(client_fd, &r, sizeof(r)); +} + +void Listen(int client_fd, uint8_t *data, uint64_t numBytes) // int listen(int socket, int backlog); +{ + struct MSG { + SocketCallHeader header; + int socket; + int backlog; + }; + MSG *d = (MSG*)data; + + int ret, errorCode; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = listen(d->socket, d->backlog); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; +#ifdef POSIX_SOCKET_DEBUG + printf("listen(socket=%d,backlog=%d)->%d\n", d->socket, d->backlog, ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + } + else + { + fprintf(stderr, "bind(): Proxy client connection client_fd=%d attempted to call bind() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + } + + struct { + int callId; + int ret; + int errno_; + } r; + r.callId = d->header.callId; + r.ret = ret; + r.errno_ = (ret != 0) ? errno : 0; + SendWebSocketMessage(client_fd, &r, sizeof(r)); +} + +void Accept(int client_fd, uint8_t *data, uint64_t numBytes) // int accept(int socket, struct sockaddr *address, socklen_t *address_len); +{ + struct MSG { + SocketCallHeader header; + int socket; + uint32_t/*socklen_t*/ address_len; + }; + MSG *d = (MSG*)data; + + uint8_t address[MAX_SOCKADDR_SIZE] = {}; + socklen_t addressLen = (socklen_t)MAX(0, MIN(d->address_len, MAX_SOCKADDR_SIZE)); + + int ret, errorCode; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { +#ifdef POSIX_SOCKET_DEBUG + printf("accept(socket=%d,address=%p,address_len=%u, address=\"%s\")\n", d->socket, address, d->address_len, BufferToString(address, addressLen)); +#endif + ret = accept(d->socket, d->address_len ? (sockaddr*)address : 0, d->address_len ? &addressLen : 0); + errorCode = (ret < 0) ? GET_SOCKET_ERROR() : 0; + +#ifdef POSIX_SOCKET_DEBUG + printf("accept returned %d (address=\"%s\")\n", ret, BufferToString(address, addressLen)); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + + if (ret > 0) + { + // New connection socket created by the proxy bridge, mark it as part of this WebSocket proxy connection. + TrackSocketUsedByConnection(client_fd, ret); + } + } + else + { + fprintf(stderr, "accept(): Proxy client connection client_fd=%d attempted to call accept() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + addressLen = 0; + } + + struct Result { + int callId; + int ret; + int errno_; + int address_len; + uint8_t address[]; + }; + + int actualAddressLen = MIN(addressLen, (socklen_t)d->address_len); + int resultSize = sizeof(Result) + actualAddressLen; + Result *r = (Result*)malloc(resultSize); + r->callId = d->header.callId; + r->ret = ret; + r->errno_ = errorCode; + r->address_len = addressLen; + memcpy(r->address, address, actualAddressLen); + SendWebSocketMessage(client_fd, r, resultSize); + free(r); +} + +void Getsockname(int client_fd, uint8_t *data, uint64_t numBytes) // int getsockname(int socket, struct sockaddr *address, socklen_t *address_len); +{ + struct MSG { + SocketCallHeader header; + int socket; + uint32_t/*socklen_t*/ address_len; + }; + MSG *d = (MSG*)data; + + uint8_t address[MAX_SOCKADDR_SIZE]; + + socklen_t addressLen = (socklen_t)d->address_len; + + int ret, errorCode; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = getsockname(d->socket, (sockaddr*)address, &addressLen); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; + +#ifdef POSIX_SOCKET_DEBUG + printf("getsockname(socket=%d,address=%p,address_len=%u)->%d (ret address: \"%s\")\n", d->socket, address, d->address_len, ret, BufferToString(address, addressLen)); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + } + else + { + fprintf(stderr, "getsockname(): Proxy client connection client_fd=%d attempted to call getsockname() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + addressLen = 0; + } + + struct Result { + int callId; + int ret; + int errno_; + int address_len; + uint8_t address[]; + }; + int actualAddressLen = MIN(addressLen, (socklen_t)d->address_len); + int resultSize = sizeof(Result) + actualAddressLen; + Result *r = (Result*)malloc(resultSize); + r->callId = d->header.callId; + r->ret = ret; + r->errno_ = errorCode; + r->address_len = addressLen; + memcpy(r->address, address, actualAddressLen); + SendWebSocketMessage(client_fd, r, resultSize); + free(r); +} + +void Getpeername(int client_fd, uint8_t *data, uint64_t numBytes) // int getpeername(int socket, struct sockaddr *address, socklen_t *address_len); +{ + struct MSG { + SocketCallHeader header; + int socket; + uint32_t/*socklen_t*/ address_len; + }; + MSG *d = (MSG*)data; + + uint8_t address[MAX_SOCKADDR_SIZE]; + socklen_t addressLen = (socklen_t)d->address_len; + + int ret, errorCode; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = getpeername(d->socket, (sockaddr*)address, &addressLen); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; + +#ifdef POSIX_SOCKET_DEBUG + printf("getpeername(socket=%d,address=%p,address_len=%u, address=\"%s\")->%d\n", d->socket, address, d->address_len, BufferToString(address, addressLen), ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + } + else + { + fprintf(stderr, "getpeername(): Proxy client connection client_fd=%d attempted to call getpeername() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + addressLen = 0; + } + + struct Result { + int callId; + int ret; + int errno_; + int address_len; + uint8_t address[]; + }; + int actualAddressLen = MIN(addressLen, (socklen_t)d->address_len); + int resultSize = sizeof(Result) + actualAddressLen; + Result *r = (Result*)malloc(resultSize); + r->callId = d->header.callId; + r->ret = ret; + r->errno_ = errorCode; + r->address_len = addressLen; + memcpy(r->address, address, actualAddressLen); + SendWebSocketMessage(client_fd, r, resultSize); + free(r); +} + +void Send(int client_fd, uint8_t *data, uint64_t numBytes) // ssize_t/int send(int socket, const void *message, size_t length, int flags); +{ + struct MSG { + SocketCallHeader header; + int socket; + uint32_t/*size_t*/ length; + int flags; + uint8_t message[]; + }; + MSG *d = (MSG*)data; + + int actualBytes = MIN((int)numBytes - sizeof(MSG), d->length); + SEND_RET_TYPE ret; + int errorCode; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = send(d->socket, (const char *)d->message, actualBytes, d->flags); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; + +#ifdef POSIX_SOCKET_DEBUG + printf("send(socket=%d,message=%p,length=%zd,flags=%d, data=\"%s\")->" SEND_FORMATTING_SPECIFIER "\n", d->socket, d->message, d->length, d->flags, BufferToString(d->message, d->length), ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + } + else + { + fprintf(stderr, "send(): Proxy client connection client_fd=%d attempted to call send() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + } + + struct { + int callId; + int/*ssize_t/int*/ ret; + int errno_; + } r; + r.callId = d->header.callId; + r.ret = (int)ret; + r.errno_ = (ret != 0) ? errno : 0; + SendWebSocketMessage(client_fd, &r, sizeof(r)); +} + +void Recv(int client_fd, uint8_t *data, uint64_t numBytes) // ssize_t/int recv(int socket, void *buffer, size_t length, int flags); +{ + struct MSG { + SocketCallHeader header; + int socket; + uint32_t/*size_t*/ length; + int flags; + }; + MSG *d = (MSG*)data; + + uint8_t *buffer = (uint8_t*)malloc(d->length); + SEND_RET_TYPE ret; + int errorCode; + int receivedBytes; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = recv(d->socket, (char *)buffer, d->length, d->flags); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; + receivedBytes = MAX(ret, 0); + +#ifdef POSIX_SOCKET_DEBUG + printf("recv(socket=%d,buffer=%p,length=%zd,flags=%d)->" SEND_FORMATTING_SPECIFIER " received \"%s\"\n", d->socket, buffer, d->length, d->flags, ret, BufferToString(buffer, receivedBytes)); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + } + else + { + fprintf(stderr, "recv(): Proxy client connection client_fd=%d attempted to call recv() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + receivedBytes = 0; + } + + struct Result { + int callId; + int/*ssize_t/int*/ ret; + int errno_; + uint8_t data[]; + }; + int resultSize = sizeof(Result) + receivedBytes; + Result *r = (Result *)malloc(resultSize); + r->callId = d->header.callId; + r->ret = (int)ret; + r->errno_ = errorCode; + memcpy(r->data, buffer, receivedBytes); + free(buffer); + SendWebSocketMessage(client_fd, r, resultSize); + free(r); +} + +void Sendto(int client_fd, uint8_t *data, uint64_t numBytes) // ssize_t/int sendto(int socket, const void *message, size_t length, int flags, const struct sockaddr *dest_addr, socklen_t dest_len); +{ + struct MSG { + SocketCallHeader header; + int socket; + uint32_t/*size_t*/ length; + int flags; + uint32_t/*socklen_t*/ dest_len; + uint8_t dest_addr[MAX_SOCKADDR_SIZE]; + uint8_t message[]; + }; + MSG *d = (MSG*)data; + + SEND_RET_TYPE ret; + int errorCode; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = sendto(d->socket, (const char *)d->message, d->length, d->flags, (sockaddr*)d->dest_addr, d->dest_len); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; + +#ifdef POSIX_SOCKET_DEBUG + printf("sendto(socket=%d,message=%p,length=%zd,flags=%d,dest_addr=%p,dest_len=%d)->" SEND_FORMATTING_SPECIFIER "\n", d->socket, d->message, d->length, d->flags, d->dest_addr, d->dest_len, ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + } + else + { + fprintf(stderr, "sendto(): Proxy client connection client_fd=%d attempted to call sendto() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + } + + struct { + int callId; + int/*ssize_t/int*/ ret; + int errno_; + } r; + r.callId = d->header.callId; + r.ret = (int)ret; + r.errno_ = (ret != 0) ? errno : 0; + SendWebSocketMessage(client_fd, &r, sizeof(r)); +} + +void Recvfrom(int client_fd, uint8_t *data, uint64_t numBytes) // ssize_t/int recvfrom(int socket, void *buffer, size_t length, int flags, struct sockaddr *address, socklen_t *address_len); +{ + struct MSG { + SocketCallHeader header; + int socket; + uint32_t/*size_t*/ length; + int flags; + uint32_t/*socklen_t*/ address_len; + }; + MSG *d = (MSG*)data; + + uint8_t address[MAX_SOCKADDR_SIZE]; + uint8_t *buffer = (uint8_t *)malloc(d->length); + + socklen_t address_len = (socklen_t)d->address_len; + + int ret, errorCode, receivedBytes; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = recvfrom(d->socket, (char *)buffer, d->length, d->flags, (sockaddr*)address, &address_len); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; +#ifdef POSIX_SOCKET_DEBUG + printf("recvfrom(socket=%d,buffer=%p,length=%zd,flags=%d,address=%p,address_len=%u, address=\"%s\")->%d\n", d->socket, buffer, d->length, d->flags, address, d->address_len, BufferToString(address, address_len), ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + receivedBytes = MAX(ret, 0); + } + else + { + fprintf(stderr, "recvfrom(): Proxy client connection client_fd=%d attempted to call recvfrom() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + receivedBytes = 0; + address_len = 0; + } + + int actualAddressLen = MIN(address_len, (socklen_t)d->address_len); + + struct Result { + int callId; + int/*ssize_t/int*/ ret; + int errno_; + int data_len; + int address_len; // N.B. this is the reported address length of the sender, that may be larger than what is actually serialized to this message. + uint8_t data_and_address[]; + }; + int resultSize = sizeof(Result) + receivedBytes + actualAddressLen; + Result *r = (Result *)malloc(resultSize); + r->callId = d->header.callId; + r->ret = (int)ret; + r->errno_ = errorCode; + r->data_len = receivedBytes; + r->address_len = d->address_len; // How many bytes would have been needed to fit the whole sender address, not the actual size provided + memcpy(r->data_and_address, buffer, receivedBytes); + memcpy(r->data_and_address + receivedBytes, address, actualAddressLen); + SendWebSocketMessage(client_fd, r, resultSize); + free(r); +} + +void Sendmsg(int client_fd, uint8_t *data, uint64_t numBytes) // ssize_t/int sendmsg(int socket, const struct msghdr *message, int flags); +{ + printf("TODO implement sendmsg()\n"); +#ifdef POSIX_SOCKET_DEBUG +// printf("sendmsg(socket=%d,message=%p,flags=%d)\n", d->socket, d->message, d->flags); +#endif + + // TODO +} + +void Recvmsg(int client_fd, uint8_t *data, uint64_t numBytes) // ssize_t/int recvmsg(int socket, struct msghdr *message, int flags); +{ + printf("TODO implement recvmsg()\n"); +#ifdef POSIX_SOCKET_DEBUG +// printf("recvmsg(socket=%d,message=%p,flags=%d)\n", d->socket, d->message, d->flags); +#endif +} + +void Getsockopt(int client_fd, uint8_t *data, uint64_t numBytes) // int getsockopt(int socket, int level, int option_name, void *option_value, socklen_t *option_len); +{ + struct MSG { + SocketCallHeader header; + int socket; + int level; + int option_name; + uint32_t/*socklen_t*/ option_len; + }; + MSG *d = (MSG*)data; + + uint8_t option_value[MAX_OPTIONVALUE_SIZE]; + + d->level = Translate_Socket_Level(d->level); + d->option_name = Translate_SOL_SOCKET_option(d->option_name); + + socklen_t option_len = (socklen_t)d->option_len; + + int ret, errorCode; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = getsockopt(d->socket, d->level, d->option_name, (char*)option_value, &option_len); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; + +#ifdef POSIX_SOCKET_DEBUG + printf("getsockopt(socket=%d,level=%d,option_name=%d,option_value=%p,option_len=%u, optionData=\"%s\")->%d\n", d->socket, d->level, d->option_name, option_value, d->option_len, BufferToString(option_value, option_len), ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + } + else + { + fprintf(stderr, "getsockopt(): Proxy client connection client_fd=%d attempted to call getsockopt() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + option_len = 0; + } + + struct Result { + int callId; + int ret; + int errno_; + int option_len; + uint8_t option_value[]; + }; + + int actualOptionLen = MIN(option_len, (socklen_t)d->option_len); + int resultSize = sizeof(Result) + actualOptionLen; + Result *r = (Result*)malloc(resultSize); + r->callId = d->header.callId; + r->ret = ret; + r->errno_ = errorCode; + r->option_len = option_len; + memcpy(r->option_value, option_value, actualOptionLen); + SendWebSocketMessage(client_fd, r, resultSize); + free(r); +} + +void Setsockopt(int client_fd, uint8_t *data, uint64_t numBytes) // int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len); +{ + struct MSG { + SocketCallHeader header; + int socket; + int level; + int option_name; + int option_len; + uint8_t option_value[]; + }; + MSG *d = (MSG*)data; + int actualOptionLen = MIN(d->option_len, (int)(numBytes - sizeof(MSG))); + + d->level = Translate_Socket_Level(d->level); + switch(d->level) + { + case SOL_SOCKET: d->option_name = Translate_SOL_SOCKET_option(d->option_name); break; + case IPPROTO_TCP: d->option_name = Translate_IPPROTO_TCP_option(d->option_name); break; + default: + fprintf(stderr, "Unknown socket level %d, unable to translate socket option\n", d->level); + break; + } + + int ret, errorCode; + + if (IsSocketPartOfConnection(client_fd, d->socket)) + { + ret = setsockopt(d->socket, d->level, d->option_name, (const char *)d->option_value, actualOptionLen); + errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; + +#ifdef POSIX_SOCKET_DEBUG + printf("setsockopt(socket=%d,level=%d,option_name=%d,option_value=%p,option_len=%d, optionData=\"%s\")->%d\n", d->socket, d->level, d->option_name, d->option_value, d->option_len, BufferToString(d->option_value, actualOptionLen), ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + } + else + { + fprintf(stderr, "setsockopt(): Proxy client connection client_fd=%d attempted to call setsockopt() on a socket fd=%d that it did not create (or has already shut down)\n", client_fd, d->socket); + ret = errorCode = -1; + } + + struct { + int callId; + int ret; + int errno_; + } r; + r.callId = d->header.callId; + r.ret = ret; + r.errno_ = (ret != 0) ? errno : 0; + SendWebSocketMessage(client_fd, &r, sizeof(r)); +} + +void Getaddrinfo(int client_fd, uint8_t *data, uint64_t numBytes) // int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res); +{ +#define MAX_NODE_LEN 2048 +#define MAX_SERVICE_LEN 128 + + struct MSG { + SocketCallHeader header; + char node[MAX_NODE_LEN]; // Arbitrary max length limit + char service[MAX_SERVICE_LEN]; // Arbitrary max length limit + int hasHints; + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + }; + MSG *d = (MSG*)data; + + addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_flags = d->ai_flags; + hints.ai_family = d->ai_family; + hints.ai_socktype = d->ai_socktype; + hints.ai_protocol = d->ai_protocol; + + addrinfo *res = 0; + int ret = getaddrinfo(d->node, d->service, d->hasHints ? &hints : 0, &res); + int errorCode = (ret != 0) ? GET_SOCKET_ERROR() : 0; + +#ifdef POSIX_SOCKET_DEBUG + printf("getaddrinfo(node=%s,service=%s,hasHints=%d,ai_flags=%d,ai_family=%d,ai_socktype=%d,ai_protocol=%d)->%d\n", d->node, d->service, d->hasHints, d->ai_flags, d->ai_family, d->ai_socktype, d->ai_protocol, ret); + if (errorCode) PRINT_SOCKET_ERROR(errorCode); +#endif + + char ai_canonname[MAX_NODE_LEN] = {}; + int ai_addrTotalLen = 0; + int addrCount = 0; + + if (ret == 0) + { + if (res && res->ai_canonname) + { + if (strlen(res->ai_canonname) >= MAX_NODE_LEN) printf("Warning: Truncated res->ai_canonname to %d bytes (was %s)\n", MAX_NODE_LEN, res->ai_canonname); + strncpy(ai_canonname, res->ai_canonname, MAX_NODE_LEN-1); + } + + addrinfo *ai = res; + while(ai) + { + ai_addrTotalLen += ai->ai_addrlen; + ++addrCount; + ai = ai->ai_next; + } + } + + struct ResAddrinfo + { + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + int/*socklen_t*/ ai_addrlen; + uint8_t /*sockaddr **/ ai_addr[]; + }; + + struct Result { + int callId; + int ret; + int errno_; + char ai_canonname[MAX_NODE_LEN]; + int addrCount; + uint8_t /*ResAddrinfo[]*/ addr[]; + }; + + int resultSize = sizeof(Result) + sizeof(ResAddrinfo)*addrCount + ai_addrTotalLen; + Result *r = (Result*)malloc(resultSize); + + memset(r, 0, resultSize); + r->callId = d->header.callId; + r->ret = ret; + r->errno_ = errorCode; + strncpy(r->ai_canonname, ai_canonname, MAX_NODE_LEN-1); + r->addrCount = addrCount; + + addrinfo *ai = res; + int offset = 0; + while(ai) + { + ResAddrinfo *o = (ResAddrinfo*)(r->addr + offset); + o->ai_flags = ai->ai_flags; + o->ai_family = ai->ai_family; + o->ai_socktype = ai->ai_socktype; + o->ai_protocol = ai->ai_protocol; + o->ai_addrlen = ai->ai_addrlen; + memcpy(o->ai_addr, ai->ai_addr, ai->ai_addrlen); + offset += sizeof(ResAddrinfo) + ai->ai_addrlen; + ai = ai->ai_next; + } + if (res) freeaddrinfo(res); + + SendWebSocketMessage(client_fd, r, resultSize); + + free(r); +} + +void Getnameinfo(int client_fd, uint8_t *data, uint64_t numBytes) // int getnameinfo(const struct sockaddr *addr, socklen_t addrlen, char *host, socklen_t hostlen, char *serv, socklen_t servlen, int flags); +{ + fprintf(stderr, "TODO getnameinfo() unimplemented!\n"); +} + +static void *memdup(const void *ptr, size_t sz) +{ + if (!ptr) return 0; + void *dup = malloc(sz); + if (dup) memcpy(dup, ptr, sz); + return dup; +} + +struct MessageArg +{ + int client_fd; + uint8_t *payload; + uint64_t numBytes; +}; + +void ProcessWebSocketMessageSynchronouslyInCurrentThread(int client_fd, uint8_t *payload, uint64_t numBytes); + +THREAD_RETURN_T message_processing_thread(void *arg) +{ + MessageArg *msg = (MessageArg*)arg; + assert(msg); + assert(msg->client_fd); + ProcessWebSocketMessageSynchronouslyInCurrentThread(msg->client_fd, msg->payload, msg->numBytes); + free(msg->payload); + free(msg); + EXIT_THREAD(0); +} + +// Offloads the processing of the given message to a background thread. +void ProcessWebSocketMessageAsynchronouslyInBackgroundThread(int client_fd, uint8_t *payload, uint64_t numBytes) +{ + MessageArg *arg = (MessageArg*)malloc(sizeof(MessageArg)); + arg->client_fd = client_fd; + arg->payload = (uint8_t*)memdup(payload, (size_t)numBytes); + arg->numBytes = numBytes; + THREAD_T thread; + // TODO: Instead of unconditionally always creating a thread here, create a thread pool and push messages to it. + // (leaving this as a future optimization because not sure if it matters here much at all for performance) + CREATE_THREAD(thread, message_processing_thread, arg); +} + +void ProcessWebSocketMessageSynchronouslyInCurrentThread(int client_fd, uint8_t *payload, uint64_t numBytes) +{ + assert(numBytes >= sizeof(SocketCallHeader)); // Already validated in ProcessWebSocketMessage() before coming here, so we should be good. + SocketCallHeader *header = (SocketCallHeader*)payload; + switch(header->function) + { + case POSIX_SOCKET_MSG_SOCKET: Socket(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_SOCKETPAIR: Socketpair(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_SHUTDOWN: Shutdown(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_BIND: Bind(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_CONNECT: Connect(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_LISTEN: Listen(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_ACCEPT: Accept(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_GETSOCKNAME: Getsockname(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_GETPEERNAME: Getpeername(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_SEND: Send(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_RECV: Recv(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_SENDTO: Sendto(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_RECVFROM: Recvfrom(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_SENDMSG: Sendmsg(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_RECVMSG: Recvmsg(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_GETSOCKOPT: Getsockopt(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_SETSOCKOPT: Setsockopt(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_GETADDRINFO: Getaddrinfo(client_fd, payload, numBytes); break; + case POSIX_SOCKET_MSG_GETNAMEINFO: Getnameinfo(client_fd, payload, numBytes); break; + default: + printf("Unknown POSIX_SOCKET_MSG %u received!\n", header->function); + break; + } +} + +void ProcessWebSocketMessage(int client_fd, uint8_t *payload, uint64_t numBytes) +{ + if (numBytes < sizeof(SocketCallHeader)) + { + printf("Received too small sockets call message! size: %d bytes, expected at least %d bytes\n", (int)numBytes, (int)sizeof(SocketCallHeader)); + return; + } + SocketCallHeader *header = (SocketCallHeader*)payload; + if (header->function == POSIX_SOCKET_MSG_RECV || header->function == POSIX_SOCKET_MSG_RECVFROM || header->function == POSIX_SOCKET_MSG_RECVMSG || header->function == POSIX_SOCKET_MSG_CONNECT || header->function == POSIX_SOCKET_MSG_LISTEN) + { + // Synchonous/blocking recv()s can halt indefinitely until a message is actually received. An application might + // be send()ing messages in one thread while using another thread to wait for recv(). Therefore run these potentially + // blocking recv()s in a separate thread. The nonblocking operations can run synchronously in calling thread (they could + // also run in a background thread, but for performance, do not offload them since it is not necessary) + ProcessWebSocketMessageAsynchronouslyInBackgroundThread(client_fd, payload, numBytes); + } + else + { + ProcessWebSocketMessageSynchronouslyInCurrentThread(client_fd, payload, numBytes); + } +} diff --git a/tools/websocket_to_posix_proxy/src/websocket_to_posix_proxy.h b/tools/websocket_to_posix_proxy/src/websocket_to_posix_proxy.h new file mode 100644 index 0000000000000..85b3bc34ff2bf --- /dev/null +++ b/tools/websocket_to_posix_proxy/src/websocket_to_posix_proxy.h @@ -0,0 +1,31 @@ +#pragma once + +#include + +uint64_t ntoh64(uint64_t x); +#define hton64 ntoh64 + +void WebSocketMessageUnmaskPayload(uint8_t *payload, uint64_t payloadLength, uint32_t maskingKey); +void ProcessWebSocketMessage(int client_fd, uint8_t *payload, uint64_t numBytes); + +#ifdef _MSC_VER +#pragma pack(push,1) +#endif + +struct +#if defined(__GNUC__) +__attribute__ ((packed, aligned(1))) +#endif + +WebSocketMessageHeader +{ + unsigned opcode : 4; + unsigned rsv : 3; + unsigned fin : 1; + unsigned payloadLength : 7; + unsigned mask : 1; +}; + +#ifdef _MSC_VER +__pragma(pack(pop)) +#endif