add changelog for 1.13
[beanstalkd.git] / main.c
blob7e7dc07875f3e090faba2abb356eef111bc57405
1 #include "dat.h"
2 #include <stdint.h>
3 #include <signal.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <errno.h>
7 #include <sys/stat.h>
8 #include <unistd.h>
9 #include <pwd.h>
10 #include <fcntl.h>
12 static void
13 su(const char *user)
15 errno = 0;
16 struct passwd *pwent = getpwnam(user);
17 if (errno) {
18 twarn("getpwnam(\"%s\")", user);
19 exit(32);
21 if (!pwent) {
22 twarnx("getpwnam(\"%s\"): no such user", user);
23 exit(33);
26 int r = setgid(pwent->pw_gid);
27 if (r == -1) {
28 twarn("setgid(%d \"%s\")", pwent->pw_gid, user);
29 exit(34);
32 r = setuid(pwent->pw_uid);
33 if (r == -1) {
34 twarn("setuid(%d \"%s\")", pwent->pw_uid, user);
35 exit(34);
39 static void
40 handle_sigterm_pid1()
42 exit(143);
45 static void
46 set_sig_handlers()
48 struct sigaction sa;
50 sa.sa_handler = SIG_IGN;
51 sa.sa_flags = 0;
52 int r = sigemptyset(&sa.sa_mask);
53 if (r == -1) {
54 twarn("sigemptyset()");
55 exit(111);
58 r = sigaction(SIGPIPE, &sa, 0);
59 if (r == -1) {
60 twarn("sigaction(SIGPIPE)");
61 exit(111);
64 sa.sa_handler = enter_drain_mode;
65 r = sigaction(SIGUSR1, &sa, 0);
66 if (r == -1) {
67 twarn("sigaction(SIGUSR1)");
68 exit(111);
71 // Workaround for running the server with pid=1 in Docker.
72 // Handle SIGTERM so the server is killed immediately and
73 // not after 10 seconds timeout. See issue #527.
74 if (getpid() == 1) {
75 sa.sa_handler = handle_sigterm_pid1;
76 r = sigaction(SIGTERM, &sa, 0);
77 if (r == -1) {
78 twarn("sigaction(SIGTERM)");
79 exit(111);
84 int
85 main(int argc, char **argv)
87 UNUSED_PARAMETER(argc);
89 progname = argv[0];
90 setlinebuf(stdout);
91 optparse(&srv, argv+1);
93 if (verbose) {
94 printf("pid %d\n", getpid());
97 int r = make_server_socket(srv.addr, srv.port);
98 if (r == -1) {
99 twarnx("make_server_socket()");
100 exit(111);
103 srv.sock.fd = r;
105 prot_init();
107 if (srv.user)
108 su(srv.user);
109 set_sig_handlers();
111 srv_acquire_wal(&srv);
112 srvserve(&srv);
113 exit(0);