source: unix.c @ 8a220893

Last change on this file since 8a220893 was 10b3683, checked in by dx <dx@…>, at 2019-05-23T11:06:37Z

Don't make early warnings go nowhere

between log_init and the existing log_link calls, all errors and
warnings would go nowhere. Let's show them on the console.

Signed-off-by: Ævar Arnfjörð Bjarmason <avarab@…>

  • Property mode set to 100644
File size: 11.5 KB
Line 
1/********************************************************************\
2  * BitlBee -- An IRC to other IM-networks gateway                     *
3  *                                                                    *
4  * Copyright 2002-2012 Wilmer van der Gaast and others                *
5  \********************************************************************/
6
7/* Main file (Unix specific part)                                       */
8
9/*
10  This program is free software; you can redistribute it and/or modify
11  it under the terms of the GNU General Public License as published by
12  the Free Software Foundation; either version 2 of the License, or
13  (at your option) any later version.
14
15  This program is distributed in the hope that it will be useful,
16  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  GNU General Public License for more details.
19
20  You should have received a copy of the GNU General Public License with
21  the Debian GNU/Linux distribution in /usr/share/common-licenses/GPL;
22  if not, write to the Free Software Foundation, Inc., 51 Franklin St.,
23  Fifth Floor, Boston, MA  02110-1301  USA
24*/
25
26#include "bitlbee.h"
27
28#include "arc.h"
29#include "base64.h"
30#include "commands.h"
31#include "protocols/nogaim.h"
32#include "help.h"
33#include "ipc.h"
34#include "md5.h"
35#include "misc.h"
36#include <signal.h>
37#include <unistd.h>
38#include <sys/time.h>
39#include <sys/wait.h>
40#include <pwd.h>
41#include <locale.h>
42#include <grp.h>
43
44#if defined(OTR_BI) || defined(OTR_PI)
45#include "otr.h"
46#endif
47
48#ifdef HAVE_BACKTRACE
49#include <execinfo.h>
50#endif
51
52global_t global;        /* Against global namespace pollution */
53
54static struct {
55        int fd[2];
56        int tag;
57} shutdown_pipe = {{-1 , -1}, 0};
58
59static void sighandler_shutdown(int signal);
60static void sighandler_crash(int signal);
61
62static int crypt_main(int argc, char *argv[]);
63
64int main(int argc, char *argv[])
65{
66        int i = 0;
67        char *old_cwd = NULL;
68        struct sigaction sig, old;
69#ifdef HAVE_BACKTRACE
70        void *unused[1];
71#endif
72
73        /* Required to make iconv to ASCII//TRANSLIT work. This makes BitlBee
74           system-locale-sensitive. :-( */
75        setlocale(LC_CTYPE, "");
76
77        if (argc > 1 && strcmp(argv[1], "-x") == 0) {
78                return crypt_main(argc, argv);
79        }
80
81        log_init();
82        /* Catch early errors */
83        log_link(LOGLVL_ERROR, LOGOUTPUT_CONSOLE);
84        log_link(LOGLVL_WARNING, LOGOUTPUT_CONSOLE);
85
86        global.conf_file = g_strdup(CONF_FILE_DEF);
87        global.conf = conf_load(argc, argv);
88        if (global.conf == NULL) {
89                return(1);
90        }
91
92        if (global.conf->runmode == RUNMODE_INETD) {
93                log_link(LOGLVL_ERROR, LOGOUTPUT_IRC);
94                log_link(LOGLVL_WARNING, LOGOUTPUT_IRC);
95        } else {
96                log_link(LOGLVL_ERROR, LOGOUTPUT_CONSOLE);
97                log_link(LOGLVL_WARNING, LOGOUTPUT_CONSOLE);
98        }
99
100        b_main_init();
101
102        /* libpurple doesn't like fork()s after initializing itself, so if
103           we use it, do this init a little later (in case we're running in
104           ForkDaemon mode). */
105#ifndef WITH_PURPLE
106        nogaim_init();
107#endif
108
109#ifdef OTR_BI
110        otr_init();
111#endif
112
113        global.helpfile = g_strdup(HELP_FILE);
114        if (help_init(&global.help, global.helpfile) == NULL) {
115                log_message(LOGLVL_WARNING, "Error opening helpfile %s.", HELP_FILE);
116        }
117
118        global.storage = storage_init(global.conf->primary_storage, global.conf->migrate_storage);
119        if (global.storage == NULL) {
120                log_message(LOGLVL_ERROR, "Unable to load storage backend '%s'", global.conf->primary_storage);
121                return(1);
122        }
123
124        global.auth = auth_init(global.conf->auth_backend);
125        if (global.conf->auth_backend && global.auth == NULL) {
126                log_message(LOGLVL_ERROR, "Unable to load authentication backend '%s'", global.conf->auth_backend);
127                return(1);
128        }
129
130        if (global.conf->runmode == RUNMODE_INETD) {
131                i = bitlbee_inetd_init();
132                log_message(LOGLVL_INFO, "%s %s starting in inetd mode.", PACKAGE, BITLBEE_VERSION);
133
134        } else if (global.conf->runmode == RUNMODE_DAEMON) {
135                i = bitlbee_daemon_init();
136                log_message(LOGLVL_INFO, "%s %s starting in daemon mode.", PACKAGE, BITLBEE_VERSION);
137        } else if (global.conf->runmode == RUNMODE_FORKDAEMON) {
138                /* In case the operator requests a restart, we need this. */
139                old_cwd = g_malloc(256);
140                if (getcwd(old_cwd, 255) == NULL) {
141                        log_message(LOGLVL_WARNING, "Could not save current directory: %s", strerror(errno));
142                        g_free(old_cwd);
143                        old_cwd = NULL;
144                }
145
146                i = bitlbee_daemon_init();
147                log_message(LOGLVL_INFO, "%s %s starting in forking daemon mode.", PACKAGE, BITLBEE_VERSION);
148        }
149        if (i != 0) {
150                return(i);
151        }
152
153        if ((global.conf->user && *global.conf->user) &&
154            (global.conf->runmode == RUNMODE_DAEMON ||
155             global.conf->runmode == RUNMODE_FORKDAEMON) &&
156            (!getuid() || !geteuid())) {
157                struct passwd *pw = NULL;
158                pw = getpwnam(global.conf->user);
159                if (!pw) {
160                        log_message(LOGLVL_ERROR, "Failed to look up user %s.", global.conf->user);
161
162                } else if (initgroups(global.conf->user, pw->pw_gid) != 0) {
163                        log_message(LOGLVL_ERROR, "initgroups: %s.", strerror(errno));
164
165                } else if (setgid(pw->pw_gid) != 0) {
166                        log_message(LOGLVL_ERROR, "setgid(%d): %s.", pw->pw_gid, strerror(errno));
167
168                } else if (setuid(pw->pw_uid) != 0) {
169                        log_message(LOGLVL_ERROR, "setuid(%d): %s.", pw->pw_uid, strerror(errno));
170                }
171        }
172
173        /* Catch some signals to tell the user what's happening before quitting */
174        memset(&sig, 0, sizeof(sig));
175        sig.sa_handler = SIG_IGN;
176        sigaction(SIGCHLD, &sig, &old);
177        sigaction(SIGPIPE, &sig, &old);
178        sig.sa_flags = SA_RESETHAND;
179        sig.sa_handler = sighandler_crash;
180        sigaction(SIGSEGV, &sig, &old);
181
182        sighandler_shutdown_setup();
183
184        sig.sa_handler = sighandler_shutdown;
185        sigaction(SIGINT, &sig, &old);
186        sigaction(SIGTERM, &sig, &old);
187
188#ifdef HAVE_BACKTRACE
189        /* As per the backtrace(3) man page, call this outside of the signal
190         * handler once to ensure any dynamic libraries are loaded in an
191         * async-signal-safe environment to prevent deadlocks */
192        backtrace(unused, 1);
193#endif
194
195        if (!getuid() || !geteuid()) {
196                log_message(LOGLVL_WARNING, "BitlBee is running with root privileges. Why?");
197        }
198
199        b_main_run();
200
201        /* Mainly good for restarting, to make sure we close the help.txt fd. */
202        help_free(&global.help);
203
204        if (global.restart) {
205                char *fn = ipc_master_save_state();
206                char *env;
207
208                env = g_strdup_printf("_BITLBEE_RESTART_STATE=%s", fn);
209                putenv(env);
210                g_free(fn);
211                /* Looks like env should *not* be freed here as putenv
212                   doesn't make a copy. Odd. */
213
214                i = chdir(old_cwd);
215                close(global.listen_socket);
216
217                if (execv(argv[0], argv) == -1) {
218                        /* Apparently the execve() failed, so let's just
219                           jump back into our own/current main(). */
220                        /* Need more cleanup code to make this work. */
221                        return 1; /* main( argc, argv ); */
222                }
223        }
224
225        return(0);
226}
227
228static int crypt_main(int argc, char *argv[])
229{
230        int pass_len;
231        unsigned char *pass_cr, *pass_cl;
232
233        if (argc < 4 || (strcmp(argv[2], "hash") != 0 &&
234                         strcmp(argv[2], "unhash") != 0 && argc < 5)) {
235                printf("Supported:\n"
236                       "  %s -x enc <key> <cleartext password>\n"
237                       "  %s -x dec <key> <encrypted password>\n"
238                       "  %s -x hash <cleartext password>\n"
239                       "  %s -x unhash <hashed password>\n"
240                       "  %s -x chkhash <hashed password> <cleartext password>\n",
241                       argv[0], argv[0], argv[0], argv[0], argv[0]);
242        } else if (strcmp(argv[2], "enc") == 0) {
243                char *encoded;
244
245                pass_len = arc_encode(argv[4], strlen(argv[4]), &pass_cr, argv[3], 12);
246
247                encoded = base64_encode(pass_cr, pass_len);
248                printf("%s\n", encoded);
249                g_free(encoded);
250                g_free(pass_cr);
251        } else if (strcmp(argv[2], "dec") == 0) {
252                pass_len = base64_decode(argv[4], &pass_cr);
253                arc_decode(pass_cr, pass_len, (char **) &pass_cl, argv[3]);
254                printf("%s\n", pass_cl);
255
256                g_free(pass_cr);
257                g_free(pass_cl);
258        } else if (strcmp(argv[2], "hash") == 0) {
259                md5_byte_t pass_md5[21];
260                md5_state_t md5_state;
261                char *encoded;
262
263                random_bytes(pass_md5 + 16, 5);
264                md5_init(&md5_state);
265                md5_append(&md5_state, (md5_byte_t *) argv[3], strlen(argv[3]));
266                md5_append(&md5_state, pass_md5 + 16, 5);   /* Add the salt. */
267                md5_finish(&md5_state, pass_md5);
268
269                encoded = base64_encode(pass_md5, 21);
270                printf("%s\n", encoded);
271                g_free(encoded);
272        } else if (strcmp(argv[2], "unhash") == 0) {
273                printf("Hash %s submitted to a massive Beowulf cluster of\n"
274                       "overclocked 486s. Expect your answer next year somewhere around this time. :-)\n", argv[3]);
275        } else if (strcmp(argv[2], "chkhash") == 0) {
276                char *hash = strncmp(argv[3], "md5:", 4) == 0 ? argv[3] + 4 : argv[3];
277                int st = md5_verify_password(argv[4], hash);
278
279                printf("Hash %s given password.\n", st == 0 ? "matches" : "does not match");
280
281                return st;
282        }
283
284        return 0;
285}
286
287/* Set up a pipe for SIGTERM/SIGINT so the actual signal handler doesn't do anything unsafe */
288void sighandler_shutdown_setup()
289{
290        if (shutdown_pipe.fd[0] != -1) {
291                /* called again from a forked process, clean up to avoid propagating the signal */
292                b_event_remove(shutdown_pipe.tag);
293                close(shutdown_pipe.fd[0]);
294                close(shutdown_pipe.fd[1]);
295        }
296
297        if (pipe(shutdown_pipe.fd) == 0) {
298                shutdown_pipe.tag = b_input_add(shutdown_pipe.fd[0], B_EV_IO_READ, bitlbee_shutdown, NULL);
299        }
300}
301
302/* Signal handler for SIGTERM and SIGINT */
303static void sighandler_shutdown(int signal)
304{
305        int unused G_GNUC_UNUSED;
306        /* Write a single null byte to the pipe, just to send a message to the main loop.
307         * This gets handled by bitlbee_shutdown (the b_input_add callback for this pipe) */
308        unused = write(shutdown_pipe.fd[1], "", 1);
309}
310
311#ifdef HAVE_BACKTRACE
312/* Writes a backtrace to (usually) /var/lib/bitlbee/crash.log
313 * No malloc allowed means not a lot can be written to that file */
314static void sighandler_crash_backtrace()
315{
316        int fd, mapsfd;
317        int size;
318        void *trace[128];
319        const char message[] = "## " PACKAGE " crashed\n"
320                "## Version: " BITLBEE_VERSION "\n"
321                "## Configure args: " BITLBEE_CONFIGURE_ARGS "\n"
322                "##\n"
323                "## Backtrace:\n\n";
324        const char message2[] = "\n"
325                "## Hint: To get details on addresses use\n"
326                "##   addr2line -e <binary> <address>\n"
327                "## or\n"
328                "##   gdb <binary> -ex 'l *<address>' -ex q\n"
329                "## where <binary> is a filename from above and <address> is the part between (...)\n"
330                "##\n\n";
331        const char message3[] = "\n## End of memory maps. See above for the backtrace\n\n";
332
333        fd = open(CRASHFILE, O_WRONLY | O_APPEND | O_CREAT, 0600);
334
335        if (fd == -1 || write(fd, message, sizeof(message) - 1) == -1) {
336                return;
337        }
338
339        size = backtrace(trace, 128);
340        backtrace_symbols_fd(trace, size, fd);
341
342        (void) write(fd, message2, sizeof(message2) - 1);
343
344        /* a bit too linux-specific, so fail gracefully */
345        mapsfd = open("/proc/self/maps", O_RDONLY, 0);
346
347        if (mapsfd != -1) {
348                char buf[4096] = {0};
349                ssize_t bytes;
350
351                while ((bytes = read(mapsfd, buf, sizeof(buf))) > 0) {
352                        (void) write(fd, buf, bytes);
353                }
354                (void) close(mapsfd);
355                (void) write(fd, message3, sizeof(message3) - 1);
356        }
357
358        (void) close(fd);
359}
360#endif
361
362/* Signal handler for SIGSEGV
363 * A desperate attempt to tell the user that everything is wrong in the world.
364 * Avoids using irc_abort() because it has several unsafe calls to malloc */
365static void sighandler_crash(int signal)
366{
367        GSList *l;
368        const char message[] = "ERROR :BitlBee crashed! (SIGSEGV received)\r\n"
369#ifdef HAVE_BACKTRACE
370                "ERROR :Writing backtrace to " CRASHFILE "\r\n"
371#endif
372                "ERROR :This is a bug either in BitlBee or a plugin, ask us on IRC if unsure\r\n";
373
374        for (l = irc_connection_list; l; l = l->next) {
375                irc_t *irc = l->data;
376                sock_make_blocking(irc->fd);
377                if (irc->sendbuffer) {
378                        (void) write(irc->fd, irc->sendbuffer->str, irc->sendbuffer->len);
379                }
380                (void) write(irc->fd, message, sizeof(message) - 1);
381        }
382
383#ifdef HAVE_BACKTRACE
384        sighandler_crash_backtrace();
385#endif
386
387        raise(signal);
388}
389
390double gettime()
391{
392        struct timeval time[1];
393
394        gettimeofday(time, 0);
395        return((double) time->tv_sec + (double) time->tv_usec / 1000000);
396}
Note: See TracBrowser for help on using the repository browser.