Line data Source code
1 : /*
2 : *
3 : * Copyright 2015, Google Inc.
4 : * All rights reserved.
5 : *
6 : * Redistribution and use in source and binary forms, with or without
7 : * modification, are permitted provided that the following conditions are
8 : * met:
9 : *
10 : * * Redistributions of source code must retain the above copyright
11 : * notice, this list of conditions and the following disclaimer.
12 : * * Redistributions in binary form must reproduce the above
13 : * copyright notice, this list of conditions and the following disclaimer
14 : * in the documentation and/or other materials provided with the
15 : * distribution.
16 : * * Neither the name of Google Inc. nor the names of its
17 : * contributors may be used to endorse or promote products derived from
18 : * this software without specific prior written permission.
19 : *
20 : * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 : * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 : * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 : * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 : * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 : * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 : * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 : * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 : * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 : * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 : * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 : *
32 : */
33 :
34 : /* FIXME: "posix" files shouldn't be depending on _GNU_SOURCE */
35 : #ifndef _GNU_SOURCE
36 : #define _GNU_SOURCE
37 : #endif
38 :
39 : #include <grpc/support/port_platform.h>
40 :
41 : #ifdef GPR_POSIX_SOCKET
42 :
43 : #include "src/core/iomgr/tcp_server.h"
44 :
45 : #include <errno.h>
46 : #include <fcntl.h>
47 : #include <limits.h>
48 : #include <netinet/in.h>
49 : #include <netinet/tcp.h>
50 : #include <stdio.h>
51 : #include <string.h>
52 : #include <sys/socket.h>
53 : #include <sys/stat.h>
54 : #include <sys/types.h>
55 : #include <sys/un.h>
56 : #include <unistd.h>
57 :
58 : #include "src/core/iomgr/pollset_posix.h"
59 : #include "src/core/iomgr/resolve_address.h"
60 : #include "src/core/iomgr/sockaddr_utils.h"
61 : #include "src/core/iomgr/socket_utils_posix.h"
62 : #include "src/core/iomgr/tcp_posix.h"
63 : #include "src/core/support/string.h"
64 : #include <grpc/support/alloc.h>
65 : #include <grpc/support/log.h>
66 : #include <grpc/support/string_util.h>
67 : #include <grpc/support/sync.h>
68 : #include <grpc/support/time.h>
69 :
70 : #define INIT_PORT_CAP 2
71 : #define MIN_SAFE_ACCEPT_QUEUE_SIZE 100
72 :
73 : static gpr_once s_init_max_accept_queue_size;
74 : static int s_max_accept_queue_size;
75 :
76 : /* one listening port */
77 : typedef struct {
78 : int fd;
79 : grpc_fd *emfd;
80 : grpc_tcp_server *server;
81 : union {
82 : gpr_uint8 untyped[GRPC_MAX_SOCKADDR_SIZE];
83 : struct sockaddr sockaddr;
84 : struct sockaddr_un un;
85 : } addr;
86 : size_t addr_len;
87 : grpc_closure read_closure;
88 : grpc_closure destroyed_closure;
89 : } server_port;
90 :
91 640 : static void unlink_if_unix_domain_socket(const struct sockaddr_un *un) {
92 : struct stat st;
93 :
94 640 : if (stat(un->sun_path, &st) == 0 && (st.st_mode & S_IFMT) == S_IFSOCK) {
95 321 : unlink(un->sun_path);
96 : }
97 640 : }
98 :
99 : /* the overall server */
100 : struct grpc_tcp_server {
101 : /* Called whenever accept() succeeds on a server port. */
102 : grpc_tcp_server_cb on_accept_cb;
103 : void *on_accept_cb_arg;
104 :
105 : gpr_mu mu;
106 :
107 : /* active port count: how many ports are actually still listening */
108 : size_t active_ports;
109 : /* destroyed port count: how many ports are completely destroyed */
110 : size_t destroyed_ports;
111 :
112 : /* is this server shutting down? (boolean) */
113 : int shutdown;
114 :
115 : /* all listening ports */
116 : server_port *ports;
117 : size_t nports;
118 : size_t port_capacity;
119 :
120 : /* shutdown callback */
121 : grpc_closure *shutdown_complete;
122 :
123 : /* all pollsets interested in new connections */
124 : grpc_pollset **pollsets;
125 : /* number of pollsets in the pollsets array */
126 : size_t pollset_count;
127 : };
128 :
129 1779 : grpc_tcp_server *grpc_tcp_server_create(void) {
130 1779 : grpc_tcp_server *s = gpr_malloc(sizeof(grpc_tcp_server));
131 1779 : gpr_mu_init(&s->mu);
132 1779 : s->active_ports = 0;
133 1779 : s->destroyed_ports = 0;
134 1779 : s->shutdown = 0;
135 1779 : s->on_accept_cb = NULL;
136 1779 : s->on_accept_cb_arg = NULL;
137 1779 : s->ports = gpr_malloc(sizeof(server_port) * INIT_PORT_CAP);
138 1779 : s->nports = 0;
139 1779 : s->port_capacity = INIT_PORT_CAP;
140 1779 : return s;
141 : }
142 :
143 1779 : static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) {
144 1779 : grpc_exec_ctx_enqueue(exec_ctx, s->shutdown_complete, 1);
145 :
146 1779 : gpr_mu_destroy(&s->mu);
147 :
148 1779 : gpr_free(s->ports);
149 1779 : gpr_free(s);
150 1779 : }
151 :
152 1796 : static void destroyed_port(grpc_exec_ctx *exec_ctx, void *server, int success) {
153 1796 : grpc_tcp_server *s = server;
154 1796 : gpr_mu_lock(&s->mu);
155 1796 : s->destroyed_ports++;
156 1796 : if (s->destroyed_ports == s->nports) {
157 1777 : gpr_mu_unlock(&s->mu);
158 1777 : finish_shutdown(exec_ctx, s);
159 : } else {
160 19 : GPR_ASSERT(s->destroyed_ports < s->nports);
161 19 : gpr_mu_unlock(&s->mu);
162 : }
163 1796 : }
164 :
165 : /* called when all listening endpoints have been shutdown, so no further
166 : events will be received on them - at this point it's safe to destroy
167 : things */
168 1779 : static void deactivated_all_ports(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) {
169 : size_t i;
170 :
171 : /* delete ALL the things */
172 1779 : gpr_mu_lock(&s->mu);
173 :
174 1779 : if (!s->shutdown) {
175 0 : gpr_mu_unlock(&s->mu);
176 1779 : return;
177 : }
178 :
179 1779 : if (s->nports) {
180 3573 : for (i = 0; i < s->nports; i++) {
181 1796 : server_port *sp = &s->ports[i];
182 1796 : if (sp->addr.sockaddr.sa_family == AF_UNIX) {
183 320 : unlink_if_unix_domain_socket(&sp->addr.un);
184 : }
185 1796 : sp->destroyed_closure.cb = destroyed_port;
186 1796 : sp->destroyed_closure.cb_arg = s;
187 1796 : grpc_fd_orphan(exec_ctx, sp->emfd, &sp->destroyed_closure,
188 : "tcp_listener_shutdown");
189 : }
190 1777 : gpr_mu_unlock(&s->mu);
191 : } else {
192 2 : gpr_mu_unlock(&s->mu);
193 2 : finish_shutdown(exec_ctx, s);
194 : }
195 : }
196 :
197 1779 : void grpc_tcp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s,
198 : grpc_closure *closure) {
199 : size_t i;
200 1779 : gpr_mu_lock(&s->mu);
201 :
202 1779 : GPR_ASSERT(!s->shutdown);
203 1779 : s->shutdown = 1;
204 :
205 1779 : s->shutdown_complete = closure;
206 :
207 : /* shutdown all fd's */
208 1779 : if (s->active_ports) {
209 3571 : for (i = 0; i < s->nports; i++) {
210 1795 : grpc_fd_shutdown(exec_ctx, s->ports[i].emfd);
211 : }
212 1776 : gpr_mu_unlock(&s->mu);
213 : } else {
214 3 : gpr_mu_unlock(&s->mu);
215 3 : deactivated_all_ports(exec_ctx, s);
216 : }
217 1779 : }
218 :
219 : /* get max listen queue size on linux */
220 523 : static void init_max_accept_queue_size(void) {
221 523 : int n = SOMAXCONN;
222 : char buf[64];
223 523 : FILE *fp = fopen("/proc/sys/net/core/somaxconn", "r");
224 523 : if (fp == NULL) {
225 : /* 2.4 kernel. */
226 0 : s_max_accept_queue_size = SOMAXCONN;
227 523 : return;
228 : }
229 523 : if (fgets(buf, sizeof buf, fp)) {
230 : char *end;
231 523 : long i = strtol(buf, &end, 10);
232 523 : if (i > 0 && i <= INT_MAX && end && *end == 0) {
233 0 : n = (int)i;
234 : }
235 : }
236 523 : fclose(fp);
237 523 : s_max_accept_queue_size = n;
238 :
239 523 : if (s_max_accept_queue_size < MIN_SAFE_ACCEPT_QUEUE_SIZE) {
240 0 : gpr_log(GPR_INFO,
241 : "Suspiciously small accept queue (%d) will probably lead to "
242 : "connection drops",
243 : s_max_accept_queue_size);
244 : }
245 : }
246 :
247 1796 : static int get_max_accept_queue_size(void) {
248 1796 : gpr_once_init(&s_init_max_accept_queue_size, init_max_accept_queue_size);
249 1796 : return s_max_accept_queue_size;
250 : }
251 :
252 : /* Prepare a recently-created socket for listening. */
253 1796 : static int prepare_socket(int fd, const struct sockaddr *addr,
254 : size_t addr_len) {
255 : struct sockaddr_storage sockname_temp;
256 : socklen_t sockname_len;
257 :
258 1796 : if (fd < 0) {
259 0 : goto error;
260 : }
261 :
262 3592 : if (!grpc_set_socket_nonblocking(fd, 1) || !grpc_set_socket_cloexec(fd, 1) ||
263 4748 : (addr->sa_family != AF_UNIX && (!grpc_set_socket_low_latency(fd, 1) ||
264 3272 : !grpc_set_socket_reuse_addr(fd, 1))) ||
265 1796 : !grpc_set_socket_no_sigpipe_if_possible(fd)) {
266 0 : gpr_log(GPR_ERROR, "Unable to configure socket %d: %s", fd,
267 0 : strerror(errno));
268 0 : goto error;
269 : }
270 :
271 1796 : GPR_ASSERT(addr_len < ~(socklen_t)0);
272 1796 : if (bind(fd, addr, (socklen_t)addr_len) < 0) {
273 : char *addr_str;
274 0 : grpc_sockaddr_to_string(&addr_str, addr, 0);
275 0 : gpr_log(GPR_ERROR, "bind addr=%s: %s", addr_str, strerror(errno));
276 0 : gpr_free(addr_str);
277 0 : goto error;
278 : }
279 :
280 1796 : if (listen(fd, get_max_accept_queue_size()) < 0) {
281 0 : gpr_log(GPR_ERROR, "listen: %s", strerror(errno));
282 0 : goto error;
283 : }
284 :
285 1796 : sockname_len = sizeof(sockname_temp);
286 1796 : if (getsockname(fd, (struct sockaddr *)&sockname_temp, &sockname_len) < 0) {
287 0 : goto error;
288 : }
289 :
290 1796 : return grpc_sockaddr_get_port((struct sockaddr *)&sockname_temp);
291 :
292 : error:
293 0 : if (fd >= 0) {
294 0 : close(fd);
295 : }
296 0 : return -1;
297 : }
298 :
299 : /* event manager callback when reads are ready */
300 3344 : static void on_read(grpc_exec_ctx *exec_ctx, void *arg, int success) {
301 3344 : server_port *sp = arg;
302 : grpc_fd *fdobj;
303 : size_t i;
304 :
305 3344 : if (!success) {
306 1795 : goto error;
307 : }
308 :
309 : /* loop until accept4 returns EAGAIN, and then re-arm notification */
310 : for (;;) {
311 : struct sockaddr_storage addr;
312 3105 : socklen_t addrlen = sizeof(addr);
313 : char *addr_str;
314 : char *name;
315 : /* Note: If we ever decide to return this address to the user, remember to
316 : strip off the ::ffff:0.0.0.0/96 prefix first. */
317 3105 : int fd = grpc_accept4(sp->fd, (struct sockaddr *)&addr, &addrlen, 1, 1);
318 3105 : if (fd < 0) {
319 1549 : switch (errno) {
320 : case EINTR:
321 0 : continue;
322 : case EAGAIN:
323 1549 : grpc_fd_notify_on_read(exec_ctx, sp->emfd, &sp->read_closure);
324 4893 : return;
325 : default:
326 0 : gpr_log(GPR_ERROR, "Failed accept4: %s", strerror(errno));
327 0 : goto error;
328 : }
329 : }
330 :
331 1556 : grpc_set_socket_no_sigpipe_if_possible(fd);
332 :
333 1556 : addr_str = grpc_sockaddr_to_uri((struct sockaddr *)&addr);
334 1556 : gpr_asprintf(&name, "tcp-server-connection:%s", addr_str);
335 :
336 1556 : if (grpc_tcp_trace) {
337 0 : gpr_log(GPR_DEBUG, "SERVER_CONNECT: incoming connection: %s", addr_str);
338 : }
339 :
340 1556 : fdobj = grpc_fd_create(fd, name);
341 : /* TODO(ctiller): revise this when we have server-side sharding
342 : of channels -- we certainly should not be automatically adding every
343 : incoming channel to every pollset owned by the server */
344 3239 : for (i = 0; i < sp->server->pollset_count; i++) {
345 1683 : grpc_pollset_add_fd(exec_ctx, sp->server->pollsets[i], fdobj);
346 : }
347 3112 : sp->server->on_accept_cb(
348 1556 : exec_ctx, sp->server->on_accept_cb_arg,
349 : grpc_tcp_create(fdobj, GRPC_TCP_DEFAULT_READ_SLICE_SIZE, addr_str));
350 :
351 1556 : gpr_free(name);
352 1556 : gpr_free(addr_str);
353 1556 : }
354 :
355 : GPR_UNREACHABLE_CODE(return );
356 :
357 : error:
358 1795 : gpr_mu_lock(&sp->server->mu);
359 1795 : if (0 == --sp->server->active_ports) {
360 1776 : gpr_mu_unlock(&sp->server->mu);
361 1776 : deactivated_all_ports(exec_ctx, sp->server);
362 : } else {
363 19 : gpr_mu_unlock(&sp->server->mu);
364 : }
365 : }
366 :
367 1796 : static int add_socket_to_server(grpc_tcp_server *s, int fd,
368 : const struct sockaddr *addr, size_t addr_len) {
369 : server_port *sp;
370 : int port;
371 : char *addr_str;
372 : char *name;
373 :
374 1796 : port = prepare_socket(fd, addr, addr_len);
375 1796 : if (port >= 0) {
376 1796 : grpc_sockaddr_to_string(&addr_str, (struct sockaddr *)&addr, 1);
377 1796 : gpr_asprintf(&name, "tcp-server-listener:%s", addr_str);
378 1796 : gpr_mu_lock(&s->mu);
379 1796 : GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server");
380 : /* append it to the list under a lock */
381 1796 : if (s->nports == s->port_capacity) {
382 0 : s->port_capacity *= 2;
383 0 : s->ports = gpr_realloc(s->ports, sizeof(server_port) * s->port_capacity);
384 : }
385 1796 : sp = &s->ports[s->nports++];
386 1796 : sp->server = s;
387 1796 : sp->fd = fd;
388 1796 : sp->emfd = grpc_fd_create(fd, name);
389 1796 : memcpy(sp->addr.untyped, addr, addr_len);
390 1796 : sp->addr_len = addr_len;
391 1796 : GPR_ASSERT(sp->emfd);
392 1796 : gpr_mu_unlock(&s->mu);
393 1796 : gpr_free(addr_str);
394 1796 : gpr_free(name);
395 : }
396 :
397 1796 : return port;
398 : }
399 :
400 1781 : int grpc_tcp_server_add_port(grpc_tcp_server *s, const void *addr,
401 : size_t addr_len) {
402 1781 : int allocated_port1 = -1;
403 1781 : int allocated_port2 = -1;
404 : unsigned i;
405 : int fd;
406 : grpc_dualstack_mode dsmode;
407 : struct sockaddr_in6 addr6_v4mapped;
408 : struct sockaddr_in wild4;
409 : struct sockaddr_in6 wild6;
410 : struct sockaddr_in addr4_copy;
411 1781 : struct sockaddr *allocated_addr = NULL;
412 : struct sockaddr_storage sockname_temp;
413 : socklen_t sockname_len;
414 : int port;
415 :
416 1781 : if (((struct sockaddr *)addr)->sa_family == AF_UNIX) {
417 320 : unlink_if_unix_domain_socket(addr);
418 : }
419 :
420 : /* Check if this is a wildcard port, and if so, try to keep the port the same
421 : as some previously created listener. */
422 1781 : if (grpc_sockaddr_get_port(addr) == 0) {
423 5 : for (i = 0; i < s->nports; i++) {
424 0 : sockname_len = sizeof(sockname_temp);
425 0 : if (0 == getsockname(s->ports[i].fd, (struct sockaddr *)&sockname_temp,
426 : &sockname_len)) {
427 0 : port = grpc_sockaddr_get_port((struct sockaddr *)&sockname_temp);
428 0 : if (port > 0) {
429 0 : allocated_addr = malloc(addr_len);
430 0 : memcpy(allocated_addr, addr, addr_len);
431 0 : grpc_sockaddr_set_port(allocated_addr, port);
432 0 : addr = allocated_addr;
433 0 : break;
434 : }
435 : }
436 : }
437 : }
438 :
439 1781 : if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
440 1412 : addr = (const struct sockaddr *)&addr6_v4mapped;
441 1412 : addr_len = sizeof(addr6_v4mapped);
442 : }
443 :
444 : /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */
445 1781 : if (grpc_sockaddr_is_wildcard(addr, &port)) {
446 54 : grpc_sockaddr_make_wildcards(port, &wild4, &wild6);
447 :
448 : /* Try listening on IPv6 first. */
449 54 : addr = (struct sockaddr *)&wild6;
450 54 : addr_len = sizeof(wild6);
451 54 : fd = grpc_create_dualstack_socket(addr, SOCK_STREAM, 0, &dsmode);
452 54 : allocated_port1 = add_socket_to_server(s, fd, addr, addr_len);
453 54 : if (fd >= 0 && dsmode == GRPC_DSMODE_DUALSTACK) {
454 39 : goto done;
455 : }
456 :
457 : /* If we didn't get a dualstack socket, also listen on 0.0.0.0. */
458 15 : if (port == 0 && allocated_port1 > 0) {
459 0 : grpc_sockaddr_set_port((struct sockaddr *)&wild4, allocated_port1);
460 : }
461 15 : addr = (struct sockaddr *)&wild4;
462 15 : addr_len = sizeof(wild4);
463 : }
464 :
465 1742 : fd = grpc_create_dualstack_socket(addr, SOCK_STREAM, 0, &dsmode);
466 1742 : if (fd < 0) {
467 0 : gpr_log(GPR_ERROR, "Unable to create socket: %s", strerror(errno));
468 : }
469 1765 : if (dsmode == GRPC_DSMODE_IPV4 &&
470 23 : grpc_sockaddr_is_v4mapped(addr, &addr4_copy)) {
471 8 : addr = (struct sockaddr *)&addr4_copy;
472 8 : addr_len = sizeof(addr4_copy);
473 : }
474 1742 : allocated_port2 = add_socket_to_server(s, fd, addr, addr_len);
475 :
476 : done:
477 1781 : gpr_free(allocated_addr);
478 1781 : return allocated_port1 >= 0 ? allocated_port1 : allocated_port2;
479 : }
480 :
481 2 : int grpc_tcp_server_get_fd(grpc_tcp_server *s, unsigned port_index) {
482 2 : return (port_index < s->nports) ? s->ports[port_index].fd : -1;
483 : }
484 :
485 1777 : void grpc_tcp_server_start(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s,
486 : grpc_pollset **pollsets, size_t pollset_count,
487 : grpc_tcp_server_cb on_accept_cb,
488 : void *on_accept_cb_arg) {
489 : size_t i, j;
490 1777 : GPR_ASSERT(on_accept_cb);
491 1777 : gpr_mu_lock(&s->mu);
492 1777 : GPR_ASSERT(!s->on_accept_cb);
493 1777 : GPR_ASSERT(s->active_ports == 0);
494 1777 : s->on_accept_cb = on_accept_cb;
495 1777 : s->on_accept_cb_arg = on_accept_cb_arg;
496 1777 : s->pollsets = pollsets;
497 1777 : s->pollset_count = pollset_count;
498 3572 : for (i = 0; i < s->nports; i++) {
499 3633 : for (j = 0; j < pollset_count; j++) {
500 1838 : grpc_pollset_add_fd(exec_ctx, pollsets[j], s->ports[i].emfd);
501 : }
502 1795 : s->ports[i].read_closure.cb = on_read;
503 1795 : s->ports[i].read_closure.cb_arg = &s->ports[i];
504 1795 : grpc_fd_notify_on_read(exec_ctx, s->ports[i].emfd,
505 1795 : &s->ports[i].read_closure);
506 1795 : s->active_ports++;
507 : }
508 1777 : gpr_mu_unlock(&s->mu);
509 1777 : }
510 :
511 : #endif
|