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