tcp_server_posix.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. /* FIXME: "posix" files shouldn't be depending on _GNU_SOURCE */
  34. #ifndef _GNU_SOURCE
  35. #define _GNU_SOURCE
  36. #endif
  37. #include <grpc/support/port_platform.h>
  38. #ifdef GPR_POSIX_SOCKET
  39. #include "src/core/iomgr/tcp_server.h"
  40. #include <errno.h>
  41. #include <fcntl.h>
  42. #include <limits.h>
  43. #include <netinet/in.h>
  44. #include <netinet/tcp.h>
  45. #include <stdio.h>
  46. #include <string.h>
  47. #include <sys/socket.h>
  48. #include <sys/stat.h>
  49. #include <sys/types.h>
  50. #include <sys/un.h>
  51. #include <unistd.h>
  52. #include "src/core/iomgr/pollset_posix.h"
  53. #include "src/core/iomgr/resolve_address.h"
  54. #include "src/core/iomgr/sockaddr_utils.h"
  55. #include "src/core/iomgr/socket_utils_posix.h"
  56. #include "src/core/iomgr/tcp_posix.h"
  57. #include "src/core/support/string.h"
  58. #include <grpc/support/alloc.h>
  59. #include <grpc/support/log.h>
  60. #include <grpc/support/string_util.h>
  61. #include <grpc/support/sync.h>
  62. #include <grpc/support/time.h>
  63. #define INIT_PORT_CAP 2
  64. #define MIN_SAFE_ACCEPT_QUEUE_SIZE 100
  65. static gpr_once s_init_max_accept_queue_size;
  66. static int s_max_accept_queue_size;
  67. /* one listening port */
  68. typedef struct {
  69. int fd;
  70. grpc_fd *emfd;
  71. grpc_tcp_server *server;
  72. union {
  73. gpr_uint8 untyped[GRPC_MAX_SOCKADDR_SIZE];
  74. struct sockaddr sockaddr;
  75. struct sockaddr_un un;
  76. } addr;
  77. int addr_len;
  78. grpc_iomgr_closure read_closure;
  79. grpc_iomgr_closure destroyed_closure;
  80. } server_port;
  81. static void unlink_if_unix_domain_socket(const struct sockaddr_un *un) {
  82. struct stat st;
  83. if (stat(un->sun_path, &st) == 0 && (st.st_mode & S_IFMT) == S_IFSOCK) {
  84. unlink(un->sun_path);
  85. }
  86. }
  87. /* the overall server */
  88. struct grpc_tcp_server {
  89. grpc_tcp_server_cb cb;
  90. void *cb_arg;
  91. gpr_mu mu;
  92. /* active port count: how many ports are actually still listening */
  93. size_t active_ports;
  94. /* destroyed port count: how many ports are completely destroyed */
  95. size_t destroyed_ports;
  96. int shutdown;
  97. /* all listening ports */
  98. server_port *ports;
  99. size_t nports;
  100. size_t port_capacity;
  101. /* shutdown callback */
  102. void (*shutdown_complete)(void *);
  103. void *shutdown_complete_arg;
  104. grpc_pollset **pollsets;
  105. size_t pollset_count;
  106. };
  107. grpc_tcp_server *grpc_tcp_server_create(void) {
  108. grpc_tcp_server *s = gpr_malloc(sizeof(grpc_tcp_server));
  109. gpr_mu_init(&s->mu);
  110. s->active_ports = 0;
  111. s->destroyed_ports = 0;
  112. s->shutdown = 0;
  113. s->cb = NULL;
  114. s->cb_arg = NULL;
  115. s->ports = gpr_malloc(sizeof(server_port) * INIT_PORT_CAP);
  116. s->nports = 0;
  117. s->port_capacity = INIT_PORT_CAP;
  118. return s;
  119. }
  120. static void finish_shutdown(grpc_tcp_server *s) {
  121. s->shutdown_complete(s->shutdown_complete_arg);
  122. gpr_mu_destroy(&s->mu);
  123. gpr_free(s->ports);
  124. gpr_free(s);
  125. }
  126. static void destroyed_port(void *server, int success) {
  127. grpc_tcp_server *s = server;
  128. gpr_mu_lock(&s->mu);
  129. s->destroyed_ports++;
  130. if (s->destroyed_ports == s->nports) {
  131. gpr_mu_unlock(&s->mu);
  132. finish_shutdown(s);
  133. } else {
  134. gpr_mu_unlock(&s->mu);
  135. }
  136. }
  137. static void dont_care_about_shutdown_completion(void *ignored) {}
  138. static void deactivated_all_ports(grpc_tcp_server *s) {
  139. size_t i;
  140. /* delete ALL the things */
  141. gpr_mu_lock(&s->mu);
  142. if (!s->shutdown) {
  143. gpr_mu_unlock(&s->mu);
  144. return;
  145. }
  146. if (s->nports) {
  147. for (i = 0; i < s->nports; i++) {
  148. server_port *sp = &s->ports[i];
  149. if (sp->addr.sockaddr.sa_family == AF_UNIX) {
  150. unlink_if_unix_domain_socket(&sp->addr.un);
  151. }
  152. sp->destroyed_closure.cb = destroyed_port;
  153. sp->destroyed_closure.cb_arg = s;
  154. grpc_fd_orphan(sp->emfd, &sp->destroyed_closure, "tcp_listener_shutdown");
  155. }
  156. gpr_mu_unlock(&s->mu);
  157. } else {
  158. gpr_mu_unlock(&s->mu);
  159. finish_shutdown(s);
  160. }
  161. }
  162. void grpc_tcp_server_destroy(
  163. grpc_tcp_server *s, void (*shutdown_complete)(void *shutdown_complete_arg),
  164. void *shutdown_complete_arg) {
  165. size_t i;
  166. gpr_mu_lock(&s->mu);
  167. GPR_ASSERT(!s->shutdown);
  168. s->shutdown = 1;
  169. s->shutdown_complete = shutdown_complete
  170. ? shutdown_complete
  171. : dont_care_about_shutdown_completion;
  172. s->shutdown_complete_arg = shutdown_complete_arg;
  173. /* shutdown all fd's */
  174. if (s->active_ports) {
  175. for (i = 0; i < s->nports; i++) {
  176. grpc_fd_shutdown(s->ports[i].emfd);
  177. }
  178. gpr_mu_unlock(&s->mu);
  179. } else {
  180. gpr_mu_unlock(&s->mu);
  181. deactivated_all_ports(s);
  182. }
  183. }
  184. /* get max listen queue size on linux */
  185. static void init_max_accept_queue_size(void) {
  186. int n = SOMAXCONN;
  187. char buf[64];
  188. FILE *fp = fopen("/proc/sys/net/core/somaxconn", "r");
  189. if (fp == NULL) {
  190. /* 2.4 kernel. */
  191. s_max_accept_queue_size = SOMAXCONN;
  192. return;
  193. }
  194. if (fgets(buf, sizeof buf, fp)) {
  195. char *end;
  196. long i = strtol(buf, &end, 10);
  197. if (i > 0 && i <= INT_MAX && end && *end == 0) {
  198. n = i;
  199. }
  200. }
  201. fclose(fp);
  202. s_max_accept_queue_size = n;
  203. if (s_max_accept_queue_size < MIN_SAFE_ACCEPT_QUEUE_SIZE) {
  204. gpr_log(GPR_INFO,
  205. "Suspiciously small accept queue (%d) will probably lead to "
  206. "connection drops",
  207. s_max_accept_queue_size);
  208. }
  209. }
  210. static int get_max_accept_queue_size(void) {
  211. gpr_once_init(&s_init_max_accept_queue_size, init_max_accept_queue_size);
  212. return s_max_accept_queue_size;
  213. }
  214. /* Prepare a recently-created socket for listening. */
  215. static int prepare_socket(int fd, const struct sockaddr *addr, int addr_len) {
  216. struct sockaddr_storage sockname_temp;
  217. socklen_t sockname_len;
  218. if (fd < 0) {
  219. goto error;
  220. }
  221. if (!grpc_set_socket_nonblocking(fd, 1) || !grpc_set_socket_cloexec(fd, 1) ||
  222. (addr->sa_family != AF_UNIX && (!grpc_set_socket_low_latency(fd, 1) ||
  223. !grpc_set_socket_reuse_addr(fd, 1))) ||
  224. !grpc_set_socket_no_sigpipe_if_possible(fd)) {
  225. gpr_log(GPR_ERROR, "Unable to configure socket %d: %s", fd,
  226. strerror(errno));
  227. goto error;
  228. }
  229. if (bind(fd, addr, addr_len) < 0) {
  230. char *addr_str;
  231. grpc_sockaddr_to_string(&addr_str, addr, 0);
  232. gpr_log(GPR_ERROR, "bind addr=%s: %s", addr_str, strerror(errno));
  233. gpr_free(addr_str);
  234. goto error;
  235. }
  236. if (listen(fd, get_max_accept_queue_size()) < 0) {
  237. gpr_log(GPR_ERROR, "listen: %s", strerror(errno));
  238. goto error;
  239. }
  240. sockname_len = sizeof(sockname_temp);
  241. if (getsockname(fd, (struct sockaddr *)&sockname_temp, &sockname_len) < 0) {
  242. goto error;
  243. }
  244. return grpc_sockaddr_get_port((struct sockaddr *)&sockname_temp);
  245. error:
  246. if (fd >= 0) {
  247. close(fd);
  248. }
  249. return -1;
  250. }
  251. /* event manager callback when reads are ready */
  252. static void on_read(void *arg, int success) {
  253. server_port *sp = arg;
  254. grpc_fd *fdobj;
  255. size_t i;
  256. if (!success) {
  257. goto error;
  258. }
  259. /* loop until accept4 returns EAGAIN, and then re-arm notification */
  260. for (;;) {
  261. struct sockaddr_storage addr;
  262. socklen_t addrlen = sizeof(addr);
  263. char *addr_str;
  264. char *name;
  265. /* Note: If we ever decide to return this address to the user, remember to
  266. strip off the ::ffff:0.0.0.0/96 prefix first. */
  267. int fd = grpc_accept4(sp->fd, (struct sockaddr *)&addr, &addrlen, 1, 1);
  268. if (fd < 0) {
  269. switch (errno) {
  270. case EINTR:
  271. continue;
  272. case EAGAIN:
  273. grpc_fd_notify_on_read(sp->emfd, &sp->read_closure);
  274. return;
  275. default:
  276. gpr_log(GPR_ERROR, "Failed accept4: %s", strerror(errno));
  277. goto error;
  278. }
  279. }
  280. grpc_set_socket_no_sigpipe_if_possible(fd);
  281. grpc_sockaddr_to_string(&addr_str, (struct sockaddr *)&addr, 1);
  282. gpr_asprintf(&name, "tcp-server-connection:%s", addr_str);
  283. fdobj = grpc_fd_create(fd, name);
  284. /* TODO(ctiller): revise this when we have server-side sharding
  285. of channels -- we certainly should not be automatically adding every
  286. incoming channel to every pollset owned by the server */
  287. for (i = 0; i < sp->server->pollset_count; i++) {
  288. grpc_pollset_add_fd(sp->server->pollsets[i], fdobj);
  289. }
  290. sp->server->cb(
  291. sp->server->cb_arg,
  292. grpc_tcp_create(fdobj, GRPC_TCP_DEFAULT_READ_SLICE_SIZE));
  293. gpr_free(name);
  294. gpr_free(addr_str);
  295. }
  296. abort();
  297. error:
  298. gpr_mu_lock(&sp->server->mu);
  299. if (0 == --sp->server->active_ports) {
  300. gpr_mu_unlock(&sp->server->mu);
  301. deactivated_all_ports(sp->server);
  302. } else {
  303. gpr_mu_unlock(&sp->server->mu);
  304. }
  305. }
  306. static int add_socket_to_server(grpc_tcp_server *s, int fd,
  307. const struct sockaddr *addr, int addr_len) {
  308. server_port *sp;
  309. int port;
  310. char *addr_str;
  311. char *name;
  312. port = prepare_socket(fd, addr, addr_len);
  313. if (port >= 0) {
  314. grpc_sockaddr_to_string(&addr_str, (struct sockaddr *)&addr, 1);
  315. gpr_asprintf(&name, "tcp-server-listener:%s", addr_str);
  316. gpr_mu_lock(&s->mu);
  317. GPR_ASSERT(!s->cb && "must add ports before starting server");
  318. /* append it to the list under a lock */
  319. if (s->nports == s->port_capacity) {
  320. s->port_capacity *= 2;
  321. s->ports = gpr_realloc(s->ports, sizeof(server_port) * s->port_capacity);
  322. }
  323. sp = &s->ports[s->nports++];
  324. sp->server = s;
  325. sp->fd = fd;
  326. sp->emfd = grpc_fd_create(fd, name);
  327. memcpy(sp->addr.untyped, addr, addr_len);
  328. sp->addr_len = addr_len;
  329. GPR_ASSERT(sp->emfd);
  330. gpr_mu_unlock(&s->mu);
  331. gpr_free(addr_str);
  332. gpr_free(name);
  333. }
  334. return port;
  335. }
  336. int grpc_tcp_server_add_port(grpc_tcp_server *s, const void *addr,
  337. int addr_len) {
  338. int allocated_port1 = -1;
  339. int allocated_port2 = -1;
  340. unsigned i;
  341. int fd;
  342. grpc_dualstack_mode dsmode;
  343. struct sockaddr_in6 addr6_v4mapped;
  344. struct sockaddr_in wild4;
  345. struct sockaddr_in6 wild6;
  346. struct sockaddr_in addr4_copy;
  347. struct sockaddr *allocated_addr = NULL;
  348. struct sockaddr_storage sockname_temp;
  349. socklen_t sockname_len;
  350. int port;
  351. if (((struct sockaddr *)addr)->sa_family == AF_UNIX) {
  352. unlink_if_unix_domain_socket(addr);
  353. }
  354. /* Check if this is a wildcard port, and if so, try to keep the port the same
  355. as some previously created listener. */
  356. if (grpc_sockaddr_get_port(addr) == 0) {
  357. for (i = 0; i < s->nports; i++) {
  358. sockname_len = sizeof(sockname_temp);
  359. if (0 == getsockname(s->ports[i].fd, (struct sockaddr *)&sockname_temp,
  360. &sockname_len)) {
  361. port = grpc_sockaddr_get_port((struct sockaddr *)&sockname_temp);
  362. if (port > 0) {
  363. allocated_addr = malloc(addr_len);
  364. memcpy(allocated_addr, addr, addr_len);
  365. grpc_sockaddr_set_port(allocated_addr, port);
  366. addr = allocated_addr;
  367. break;
  368. }
  369. }
  370. }
  371. }
  372. if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
  373. addr = (const struct sockaddr *)&addr6_v4mapped;
  374. addr_len = sizeof(addr6_v4mapped);
  375. }
  376. /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */
  377. if (grpc_sockaddr_is_wildcard(addr, &port)) {
  378. grpc_sockaddr_make_wildcards(port, &wild4, &wild6);
  379. /* Try listening on IPv6 first. */
  380. addr = (struct sockaddr *)&wild6;
  381. addr_len = sizeof(wild6);
  382. fd = grpc_create_dualstack_socket(addr, SOCK_STREAM, 0, &dsmode);
  383. allocated_port1 = add_socket_to_server(s, fd, addr, addr_len);
  384. if (fd >= 0 && dsmode == GRPC_DSMODE_DUALSTACK) {
  385. goto done;
  386. }
  387. /* If we didn't get a dualstack socket, also listen on 0.0.0.0. */
  388. if (port == 0 && allocated_port1 > 0) {
  389. grpc_sockaddr_set_port((struct sockaddr *)&wild4, allocated_port1);
  390. }
  391. addr = (struct sockaddr *)&wild4;
  392. addr_len = sizeof(wild4);
  393. }
  394. fd = grpc_create_dualstack_socket(addr, SOCK_STREAM, 0, &dsmode);
  395. if (fd < 0) {
  396. gpr_log(GPR_ERROR, "Unable to create socket: %s", strerror(errno));
  397. }
  398. if (dsmode == GRPC_DSMODE_IPV4 &&
  399. grpc_sockaddr_is_v4mapped(addr, &addr4_copy)) {
  400. addr = (struct sockaddr *)&addr4_copy;
  401. addr_len = sizeof(addr4_copy);
  402. }
  403. allocated_port2 = add_socket_to_server(s, fd, addr, addr_len);
  404. done:
  405. gpr_free(allocated_addr);
  406. return allocated_port1 >= 0 ? allocated_port1 : allocated_port2;
  407. }
  408. int grpc_tcp_server_get_fd(grpc_tcp_server *s, unsigned index) {
  409. return (index < s->nports) ? s->ports[index].fd : -1;
  410. }
  411. void grpc_tcp_server_start(grpc_tcp_server *s, grpc_pollset **pollsets,
  412. size_t pollset_count, grpc_tcp_server_cb cb,
  413. void *cb_arg) {
  414. size_t i, j;
  415. GPR_ASSERT(cb);
  416. gpr_mu_lock(&s->mu);
  417. GPR_ASSERT(!s->cb);
  418. GPR_ASSERT(s->active_ports == 0);
  419. s->cb = cb;
  420. s->cb_arg = cb_arg;
  421. s->pollsets = pollsets;
  422. s->pollset_count = pollset_count;
  423. for (i = 0; i < s->nports; i++) {
  424. for (j = 0; j < pollset_count; j++) {
  425. grpc_pollset_add_fd(pollsets[j], s->ports[i].emfd);
  426. }
  427. s->ports[i].read_closure.cb = on_read;
  428. s->ports[i].read_closure.cb_arg = &s->ports[i];
  429. grpc_fd_notify_on_read(s->ports[i].emfd, &s->ports[i].read_closure);
  430. s->active_ports++;
  431. }
  432. gpr_mu_unlock(&s->mu);
  433. }
  434. #endif