Skip to content

Commit 3acd086

Browse files
authored
socket: return EPROTONOSUPPORT on invalid protocol (#16479)
Invalid socket protocol now fails with `EPROTONOSUPPORT` instead of crashing with an assertion error.
1 parent 605535b commit 3acd086

File tree

3 files changed

+43
-2
lines changed

3 files changed

+43
-2
lines changed

src/library_sockfs.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ mergeInto(LibraryManager.library, {
4848
createSocket: function(family, type, protocol) {
4949
type &= ~{{{ cDefine('SOCK_CLOEXEC') | cDefine('SOCK_NONBLOCK') }}}; // Some applications may pass it; it makes no sense for a single process.
5050
var streaming = type == {{{ cDefine('SOCK_STREAM') }}};
51-
if (protocol) {
52-
assert(streaming == (protocol == {{{ cDefine('IPPROTO_TCP') }}})); // if SOCK_STREAM, must be tcp
51+
if (streaming && protocol && protocol != {{{ cDefine('IPPROTO_TCP') }}}) {
52+
throw new FS.ErrnoError({{{ cDefine('EPROTONOSUPPORT') }}}); // if SOCK_STREAM, must be tcp or 0.
5353
}
5454

5555
// create our internal socket structure

tests/sockets/test_create_socket.c

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* Copyright 2022 The Emscripten Authors. All rights reserved.
3+
* Emscripten is available under two separate licenses, the MIT license and the
4+
* University of Illinois/NCSA Open Source License. Both these licenses can be
5+
* found in the LICENSE file.
6+
*/
7+
8+
#include <assert.h>
9+
#include <errno.h>
10+
#include <netdb.h>
11+
#include <sys/socket.h>
12+
#include <stdio.h>
13+
#include <stdlib.h>
14+
#include <unistd.h>
15+
16+
int main() {
17+
int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
18+
assert(sockfd >= 0);
19+
close(sockfd);
20+
21+
sockfd = socket(AF_INET, SOCK_STREAM, 0);
22+
assert(sockfd >= 0);
23+
close(sockfd);
24+
25+
errno = 0;
26+
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_UDP);
27+
assert(sockfd == -1);
28+
assert(errno == EPROTONOSUPPORT);
29+
30+
errno = 0;
31+
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP);
32+
assert(sockfd == -1);
33+
assert(errno == EPROTONOSUPPORT);
34+
35+
puts("success");
36+
37+
return EXIT_SUCCESS;
38+
}

tests/test_other.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8991,6 +8991,9 @@ def test_gethostbyname(self):
89918991
def test_getprotobyname(self):
89928992
self.do_runf(test_file('sockets/test_getprotobyname.c'), 'success')
89938993

8994+
def test_create_socket(self):
8995+
self.do_runf(test_file('sockets/test_create_socket.c'), 'success')
8996+
89948997
def test_socketpair(self):
89958998
self.do_run(r'''
89968999
#include <sys/socket.h>

0 commit comments

Comments
 (0)