updates.
[silc.git] / apps / silc / silc.c
1 /*
2
3   silc.c
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   Copyright (C) 1997 - 2000 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /* $Id$ */
21
22 #include "clientincludes.h"
23 #include "version.h"
24
25 /* Static function prototypes */
26 static int silc_client_bad_keys(unsigned char key);
27 static void silc_client_clear_input(SilcClientInternal app);
28 static void silc_client_process_message(SilcClientInternal app);
29 static char *silc_client_parse_command(unsigned char *buffer);
30
31 void silc_client_create_main_window(SilcClientInternal app);
32
33 /* Static task callback prototypes */
34 SILC_TASK_CALLBACK(silc_client_update_clock);
35 SILC_TASK_CALLBACK(silc_client_run_commands);
36 SILC_TASK_CALLBACK(silc_client_process_key_press);
37
38 /* Long command line options */
39 static struct option long_opts[] = 
40 {
41   /* Generic options */
42   { "server", 1, NULL, 's' },
43   { "port", 1, NULL, 'p' },
44   { "nickname", 1, NULL, 'n' },
45   { "channel", 1, NULL, 'c' },
46   { "cipher", 1, NULL, 'r' },
47   { "public-key", 1, NULL, 'b' },
48   { "private-key", 1, NULL, 'k' },
49   { "config-file", 1, NULL, 'f' },
50   { "no-silcrc", 0, NULL, 'q' },
51   { "debug", 0, NULL, 'd' },
52   { "help", 0, NULL, 'h' },
53   { "version", 0, NULL, 'V' },
54   { "list-ciphers", 0, NULL, 1 },
55   { "list-hash-funcs", 0, NULL, 2 },
56   { "list-pkcs", 0, NULL, 3 },
57
58   /* Key management options */
59   { "create-key-pair", 0, NULL, 'C' },
60   { "pkcs", 1, NULL, 10 },
61   { "bits", 1, NULL, 11 },
62
63   { NULL, 0, NULL, 0 }
64 };
65
66 /* Command line option variables */
67 static char *opt_server = NULL;
68 static int opt_port = 0;
69 static char *opt_nickname = NULL;
70 static char *opt_channel = NULL;
71 static char *opt_cipher = NULL;
72 static char *opt_public_key = NULL;
73 static char *opt_private_key = NULL;
74 static char *opt_config_file = NULL;
75 static int opt_no_silcrc = FALSE;
76
77 static int opt_create_keypair = FALSE;
78 static char *opt_pkcs = NULL;
79 static int opt_bits = 0;
80
81 /* SILC Client operations */
82 extern SilcClientOperations ops;
83
84 /* Prints out the usage of silc client */
85
86 void usage()
87 {
88   printf("\
89 Usage: silc [options]\n\
90 \n\
91   Generic Options:\n\
92   -s, --server=HOST            Open connection to server HOST\n\
93   -p, --port=PORT              Set PORT as default port to connect\n\
94   -n, --nickname=STRING        Set default nickname on startup\n\
95   -c, --channel=STRING         Join channel on startup\n\
96   -r, --cipher=CIPHER          Use CIPHER as default cipher in SILC\n\
97   -b, --public-key=FILE        Public key used in SILC\n\
98   -k, --private-key=FILE       Private key used in SILC\n\
99   -f, --config-file=FILE       Alternate configuration file\n\
100   -q, --no-silcrc              Don't load ~/.silcrc on startup\n\
101   -d, --debug                  Enable debugging\n\
102   -h, --help                   Display this help message\n\
103   -V, --version                Display version\n\
104       --list-ciphers           List supported ciphers\n\
105       --list-hash-funcs        List supported hash functions\n\
106       --list-pkcs              List supported PKCS's\n\
107 \n\
108   Key Management Options:\n\
109   -C, --create-key-pair        Create new public key pair\n\
110       --pkcs=PKCS              Set the PKCS of the public key pair\n\
111       --bits=VALUE             Set length of the public key pair\n\
112 \n");
113 }
114
115 int main(int argc, char **argv)
116 {
117   int opt, option_index = 1;
118   int ret;
119   SilcClient silc = NULL;
120   SilcClientInternal app = NULL;
121
122   silc_debug = FALSE;
123
124   if (argc > 1) 
125     {
126       while ((opt = 
127               getopt_long(argc, argv,
128                           "s:p:n:c:b:k:f:qdhVC",
129                           long_opts, &option_index)) != EOF)
130         {
131           switch(opt) 
132             {
133               /* 
134                * Generic options
135                */
136             case 's':
137               if (optarg)
138                 opt_server = strdup(optarg);
139               break;
140             case 'p':
141               if (optarg)
142                 opt_port = atoi(optarg);
143               break;
144             case 'n':
145               if (optarg)
146                 opt_nickname = strdup(optarg);
147               break;
148             case 'c':
149               if (optarg)
150                 opt_channel = strdup(optarg);
151               break;
152             case 'r':
153               if (optarg)
154                 opt_cipher = strdup(optarg);
155               break;
156             case 'b':
157               if (optarg)
158                 opt_public_key = strdup(optarg);
159               break;
160             case 'k':
161               if (optarg)
162                 opt_private_key = strdup(optarg);
163               break;
164             case 'f':
165               if (optarg)
166                 opt_config_file = strdup(optarg);
167               break;
168             case 'q':
169               opt_no_silcrc = TRUE;
170               break;
171             case 'd':
172               silc_debug = TRUE;
173               break;
174             case 'h':
175               usage();
176               exit(0);
177               break;
178             case 'V':
179               printf("\
180 SILC Secure Internet Live Conferencing, version %s\n", 
181                      silc_version);
182               printf("\
183 (c) 1997 - 2000 Pekka Riikonen <priikone@poseidon.pspt.fi>\n");
184               exit(0);
185               break;
186             case 1:
187               silc_client_list_ciphers();
188               exit(0);
189               break;
190             case 2:
191               silc_client_list_hash_funcs();
192               exit(0);
193               break;
194             case 3:
195               silc_client_list_pkcs();
196               exit(0);
197               break;
198
199               /*
200                * Key management options
201                */
202             case 'C':
203               opt_create_keypair = TRUE;
204               break;
205             case 10:
206               if (optarg)
207                 opt_pkcs = strdup(optarg);
208               break;
209             case 11:
210               if (optarg)
211                 opt_bits = atoi(optarg);
212               break;
213
214             default:
215               exit(0);
216               break;
217             }
218         }
219     }
220
221   /* Init signals */
222   signal(SIGHUP, SIG_DFL);
223   signal(SIGTERM, SIG_DFL);
224   signal(SIGPIPE, SIG_IGN);
225   signal(SIGCHLD, SIG_DFL);
226   signal(SIGALRM, SIG_IGN);
227   signal(SIGQUIT, SIG_IGN);
228   signal(SIGSEGV, SIG_DFL);
229   signal(SIGBUS, SIG_DFL);
230   signal(SIGFPE, SIG_DFL);
231   //  signal(SIGINT, SIG_IGN);
232   
233 #ifdef SOCKS
234   /* Init SOCKS */
235   SOCKSinit(argv[0]);
236 #endif
237
238   if (opt_create_keypair == TRUE) {
239     /* Create new key pair and exit */
240     silc_client_create_key_pair(opt_pkcs, opt_bits, 
241                                 NULL, NULL, NULL, NULL, NULL);
242     exit(0);
243   }
244
245   /* Default configuration file */
246   if (!opt_config_file)
247     opt_config_file = strdup(SILC_CLIENT_CONFIG_FILE);
248
249   /* Allocate internal application context */
250   app = silc_calloc(1, sizeof(*app));
251
252   /* Allocate new client */
253   app->client = silc = silc_client_alloc(&ops, app);
254   if (!silc)
255     goto fail;
256
257   /* Read global configuration file. */
258   app->config = silc_client_config_alloc(opt_config_file);
259   if (app->config == NULL)
260     goto fail;
261
262   /* XXX Read local configuration file */
263
264   /* Check ~/.silc directory and public and private keys */
265   if (silc_client_check_silc_dir() == FALSE)
266     goto fail;
267
268   /* Get user information */
269   silc->username = silc_get_username();
270   silc->hostname = silc_net_localhost();
271   silc->realname = silc_get_real_name();
272
273   /* Register all configured ciphers, PKCS and hash functions. */
274   app->config->client = (void *)app;
275   silc_client_config_register_ciphers(app->config);
276   silc_client_config_register_pkcs(app->config);
277   silc_client_config_register_hashfuncs(app->config);
278   silc_client_config_register_hmacs(app->config);
279
280   /* Load public and private key */
281   if (silc_client_load_keys(silc) == FALSE)
282     goto fail;
283
284   /* Initialize the client. This initializes the client library and
285      sets everything ready for silc_client_run. */
286   ret = silc_client_init(silc);
287   if (ret == FALSE)
288     goto fail;
289
290   /* Register the main task that is used in client. This receives
291      the key pressings. */
292   silc_task_register(silc->io_queue, fileno(stdin), 
293                      silc_client_process_key_press,
294                      (void *)silc, 0, 0, 
295                      SILC_TASK_FD,
296                      SILC_TASK_PRI_NORMAL);
297
298   /* Register timeout task that updates clock every minute. */
299   silc_task_register(silc->timeout_queue, 0,
300                      silc_client_update_clock,
301                      (void *)silc, 
302                      silc_client_time_til_next_min(), 0,
303                      SILC_TASK_TIMEOUT,
304                      SILC_TASK_PRI_LOW);
305
306   if (app->config->commands) {
307     /* Run user configured commands with timeout */
308     silc_task_register(silc->timeout_queue, 0,
309                        silc_client_run_commands,
310                        (void *)silc, 0, 1,
311                        SILC_TASK_TIMEOUT,
312                        SILC_TASK_PRI_LOW);
313   }
314
315   /* Allocate the input buffer used to save typed characters */
316   app->input_buffer = silc_buffer_alloc(SILC_SCREEN_INPUT_WIN_SIZE);
317   silc_buffer_pull_tail(app->input_buffer, 
318                         SILC_BUFFER_END(app->input_buffer));
319
320   /* Initialize the screen */
321   silc_client_create_main_window(app);
322   silc_screen_print_coordinates(app->screen, 0);
323
324   /* Run the client. When this returns the application will be
325      terminated. */
326   silc_client_run(silc);
327
328   /* Stop the client. This probably has been done already but it
329      doesn't hurt to do it here again. */
330   silc_client_stop(silc);
331   silc_client_free(silc);
332   
333   exit(0);
334
335  fail:
336   if (opt_config_file)
337     silc_free(opt_config_file);
338   if (app->config)
339     silc_client_config_free(app->config);
340   if (silc)
341     silc_client_free(silc);
342   exit(1);
343 }
344
345 /* Creates the main window used in SILC client. This is called always
346    at the initialization of the client. If user wants to create more
347    than one windows a new windows are always created by calling 
348    silc_client_add_window. */
349
350 void silc_client_create_main_window(SilcClientInternal app)
351 {
352   void *screen;
353
354   SILC_LOG_DEBUG(("Creating main window"));
355
356   app->screen = silc_screen_init();
357   app->screen->input_buffer = app->input_buffer->data;
358   app->screen->u_stat_line.program_name = silc_name;
359   app->screen->u_stat_line.program_version = silc_version;
360
361   /* Create the actual screen */
362   screen = (void *)silc_screen_create_output_window(app->screen);
363   silc_screen_create_input_window(app->screen);
364   silc_screen_init_upper_status_line(app->screen);
365   silc_screen_init_output_status_line(app->screen);
366
367   app->screen->bottom_line->nickname = silc_get_username();
368   silc_screen_print_bottom_line(app->screen, 0);
369 }
370
371 /* The main task on SILC client. This processes the key pressings user
372    has made. */
373
374 SILC_TASK_CALLBACK(silc_client_process_key_press)
375 {
376   SilcClient client = (SilcClient)context;
377   SilcClientInternal app = (SilcClientInternal)client->application;
378   int c;
379
380   /* There is data pending in stdin, this gets it directly */
381   c = wgetch(app->screen->input_win);
382   if (silc_client_bad_keys(c))
383     return;
384
385   SILC_LOG_DEBUG(("Pressed key: %d", c));
386
387   switch(c) {
388     /* 
389      * Special character handling
390      */
391   case KEY_UP: 
392   case KEY_DOWN:
393     break;
394   case KEY_RIGHT:
395     /* Right arrow */
396     SILC_LOG_DEBUG(("RIGHT"));
397     silc_screen_input_cursor_right(app->screen);
398     break;
399   case KEY_LEFT:
400     /* Left arrow */
401     SILC_LOG_DEBUG(("LEFT"));
402     silc_screen_input_cursor_left(app->screen);
403     break;
404   case KEY_BACKSPACE:
405   case KEY_DC:
406   case '\177':
407   case '\b':
408     /* Backspace */
409     silc_screen_input_backspace(app->screen);
410     break;
411   case '\011':
412     /* Tabulator */
413     break;
414   case KEY_IC:
415     /* Insert switch. Turns on/off insert on input window */
416     silc_screen_input_insert(app->screen);
417     break;
418   case CTRL('j'):
419   case '\r':
420     /* Enter, Return. User pressed enter we are ready to
421        process the message. */
422     silc_client_process_message(app);
423     break;
424   case CTRL('l'):
425     /* Refresh screen, Ctrl^l */
426     silc_screen_refresh_all(app->screen);
427     break;
428   case CTRL('a'):
429   case KEY_HOME:
430 #ifdef KEY_BEG
431   case KEY_BEG:
432 #endif
433     /* Beginning, Home */
434     silc_screen_input_cursor_home(app->screen);
435     break;
436   case CTRL('e'):
437 #ifdef KEY_END
438   case KEY_END:
439 #endif
440   case KEY_LL:
441     /* End */
442     silc_screen_input_cursor_end(app->screen);
443     break;
444   case CTRL('g'):
445     /* Bell, Ctrl^g */
446     beep();
447     break;
448   case KEY_DL:
449   case CTRL('u'):
450     /* Delete line */
451     silc_client_clear_input(app);
452     break;
453   default:
454     /* 
455      * Other characters 
456      */
457     if (c < 32) {
458       /* Control codes are printed as reversed */
459       c = (c & 127) | 64;
460       wattron(app->screen->input_win, A_REVERSE);
461       silc_screen_input_print(app->screen, c);
462       wattroff(app->screen->input_win, A_REVERSE);
463     } else  {
464       /* Normal character */
465       silc_screen_input_print(app->screen, c);
466     }
467   }
468
469   silc_screen_print_coordinates(app->screen, 0);
470   silc_screen_refresh_win(app->screen->input_win);
471 }
472
473 static int silc_client_bad_keys(unsigned char key)
474 {
475   /* these are explained in curses.h */
476   switch(key) {
477   case KEY_SF:
478   case KEY_SR:
479   case KEY_NPAGE:
480   case KEY_PPAGE:
481   case KEY_PRINT:
482   case KEY_A1:
483   case KEY_A3:
484   case KEY_B2:
485   case KEY_C1:
486   case KEY_C3:
487 #ifdef KEY_UNDO
488   case KEY_UNDO:
489 #endif
490 #ifdef KEY_EXIT
491   case KEY_EXIT:
492 #endif
493   case '\v':           /* VT */
494   case '\E':           /* we ignore ESC */
495     return TRUE;
496   default: 
497     return FALSE; 
498   }
499 }
500
501 /* Clears input buffer */
502
503 static void silc_client_clear_input(SilcClientInternal app)
504 {
505   silc_buffer_clear(app->input_buffer);
506   silc_buffer_pull_tail(app->input_buffer,
507                         SILC_BUFFER_END(app->input_buffer));
508   silc_screen_input_reset(app->screen);
509 }
510
511 /* Processes messages user has typed on the screen. This either sends
512    a packet out to network or if command were written executes it. */
513
514 static void silc_client_process_message(SilcClientInternal app)
515 {
516   unsigned char *data;
517   unsigned int len;
518
519   SILC_LOG_DEBUG(("Start"));
520
521   data = app->input_buffer->data;
522   len = strlen(data);
523
524   if (data[0] == '/' && data[1] != ' ') {
525     /* Command */
526     unsigned int argc = 0;
527     unsigned char **argv, *tmpcmd;
528     unsigned int *argv_lens, *argv_types;
529     SilcClientCommand *cmd;
530     SilcClientCommandContext ctx;
531
532     /* Get the command */
533     tmpcmd = silc_client_parse_command(data);
534     cmd = silc_client_local_command_find(tmpcmd);
535     if (!cmd && (cmd = silc_client_command_find(tmpcmd)) == NULL) {
536       silc_say(app->client, app->current_win, "Invalid command: %s", tmpcmd);
537       silc_free(tmpcmd);
538       goto out;
539     }
540
541     /* Now parse all arguments */
542     silc_parse_command_line(data + 1, &argv, &argv_lens, 
543                             &argv_types, &argc, cmd->max_args);
544     silc_free(tmpcmd);
545
546     SILC_LOG_DEBUG(("Executing command: %s", cmd->name));
547
548     /* Allocate command context. This and its internals must be free'd 
549        by the command routine receiving it. */
550     ctx = silc_client_command_alloc();
551     ctx->client = app->client;
552     ctx->conn = app->conn;
553     ctx->command = cmd;
554     ctx->argc = argc;
555     ctx->argv = argv;
556     ctx->argv_lens = argv_lens;
557     ctx->argv_types = argv_types;
558
559     /* Execute command */
560     (*cmd->cb)(ctx);
561
562   } else {
563     /* Normal message to a channel */
564     if (len && app->conn && app->conn->current_channel &&
565         app->conn->current_channel->on_channel == TRUE) {
566       silc_print(app->client, "> %s", data);
567       silc_client_send_channel_message(app->client, 
568                                        app->conn,
569                                        app->conn->current_channel,
570                                        data, strlen(data), TRUE);
571     }
572   }
573
574  out:
575   /* Clear the input buffer */
576   silc_client_clear_input(app);
577 }
578
579 /* Returns the command fetched from user typed command line */
580
581 static char *silc_client_parse_command(unsigned char *buffer)
582 {
583   char *ret;
584   const char *cp = buffer;
585   int len;
586
587   len = strcspn(cp, " ");
588   ret = silc_to_upper((char *)++cp);
589   ret[len - 1] = 0;
590
591   return ret;
592 }
593
594 /* Updates clock on the screen every minute. */
595
596 SILC_TASK_CALLBACK(silc_client_update_clock)
597 {
598   SilcClient client = (SilcClient)context;
599   SilcClientInternal app = (SilcClientInternal)client->application;
600
601   /* Update the clock on the screen */
602   silc_screen_print_clock(app->screen);
603
604   /* Re-register this same task */
605   silc_task_register(qptr, 0, silc_client_update_clock, context, 
606                      silc_client_time_til_next_min(), 0,
607                      SILC_TASK_TIMEOUT,
608                      SILC_TASK_PRI_LOW);
609
610   silc_screen_refresh_win(app->screen->input_win);
611 }
612
613 /* Runs commands user configured in configuration file. This is
614    called when initializing client. */
615
616 SILC_TASK_CALLBACK(silc_client_run_commands)
617 {
618   SilcClient client = (SilcClient)context;
619   SilcClientInternal app = (SilcClientInternal)client->application;
620   SilcClientConfigSectionCommand *cs;
621
622   SILC_LOG_DEBUG(("Start"));
623
624   cs = app->config->commands;
625   while(cs) {
626     unsigned int argc = 0;
627     unsigned char **argv, *tmpcmd;
628     unsigned int *argv_lens, *argv_types;
629     SilcClientCommand *cmd;
630     SilcClientCommandContext ctx;
631
632     /* Get the command */
633     tmpcmd = silc_client_parse_command(cs->command);
634     cmd = silc_client_local_command_find(tmpcmd);
635     if (!cmd && (cmd = silc_client_command_find(tmpcmd)) == NULL) {
636       silc_say(client, app->conn, "Invalid command: %s", tmpcmd);
637       silc_free(tmpcmd);
638       continue;
639     }
640     
641     /* Now parse all arguments */
642     silc_parse_command_line(cs->command + 1, &argv, &argv_lens, 
643                             &argv_types, &argc, cmd->max_args);
644     silc_free(tmpcmd);
645
646     SILC_LOG_DEBUG(("Executing command: %s", cmd->name));
647
648     /* Allocate command context. This and its internals must be free'd 
649        by the command routine receiving it. */
650     ctx = silc_client_command_alloc();
651     ctx->client = client;
652     ctx->conn = app->conn;
653     ctx->command = cmd;
654     ctx->argc = argc;
655     ctx->argv = argv;
656     ctx->argv_lens = argv_lens;
657     ctx->argv_types = argv_types;
658
659     /* Execute command */
660     (*cmd->cb)(ctx);
661
662     cs = cs->next;
663   }
664 }