Created SILC Client Libary by moving stuff from silc/ directory.
[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->realname = silc_get_real_name();
271
272   /* Register all configured ciphers, PKCS and hash functions. */
273   app->config->client = (void *)app;
274   silc_client_config_register_ciphers(app->config);
275   silc_client_config_register_pkcs(app->config);
276   silc_client_config_register_hashfuncs(app->config);
277
278   /* Load public and private key */
279   if (silc_client_load_keys(silc) == FALSE)
280     goto fail;
281
282   /* Initialize the client. This initializes the client library and
283      sets everything ready for silc_client_run. */
284   ret = silc_client_init(silc);
285   if (ret == FALSE)
286     goto fail;
287
288   /* Register the main task that is used in client. This receives
289      the key pressings. */
290   silc_task_register(silc->io_queue, fileno(stdin), 
291                      silc_client_process_key_press,
292                      (void *)silc, 0, 0, 
293                      SILC_TASK_FD,
294                      SILC_TASK_PRI_NORMAL);
295
296   /* Register timeout task that updates clock every minute. */
297   silc_task_register(silc->timeout_queue, 0,
298                      silc_client_update_clock,
299                      (void *)silc, 
300                      silc_client_time_til_next_min(), 0,
301                      SILC_TASK_TIMEOUT,
302                      SILC_TASK_PRI_LOW);
303
304   if (app->config->commands) {
305     /* Run user configured commands with timeout */
306     silc_task_register(silc->timeout_queue, 0,
307                        silc_client_run_commands,
308                        (void *)silc, 0, 1,
309                        SILC_TASK_TIMEOUT,
310                        SILC_TASK_PRI_LOW);
311   }
312
313   /* Allocate the input buffer used to save typed characters */
314   app->input_buffer = silc_buffer_alloc(SILC_SCREEN_INPUT_WIN_SIZE);
315   silc_buffer_pull_tail(app->input_buffer, 
316                         SILC_BUFFER_END(app->input_buffer));
317
318   /* Initialize the screen */
319   silc_client_create_main_window(app);
320   silc_screen_print_coordinates(app->screen, 0);
321
322   /* Run the client. When this returns the application will be
323      terminated. */
324   silc_client_run(silc);
325
326   /* Stop the client. This probably has been done already but it
327      doesn't hurt to do it here again. */
328   silc_client_stop(silc);
329   silc_client_free(silc);
330   
331   exit(0);
332
333  fail:
334   if (opt_config_file)
335     silc_free(opt_config_file);
336   if (app->config)
337     silc_client_config_free(app->config);
338   if (silc)
339     silc_client_free(silc);
340   exit(1);
341 }
342
343 /* Creates the main window used in SILC client. This is called always
344    at the initialization of the client. If user wants to create more
345    than one windows a new windows are always created by calling 
346    silc_client_add_window. */
347
348 void silc_client_create_main_window(SilcClientInternal app)
349 {
350   void *screen;
351
352   SILC_LOG_DEBUG(("Creating main window"));
353
354   app->screen = silc_screen_init();
355   app->screen->input_buffer = app->input_buffer->data;
356   app->screen->u_stat_line.program_name = silc_name;
357   app->screen->u_stat_line.program_version = silc_version;
358
359   /* Create the actual screen */
360   screen = (void *)silc_screen_create_output_window(app->screen);
361   silc_screen_create_input_window(app->screen);
362   silc_screen_init_upper_status_line(app->screen);
363   silc_screen_init_output_status_line(app->screen);
364
365   app->screen->bottom_line->nickname = silc_get_username();
366   silc_screen_print_bottom_line(app->screen, 0);
367 }
368
369 /* The main task on SILC client. This processes the key pressings user
370    has made. */
371
372 SILC_TASK_CALLBACK(silc_client_process_key_press)
373 {
374   SilcClient client = (SilcClient)context;
375   SilcClientInternal app = (SilcClientInternal)client->application;
376   int c;
377
378   /* There is data pending in stdin, this gets it directly */
379   c = wgetch(app->screen->input_win);
380   if (silc_client_bad_keys(c))
381     return;
382
383   SILC_LOG_DEBUG(("Pressed key: %d", c));
384
385   switch(c) {
386     /* 
387      * Special character handling
388      */
389   case KEY_UP: 
390   case KEY_DOWN:
391     break;
392   case KEY_RIGHT:
393     /* Right arrow */
394     SILC_LOG_DEBUG(("RIGHT"));
395     silc_screen_input_cursor_right(app->screen);
396     break;
397   case KEY_LEFT:
398     /* Left arrow */
399     SILC_LOG_DEBUG(("LEFT"));
400     silc_screen_input_cursor_left(app->screen);
401     break;
402   case KEY_BACKSPACE:
403   case KEY_DC:
404   case '\177':
405   case '\b':
406     /* Backspace */
407     silc_screen_input_backspace(app->screen);
408     break;
409   case '\011':
410     /* Tabulator */
411     break;
412   case KEY_IC:
413     /* Insert switch. Turns on/off insert on input window */
414     silc_screen_input_insert(app->screen);
415     break;
416   case CTRL('j'):
417   case '\r':
418     /* Enter, Return. User pressed enter we are ready to
419        process the message. */
420     silc_client_process_message(app);
421     break;
422   case CTRL('l'):
423     /* Refresh screen, Ctrl^l */
424     silc_screen_refresh_all(app->screen);
425     break;
426   case CTRL('a'):
427   case KEY_HOME:
428   case KEY_BEG:
429     /* Beginning, Home */
430     silc_screen_input_cursor_home(app->screen);
431     break;
432   case CTRL('e'):
433   case KEY_END:
434     /* End */
435     silc_screen_input_cursor_end(app->screen);
436     break;
437   case KEY_LL:
438     /* End */
439     break;
440   case CTRL('g'):
441     /* Bell, Ctrl^g */
442     beep();
443     break;
444   case KEY_DL:
445   case CTRL('u'):
446     /* Delete line */
447     silc_client_clear_input(app);
448     break;
449   default:
450     /* 
451      * Other characters 
452      */
453     if (c < 32) {
454       /* Control codes are printed as reversed */
455       c = (c & 127) | 64;
456       wattron(app->screen->input_win, A_REVERSE);
457       silc_screen_input_print(app->screen, c);
458       wattroff(app->screen->input_win, A_REVERSE);
459     } else  {
460       /* Normal character */
461       silc_screen_input_print(app->screen, c);
462     }
463   }
464
465   silc_screen_print_coordinates(app->screen, 0);
466   silc_screen_refresh_win(app->screen->input_win);
467 }
468
469 static int silc_client_bad_keys(unsigned char key)
470 {
471   /* these are explained in curses.h */
472   switch(key) {
473   case KEY_SF:
474   case KEY_SR:
475   case KEY_NPAGE:
476   case KEY_PPAGE:
477   case KEY_PRINT:
478   case KEY_A1:
479   case KEY_A3:
480   case KEY_B2:
481   case KEY_C1:
482   case KEY_C3:
483   case KEY_UNDO:
484   case KEY_EXIT:
485   case '\v':           /* VT */
486   case '\E':           /* we ignore ESC */
487     return TRUE;
488   default: 
489     return FALSE; 
490   }
491 }
492
493 /* Clears input buffer */
494
495 static void silc_client_clear_input(SilcClientInternal app)
496 {
497   silc_buffer_clear(app->input_buffer);
498   silc_buffer_pull_tail(app->input_buffer,
499                         SILC_BUFFER_END(app->input_buffer));
500   silc_screen_input_reset(app->screen);
501 }
502
503 /* Processes messages user has typed on the screen. This either sends
504    a packet out to network or if command were written executes it. */
505
506 static void silc_client_process_message(SilcClientInternal app)
507 {
508   unsigned char *data;
509   unsigned int len;
510
511   SILC_LOG_DEBUG(("Start"));
512
513   data = app->input_buffer->data;
514   len = strlen(data);
515
516   if (data[0] == '/' && data[1] != ' ') {
517     /* Command */
518     unsigned int argc = 0;
519     unsigned char **argv, *tmpcmd;
520     unsigned int *argv_lens, *argv_types;
521     SilcClientCommand *cmd;
522     SilcClientCommandContext ctx;
523
524     /* Get the command */
525     tmpcmd = silc_client_parse_command(data);
526     cmd = silc_client_local_command_find(tmpcmd);
527     if (!cmd && (cmd = silc_client_command_find(tmpcmd)) == NULL) {
528       silc_say(app->client, app->current_win, "Invalid command: %s", tmpcmd);
529       silc_free(tmpcmd);
530       goto out;
531     }
532
533     /* Now parse all arguments */
534     silc_parse_command_line(data + 1, &argv, &argv_lens, 
535                             &argv_types, &argc, cmd->max_args);
536     silc_free(tmpcmd);
537
538     SILC_LOG_DEBUG(("Executing command: %s", cmd->name));
539
540     /* Allocate command context. This and its internals must be free'd 
541        by the command routine receiving it. */
542     ctx = silc_calloc(1, sizeof(*ctx));
543     ctx->client = app->client;
544     ctx->conn = app->conn;
545     ctx->command = cmd;
546     ctx->argc = argc;
547     ctx->argv = argv;
548     ctx->argv_lens = argv_lens;
549     ctx->argv_types = argv_types;
550
551     /* Execute command */
552     (*cmd->cb)(ctx);
553
554   } else {
555     /* Normal message to a channel */
556     if (len && app->conn->current_channel &&
557         app->conn->current_channel->on_channel == TRUE) {
558       silc_print(app->client, "> %s", data);
559       silc_client_packet_send_to_channel(app->client, 
560                                          app->conn->sock,
561                                          app->conn->current_channel,
562                                          data, strlen(data), TRUE);
563     }
564   }
565
566  out:
567   /* Clear the input buffer */
568   silc_client_clear_input(app);
569 }
570
571 /* Returns the command fetched from user typed command line */
572
573 static char *silc_client_parse_command(unsigned char *buffer)
574 {
575   char *ret;
576   const char *cp = buffer;
577   int len;
578
579   len = strcspn(cp, " ");
580   ret = silc_to_upper((char *)++cp);
581   ret[len - 1] = 0;
582
583   return ret;
584 }
585
586 /* Updates clock on the screen every minute. */
587
588 SILC_TASK_CALLBACK(silc_client_update_clock)
589 {
590   SilcClient client = (SilcClient)context;
591   SilcClientInternal app = (SilcClientInternal)client->application;
592
593   /* Update the clock on the screen */
594   silc_screen_print_clock(app->screen);
595
596   /* Re-register this same task */
597   silc_task_register(qptr, 0, silc_client_update_clock, context, 
598                      silc_client_time_til_next_min(), 0,
599                      SILC_TASK_TIMEOUT,
600                      SILC_TASK_PRI_LOW);
601
602   silc_screen_refresh_win(app->screen->input_win);
603 }
604
605 /* Runs commands user configured in configuration file. This is
606    called when initializing client. */
607
608 SILC_TASK_CALLBACK(silc_client_run_commands)
609 {
610   SilcClient client = (SilcClient)context;
611   SilcClientInternal app = (SilcClientInternal)client->application;
612   SilcClientConfigSectionCommand *cs;
613
614   SILC_LOG_DEBUG(("Start"));
615
616   cs = app->config->commands;
617   while(cs) {
618     unsigned int argc = 0;
619     unsigned char **argv, *tmpcmd;
620     unsigned int *argv_lens, *argv_types;
621     SilcClientCommand *cmd;
622     SilcClientCommandContext ctx;
623
624     /* Get the command */
625     tmpcmd = silc_client_parse_command(cs->command);
626     cmd = silc_client_local_command_find(tmpcmd);
627     if (!cmd && (cmd = silc_client_command_find(tmpcmd)) == NULL) {
628       silc_say(client, app->conn, "Invalid command: %s", tmpcmd);
629       silc_free(tmpcmd);
630       continue;
631     }
632     
633     /* Now parse all arguments */
634     silc_parse_command_line(cs->command + 1, &argv, &argv_lens, 
635                             &argv_types, &argc, cmd->max_args);
636     silc_free(tmpcmd);
637
638     SILC_LOG_DEBUG(("Executing command: %s", cmd->name));
639
640     /* Allocate command context. This and its internals must be free'd 
641        by the command routine receiving it. */
642     ctx = silc_calloc(1, sizeof(*ctx));
643     ctx->client = client;
644     ctx->conn = app->conn;
645     ctx->command = cmd;
646     ctx->argc = argc;
647     ctx->argv = argv;
648     ctx->argv_lens = argv_lens;
649     ctx->argv_types = argv_types;
650
651     /* Execute command */
652     (*cmd->cb)(ctx);
653
654     cs = cs->next;
655   }
656 }