Line data Source code
1 : /* TDSPool - Connection pooling for TDS based databases
2 : * Copyright (C) 2001 Brian Bruns
3 : *
4 : * This program is free software; you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation; either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * This program is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with this program; if not, write to the Free Software
16 : * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 : *
18 : */
19 :
20 : /*
21 : * Note on terminology: a pool member is a connection to the database,
22 : * a pool user is a client connection that is temporarily assigned to a
23 : * pool member.
24 : */
25 :
26 : #include <config.h>
27 :
28 : #include <stdarg.h>
29 : #include <stdio.h>
30 : #include <signal.h>
31 : #include <errno.h>
32 : #include <fcntl.h>
33 :
34 : #if HAVE_STDLIB_H
35 : #include <stdlib.h>
36 : #endif /* HAVE_STDLIB_H */
37 :
38 : #if HAVE_STRING_H
39 : #include <string.h>
40 : #endif /* HAVE_STRING_H */
41 :
42 : #if HAVE_UNISTD_H
43 : #include <unistd.h>
44 : #endif /* HAVE_UNISTD_H */
45 :
46 : #if HAVE_SYS_SOCKET_H
47 : #include <sys/socket.h>
48 : #endif /* HAVE_SYS_SOCKET_H */
49 :
50 : #if HAVE_NETINET_IN_H
51 : #include <netinet/in.h>
52 : #endif /* HAVE_NETINET_IN_H */
53 :
54 : #if HAVE_ARPA_INET_H
55 : #include <arpa/inet.h>
56 : #endif /* HAVE_ARPA_INET_H */
57 :
58 : #ifdef _WIN32
59 : #include <io.h>
60 : #endif
61 :
62 : #include "pool.h"
63 :
64 : /* to be set by sig term */
65 : static bool got_sigterm = false;
66 : static const char *logfile_name = NULL;
67 :
68 : static void sigterm_handler(int sig);
69 : static void pool_schedule_waiters(TDS_POOL * pool);
70 : static void pool_socket_init(TDS_POOL * pool);
71 : static void pool_main_loop(TDS_POOL * pool);
72 : static bool pool_open_logfile(void);
73 :
74 : static void
75 2 : sigterm_handler(int sig TDS_UNUSED)
76 : {
77 2 : got_sigterm = true;
78 2 : }
79 :
80 : #ifndef _WIN32
81 : static bool got_sighup = false;
82 :
83 : static void
84 0 : sighup_handler(int sig TDS_UNUSED)
85 : {
86 0 : got_sighup = true;
87 0 : }
88 : #endif
89 :
90 : static void
91 6 : check_field(const char *pool_name, bool cond, const char *field_name)
92 : {
93 6 : if (!cond) {
94 0 : fprintf(stderr, "No %s specified for pool ``%s''.\n", field_name, pool_name);
95 0 : exit(EXIT_FAILURE);
96 : }
97 6 : }
98 :
99 : /*
100 : * pool_init creates a named pool and opens connections to the database
101 : */
102 : static TDS_POOL *
103 2 : pool_init(const char *name, const tds_dir_char *config_path)
104 : {
105 : TDS_POOL *pool;
106 2 : char *err = NULL;
107 :
108 : /* initialize the pool */
109 :
110 2 : pool = tds_new0(TDS_POOL, 1);
111 2 : if (!pool) {
112 0 : fprintf(stderr, "Could not allocate memory for pool\n");
113 0 : exit(EXIT_FAILURE);
114 : }
115 2 : pool->password = strdup("");
116 :
117 2 : pool->event_fd = INVALID_SOCKET;
118 4 : if (tds_mutex_init(&pool->events_mtx)) {
119 0 : fprintf(stderr, "Error initializing pool mutex\n");
120 0 : exit(EXIT_FAILURE);
121 : }
122 :
123 : /* FIXME -- read this from the conf file */
124 2 : if (!pool_read_conf_files(config_path, name, pool, &err)) {
125 0 : fprintf(stderr, "Configuration for pool ``%s'' not found.\n", name);
126 0 : exit(EXIT_FAILURE);
127 : }
128 :
129 2 : if (err) {
130 0 : fprintf(stderr, "%s\n", err);
131 0 : exit(EXIT_FAILURE);
132 : }
133 2 : check_field(name, pool->user != NULL, "user");
134 2 : check_field(name, pool->server != NULL, "server");
135 2 : check_field(name, pool->port != 0, "port");
136 :
137 2 : if (!pool->server_user)
138 2 : pool->server_user = strdup(pool->user);
139 2 : if (!pool->server_password)
140 2 : pool->server_password = strdup(pool->password);
141 :
142 2 : if (pool->max_open_conn < pool->min_open_conn) {
143 0 : fprintf(stderr, "Max connections less than minimum\n");
144 0 : exit(EXIT_FAILURE);
145 : }
146 :
147 2 : pool->name = strdup(name);
148 :
149 2 : pool_open_logfile();
150 :
151 2 : pool_mbr_init(pool);
152 2 : pool_user_init(pool);
153 :
154 2 : pool_socket_init(pool);
155 :
156 2 : return pool;
157 : }
158 :
159 : static void
160 2 : pool_destroy(TDS_POOL *pool)
161 : {
162 2 : pool_mbr_destroy(pool);
163 2 : pool_user_destroy(pool);
164 :
165 2 : CLOSESOCKET(pool->wakeup_fd);
166 2 : CLOSESOCKET(pool->listen_fd);
167 2 : CLOSESOCKET(pool->event_fd);
168 2 : tds_mutex_free(&pool->events_mtx);
169 :
170 2 : free(pool->user);
171 2 : free(pool->password);
172 2 : free(pool->server);
173 2 : free(pool->database);
174 2 : free(pool->name);
175 2 : free(pool->server_user);
176 2 : free(pool->server_password);
177 2 : free(pool);
178 2 : }
179 :
180 : static void
181 0 : pool_schedule_waiters(TDS_POOL * pool)
182 : {
183 : TDS_POOL_USER *puser;
184 :
185 : /* first see if there are free members to do the request */
186 0 : if (!dlist_member_first(&pool->idle_members))
187 : return;
188 :
189 0 : while ((puser = dlist_user_first(&pool->waiters)) != NULL) {
190 0 : if (puser->user_state == TDS_SRV_WAIT) {
191 : /* place back in query state */
192 0 : puser->user_state = TDS_SRV_QUERY;
193 0 : dlist_user_remove(&pool->waiters, puser);
194 0 : dlist_user_append(&pool->users, puser);
195 : /* now try again */
196 0 : pool_user_query(pool, puser);
197 0 : return;
198 : }
199 : }
200 : }
201 :
202 : typedef struct select_info
203 : {
204 : struct pollfd *fds;
205 : uint32_t num_fds, alloc_fds;
206 : } SELECT_INFO;
207 :
208 : static void
209 155484 : pool_select_add_socket(SELECT_INFO *sel, TDS_POOL_SOCKET *sock)
210 : {
211 : short events;
212 : struct pollfd *fd;
213 :
214 : /* skip dead connections */
215 155484 : if (IS_TDSDEAD(sock->tds))
216 : return;
217 155462 : if (!sock->poll_recv && !sock->poll_send)
218 : return;
219 :
220 153134 : events = 0;
221 153134 : if (sock->poll_recv)
222 153134 : events |= POLLIN;
223 153134 : if (sock->poll_send)
224 2 : events |= POLLOUT;
225 153134 : if (sel->num_fds >= sel->alloc_fds) {
226 4 : sel->alloc_fds *= 2;
227 4 : if (!TDS_RESIZE(sel->fds, sel->alloc_fds)) {
228 0 : fprintf(stderr, "Out of memory allocating fds\n");
229 0 : exit(EXIT_FAILURE);
230 : }
231 : }
232 153134 : sock->poll_index = sel->num_fds;
233 153134 : fd = &sel->fds[sel->num_fds++];
234 153134 : fd->fd = tds_get_s(sock->tds);
235 153134 : fd->events = events;
236 153134 : fd->revents = 0;
237 : }
238 :
239 : static void
240 1566 : pool_process_events(TDS_POOL *pool)
241 : {
242 : TDS_POOL_EVENT *events, *next;
243 :
244 : /* detach events from pool */
245 1566 : tds_mutex_lock(&pool->events_mtx);
246 1566 : events = pool->events;
247 1566 : pool->events = NULL;
248 1566 : tds_mutex_unlock(&pool->events_mtx);
249 :
250 : /* process them */
251 4698 : while (events) {
252 1566 : next = events->next;
253 1566 : events->next = NULL;
254 :
255 1566 : events->execute(events);
256 1566 : free(events);
257 1566 : events = next;
258 : }
259 1566 : }
260 :
261 : static bool
262 2 : pool_open_logfile(void)
263 : {
264 : int fd;
265 :
266 2 : tds_append_mode = 0;
267 2 : tdsdump_topen(tds_dir_getenv(TDS_DIR("TDSDUMP")));
268 :
269 2 : if (!logfile_name)
270 : return true;
271 0 : fd = open(logfile_name, O_WRONLY|O_CREAT|O_APPEND, 0644);
272 0 : if (fd < 0)
273 : return false;
274 :
275 0 : fflush(stdout);
276 0 : fflush(stderr);
277 0 : while (dup2(fd, fileno(stdout)) < 0 && errno == EINTR)
278 0 : continue;
279 0 : while (dup2(fd, fileno(stderr)) < 0 && errno == EINTR)
280 0 : continue;
281 0 : close(fd);
282 0 : fflush(stdout);
283 0 : fflush(stderr);
284 :
285 0 : return true;
286 : }
287 :
288 : /* listening socket received from inetd/xinetd or systemd, if any */
289 : static TDS_SYS_SOCKET inherited_listen_fd = INVALID_SOCKET;
290 :
291 : static void
292 2 : pool_socket_init(TDS_POOL * pool)
293 : {
294 : struct sockaddr_in sin;
295 : TDS_SYS_SOCKET s, event_pair[2];
296 2 : int socktrue = 1;
297 :
298 : /* FIXME -- read the interfaces file and bind accordingly */
299 2 : sin.sin_addr.s_addr = INADDR_ANY;
300 2 : sin.sin_port = htons(pool->port);
301 2 : sin.sin_family = AF_INET;
302 :
303 2 : if (!TDS_IS_SOCKET_INVALID(inherited_listen_fd)) {
304 0 : s = inherited_listen_fd;
305 0 : inherited_listen_fd = INVALID_SOCKET;
306 0 : tds_socket_set_nonblocking(s);
307 : } else {
308 2 : if (TDS_IS_SOCKET_INVALID(s = socket(AF_INET, SOCK_STREAM, 0))) {
309 0 : perror("socket");
310 0 : exit(1);
311 : }
312 2 : tds_socket_set_nonblocking(s);
313 : /* don't keep addr in use from s.craig@andronics.com */
314 2 : setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const void *) &socktrue, sizeof(socktrue));
315 :
316 2 : fprintf(stderr, "Listening on port %d\n", pool->port);
317 2 : if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
318 0 : perror("bind");
319 0 : exit(1);
320 : }
321 2 : listen(s, 5);
322 : }
323 2 : pool->listen_fd = s;
324 :
325 2 : if (socketpair(AF_UNIX, SOCK_STREAM, 0, event_pair) < 0) {
326 0 : perror("socketpair");
327 0 : exit(1);
328 : }
329 2 : tds_socket_set_nonblocking(event_pair[0]);
330 2 : tds_socket_set_nonblocking(event_pair[1]);
331 2 : pool->event_fd = event_pair[1];
332 2 : pool->wakeup_fd = event_pair[0];
333 2 : }
334 :
335 : /*
336 : * pool_main_loop
337 : * Accept new connections from clients, and handle all input from clients and
338 : * pool members.
339 : */
340 : static void
341 2 : pool_main_loop(TDS_POOL * pool)
342 : {
343 : TDS_POOL_MEMBER *pmbr;
344 : TDS_POOL_USER *puser;
345 : TDS_SYS_SOCKET s, wakeup;
346 2 : SELECT_INFO sel = { NULL, 0, 8 };
347 2 : int min_expire_left = -1;
348 : int rc;
349 :
350 2 : s = pool->listen_fd;
351 2 : wakeup = pool->wakeup_fd;
352 :
353 : /* add the listening socket to the read list */
354 2 : if (!TDS_RESIZE(sel.fds, sel.alloc_fds)) {
355 0 : fprintf(stderr, "Out of memory allocating fds\n");
356 0 : exit(EXIT_FAILURE);
357 : }
358 2 : sel.fds[0].fd = s;
359 2 : sel.fds[0].events = POLLIN;
360 2 : sel.fds[1].fd = wakeup;
361 2 : sel.fds[1].events = POLLIN;
362 :
363 39995 : while (!got_sigterm) {
364 :
365 39991 : sel.num_fds = 2;
366 39991 : sel.fds[0].revents = 0;
367 39991 : sel.fds[1].revents = 0;
368 :
369 : /* add the user sockets to the read list */
370 157012 : DLIST_FOREACH(dlist_user, &pool->users, puser)
371 78134 : pool_select_add_socket(&sel, &puser->sock);
372 :
373 : /* add the pool member sockets to the read list */
374 156186 : DLIST_FOREACH(dlist_member, &pool->active_members, pmbr)
375 77350 : pool_select_add_socket(&sel, &pmbr->sock);
376 :
377 39991 : if (min_expire_left > 0)
378 24907 : min_expire_left *= 1000;
379 :
380 39991 : rc = poll(sel.fds, sel.num_fds, min_expire_left);
381 39991 : if (TDS_UNLIKELY(rc < 0)) {
382 : char *errstr;
383 :
384 2 : if (sock_errno == TDSSOCK_EINTR)
385 2 : continue;
386 0 : errstr = sock_strerror(sock_errno);
387 0 : fprintf(stderr, "Error: poll returned %d, %s\n", sock_errno, errstr);
388 : sock_strerror_free(errstr);
389 0 : exit(EXIT_FAILURE);
390 : }
391 39989 : if (TDS_UNLIKELY(got_sigterm))
392 : break;
393 :
394 : #ifndef _WIN32
395 39989 : if (TDS_UNLIKELY(got_sighup)) {
396 0 : got_sighup = false;
397 0 : pool_open_logfile();
398 : }
399 : #endif
400 :
401 : /* process events */
402 39989 : if ((sel.fds[1].revents & POLLIN) != 0) {
403 : char buf[32];
404 1566 : READSOCKET(wakeup, buf, sizeof(buf));
405 :
406 1566 : pool_process_events(pool);
407 : }
408 :
409 : /* process the sockets */
410 39989 : if ((sel.fds[0].revents & POLLIN) != 0) {
411 784 : pool_user_create(pool, s);
412 : }
413 39989 : pool_process_users(pool, sel.fds, sel.num_fds);
414 39989 : min_expire_left = pool_process_members(pool, sel.fds, sel.num_fds);
415 :
416 : /* back from members */
417 39989 : if (dlist_user_first(&pool->waiters))
418 0 : pool_schedule_waiters(pool);
419 : } /* while !got_sigterm */
420 2 : tdsdump_log(TDS_DBG_INFO2, "Shutdown Requested\n");
421 2 : }
422 :
423 : static void
424 : print_usage(const char *progname)
425 : {
426 0 : fprintf(stderr, "Usage:\t%s [-l <log file>] [-c <conf file>] [-d] [-x] <pool name>\n", progname);
427 : }
428 :
429 : #ifndef _WIN32
430 : /**
431 : * Check that a file descriptor is a listening socket.
432 : * \param fd file descriptor to check
433 : * \return true if fd is a listening socket or if it cannot be checked
434 : */
435 : static bool
436 0 : pool_is_listen_socket(int fd)
437 : {
438 : #ifdef SO_ACCEPTCONN
439 0 : int accept_conn = 0;
440 0 : SOCKLEN_T len = sizeof(accept_conn);
441 :
442 0 : if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, (void *) &accept_conn, &len) < 0 || !accept_conn)
443 : return false;
444 : #endif
445 0 : return true;
446 : }
447 :
448 : /**
449 : * Set up the process when started by inetd/xinetd in "wait" mode.
450 : * In this mode the listening socket is passed as file descriptors 0, 1 and 2;
451 : * keep a copy of it and redirect standard streams to /dev/null.
452 : * Logging can be enabled with the -l option.
453 : * \return true on success, false on error
454 : */
455 : static bool
456 0 : pool_inetd_init(void)
457 : {
458 : TDS_SYS_SOCKET s;
459 : int fd;
460 :
461 0 : if (!pool_is_listen_socket(0)) {
462 0 : fprintf(stderr, "Standard input is not a listening socket, check inetd service is configured with \"wait\"\n");
463 0 : return false;
464 : }
465 :
466 0 : s = dup(0);
467 0 : if (TDS_IS_SOCKET_INVALID(s)) {
468 0 : perror("dup");
469 0 : return false;
470 : }
471 :
472 0 : fd = open("/dev/null", O_RDWR);
473 0 : if (fd < 0) {
474 0 : perror("open /dev/null");
475 0 : CLOSESOCKET(s);
476 0 : return false;
477 : }
478 0 : fflush(stdout);
479 0 : fflush(stderr);
480 0 : while (dup2(fd, 0) < 0 && errno == EINTR)
481 0 : continue;
482 0 : while (dup2(fd, 1) < 0 && errno == EINTR)
483 0 : continue;
484 0 : while (dup2(fd, 2) < 0 && errno == EINTR)
485 0 : continue;
486 0 : if (fd > 2)
487 0 : close(fd);
488 :
489 0 : inherited_listen_fd = s;
490 0 : return true;
491 : }
492 :
493 : /* first file descriptor passed by systemd, see sd_listen_fds(3) */
494 : #define SYSTEMD_LISTEN_FDS_START 3
495 :
496 : /**
497 : * Detect systemd socket activation (see sd_listen_fds(3)).
498 : * The socket unit must have Accept=no and a single ListenStream.
499 : * \param found set to true if a listening socket was passed
500 : * \return true on success, false on error
501 : */
502 : static bool
503 2 : pool_systemd_init(bool *found)
504 : {
505 : const char *env;
506 : char *end;
507 : long val;
508 2 : int fd = SYSTEMD_LISTEN_FDS_START;
509 :
510 2 : *found = false;
511 :
512 : /* the variables are for us only if LISTEN_PID is our pid */
513 2 : env = getenv("LISTEN_PID");
514 2 : if (!env)
515 : return true;
516 0 : val = strtol(env, &end, 10);
517 0 : if (end == env || *end || val != (long) getpid())
518 : return true;
519 :
520 0 : env = getenv("LISTEN_FDS");
521 0 : if (!env)
522 : return true;
523 0 : val = strtol(env, &end, 10);
524 0 : if (end == env || *end || val <= 0)
525 : return true;
526 0 : if (val != 1) {
527 0 : fprintf(stderr, "systemd passed %ld sockets, only one is supported\n", val);
528 0 : return false;
529 : }
530 :
531 0 : if (!pool_is_listen_socket(fd)) {
532 0 : fprintf(stderr, "File descriptor %d is not a listening socket, check systemd socket is configured with Accept=no\n", fd);
533 0 : return false;
534 : }
535 :
536 : /* do not leak the socket to other programs, as sd_listen_fds does */
537 0 : fcntl(fd, F_SETFD, FD_CLOEXEC);
538 :
539 0 : inherited_listen_fd = fd;
540 0 : *found = true;
541 0 : return true;
542 : }
543 : # define INETD_OPT "x"
544 : #else
545 : # define INETD_OPT ""
546 : #endif
547 :
548 : int
549 2 : main(int argc, char **argv)
550 : {
551 : int opt;
552 : #ifdef HAVE_FORK
553 2 : bool daemonize = false;
554 : # define DAEMON_OPT "d"
555 : #else
556 : # define DAEMON_OPT ""
557 : #endif
558 : #ifndef _WIN32
559 2 : bool inetd = false;
560 : #endif
561 : TDS_POOL *pool;
562 2 : tds_dir_char *config_path = NULL;
563 :
564 2 : signal(SIGTERM, sigterm_handler);
565 2 : signal(SIGINT, sigterm_handler);
566 : #ifndef _WIN32
567 2 : signal(SIGHUP, sighup_handler);
568 2 : signal(SIGPIPE, SIG_IGN);
569 : #endif
570 :
571 4 : while ((opt = getopt(argc, argv, "l:c:" DAEMON_OPT INETD_OPT)) != -1) {
572 0 : switch (opt) {
573 0 : case 'l':
574 0 : logfile_name = optarg;
575 0 : break;
576 : #ifdef HAVE_FORK
577 : case 'd':
578 : daemonize = true;
579 : break;
580 : #endif
581 0 : case 'c':
582 0 : config_path = tds_dir_from_cstr(optarg);
583 0 : if (!config_path) {
584 0 : fprintf(stderr, "Out of memory\n");
585 0 : return EXIT_FAILURE;
586 : }
587 : break;
588 : #ifndef _WIN32
589 0 : case 'x':
590 0 : inetd = true;
591 0 : break;
592 : #endif
593 0 : default:
594 0 : print_usage(argv[0]);
595 0 : return EXIT_FAILURE;
596 : }
597 : }
598 2 : if (optind >= argc) {
599 0 : print_usage(argv[0]);
600 0 : return EXIT_FAILURE;
601 : }
602 : #ifndef _WIN32
603 2 : if (inetd) {
604 : #ifdef HAVE_FORK
605 : /* inetd waits for the process it started, it must not go away */
606 0 : if (daemonize) {
607 0 : fprintf(stderr, "Options -d and -x cannot be used together\n");
608 0 : return EXIT_FAILURE;
609 : }
610 : #endif
611 0 : if (!pool_inetd_init())
612 : return EXIT_FAILURE;
613 : } else {
614 : bool found;
615 :
616 2 : if (!pool_systemd_init(&found))
617 0 : return EXIT_FAILURE;
618 2 : if (found)
619 0 : fprintf(stderr, "Using listening socket passed by systemd\n");
620 : }
621 : #endif
622 2 : pool = pool_init(argv[optind], config_path);
623 2 : TDS_ZERO_FREE(config_path);
624 : #ifdef HAVE_FORK
625 2 : if (daemonize) {
626 : /* daemon() is deprecated on macOS but still works, replacing it requires re-executing the program */
627 : #ifdef __APPLE__
628 : #pragma GCC diagnostic push
629 : #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
630 : #endif
631 0 : if (daemon(0, 0) < 0) {
632 0 : fprintf(stderr, "Failed to daemonize %s\n", argv[0]);
633 0 : return EXIT_FAILURE;
634 : }
635 : #ifdef __APPLE__
636 : #pragma GCC diagnostic pop
637 : #endif
638 : }
639 : #endif
640 2 : pool_main_loop(pool);
641 2 : printf("User logins %lu members logins %lu members at end %d\n", pool->user_logins, pool->member_logins, pool->num_active_members);
642 2 : pool_destroy(pool);
643 2 : printf("tdspool Shutdown\n");
644 2 : return EXIT_SUCCESS;
645 : }
|