diff --git a/.gitignore b/.gitignore index 6617bc2b77..311fec9fb8 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,10 @@ # gyp generated stuff. /worker/out/ /worker/**/*.xcodeproj/ +/worker/**/*.sln +/worker/**/*.vcxproj +/worker/**/*.vcxproj.filters +/worker/**/*.vcxproj.user # clang-fuzzer stuff is too big. /worker/deps/clang-fuzzer @@ -22,3 +26,14 @@ # Mac Stuff. .DS_Store + +# Python generated stuff in Windows. +/worker/scripts/configure.pyc + +# Vistual Studio generated Stuff. +/worker/**/Debug/ +/worker/**/Release/ +/worker/.vs/ + +# Vistual Studio Code stuff. +/.vscode/ diff --git a/lib/Channel.js b/lib/Channel.js index 7cd8e6c909..b1864a1f69 100644 --- a/lib/Channel.js +++ b/lib/Channel.js @@ -12,7 +12,7 @@ class Channel extends EnhancedEventEmitter /** * @private */ - constructor({ socket, pid }) + constructor({ producerSocket, consumerSocket, pid }) { const logger = new Logger(`Channel[pid:${pid}]`); const workerLogger = new Logger(`worker[pid:${pid}]`); @@ -30,7 +30,8 @@ class Channel extends EnhancedEventEmitter // Unix Socket instance. // @type {net.Socket} - this._socket = socket; + this._producerSocket = producerSocket; + this._consumerSocket = consumerSocket; // Next request id. // @type {Number} @@ -45,7 +46,7 @@ class Channel extends EnhancedEventEmitter this._recvBuffer = null; // Read Channel responses/notifications from the worker. - this._socket.on('data', (buffer) => + this._consumerSocket.on('data', (buffer) => { if (!this._recvBuffer) { @@ -147,8 +148,11 @@ class Channel extends EnhancedEventEmitter } }); - this._socket.on('end', () => this._logger.debug('Channel ended by the worker process')); - this._socket.on('error', (error) => this._logger.error('Channel error: %s', String(error))); + this._consumerSocket.on('end', () => this._logger.debug('Consumer Channel ended by the worker process')); + this._consumerSocket.on('error', (error) => this._logger.error('Consumer Channel error: %s', String(error))); + + this._producerSocket.on('end', () => this._logger.debug('Producer Channel ended by the worker process')); + this._producerSocket.on('error', (error) => this._logger.error('Producer Channel error: %s', String(error))); } /** @@ -171,14 +175,20 @@ class Channel extends EnhancedEventEmitter // Remove event listeners but leave a fake 'error' hander to avoid // propagation. - this._socket.removeAllListeners('end'); - this._socket.removeAllListeners('error'); - this._socket.on('error', () => {}); + this._consumerSocket.removeAllListeners('end'); + this._consumerSocket.removeAllListeners('error'); + this._consumerSocket.on('error', () => {}); + + this._producerSocket.removeAllListeners('end'); + this._producerSocket.removeAllListeners('error'); + this._producerSocket.on('error', () => {}); // Destroy the socket after a while to allow pending incoming messages. setTimeout(() => { - try { this._socket.destroy(); } + try { this._producerSocket.destroy(); } + catch (error) {} + try { this._consumerSocket.destroy(); } catch (error) {} }, 200); } @@ -206,7 +216,7 @@ class Channel extends EnhancedEventEmitter throw new Error('Channel request too big'); // This may throw if closed or remote side ended. - this._socket.write(ns); + this._producerSocket.write(ns); return new Promise((pResolve, pReject) => { diff --git a/lib/Worker.js b/lib/Worker.js index 848135f291..0314295b87 100644 --- a/lib/Worker.js +++ b/lib/Worker.js @@ -90,9 +90,10 @@ class Worker extends EnhancedEventEmitter * fd 0 (stdin) : Just ignore it. * fd 1 (stdout) : Pipe it for 3rd libraries that log their own stuff. * fd 2 (stderr) : Same as stdout. - * fd 3 (channel) : Channel fd. + * fd 3 (channel) : Producer Channel fd. + * fd 4 (channel) : Consumer Channel fd. */ - stdio : [ 'ignore', 'pipe', 'pipe', 'pipe' ] + stdio : [ 'ignore', 'pipe', 'pipe', 'pipe', 'pipe' ] }); this._workerLogger = new Logger(`worker[pid:${this._child.pid}]`); @@ -105,8 +106,9 @@ class Worker extends EnhancedEventEmitter // @type {Channel} this._channel = new Channel( { - socket : this._child.stdio[3], - pid : this._pid + producerSocket : this._child.stdio[3], + consumerSocket : this._child.stdio[4], + pid : this._pid }); // Closed flag. diff --git a/package.json b/package.json index 8ec45e07c1..6ad5503a51 100644 --- a/package.json +++ b/package.json @@ -19,22 +19,27 @@ "sfu", "nodejs" ], - "os": [ - "!win32" - ], "engines": { "node": ">=8.6.0" }, "scripts": { "lint": "npm run lint:node && npm run lint:worker", - "lint:node": "eslint -c .eslintrc.js gulpfile.js lib test", - "lint:worker": "make lint -C worker", - "format:worker": "make format -C worker", + "lint:node": "eslint -c .eslintrc.js gulpfile.js lib test worker/win-tasks.js", + "lint:worker": "run-script-os", + "lint:worker:win32": "\"\"%NODE%\"\" ./worker/win-tasks.js lint", + "lint:worker:default": "make lint -C worker", + "format:worker": "run-script-os", + "format:worker:win32": "\"\"%NODE%\"\" ./worker/win-tasks.js format", + "format:worker:default": "make format -C worker", "test": "npm run test:node && npm run test:worker", - "test:node": "make -C worker && jest", - "test:worker": "make test -C worker", - "coverage:node": "make -C worker && jest --coverage && open-cli coverage/lcov-report/index.html", - "postinstall": "make -C worker" + "test:node": "npm run postinstall && jest", + "test:worker": "run-script-os", + "test:worker:win32": "\"\"%NODE%\"\" ./worker/win-tasks.js test", + "test:worker:default": "make test -C worker", + "coverage:node": "npm run postinstall && jest --coverage && open-cli coverage/lcov-report/index.html", + "postinstall": "run-script-os", + "postinstall:win32": "\"\"%NODE%\"\" ./worker/win-tasks.js make", + "postinstall:default": "make -C worker" }, "jest": { "verbose": true, @@ -46,6 +51,7 @@ "h264-profile-level-id": "^1.0.0", "netstring": "^0.3.0", "random-number": "^0.0.9", + "@dr.amaton/run-script-os": "^1.1.2", "uuid": "^3.3.3" }, "devDependencies": { diff --git a/test/test-Worker.js b/test/test-Worker.js index 90553e805f..7569a4d81c 100644 --- a/test/test-Worker.js +++ b/test/test-Worker.js @@ -1,3 +1,4 @@ +const os = require('os'); const process = require('process'); const { toBeType } = require('jest-tobetype'); const mediasoup = require('../'); @@ -194,6 +195,11 @@ test('Worker emits "died" if worker process died unexpectedly', async () => test('worker process ignores PIPE, HUP, ALRM, USR1 and USR2 signals', async () => { + // Windows doesn't have some signals such as SIGPIPE, SIGALRM, SIGUSR1, SIGUSR2 + // so we just skip this test in Windows. + if (os.platform() === 'win32') + return; + worker = await createWorker({ logLevel: 'warn' }); await new Promise((resolve, reject) => diff --git a/worker/deps/getopt/getopt.gyp b/worker/deps/getopt/getopt.gyp new file mode 100644 index 0000000000..fa63de7123 --- /dev/null +++ b/worker/deps/getopt/getopt.gyp @@ -0,0 +1,22 @@ +{ + 'targets': + [ + { + 'target_name': 'getopt', + 'type': 'static_library', + 'sources': + [ + 'getopt/src/getopt.h', + 'getopt/src/getopt.c' + ], + 'include_dirs': + [ + 'getopt/src/' + ], + 'direct_dependent_settings': + { + 'include_dirs': ['getopt/src/'] + }, + } + ] +} diff --git a/worker/deps/getopt/getopt/.gitignore b/worker/deps/getopt/getopt/.gitignore new file mode 100644 index 0000000000..5500d01460 --- /dev/null +++ b/worker/deps/getopt/getopt/.gitignore @@ -0,0 +1,8 @@ +CMakeCache.txt +CMakeFiles +Makefile +cmake_install.cmake +install_manifest.txt +build +*.lib +*.pdb diff --git a/worker/deps/getopt/getopt/CMakeLists.txt b/worker/deps/getopt/getopt/CMakeLists.txt new file mode 100644 index 0000000000..663f0c02e3 --- /dev/null +++ b/worker/deps/getopt/getopt/CMakeLists.txt @@ -0,0 +1,23 @@ +PROJECT(wingetopt) +cmake_minimum_required(VERSION 2.8) + +option(BUILD_SHARED_LIBS "Build the shared library" OFF) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src) + +add_definitions(-D_CRT_SECURE_NO_WARNINGS) + +if(BUILD_SHARED_LIBS) + set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) + add_definitions(-DBUILDING_WINGETOPT_DLL -DWINGETOPT_SHARED_LIB) +endif() + +add_library(wingetopt src/getopt.c src/getopt.h) + +install(FILES src/getopt.h DESTINATION include) + +install(TARGETS wingetopt + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib) + diff --git a/worker/deps/getopt/getopt/LICENSE b/worker/deps/getopt/getopt/LICENSE new file mode 100644 index 0000000000..b1ded6d834 --- /dev/null +++ b/worker/deps/getopt/getopt/LICENSE @@ -0,0 +1,54 @@ +#### AUTHORS: + +* Todd C. Miller +* The NetBSD Foundation, Inc. +* Alexei Kasatkin is the author of trivial CMakeLists.txt, build script itself is Public Domain + +#### LICENSE + + Copyright (c) 2002 Todd C. Miller + + Permission to use, copy, modify, and distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + Sponsored in part by the Defense Advanced Research Projects + Agency (DARPA) and Air Force Research Laboratory, Air Force + Materiel Command, USAF, under agreement number F39502-99-1-0512. + +*** + + Copyright (c) 2000 The NetBSD Foundation, Inc. + All rights reserved. + + This code is derived from software contributed to The NetBSD Foundation + by Dieter Baron and Thomas Klausner. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. diff --git a/worker/deps/getopt/getopt/README.md b/worker/deps/getopt/getopt/README.md new file mode 100644 index 0000000000..16b855a614 --- /dev/null +++ b/worker/deps/getopt/getopt/README.md @@ -0,0 +1,63 @@ +# wingetopt + +getopt library for Windows compilers + + +This library was created to allow compilation linux-based software on Windows. +http://en.wikipedia.org/wiki/Getopt + +The sources were taken from MinGW-runtime project. + +#### AUTHORS: + +* Todd C. Miller +* The NetBSD Foundation, Inc. + +#### LICENSE + + Copyright (c) 2002 Todd C. Miller + + Permission to use, copy, modify, and distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + Sponsored in part by the Defense Advanced Research Projects + Agency (DARPA) and Air Force Research Laboratory, Air Force + Materiel Command, USAF, under agreement number F39502-99-1-0512. + +*** + + Copyright (c) 2000 The NetBSD Foundation, Inc. + All rights reserved. + + This code is derived from software contributed to The NetBSD Foundation + by Dieter Baron and Thomas Klausner. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. diff --git a/worker/deps/getopt/getopt/src/getopt.c b/worker/deps/getopt/getopt/src/getopt.c new file mode 100644 index 0000000000..0ed0dd2596 --- /dev/null +++ b/worker/deps/getopt/getopt/src/getopt.c @@ -0,0 +1,562 @@ +/* $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl Exp $ */ +/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */ + +/* + * Copyright (c) 2002 Todd C. Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Sponsored in part by the Defense Advanced Research Projects + * Agency (DARPA) and Air Force Research Laboratory, Air Force + * Materiel Command, USAF, under agreement number F39502-99-1-0512. + */ +/*- + * Copyright (c) 2000 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Dieter Baron and Thomas Klausner. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define REPLACE_GETOPT /* use this getopt as the system getopt(3) */ + +#ifdef REPLACE_GETOPT +int opterr = 1; /* if error message should be printed */ +int optind = 1; /* index into parent argv vector */ +int optopt = '?'; /* character checked for validity */ +#undef optreset /* see getopt.h */ +#define optreset __mingw_optreset +int optreset; /* reset getopt */ +char *optarg; /* argument associated with option */ +#endif + +#define PRINT_ERROR ((opterr) && (*options != ':')) + +#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */ +#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */ +#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */ + +/* return values */ +#define BADCH (int)'?' +#define BADARG ((*options == ':') ? (int)':' : (int)'?') +#define INORDER (int)1 + +#ifndef __CYGWIN__ +#define __progname __argv[0] +#else +extern char __declspec(dllimport) *__progname; +#endif + +#ifdef __CYGWIN__ +static char EMSG[] = ""; +#else +#define EMSG "" +#endif + +static int getopt_internal(int, char * const *, const char *, + const struct option *, int *, int); +static int parse_long_options(char * const *, const char *, + const struct option *, int *, int); +static int gcd(int, int); +static void permute_args(int, int, int, char * const *); + +static char *place = EMSG; /* option letter processing */ + +/* XXX: set optreset to 1 rather than these two */ +static int nonopt_start = -1; /* first non option argument (for permute) */ +static int nonopt_end = -1; /* first option after non options (for permute) */ + +/* Error messages */ +static const char recargchar[] = "option requires an argument -- %c"; +static const char recargstring[] = "option requires an argument -- %s"; +static const char ambig[] = "ambiguous option -- %.*s"; +static const char noarg[] = "option doesn't take an argument -- %.*s"; +static const char illoptchar[] = "unknown option -- %c"; +static const char illoptstring[] = "unknown option -- %s"; + +static void +_vwarnx(const char *fmt,va_list ap) +{ + (void)fprintf(stderr,"%s: ",__progname); + if (fmt != NULL) + (void)vfprintf(stderr,fmt,ap); + (void)fprintf(stderr,"\n"); +} + +static void +warnx(const char *fmt,...) +{ + va_list ap; + va_start(ap,fmt); + _vwarnx(fmt,ap); + va_end(ap); +} + +/* + * Compute the greatest common divisor of a and b. + */ +static int +gcd(int a, int b) +{ + int c; + + c = a % b; + while (c != 0) { + a = b; + b = c; + c = a % b; + } + + return (b); +} + +/* + * Exchange the block from nonopt_start to nonopt_end with the block + * from nonopt_end to opt_end (keeping the same order of arguments + * in each block). + */ +static void +permute_args(int panonopt_start, int panonopt_end, int opt_end, + char * const *nargv) +{ + int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; + char *swap; + + /* + * compute lengths of blocks and number and size of cycles + */ + nnonopts = panonopt_end - panonopt_start; + nopts = opt_end - panonopt_end; + ncycle = gcd(nnonopts, nopts); + cyclelen = (opt_end - panonopt_start) / ncycle; + + for (i = 0; i < ncycle; i++) { + cstart = panonopt_end+i; + pos = cstart; + for (j = 0; j < cyclelen; j++) { + if (pos >= panonopt_end) + pos -= nnonopts; + else + pos += nopts; + swap = nargv[pos]; + /* LINTED const cast */ + ((char **) nargv)[pos] = nargv[cstart]; + /* LINTED const cast */ + ((char **)nargv)[cstart] = swap; + } + } +} + +/* + * parse_long_options -- + * Parse long options in argc/argv argument vector. + * Returns -1 if short_too is set and the option does not match long_options. + */ +static int +parse_long_options(char * const *nargv, const char *options, + const struct option *long_options, int *idx, int short_too) +{ + char *current_argv, *has_equal; + size_t current_argv_len; + int i, ambiguous, match; + +#define IDENTICAL_INTERPRETATION(_x, _y) \ + (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \ + long_options[(_x)].flag == long_options[(_y)].flag && \ + long_options[(_x)].val == long_options[(_y)].val) + + current_argv = place; + match = -1; + ambiguous = 0; + + optind++; + + if ((has_equal = strchr(current_argv, '=')) != NULL) { + /* argument found (--option=arg) */ + current_argv_len = has_equal - current_argv; + has_equal++; + } else + current_argv_len = strlen(current_argv); + + for (i = 0; long_options[i].name; i++) { + /* find matching long option */ + if (strncmp(current_argv, long_options[i].name, + current_argv_len)) + continue; + + if (strlen(long_options[i].name) == current_argv_len) { + /* exact match */ + match = i; + ambiguous = 0; + break; + } + /* + * If this is a known short option, don't allow + * a partial match of a single character. + */ + if (short_too && current_argv_len == 1) + continue; + + if (match == -1) /* partial match */ + match = i; + else if (!IDENTICAL_INTERPRETATION(i, match)) + ambiguous = 1; + } + if (ambiguous) { + /* ambiguous abbreviation */ + if (PRINT_ERROR) + warnx(ambig, (int)current_argv_len, + current_argv); + optopt = 0; + return (BADCH); + } + if (match != -1) { /* option found */ + if (long_options[match].has_arg == no_argument + && has_equal) { + if (PRINT_ERROR) + warnx(noarg, (int)current_argv_len, + current_argv); + /* + * XXX: GNU sets optopt to val regardless of flag + */ + if (long_options[match].flag == NULL) + optopt = long_options[match].val; + else + optopt = 0; + return (BADARG); + } + if (long_options[match].has_arg == required_argument || + long_options[match].has_arg == optional_argument) { + if (has_equal) + optarg = has_equal; + else if (long_options[match].has_arg == + required_argument) { + /* + * optional argument doesn't use next nargv + */ + optarg = nargv[optind++]; + } + } + if ((long_options[match].has_arg == required_argument) + && (optarg == NULL)) { + /* + * Missing argument; leading ':' indicates no error + * should be generated. + */ + if (PRINT_ERROR) + warnx(recargstring, + current_argv); + /* + * XXX: GNU sets optopt to val regardless of flag + */ + if (long_options[match].flag == NULL) + optopt = long_options[match].val; + else + optopt = 0; + --optind; + return (BADARG); + } + } else { /* unknown option */ + if (short_too) { + --optind; + return (-1); + } + if (PRINT_ERROR) + warnx(illoptstring, current_argv); + optopt = 0; + return (BADCH); + } + if (idx) + *idx = match; + if (long_options[match].flag) { + *long_options[match].flag = long_options[match].val; + return (0); + } else + return (long_options[match].val); +#undef IDENTICAL_INTERPRETATION +} + +/* + * getopt_internal -- + * Parse argc/argv argument vector. Called by user level routines. + */ +static int +getopt_internal(int nargc, char * const *nargv, const char *options, + const struct option *long_options, int *idx, int flags) +{ + const char *oli; /* option letter list index */ + int optchar, short_too; + static int posixly_correct = -1; + + if (options == NULL) + return (-1); + + /* + * XXX Some GNU programs (like cvs) set optind to 0 instead of + * XXX using optreset. Work around this braindamage. + */ + if (optind == 0) + optind = optreset = 1; + + /* + * Disable GNU extensions if POSIXLY_CORRECT is set or options + * string begins with a '+'. + * + * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or + * optreset != 0 for GNU compatibility. + */ + if (posixly_correct == -1 || optreset != 0) + posixly_correct = (getenv("POSIXLY_CORRECT") != NULL); + if (*options == '-') + flags |= FLAG_ALLARGS; + else if (posixly_correct || *options == '+') + flags &= ~FLAG_PERMUTE; + if (*options == '+' || *options == '-') + options++; + + optarg = NULL; + if (optreset) + nonopt_start = nonopt_end = -1; +start: + if (optreset || !*place) { /* update scanning pointer */ + optreset = 0; + if (optind >= nargc) { /* end of argument vector */ + place = EMSG; + if (nonopt_end != -1) { + /* do permutation, if we have to */ + permute_args(nonopt_start, nonopt_end, + optind, nargv); + optind -= nonopt_end - nonopt_start; + } + else if (nonopt_start != -1) { + /* + * If we skipped non-options, set optind + * to the first of them. + */ + optind = nonopt_start; + } + nonopt_start = nonopt_end = -1; + return (-1); + } + if (*(place = nargv[optind]) != '-' || + (place[1] == '\0' && strchr(options, '-') == NULL)) { + place = EMSG; /* found non-option */ + if (flags & FLAG_ALLARGS) { + /* + * GNU extension: + * return non-option as argument to option 1 + */ + optarg = nargv[optind++]; + return (INORDER); + } + if (!(flags & FLAG_PERMUTE)) { + /* + * If no permutation wanted, stop parsing + * at first non-option. + */ + return (-1); + } + /* do permutation */ + if (nonopt_start == -1) + nonopt_start = optind; + else if (nonopt_end != -1) { + permute_args(nonopt_start, nonopt_end, + optind, nargv); + nonopt_start = optind - + (nonopt_end - nonopt_start); + nonopt_end = -1; + } + optind++; + /* process next argument */ + goto start; + } + if (nonopt_start != -1 && nonopt_end == -1) + nonopt_end = optind; + + /* + * If we have "-" do nothing, if "--" we are done. + */ + if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { + optind++; + place = EMSG; + /* + * We found an option (--), so if we skipped + * non-options, we have to permute. + */ + if (nonopt_end != -1) { + permute_args(nonopt_start, nonopt_end, + optind, nargv); + optind -= nonopt_end - nonopt_start; + } + nonopt_start = nonopt_end = -1; + return (-1); + } + } + + /* + * Check long options if: + * 1) we were passed some + * 2) the arg is not just "-" + * 3) either the arg starts with -- we are getopt_long_only() + */ + if (long_options != NULL && place != nargv[optind] && + (*place == '-' || (flags & FLAG_LONGONLY))) { + short_too = 0; + if (*place == '-') + place++; /* --foo long option */ + else if (*place != ':' && strchr(options, *place) != NULL) + short_too = 1; /* could be short option too */ + + optchar = parse_long_options(nargv, options, long_options, + idx, short_too); + if (optchar != -1) { + place = EMSG; + return (optchar); + } + } + + if ((optchar = (int)*place++) == (int)':' || + (optchar == (int)'-' && *place != '\0') || + (oli = strchr(options, optchar)) == NULL) { + /* + * If the user specified "-" and '-' isn't listed in + * options, return -1 (non-option) as per POSIX. + * Otherwise, it is an unknown option character (or ':'). + */ + if (optchar == (int)'-' && *place == '\0') + return (-1); + if (!*place) + ++optind; + if (PRINT_ERROR) + warnx(illoptchar, optchar); + optopt = optchar; + return (BADCH); + } + if (long_options != NULL && optchar == 'W' && oli[1] == ';') { + /* -W long-option */ + if (*place) /* no space */ + /* NOTHING */; + else if (++optind >= nargc) { /* no arg */ + place = EMSG; + if (PRINT_ERROR) + warnx(recargchar, optchar); + optopt = optchar; + return (BADARG); + } else /* white space */ + place = nargv[optind]; + optchar = parse_long_options(nargv, options, long_options, + idx, 0); + place = EMSG; + return (optchar); + } + if (*++oli != ':') { /* doesn't take argument */ + if (!*place) + ++optind; + } else { /* takes (optional) argument */ + optarg = NULL; + if (*place) /* no white space */ + optarg = place; + else if (oli[1] != ':') { /* arg not optional */ + if (++optind >= nargc) { /* no arg */ + place = EMSG; + if (PRINT_ERROR) + warnx(recargchar, optchar); + optopt = optchar; + return (BADARG); + } else + optarg = nargv[optind]; + } + place = EMSG; + ++optind; + } + /* dump back option letter */ + return (optchar); +} + +#ifdef REPLACE_GETOPT +/* + * getopt -- + * Parse argc/argv argument vector. + * + * [eventually this will replace the BSD getopt] + */ +int +getopt(int nargc, char * const *nargv, const char *options) +{ + + /* + * We don't pass FLAG_PERMUTE to getopt_internal() since + * the BSD getopt(3) (unlike GNU) has never done this. + * + * Furthermore, since many privileged programs call getopt() + * before dropping privileges it makes sense to keep things + * as simple (and bug-free) as possible. + */ + return (getopt_internal(nargc, nargv, options, NULL, NULL, 0)); +} +#endif /* REPLACE_GETOPT */ + +/* + * getopt_long -- + * Parse argc/argv argument vector. + */ +int +getopt_long(int nargc, char * const *nargv, const char *options, + const struct option *long_options, int *idx) +{ + + return (getopt_internal(nargc, nargv, options, long_options, idx, + FLAG_PERMUTE)); +} + +/* + * getopt_long_only -- + * Parse argc/argv argument vector. + */ +int +getopt_long_only(int nargc, char * const *nargv, const char *options, + const struct option *long_options, int *idx) +{ + + return (getopt_internal(nargc, nargv, options, long_options, idx, + FLAG_PERMUTE|FLAG_LONGONLY)); +} diff --git a/worker/deps/getopt/getopt/src/getopt.h b/worker/deps/getopt/getopt/src/getopt.h new file mode 100644 index 0000000000..f3f864bda6 --- /dev/null +++ b/worker/deps/getopt/getopt/src/getopt.h @@ -0,0 +1,105 @@ +#ifndef __GETOPT_H__ +/** + * DISCLAIMER + * This file has no copyright assigned and is placed in the Public Domain. + * This file is a part of the w64 mingw-runtime package. + * + * The w64 mingw-runtime package and its code is distributed in the hope that it + * will be useful but WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESSED OR + * IMPLIED ARE HEREBY DISCLAIMED. This includes but is not limited to + * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ + +#define __GETOPT_H__ + +/* All the headers include this file. */ +#include + +#if defined( WINGETOPT_SHARED_LIB ) +# if defined( BUILDING_WINGETOPT_DLL ) +# define WINGETOPT_API __declspec(dllexport) +# else +# define WINGETOPT_API __declspec(dllimport) +# endif +#else +# define WINGETOPT_API +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +WINGETOPT_API extern int optind; /* index of first non-option in argv */ +WINGETOPT_API extern int optopt; /* single option character, as parsed */ +WINGETOPT_API extern int opterr; /* flag to enable built-in diagnostics... */ + /* (user may set to zero, to suppress) */ + +WINGETOPT_API extern char *optarg; /* pointer to argument of current option */ + +extern int getopt(int nargc, char * const *nargv, const char *options); + +#ifdef _BSD_SOURCE +/* + * BSD adds the non-standard `optreset' feature, for reinitialisation + * of `getopt' parsing. We support this feature, for applications which + * proclaim their BSD heritage, before including this header; however, + * to maintain portability, developers are advised to avoid it. + */ +# define optreset __mingw_optreset +extern int optreset; +#endif +#ifdef __cplusplus +} +#endif +/* + * POSIX requires the `getopt' API to be specified in `unistd.h'; + * thus, `unistd.h' includes this header. However, we do not want + * to expose the `getopt_long' or `getopt_long_only' APIs, when + * included in this manner. Thus, close the standard __GETOPT_H__ + * declarations block, and open an additional __GETOPT_LONG_H__ + * specific block, only when *not* __UNISTD_H_SOURCED__, in which + * to declare the extended API. + */ +#endif /* !defined(__GETOPT_H__) */ + +#if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) +#define __GETOPT_LONG_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +struct option /* specification for a long form option... */ +{ + const char *name; /* option name, without leading hyphens */ + int has_arg; /* does it take an argument? */ + int *flag; /* where to save its status, or NULL */ + int val; /* its associated status value */ +}; + +enum /* permitted values for its `has_arg' field... */ +{ + no_argument = 0, /* option never takes an argument */ + required_argument, /* option always requires an argument */ + optional_argument /* option may take an argument */ +}; + +extern int getopt_long(int nargc, char * const *nargv, const char *options, + const struct option *long_options, int *idx); +extern int getopt_long_only(int nargc, char * const *nargv, const char *options, + const struct option *long_options, int *idx); +/* + * Previous MinGW implementation had... + */ +#ifndef HAVE_DECL_GETOPT +/* + * ...for the long form API only; keep this for compatibility. + */ +# define HAVE_DECL_GETOPT 1 +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */ diff --git a/worker/deps/libsrtp/libsrtp.gyp b/worker/deps/libsrtp/libsrtp.gyp index 8919320d79..9b0a9be076 100644 --- a/worker/deps/libsrtp/libsrtp.gyp +++ b/worker/deps/libsrtp/libsrtp.gyp @@ -53,6 +53,7 @@ # All Windows architectures are this way. 'SIZEOF_UNSIGNED_LONG=4', 'SIZEOF_UNSIGNED_LONG_LONG=8', + 'HAVE_WINSOCK2_H', ], }], ['target_arch=="x64" or target_arch=="ia32"', { diff --git a/worker/deps/libwebrtc/deps/abseil-cpp/abseil-cpp.gyp b/worker/deps/libwebrtc/deps/abseil-cpp/abseil-cpp.gyp index 7f9658eaf6..a2f862711c 100644 --- a/worker/deps/libwebrtc/deps/abseil-cpp/abseil-cpp.gyp +++ b/worker/deps/libwebrtc/deps/abseil-cpp/abseil-cpp.gyp @@ -49,6 +49,16 @@ '/wd4068', # unknown pragma '/wd4702' # unreachable code ], + 'defines': [ + 'NOMINMAX', # Don't define min and max macros (windows.h) + # Don't bloat namespace with incompatible winsock versions. + 'WIN32_LEAN_AND_MEAN', + # Don't warn about usage of insecure C functions. + '_CRT_SECURE_NO_WARNINGS', + '_SCL_SECURE_NO_WARNINGS', + # Introduced in VS 2017 15.8, allow overaligned types in aligned_storage. + '_ENABLE_EXTENDED_ALIGNED_STORAGE' + ] }] ], }, diff --git a/worker/include/Channel/UnixStreamSocket.hpp b/worker/include/Channel/UnixStreamSocket.hpp index 9806164da6..1864faefb6 100644 --- a/worker/include/Channel/UnixStreamSocket.hpp +++ b/worker/include/Channel/UnixStreamSocket.hpp @@ -8,7 +8,45 @@ namespace Channel { - class UnixStreamSocket : public ::UnixStreamSocket + class ConsumerSocket : public ::UnixStreamSocket + { + public: + class Listener + { + public: + virtual void OnConsumerSocketMessage(ConsumerSocket* consumerSocket, json& jsonMessage) = 0; + virtual void OnConsumerSocketClosed(ConsumerSocket* consumerSocket) = 0; + }; + + public: + ConsumerSocket(int fd, size_t bufferSize, Listener* listener); + /* Pure virtual methods inherited from ::UnixStreamSocket. */ + public: + void UserOnUnixStreamRead() override; + void UserOnUnixStreamSocketClosed() override; + + private: + // Passed by argument. + Listener* listener{ nullptr }; + // Others. + size_t msgStart{ 0 }; // Where the latest message starts. + }; + + class ProducerSocket : public ::UnixStreamSocket + { + public: + ProducerSocket(int fd, size_t bufferSize); + /* Pure virtual methods inherited from ::UnixStreamSocket. */ + public: + void UserOnUnixStreamRead() override + { + } + void UserOnUnixStreamSocketClosed() override + { + } + }; + + class UnixStreamSocket : public ConsumerSocket::Listener { public: class Listener @@ -19,7 +57,8 @@ namespace Channel }; public: - explicit UnixStreamSocket(int fd); + explicit UnixStreamSocket(int consumerFd, int producerFd); + virtual ~UnixStreamSocket(); public: void SetListener(Listener* listener); @@ -27,16 +66,17 @@ namespace Channel void SendLog(char* nsPayload, size_t nsPayloadLen); void SendBinary(const uint8_t* nsPayload, size_t nsPayloadLen); - /* Pure virtual methods inherited from ::UnixStreamSocket. */ + /* Pure virtual methods inherited from ConsumerSocket::Listener. */ public: - void UserOnUnixStreamRead() override; - void UserOnUnixStreamSocketClosed() override; + void OnConsumerSocketMessage(ConsumerSocket* consumerSocket, json& jsonMessage) override; + void OnConsumerSocketClosed(ConsumerSocket* consumerSocket) override; private: // Passed by argument. Listener* listener{ nullptr }; // Others. - size_t msgStart{ 0 }; // Where the latest message starts. + ConsumerSocket consumerSocket; + ProducerSocket producerSocket; }; } // namespace Channel diff --git a/worker/include/RTC/RTCP/FeedbackPsFir.hpp b/worker/include/RTC/RTCP/FeedbackPsFir.hpp index e32a0228da..95096de9c2 100644 --- a/worker/include/RTC/RTCP/FeedbackPsFir.hpp +++ b/worker/include/RTC/RTCP/FeedbackPsFir.hpp @@ -27,7 +27,11 @@ namespace RTC { uint32_t ssrc; uint8_t sequenceNumber; +#ifdef _WIN32 + uint8_t reserved[3]; // Alignment. +#else uint32_t reserved : 24; +#endif }; public: diff --git a/worker/include/Utils.hpp b/worker/include/Utils.hpp index 559b46ccb5..3930ca710c 100644 --- a/worker/include/Utils.hpp +++ b/worker/include/Utils.hpp @@ -6,6 +6,12 @@ #include #include // std::memcmp(), std::memcpy() #include +#ifdef _WIN32 +#include +// https://stackoverflow.com/a/24550632/2085408 +#include +#define __builtin_popcount __popcnt +#endif namespace Utils { diff --git a/worker/include/common.hpp b/worker/include/common.hpp index 1c9e5d3d50..c4e0ecc225 100644 --- a/worker/include/common.hpp +++ b/worker/include/common.hpp @@ -1,14 +1,29 @@ #ifndef MS_COMMON_HPP #define MS_COMMON_HPP -#include // std::transform(), std::find(), std::min(), std::max() +#include // std::transform(), std::find(), std::min(), std::max() +#include // PRIu64, etc +#include // size_t +#include // uint8_t, etc +#include // std::function +#include // std::addressof() +#ifdef _WIN32 +#include +// https://stackoverflow.com/a/27443191/2085408 +#undef max +#undef min +// avoid uv/win.h: error C2628 'intptr_t' followed by 'int' is illegal. +#if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED) +#include +typedef SSIZE_T ssize_t; +#define SSIZE_MAX INTPTR_MAX +#define _SSIZE_T_ +#define _SSIZE_T_DEFINED +#endif +#else #include // htonl(), htons(), ntohl(), ntohs() -#include // PRIu64, etc -#include // size_t -#include // uint8_t, etc -#include // std::function -#include // std::addressof() #include // sockaddr_in, sockaddr_in6 #include // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6 +#endif #endif diff --git a/worker/include/handles/UnixStreamSocket.hpp b/worker/include/handles/UnixStreamSocket.hpp index 14c5caf056..767461f0ec 100644 --- a/worker/include/handles/UnixStreamSocket.hpp +++ b/worker/include/handles/UnixStreamSocket.hpp @@ -15,8 +15,14 @@ class UnixStreamSocket uint8_t store[1]; }; + enum class Role + { + PRODUCER = 1, + CONSUMER + }; + public: - UnixStreamSocket(int fd, size_t bufferSize); + UnixStreamSocket(int fd, size_t bufferSize, UnixStreamSocket::Role role); UnixStreamSocket& operator=(const UnixStreamSocket&) = delete; UnixStreamSocket(const UnixStreamSocket&) = delete; virtual ~UnixStreamSocket(); @@ -49,6 +55,7 @@ class UnixStreamSocket protected: // Passed by argument. size_t bufferSize{ 0 }; + UnixStreamSocket::Role role; // Allocated by this. uint8_t* buffer{ nullptr }; // Others. diff --git a/worker/mediasoup-worker.gyp b/worker/mediasoup-worker.gyp index 7f6ff0679b..4c6b13eaf9 100644 --- a/worker/mediasoup-worker.gyp +++ b/worker/mediasoup-worker.gyp @@ -272,6 +272,23 @@ 'ldflags': [ '-Wl,--export-dynamic' ] }], + [ 'OS == "win"', { + 'dependencies': [ 'deps/getopt/getopt.gyp:getopt' ], + + # Handle multi files with same name. + # https://stackoverflow.com/a/22936230/2085408 + # https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.vcprojectengine.vcclcompilertool.objectfile?view=visualstudiosdk-2017#Microsoft_VisualStudio_VCProjectEngine_VCCLCompilerTool_ObjectFile + 'msvs_settings': { + 'VCCLCompilerTool': { 'ObjectFile': ['$(IntDir)\%(RelativeDir)\%(Filename).obj'], }, + }, + + # Output Directory setting for msvc. + # https://github.com/nodejs/node-gyp/issues/1242#issuecomment-310921441 + 'msvs_configuration_attributes': { + 'OutputDirectory': '$(SolutionDir)\\out\\$(Configuration)\\' + } + }], + [ 'OS != "win"', { 'cflags': [ '-std=c++11', '-Wall', '-Wextra', '-Wno-unused-parameter', '-Wno-implicit-fallthrough' ] }], @@ -426,6 +443,7 @@ [ 'fuzzer/include' ], + 'conditions': [ [ 'OS == "linux"', { diff --git a/worker/scripts/get-dep.sh b/worker/scripts/get-dep.sh index 2851c195e5..8c133743a0 100755 --- a/worker/scripts/get-dep.sh +++ b/worker/scripts/get-dep.sh @@ -171,10 +171,19 @@ function get_fuzzer_corpora() get_dep "${GIT_REPO}" "${GIT_TAG}" "${DEST}" } +function get_win_getopt() +{ + GIT_REPO="git@github.com:alex85k/wingetopt.git" + GIT_TAG="master" + DEST="deps/getopt/getopt" + + get_dep "${GIT_REPO}" "${GIT_TAG}" "${DEST}" +} + case "${DEP}" in '-h') echo "Usage:" - echo " ./scripts/$(basename $0) [gyp|json|netstring|libuv|openssl|libsrtp|usrsctp|abseil-cpp|catch|lcov|clang-fuzzer|fuzzer-corpora]" + echo " ./scripts/$(basename $0) [gyp|json|netstring|libuv|openssl|libsrtp|usrsctp|abseil-cpp|catch|lcov|clang-fuzzer|fuzzer-corpora|win-getopt]" echo ;; gyp) @@ -213,6 +222,9 @@ case "${DEP}" in fuzzer-corpora) get_fuzzer_corpora ;; + win-getopt) + get_win_getopt + ;; *) echo ">>> [ERROR] unknown dep '${DEP}'" >&2 exit 1 diff --git a/worker/src/Channel/UnixStreamSocket.cpp b/worker/src/Channel/UnixStreamSocket.cpp index 21790142e3..5e43dd9847 100644 --- a/worker/src/Channel/UnixStreamSocket.cpp +++ b/worker/src/Channel/UnixStreamSocket.cpp @@ -21,13 +21,17 @@ namespace Channel static uint8_t WriteBuffer[NsMessageMaxLen]; /* Instance methods. */ - - UnixStreamSocket::UnixStreamSocket(int fd) - : ::UnixStreamSocket::UnixStreamSocket(fd, NsMessageMaxLen) + UnixStreamSocket::UnixStreamSocket(int consumerFd, int producerFd) + : consumerSocket(consumerFd, NsMessageMaxLen, this), producerSocket(producerFd, NsMessageMaxLen) { MS_TRACE_STD(); } + UnixStreamSocket ::~UnixStreamSocket() + { + MS_TRACE(); + } + void UnixStreamSocket::SetListener(Listener* listener) { MS_TRACE_STD(); @@ -37,7 +41,7 @@ namespace Channel void UnixStreamSocket::Send(json& jsonMessage) { - if (IsClosed()) + if (this->producerSocket.IsClosed()) return; std::string nsPayload = jsonMessage.dump(); @@ -69,12 +73,12 @@ namespace Channel nsLen = nsNumLen + nsPayloadLen + 2; - ::UnixStreamSocket::Write(WriteBuffer, nsLen); + this->producerSocket.Write(WriteBuffer, nsLen); } void UnixStreamSocket::SendLog(char* nsPayload, size_t nsPayloadLen) { - if (IsClosed()) + if (this->producerSocket.IsClosed()) return; // MS_TRACE_STD(); @@ -106,12 +110,12 @@ namespace Channel nsLen = nsNumLen + nsPayloadLen + 2; - ::UnixStreamSocket::Write(WriteBuffer, nsLen); + this->producerSocket.Write(WriteBuffer, nsLen); } void UnixStreamSocket::SendBinary(const uint8_t* nsPayload, size_t nsPayloadLen) { - if (IsClosed()) + if (this->producerSocket.IsClosed()) return; size_t nsNumLen; @@ -141,10 +145,50 @@ namespace Channel nsLen = nsNumLen + nsPayloadLen + 2; - ::UnixStreamSocket::Write(WriteBuffer, nsLen); + this->producerSocket.Write(WriteBuffer, nsLen); + } + + void UnixStreamSocket::OnConsumerSocketMessage(ConsumerSocket* consumerSocket, json& jsonMessage) + { + try + { + auto* request = new Channel::Request(this, jsonMessage); + + // Notify the listener. + try + { + this->listener->OnChannelRequest(this, request); + } + catch (const MediaSoupTypeError& error) + { + request->TypeError(error.what()); + } + catch (const MediaSoupError& error) + { + request->Error(error.what()); + } + + // Delete the Request. + delete request; + } + catch (const MediaSoupError& error) + { + MS_ERROR_STD("discarding wrong Channel request"); + } + } + + void UnixStreamSocket::OnConsumerSocketClosed(ConsumerSocket* consumerSocket) + { + this->listener->OnChannelClosed(this); + } + + ConsumerSocket::ConsumerSocket(int fd, size_t bufferSize, Listener* listener) + : ::UnixStreamSocket(fd, bufferSize, ::UnixStreamSocket::Role::CONSUMER), listener(listener) + { + MS_TRACE_STD(); } - void UnixStreamSocket::UserOnUnixStreamRead() + void ConsumerSocket::UserOnUnixStreamRead() { MS_TRACE_STD(); @@ -244,38 +288,10 @@ namespace Channel try { - json jsonRequest = json::parse(jsonStart, jsonStart + jsonLen); - - Channel::Request* request{ nullptr }; - - try - { - request = new Channel::Request(this, jsonRequest); - } - catch (const MediaSoupError& error) - { - MS_ERROR_STD("discarding wrong Channel request"); - } - - if (request != nullptr) - { - // Notify the listener. - try - { - this->listener->OnChannelRequest(this, request); - } - catch (const MediaSoupTypeError& error) - { - request->TypeError(error.what()); - } - catch (const MediaSoupError& error) - { - request->Error(error.what()); - } + json jsonMessage = json::parse(jsonStart, jsonStart + jsonLen); - // Delete the Request. - delete request; - } + // Notify the listener. + this->listener->OnConsumerSocketMessage(this, jsonMessage); } catch (const json::parse_error& error) { @@ -307,11 +323,17 @@ namespace Channel } } - void UnixStreamSocket::UserOnUnixStreamSocketClosed() + void ConsumerSocket::UserOnUnixStreamSocketClosed() { MS_TRACE_STD(); // Notify the listener. - this->listener->OnChannelClosed(this); + this->listener->OnConsumerSocketClosed(this); + } + + ProducerSocket::ProducerSocket(int fd, size_t bufferSize) + : ::UnixStreamSocket(fd, bufferSize, ::UnixStreamSocket::Role::PRODUCER) + { + MS_TRACE_STD(); } } // namespace Channel diff --git a/worker/src/Logger.cpp b/worker/src/Logger.cpp index 0e98af26d4..ded5f69b97 100644 --- a/worker/src/Logger.cpp +++ b/worker/src/Logger.cpp @@ -2,7 +2,9 @@ // #define MS_LOG_DEV #include "Logger.hpp" +#ifndef _WIN32 #include // getpid() +#endif /* Class variables. */ diff --git a/worker/src/RTC/DtlsTransport.cpp b/worker/src/RTC/DtlsTransport.cpp index 6f1b59dc1d..cfd03ead29 100644 --- a/worker/src/RTC/DtlsTransport.cpp +++ b/worker/src/RTC/DtlsTransport.cpp @@ -1337,13 +1337,13 @@ namespace RTC } } - uint8_t srtpMaterial[srtpMasterLength * 2]; + uint8_t* srtpMaterial = new uint8_t[srtpMasterLength * 2]; uint8_t* srtpLocalKey; uint8_t* srtpLocalSalt; uint8_t* srtpRemoteKey; uint8_t* srtpRemoteSalt; - uint8_t srtpLocalMasterKey[srtpMasterLength]; - uint8_t srtpRemoteMasterKey[srtpMasterLength]; + uint8_t* srtpLocalMasterKey = new uint8_t[srtpMasterLength]; + uint8_t* srtpRemoteMasterKey = new uint8_t[srtpMasterLength]; int ret; ret = SSL_export_keying_material( @@ -1396,6 +1396,10 @@ namespace RTC srtpRemoteMasterKey, srtpMasterLength, this->remoteCert); + + delete[] srtpMaterial; + delete[] srtpLocalMasterKey; + delete[] srtpRemoteMasterKey; } inline RTC::SrtpSession::Profile DtlsTransport::GetNegotiatedSrtpProfile() diff --git a/worker/src/Utils/File.cpp b/worker/src/Utils/File.cpp index c41195702f..a19da52df5 100644 --- a/worker/src/Utils/File.cpp +++ b/worker/src/Utils/File.cpp @@ -6,7 +6,13 @@ #include "Utils.hpp" #include #include // stat() -#include // access(), R_OK +#ifdef _WIN32 +#include +#define __S_ISTYPE(mode, mask) (((mode)&_S_IFMT) == (mask)) +#define S_ISREG(mode) __S_ISTYPE((mode), _S_IFREG) +#else +#include // access(), R_OK +#endif namespace Utils { diff --git a/worker/src/handles/UnixStreamSocket.cpp b/worker/src/handles/UnixStreamSocket.cpp index a60b614d3e..feab80478a 100644 --- a/worker/src/handles/UnixStreamSocket.cpp +++ b/worker/src/handles/UnixStreamSocket.cpp @@ -69,7 +69,8 @@ inline static void onShutdown(uv_shutdown_t* req, int /*status*/) /* Instance methods. */ -UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) : bufferSize(bufferSize) +UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize, UnixStreamSocket::Role role) + : bufferSize(bufferSize), role(role) { MS_TRACE_STD(); @@ -97,17 +98,20 @@ UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) : bufferSize(buffe MS_THROW_ERROR_STD("uv_pipe_open() failed: %s", uv_strerror(err)); } - // Start reading. - err = uv_read_start( - reinterpret_cast(this->uvHandle), - static_cast(onAlloc), - static_cast(onRead)); - - if (err != 0) + if (this->role == UnixStreamSocket::Role::CONSUMER) { - uv_close(reinterpret_cast(this->uvHandle), static_cast(onClose)); + // Start reading. + err = uv_read_start( + reinterpret_cast(this->uvHandle), + static_cast(onAlloc), + static_cast(onRead)); + + if (err != 0) + { + uv_close(reinterpret_cast(this->uvHandle), static_cast(onClose)); - MS_THROW_ERROR_STD("uv_read_start() failed: %s", uv_strerror(err)); + MS_THROW_ERROR_STD("uv_read_start() failed: %s", uv_strerror(err)); + } } // NOTE: Don't allocate the buffer here. Instead wait for the first uv_alloc_cb(). @@ -137,11 +141,14 @@ void UnixStreamSocket::Close() // Tell the UV handle that the UnixStreamSocket has been closed. this->uvHandle->data = nullptr; - // Don't read more. - err = uv_read_stop(reinterpret_cast(this->uvHandle)); + if (this->role == UnixStreamSocket::Role::CONSUMER) + { + // Don't read more. + err = uv_read_stop(reinterpret_cast(this->uvHandle)); - if (err != 0) - MS_ABORT("uv_read_stop() failed: %s", uv_strerror(err)); + if (err != 0) + MS_ABORT("uv_read_stop() failed: %s", uv_strerror(err)); + } // If there is no error and the peer didn't close its pipe side then close gracefully. if (!this->hasError && !this->isClosedByPeer) diff --git a/worker/src/main.cpp b/worker/src/main.cpp index 91947156ba..21bfef1c72 100644 --- a/worker/src/main.cpp +++ b/worker/src/main.cpp @@ -21,9 +21,14 @@ #include // std::cerr, std::endl #include #include -#include // usleep() +#ifdef _WIN32 +#define usleep Sleep +#else +#include // getpid(), usleep() +#endif -static constexpr int ChannelFd{ 3 }; +static constexpr int ConsumerChannelFd{ 3 }; +static constexpr int ProducerChannelFd{ 4 }; void IgnoreSignals(); @@ -47,7 +52,7 @@ int main(int argc, char* argv[]) try { - channel = new Channel::UnixStreamSocket(ChannelFd); + channel = new Channel::UnixStreamSocket(ConsumerChannelFd, ProducerChannelFd); } catch (const MediaSoupError& error) { @@ -137,6 +142,7 @@ int main(int argc, char* argv[]) void IgnoreSignals() { +#ifndef _WIN32 MS_TRACE(); int err; @@ -170,4 +176,5 @@ void IgnoreSignals() if (err != 0) MS_THROW_ERROR("sigaction() failed for signal %s: %s", sigName.c_str(), std::strerror(errno)); } +#endif } diff --git a/worker/test/include/helpers.hpp b/worker/test/include/helpers.hpp index 36146635f2..69160ca080 100644 --- a/worker/test/include/helpers.hpp +++ b/worker/test/include/helpers.hpp @@ -10,6 +10,9 @@ namespace helpers inline bool readBinaryFile(const char* file, uint8_t* buffer, size_t* len) { std::string filePath = "test/" + std::string(file); +#ifdef _WIN32 + std::replace(filePath.begin(), filePath.end(), '/', '\\'); +#endif std::ifstream in(filePath, std::ios::ate | std::ios::binary); if (!in) diff --git a/worker/test/src/Utils/TestIP.cpp b/worker/test/src/Utils/TestIP.cpp index f5801d7460..6c3e58b745 100644 --- a/worker/test/src/Utils/TestIP.cpp +++ b/worker/test/src/Utils/TestIP.cpp @@ -2,11 +2,14 @@ #include "MediaSoupErrors.hpp" #include "Utils.hpp" #include "catch.hpp" +#include // std::memset() +#ifdef _WIN32 +#include +#else #include // htonl(), htons(), ntohl(), ntohs() -#include // std::memset() #include // sockaddr_in, sockaddr_in6 #include // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6 - +#endif using namespace Utils; SCENARIO("Utils::IP::GetFamily()") diff --git a/worker/win-tasks.js b/worker/win-tasks.js new file mode 100644 index 0000000000..d09e02f92d --- /dev/null +++ b/worker/win-tasks.js @@ -0,0 +1,81 @@ +const exec = require('child_process').exec; +const path = require('path'); + +const PYTHON = process.env.PYTHON || 'python'; +const GULP = path.join(__dirname, '..', 'node_modules', '.bin', 'gulp'); +const MSBUILD = process.env.MSBUILD || 'MSBuild'; +const MEDIASOUP_BUILDTYPE = process.env.MEDIASOUP_BUILDTYPE || 'Release'; +const MEDIASOUP_TEST_TAGS = process.env.MEDIASOUP_TEST_TAGS || ''; + +const usage = 'usage:[-h/help/make/test/lint/format]'; + +run(); + +/* eslint-disable no-console */ +function run() +{ + if (process.argv.length < 3) + { + console.error(usage); + + return; + } + + const command = process.argv[2]; + + switch (command) + { + case '-h': + case 'help': + { + console.log(usage); + break; + } + case 'make': + { + if (!process.env.MEDIASOUP_WORKER_BIN) + { + const generScript = `${PYTHON} ./worker/scripts/configure.py --format=msvs -R mediasoup-worker`; + const buildScript = `${MSBUILD} ./worker/mediasoup-worker.sln /p:Configuration=${MEDIASOUP_BUILDTYPE}`; + + execute(`${generScript} && ${buildScript}`); + } + break; + } + case 'test': + { + if (!process.env.MEDIASOUP_WORKER_BIN) + { + const generScript = `${PYTHON} ./worker/scripts/configure.py --format=msvs -R mediasoup-worker-test`; + const buildScript = `${MSBUILD} ./worker/mediasoup-worker.sln /p:Configuration=${MEDIASOUP_BUILDTYPE}`; + const testScript = `cd worker && .\\out\\${MEDIASOUP_BUILDTYPE}\\mediasoup-worker-test.exe --invisibles --use-colour=yes ${MEDIASOUP_TEST_TAGS}`; + + execute(`${generScript} && ${buildScript} && ${testScript}`); + } + break; + } + case 'lint': + { + execute(`${GULP} lint:worker`); + break; + } + case 'format': + { + execute(`${GULP} format:worker`); + break; + } + default: + { + console.warn('unknown command'); + } + } +} +/* eslint-enable no-console */ + +function execute(command) +{ + const childProcess = exec(command); + + childProcess.stdout.pipe(process.stdout); + childProcess.stderr.pipe(process.stderr); +}