source: owl.c @ 4fd3c04

Last change on this file since 4fd3c04 was 4fd3c04, checked in by Anders Kaseorg <andersk@mit.edu>, 7 years ago
Remove AIM support This code has received almost no security attention, and anyway, AIM is shutting down on December 15, 2017. https://aimemories.tumblr.com/post/166091776077/aimemories Signed-off-by: Anders Kaseorg <andersk@mit.edu>
  • Property mode set to 100644
File size: 18.5 KB
Line 
1/*  Copyright (c) 2006-2011 The BarnOwl Developers. All rights reserved.
2 *  Copyright (c) 2004 James Kretchmar. All rights reserved.
3 *
4 *  This program is free software. You can redistribute it and/or
5 *  modify under the terms of the Sleepycat License. See the COPYING
6 *  file included with the distribution for more information.
7 */
8
9#include "owl.h"
10#include <stdio.h>
11#include <getopt.h>
12#include <sys/stat.h>
13#include <locale.h>
14#include <unistd.h>
15
16#if OWL_STDERR_REDIR
17#ifdef HAVE_SYS_IOCTL_H
18#include <sys/ioctl.h>
19#endif
20#ifdef HAVE_SYS_FILIO_H
21#include <sys/filio.h>
22#endif
23int stderr_replace(void);
24#endif
25
26owl_global g;
27
28typedef struct _owl_options {
29  bool load_initial_subs;
30  char *configfile;
31  char *tty;
32  char *confdir;
33  bool debug;
34} owl_options;
35
36void usage(FILE *file)
37{
38  fprintf(file, "BarnOwl version %s\n", version);
39  fprintf(file, "Usage: barnowl [-n] [-d] [-D] [-v] [-h] [-c <configfile>] [-s <confdir>] [-t <ttyname>]\n");
40  fprintf(file, "  -n,--no-subs        don't load zephyr subscriptions\n");
41  fprintf(file, "  -d,--debug          enable debugging\n");
42  fprintf(file, "  -v,--version        print the BarnOwl version number and exit\n");
43  fprintf(file, "  -h,--help           print this help message\n");
44  fprintf(file, "  -s,--config-dir     specify an alternate config dir (default ~/.owl)\n");
45  fprintf(file, "  -c,--config-file    specify an alternate config file (default ~/.owl/init.pl)\n");
46  fprintf(file, "  -t,--tty            set the tty name\n");
47}
48
49/* TODO: free owl_options after init is done? */
50void owl_parse_options(int argc, char *argv[], owl_options *opts) {
51  static const struct option long_options[] = {
52    { "no-subs",         0, 0, 'n' },
53    { "config-file",     1, 0, 'c' },
54    { "config-dir",      1, 0, 's' },
55    { "tty",             1, 0, 't' },
56    { "debug",           0, 0, 'd' },
57    { "version",         0, 0, 'v' },
58    { "help",            0, 0, 'h' },
59    { NULL, 0, NULL, 0}
60  };
61  char c;
62
63  while((c = getopt_long(argc, argv, "nc:t:s:dDvh",
64                         long_options, NULL)) != -1) {
65    switch(c) {
66    case 'n':
67      opts->load_initial_subs = 0;
68      break;
69    case 'c':
70      opts->configfile = g_strdup(optarg);
71      break;
72    case 's':
73      opts->confdir = g_strdup(optarg);
74      break;
75    case 't':
76      opts->tty = g_strdup(optarg);
77      break;
78    case 'd':
79      opts->debug = 1;
80      break;
81    case 'v':
82      printf("This is BarnOwl version %s\n", version);
83      exit(0);
84    case 'h':
85      usage(stdout);
86      exit(0);
87    default:
88      usage(stderr);
89      exit(1);
90    }
91  }
92}
93
94void owl_start_color(void) {
95  start_color();
96#ifdef HAVE_USE_DEFAULT_COLORS
97  use_default_colors();
98#endif
99
100  /* define simple color pairs */
101  if (has_colors() && COLOR_PAIRS>=8) {
102    int bg = COLOR_BLACK;
103#ifdef HAVE_USE_DEFAULT_COLORS
104    bg = -1;
105#endif
106    init_pair(OWL_COLOR_BLACK,   COLOR_BLACK,   bg);
107    init_pair(OWL_COLOR_RED,     COLOR_RED,     bg);
108    init_pair(OWL_COLOR_GREEN,   COLOR_GREEN,   bg);
109    init_pair(OWL_COLOR_YELLOW,  COLOR_YELLOW,  bg);
110    init_pair(OWL_COLOR_BLUE,    COLOR_BLUE,    bg);
111    init_pair(OWL_COLOR_MAGENTA, COLOR_MAGENTA, bg);
112    init_pair(OWL_COLOR_CYAN,    COLOR_CYAN,    bg);
113    init_pair(OWL_COLOR_WHITE,   COLOR_WHITE,   bg);
114  }
115}
116
117void owl_start_curses(void) {
118  struct termios tio;
119  /* save initial terminal settings */
120  tcgetattr(STDIN_FILENO, owl_global_get_startup_tio(&g));
121
122  tcgetattr(STDIN_FILENO, &tio);
123  tio.c_iflag &= ~(ISTRIP|IEXTEN);
124  tio.c_cc[VQUIT] = fpathconf(STDIN_FILENO, _PC_VDISABLE);
125  tio.c_cc[VSUSP] = fpathconf(STDIN_FILENO, _PC_VDISABLE);
126  tio.c_cc[VSTART] = fpathconf(STDIN_FILENO, _PC_VDISABLE);
127  tio.c_cc[VSTOP] = fpathconf(STDIN_FILENO, _PC_VDISABLE);
128  tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
129
130  /* screen init */
131  initscr();
132  cbreak();
133  noecho();
134
135  owl_start_color();
136}
137
138void owl_shutdown_curses(void) {
139  endwin();
140  /* restore terminal settings */
141  tcsetattr(STDIN_FILENO, TCSAFLUSH, owl_global_get_startup_tio(&g));
142}
143
144/*
145 * Process a new message passed to us on the message queue from some
146 * protocol. This includes adding it to the message list, updating the
147 * view and scrolling if appropriate, logging it, and so on.
148 *
149 * Either a pointer is kept to the message internally, or it is freed
150 * if unneeded. The caller no longer ``owns'' the message's memory.
151 *
152 * Returns 1 if the message was added to the message list, and 0 if it
153 * was ignored due to user settings or otherwise.
154 */
155static int owl_process_message(owl_message *m) {
156  const owl_filter *f;
157  /* if this message it on the puntlist, nuke it and continue */
158  if (owl_global_message_is_puntable(&g, m)) {
159    owl_message_delete(m);
160    return 0;
161  }
162
163  /*  login or logout that should be ignored? */
164  if (owl_global_is_ignorelogins(&g)
165      && owl_message_is_loginout(m)) {
166    owl_message_delete(m);
167    return 0;
168  }
169
170  if (!owl_global_is_displayoutgoing(&g)
171      && owl_message_is_direction_out(m)) {
172    owl_message_delete(m);
173    return 0;
174  }
175
176  /* add it to the global list */
177  owl_messagelist_append_element(owl_global_get_msglist(&g), m);
178  /* add it to any necessary views; right now there's only the current view */
179  owl_view_consider_message(owl_global_get_current_view(&g), m);
180
181  if(owl_message_is_direction_in(m)) {
182    /* let perl know about it*/
183    owl_perlconfig_getmsg(m, NULL);
184
185    /* do we need to autoreply? */
186    if (owl_global_is_zaway(&g) && !owl_message_get_attribute_value(m, "isauto")) {
187      if (owl_message_is_type_zephyr(m)) {
188        owl_zephyr_zaway(m);
189      }
190    }
191
192    /* ring the bell if it's a personal */
193    if (!strcmp(owl_global_get_personalbell(&g), "on")) {
194      if (!owl_message_is_loginout(m) &&
195          !owl_message_is_mail(m) &&
196          owl_message_is_personal(m)) {
197        owl_function_beep();
198      }
199    } else if (!strcmp(owl_global_get_personalbell(&g), "off")) {
200      /* do nothing */
201    } else {
202      f=owl_global_get_filter(&g, owl_global_get_personalbell(&g));
203      if (f && owl_filter_message_match(f, m)) {
204        owl_function_beep();
205      }
206    }
207
208    /* if it matches the alert filter, do the alert action */
209    f=owl_global_get_filter(&g, owl_global_get_alert_filter(&g));
210    if (f && owl_filter_message_match(f, m)) {
211      owl_function_command_norv(owl_global_get_alert_action(&g));
212    }
213
214    /* if it's a zephyr login or logout, update the zbuddylist */
215    if (owl_message_is_type_zephyr(m) && owl_message_is_loginout(m)) {
216      if (owl_message_is_login(m)) {
217        owl_zbuddylist_adduser(owl_global_get_zephyr_buddylist(&g), owl_message_get_sender(m));
218      } else if (owl_message_is_logout(m)) {
219        owl_zbuddylist_deluser(owl_global_get_zephyr_buddylist(&g), owl_message_get_sender(m));
220      } else {
221        owl_function_error("Internal error: received login notice that is neither login nor logout");
222      }
223    }
224  }
225
226  /* let perl know about it */
227  owl_perlconfig_newmsg(m, NULL);
228  /* redraw the sepbar; TODO: don't violate layering */
229  owl_global_sepbar_dirty(&g);
230
231  return 1;
232}
233
234static gboolean owl_process_messages_prepare(GSource *source, int *timeout) {
235  *timeout = -1;
236  return owl_global_messagequeue_pending(&g);
237}
238
239static gboolean owl_process_messages_check(GSource *source) {
240  return owl_global_messagequeue_pending(&g);
241}
242
243/*
244 * Process any new messages we have waiting in the message queue.
245 */
246static gboolean owl_process_messages_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) {
247  int newmsgs=0;
248  int followlast = owl_global_should_followlast(&g);
249  owl_message *m;
250
251  /* Grab incoming messages. */
252  while (owl_global_messagequeue_pending(&g)) {
253    m = owl_global_messagequeue_popmsg(&g);
254    if (owl_process_message(m))
255      newmsgs = 1;
256  }
257
258  if (newmsgs) {
259    /* follow the last message if we're supposed to */
260    if (followlast)
261      owl_function_lastmsg();
262
263    /* do the newmsgproc thing */
264    owl_function_do_newmsgproc();
265
266    /* redisplay if necessary */
267    /* this should be optimized to not run if the new messages won't be displayed */
268    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
269  }
270  return TRUE;
271}
272
273static GSourceFuncs owl_process_messages_funcs = {
274  owl_process_messages_prepare,
275  owl_process_messages_check,
276  owl_process_messages_dispatch,
277  NULL
278};
279
280void owl_process_input_char(owl_input j)
281{
282  int ret;
283
284  owl_global_set_lastinputtime(&g, time(NULL));
285  owl_global_wakeup(&g);
286  ret = owl_keyhandler_process(owl_global_get_keyhandler(&g), j);
287  if (ret!=0 && ret!=1) {
288    owl_function_makemsg("Unable to handle keypress");
289  }
290}
291
292gboolean owl_process_input(GIOChannel *source, GIOCondition condition, void *data)
293{
294  owl_global *g = data;
295  owl_input j;
296
297  while (1) {
298    j.ch = wgetch(g->input_pad);
299    if (j.ch == ERR) return TRUE;
300
301    j.uch = '\0';
302    if (j.ch >= KEY_MIN && j.ch <= KEY_MAX) {
303      /* This is a curses control character. */
304    }
305    else if (j.ch > 0x7f && j.ch < 0xfe) {
306      /* Pull in a full utf-8 character. */
307      int bytes, i;
308      char utf8buf[7];
309      memset(utf8buf, '\0', 7);
310     
311      utf8buf[0] = j.ch;
312     
313      if ((j.ch & 0xc0) && (~j.ch & 0x20)) bytes = 2;
314      else if ((j.ch & 0xe0) && (~j.ch & 0x10)) bytes = 3;
315      else if ((j.ch & 0xf0) && (~j.ch & 0x08)) bytes = 4;
316      else if ((j.ch & 0xf8) && (~j.ch & 0x04)) bytes = 5;
317      else if ((j.ch & 0xfc) && (~j.ch & 0x02)) bytes = 6;
318      else bytes = 1;
319     
320      for (i = 1; i < bytes; i++) {
321        int tmp = wgetch(g->input_pad);
322        /* If what we got was not a byte, or not a continuation byte */
323        if (tmp > 0xff || !(tmp & 0x80 && ~tmp & 0x40)) {
324          /* ill-formed UTF-8 code unit subsequence, put back the
325             char we just got. */
326          ungetch(tmp);
327          j.ch = ERR;
328          break;
329        }
330        utf8buf[i] = tmp;
331      }
332     
333      if (j.ch != ERR) {
334        if (g_utf8_validate(utf8buf, -1, NULL)) {
335          j.uch = g_utf8_get_char(utf8buf);
336        }
337        else {
338          j.ch = ERR;
339        }
340      }
341    }
342    else if (j.ch <= 0x7f) {
343      j.uch = j.ch;
344    }
345
346    owl_process_input_char(j);
347  }
348  return TRUE;
349}
350
351static void sig_handler_main_thread(void *data) {
352  int sig = GPOINTER_TO_INT(data);
353
354  owl_function_debugmsg("Got signal %d", sig);
355  if (sig == SIGWINCH) {
356    owl_function_resize();
357  } else if (sig == SIGTERM || sig == SIGHUP) {
358    owl_function_quit();
359  } else if (sig == SIGINT && owl_global_take_interrupt(&g)) {
360    owl_input in;
361    in.ch = in.uch = owl_global_get_startup_tio(&g)->c_cc[VINTR];
362    owl_process_input_char(in);
363  }
364}
365
366static void sig_handler(const siginfo_t *siginfo, void *data) {
367  /* If it was an interrupt, set a flag so we can handle it earlier if
368   * needbe. sig_handler_main_thread will check the flag to make sure
369   * no one else took it. */
370  if (siginfo->si_signo == SIGINT) {
371    owl_global_add_interrupt(&g);
372  }
373  /* Send a message to the main thread. */
374  owl_select_post_task(sig_handler_main_thread,
375                       GINT_TO_POINTER(siginfo->si_signo), 
376                       NULL, g_main_context_default());
377}
378
379#define OR_DIE(s, syscall)       \
380  G_STMT_START {                 \
381    if ((syscall) == -1) {       \
382      perror((s));               \
383      exit(1);                   \
384    }                            \
385  } G_STMT_END
386
387void owl_register_signal_handlers(void) {
388  struct sigaction sig_ignore = { .sa_handler = SIG_IGN };
389  struct sigaction sig_default = { .sa_handler = SIG_DFL };
390  sigset_t sigset;
391  int ret, i;
392  const int reset_signals[] = { SIGABRT, SIGBUS, SIGCHLD, SIGFPE, SIGILL,
393                                SIGQUIT, SIGSEGV, };
394  /* Don't bother resetting watched ones because owl_signal_init will. */
395  const int watch_signals[] = { SIGWINCH, SIGTERM, SIGHUP, SIGINT, };
396
397  /* Sanitize our signals; the mask and dispositions from our parent
398   * aren't really useful. Signal list taken from equivalent code in
399   * Chromium. */
400  OR_DIE("sigemptyset", sigemptyset(&sigset));
401  if ((ret = pthread_sigmask(SIG_SETMASK, &sigset, NULL)) != 0) {
402    errno = ret;
403    perror("pthread_sigmask");
404    exit(1);
405  }
406  for (i = 0; i < G_N_ELEMENTS(reset_signals); i++) {
407    OR_DIE("sigaction", sigaction(reset_signals[i], &sig_default, NULL));
408  }
409
410  /* Turn off SIGPIPE; we check the return value of write. */
411  OR_DIE("sigaction", sigaction(SIGPIPE, &sig_ignore, NULL));
412
413  /* Register some signals with the signal thread. */
414  owl_signal_init(watch_signals, G_N_ELEMENTS(watch_signals),
415                  sig_handler, NULL);
416}
417
418#if OWL_STDERR_REDIR
419
420/* Replaces stderr with a pipe so that we can read from it.
421 * Returns the fd of the pipe from which stderr can be read. */
422int stderr_replace(void)
423{
424  int pipefds[2];
425  if (0 != pipe(pipefds)) {
426    perror("pipe");
427    owl_function_debugmsg("stderr_replace: pipe FAILED");
428    return -1;
429  }
430    owl_function_debugmsg("stderr_replace: pipe: %d,%d", pipefds[0], pipefds[1]);
431  if (-1 == dup2(pipefds[1], STDERR_FILENO)) {
432    owl_function_debugmsg("stderr_replace: dup2 FAILED (%s)", strerror(errno));
433    perror("dup2");
434    return -1;
435  }
436  return pipefds[0];
437}
438
439/* Sends stderr (read from rfd) messages to the error console */
440gboolean stderr_redirect_handler(GIOChannel *source, GIOCondition condition, void *data)
441{
442  int navail, bread;
443  char buf[4096];
444  int rfd = g_io_channel_unix_get_fd(source);
445  char *err;
446
447  /* TODO: Use g_io_channel_read_line? We'd have to be careful about
448   * blocking on the read. */
449
450  if (rfd<0) return TRUE;
451  if (-1 == ioctl(rfd, FIONREAD, &navail)) {
452    return TRUE;
453  }
454  /*owl_function_debugmsg("stderr_redirect: navail = %d\n", navail);*/
455  if (navail <= 0) return TRUE;
456  if (navail > sizeof(buf)-1) {
457    navail = sizeof(buf)-1;
458  }
459  bread = read(rfd, buf, navail);
460  if (bread == -1)
461    return TRUE;
462
463  err = g_strdup_printf("[stderr]\n%.*s", bread, buf);
464
465  owl_function_log_err(err);
466  g_free(err);
467  return TRUE;
468}
469
470#endif /* OWL_STDERR_REDIR */
471
472int main(int argc, char **argv, char **env)
473{
474  int argc_copy;
475  char **argv_copy;
476  char *perlout, *perlerr;
477  const owl_style *s;
478  const char *dir;
479  owl_options opts;
480  GSource *source;
481  GIOChannel *channel;
482
483  argc_copy = argc;
484  argv_copy = g_strdupv(argv);
485
486  setlocale(LC_ALL, "");
487
488  memset(&opts, 0, sizeof opts);
489  opts.load_initial_subs = 1;
490  owl_parse_options(argc, argv, &opts);
491  g.load_initial_subs = opts.load_initial_subs;
492
493  owl_start_curses();
494
495  /* owl global init */
496  owl_global_init(&g);
497  if (opts.debug) owl_global_set_debug_on(&g);
498  if (opts.confdir) owl_global_set_confdir(&g, opts.confdir);
499  owl_function_debugmsg("startup: first available debugging message");
500  owl_global_set_startupargs(&g, argc_copy, argv_copy);
501  g_strfreev(argv_copy);
502
503  owl_register_signal_handlers();
504
505  /* register STDIN dispatch; throw away return, we won't need it */
506  channel = g_io_channel_unix_new(STDIN_FILENO);
507  g_io_add_watch(channel, G_IO_IN | G_IO_HUP | G_IO_ERR, &owl_process_input, &g);
508  g_io_channel_unref(channel);
509  owl_zephyr_initialize();
510
511#if OWL_STDERR_REDIR
512  /* Do this only after we've started curses up... */
513  if (isatty(STDERR_FILENO)) {
514    owl_function_debugmsg("startup: doing stderr redirection");
515    channel = g_io_channel_unix_new(stderr_replace());
516    g_io_add_watch(channel, G_IO_IN | G_IO_HUP | G_IO_ERR, &stderr_redirect_handler, NULL);
517    g_io_channel_unref(channel);
518  }
519#endif
520
521  /* create the owl directory, in case it does not exist */
522  owl_function_debugmsg("startup: creating owl directory, if not present");
523  dir=owl_global_get_confdir(&g);
524  mkdir(dir, S_IRWXU);
525
526  /* set the tty, either from the command line, or by figuring it out */
527  owl_function_debugmsg("startup: setting tty name");
528  if (opts.tty) {
529    owl_global_set_tty(&g, opts.tty);
530  } else {
531    char *tty = owl_util_get_default_tty();
532    owl_global_set_tty(&g, tty);
533    g_free(tty);
534  }
535
536  /* Initialize perl */
537  owl_function_debugmsg("startup: processing config file");
538
539  owl_global_pop_context(&g);
540  owl_global_push_context(&g, OWL_CTX_READCONFIG, NULL, NULL, NULL);
541
542  perlerr=owl_perlconfig_initperl(opts.configfile, &argc, &argv, &env);
543  if (perlerr) {
544    endwin();
545    fprintf(stderr, "Internal perl error: %s\n", perlerr);
546    fflush(stderr);
547    printf("Internal perl error: %s\n", perlerr);
548    fflush(stdout);
549    exit(1);
550  }
551
552  owl_global_complete_setup(&g);
553
554  owl_global_setup_default_filters(&g);
555
556  /* set the current view */
557  owl_function_debugmsg("startup: setting the current view");
558  owl_view_create(owl_global_get_current_view(&g), "main",
559                  owl_global_get_filter(&g, "all"),
560                  owl_global_get_style_by_name(&g, "default"));
561
562  /* execute the startup function in the configfile */
563  owl_function_debugmsg("startup: executing perl startup, if applicable");
564  perlout = owl_perlconfig_execute("BarnOwl::Hooks::_startup();");
565  g_free(perlout);
566
567  /* welcome message */
568  owl_function_debugmsg("startup: creating splash message");
569  char *welcome = g_strdup_printf(
570    "-----------------------------------------------------------------------\n"
571    "Welcome to BarnOwl version %s.\n"
572    "To see a quick introduction, type ':show quickstart'.                  \n"
573    "Press 'h' for on-line help.                                            \n"
574    "                                                                       \n"
575    "BarnOwl is free software. Type ':show license' for more                \n"
576    "information.                                                     ^ ^   \n"
577    "                                                                 OvO   \n"
578    "Please report any bugs or suggestions to bug-barnowl@mit.edu    (   )  \n"
579    "-----------------------------------------------------------------m-m---\n",
580    version);
581  owl_function_adminmsg("", welcome);
582  g_free(welcome);
583
584  owl_function_debugmsg("startup: setting context interactive");
585
586  owl_global_pop_context(&g);
587  owl_global_push_context(&g, OWL_CTX_INTERACTIVE|OWL_CTX_RECV, NULL, "recv", NULL);
588
589  /* process the startup file */
590  owl_function_debugmsg("startup: processing startup file");
591  owl_function_source(NULL);
592
593  owl_function_debugmsg("startup: set style for the view: %s", owl_global_get_default_style(&g));
594  s = owl_global_get_style_by_name(&g, owl_global_get_default_style(&g));
595  if(s)
596      owl_view_set_style(owl_global_get_current_view(&g), s);
597  else
598      owl_function_error("No such style: %s", owl_global_get_default_style(&g));
599
600  source = owl_window_redraw_source_new();
601  g_source_attach(source, NULL);
602  g_source_unref(source);
603
604  source = g_source_new(&owl_process_messages_funcs, sizeof(GSource));
605  g_source_attach(source, NULL);
606  g_source_unref(source);
607
608  owl_log_init();
609
610  owl_function_debugmsg("startup: entering main loop");
611  owl_select_run_loop();
612
613  /* Shut down everything. */
614  owl_zephyr_shutdown();
615  owl_signal_shutdown();
616  owl_shutdown_curses();
617  owl_log_shutdown();
618  return 0;
619}
Note: See TracBrowser for help on using the repository browser.