updates.
[silc.git] / apps / irssi / src / silc / core / silc-core.c
1 /*
2
3   silc-core.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2001 - 2006 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
21 #include "module.h"
22 #include "chat-protocols.h"
23 #include "args.h"
24
25 #include "chatnets.h"
26 #include "servers-setup.h"
27 #include "channels-setup.h"
28 #include "silc-servers.h"
29 #include "silc-channels.h"
30 #include "silc-queries.h"
31 #include "silc-nicklist.h"
32 #include "silc-chatnets.h"
33 #include "silc-cmdqueue.h"
34
35 #include "signals.h"
36 #include "levels.h"
37 #include "settings.h"
38 #include "fe-common/core/printtext.h"
39 #include "fe-common/core/fe-channels.h"
40 #include "fe-common/core/keyboard.h"
41 #include "fe-common/silc/module-formats.h"
42
43 /* Command line option variables */
44 static char *opt_pkcs = NULL;
45 static int opt_bits = 0;
46
47 static int idletag = -1;
48
49 /* SILC Client */
50 SilcClient silc_client = NULL;
51 extern SilcClientOperations ops;
52
53 /* Our keypair */
54 SilcPublicKey irssi_pubkey = NULL;
55 SilcPrivateKey irssi_privkey = NULL;
56
57 char *opt_nickname = NULL;
58 char *opt_hostname = NULL;
59
60 /* Default hash function */
61 SilcHash sha1hash = NULL;
62
63 void silc_expandos_init(void);
64 void silc_expandos_deinit(void);
65
66 void silc_lag_init(void);
67 void silc_lag_deinit(void);
68
69 static int my_silc_scheduler(void)
70 {
71   silc_client_run_one(silc_client);
72   return 1;
73 }
74
75 static CHATNET_REC *create_chatnet(void)
76 {
77   return g_malloc0(sizeof(CHATNET_REC));
78 }
79
80 static SERVER_SETUP_REC *create_server_setup(void)
81 {
82   return g_malloc0(sizeof(SERVER_SETUP_REC));
83 }
84
85 static CHANNEL_SETUP_REC *create_channel_setup(void)
86 {
87   return g_malloc0(sizeof(CHANNEL_SETUP_REC));
88 }
89
90 static SERVER_CONNECT_REC *create_server_connect(void)
91 {
92   return g_malloc0(sizeof(SILC_SERVER_CONNECT_REC));
93 }
94
95 static void destroy_server_connect(SERVER_CONNECT_REC *conn)
96 {
97
98 }
99
100 /* Checks user information and saves them to the config file it they
101    do not exist there already. */
102
103 static void silc_init_userinfo(void)
104 {
105   const char *set, *nick, *user_name, *str;
106   char *tmp;
107
108   /* check if nick/username/realname wasn't read from setup.. */
109   set = settings_get_str("real_name");
110   if (set == NULL || *set == '\0') {
111     str = g_getenv("SILCNAME");
112     if (!str)
113       str = g_getenv("IRCNAME");
114     settings_set_str("real_name",
115                      str != NULL ? str : silc_get_real_name());
116   }
117
118   /* Check that real name is UTF-8 encoded */
119   set = settings_get_str("real_name");
120   if (!silc_utf8_valid(set, strlen(set))) {
121     int len = silc_utf8_encoded_len(set, strlen(set), SILC_STRING_LOCALE);
122     tmp = silc_calloc(len, sizeof(*tmp));
123     if (tmp) {
124       silc_utf8_encode(set, strlen(set), SILC_STRING_LOCALE, tmp, len);
125       settings_set_str("real_name", tmp);
126       silc_free(tmp);
127     }
128   }
129
130   /* username */
131   user_name = settings_get_str("user_name");
132   if (user_name == NULL || *user_name == '\0') {
133     str = g_getenv("SILCUSER");
134     if (!str)
135       str = g_getenv("IRCUSER");
136     settings_set_str("user_name",
137                      str != NULL ? str : silc_get_username());
138
139     user_name = settings_get_str("user_name");
140   }
141
142   /* nick */
143   nick = settings_get_str("nick");
144   if (nick == NULL || *nick == '\0') {
145     str = g_getenv("SILCNICK");
146     if (!str)
147       str = g_getenv("IRCNICK");
148     settings_set_str("nick", str != NULL ? str : user_name);
149
150     nick = settings_get_str("nick");
151   }
152
153   /* alternate nick */
154   set = settings_get_str("alternate_nick");
155   if (set == NULL || *set == '\0') {
156     tmp = g_strconcat(nick, "_", NULL);
157     settings_set_str("alternate_nick", tmp);
158     g_free(tmp);
159   }
160
161   /* host name */
162   set = settings_get_str("hostname");
163   if (set == NULL || *set == '\0') {
164     str = g_getenv("SILCHOST");
165     if (!str)
166       str = g_getenv("IRCHOST");
167     if (str != NULL)
168       settings_set_str("hostname", str);
169   }
170 }
171
172 #ifdef SILC_DEBUG
173 static bool i_debug;
174 static bool silc_irssi_debug_print(char *file, char *function, int line,
175                                    char *message, void *context)
176 {
177   printtext(NULL, NULL, MSGLEVEL_CLIENTCRAP,
178             "DEBUG: %s:%d: %s", function, line, message);
179   return TRUE;
180 }
181 #endif
182
183 static void sig_setup_changed(void)
184 {
185 #ifdef SILC_DEBUG
186   bool debug = settings_get_bool("debug");
187   if (debug) {
188     const char *debug_string = settings_get_str("debug_string");
189     i_debug = TRUE;
190     silc_log_debug(TRUE);
191     if (strlen(debug_string))
192       silc_log_set_debug_string(debug_string);
193     silc_log_set_debug_callbacks(silc_irssi_debug_print, NULL, NULL, NULL);
194     return;
195   }
196   if (i_debug)
197     silc_log_debug(FALSE);
198 #endif
199 }
200
201 /* Log callbacks */
202
203 static bool silc_log_misc(SilcLogType type, char *message, void *context)
204 {
205   printtext(NULL, NULL, MSGLEVEL_CLIENTCRAP, "%s: %s",
206             (type == SILC_LOG_INFO ? "[Info]" :
207              type == SILC_LOG_WARNING ? "[Warning]" : "[Error]"), message);
208   return TRUE;
209 }
210
211 static bool silc_log_stderr(SilcLogType type, char *message, void *context)
212 {
213   fprintf(stderr, "%s: %s\n",
214           (type == SILC_LOG_INFO ? "[Info]" :
215            type == SILC_LOG_WARNING ? "[Warning]" : "[Error]"), message);
216   return TRUE;
217 }
218
219 static void silc_register_cipher(SilcClient client, const char *cipher)
220 {
221   int i;
222
223   if (cipher) {
224     for (i = 0; silc_default_ciphers[i].name; i++)
225       if (!strcmp(silc_default_ciphers[i].name, cipher)) {
226         silc_cipher_register(&(silc_default_ciphers[i]));
227         break;
228       }
229
230     if (!silc_cipher_is_supported(cipher)) {
231       SILC_LOG_ERROR(("Unknown cipher `%s'", cipher));
232       exit(1);
233     }
234   }
235
236   /* Register other defaults */
237   silc_cipher_register_default();
238 }
239
240 static void silc_register_hash(SilcClient client, const char *hash)
241 {
242   int i;
243
244   if (hash) {
245     for (i = 0; silc_default_hash[i].name; i++)
246       if (!strcmp(silc_default_hash[i].name, hash)) {
247         silc_hash_register(&(silc_default_hash[i]));
248         break;
249       }
250
251     if (!silc_hash_is_supported(hash)) {
252       SILC_LOG_ERROR(("Unknown hash function `%s'", hash));
253       exit(1);
254     }
255   }
256
257   /* Register other defaults */
258   silc_hash_register_default();
259 }
260
261 static void silc_register_hmac(SilcClient client, const char *hmac)
262 {
263   int i;
264
265   if (hmac) {
266     for (i = 0; silc_default_hmacs[i].name; i++)
267       if (!strcmp(silc_default_hmacs[i].name, hmac)) {
268         silc_hmac_register(&(silc_default_hmacs[i]));
269         break;
270       }
271
272     if (!silc_hmac_is_supported(hmac)) {
273       SILC_LOG_ERROR(("Unknown HMAC `%s'", hmac));
274       exit(1);
275     }
276   }
277
278   /* Register other defaults */
279   silc_hmac_register_default();
280 }
281
282 /* Finalize init. Init finish signal calls this. */
283
284 void silc_opt_callback(poptContext con,
285                        enum poptCallbackReason reason,
286                        const struct poptOption *opt,
287                        const char *arg, void *data)
288 {
289   if (strcmp(opt->longName, "nick") == 0) {
290     g_free(opt_nickname);
291     opt_nickname = g_strdup(arg);
292   }
293
294   if (strcmp(opt->longName, "hostname") == 0) {
295     g_free(opt_hostname);
296     opt_hostname = g_strdup(arg);
297   }
298
299   if (strcmp(opt->longName, "list-ciphers") == 0) {
300     silc_cipher_register_default();
301     silc_client_list_ciphers();
302     exit(0);
303   }
304
305   if (strcmp(opt->longName, "list-hash-funcs") == 0) {
306     silc_hash_register_default();
307     silc_client_list_hash_funcs();
308     exit(0);
309   }
310
311   if (strcmp(opt->longName, "list-hmacs") == 0) {
312     silc_hmac_register_default();
313     silc_client_list_hmacs();
314     exit(0);
315   }
316
317   if (strcmp(opt->longName, "list-pkcs") == 0) {
318     silc_pkcs_register_default();
319     silc_client_list_pkcs();
320     exit(0);
321   }
322
323   if (strcmp(opt->longName, "debug") == 0) {
324     silc_log_debug(TRUE);
325     silc_log_debug_hexdump(TRUE);
326     silc_log_set_debug_string(arg);
327 #ifndef SILC_DEBUG
328     fprintf(stdout,
329             "Run-time debugging is not enabled. To enable it recompile\n"
330             "the client with --enable-debug configuration option.\n");
331     sleep(1);
332 #endif
333   }
334
335   if (strcmp(opt->longName, "create-key-pair") == 0) {
336     /* Create new key pair and exit */
337     silc_cipher_register_default();
338     silc_pkcs_register_default();
339     silc_hash_register_default();
340     silc_hmac_register_default();
341     silc_create_key_pair(opt_pkcs, opt_bits, NULL, NULL,
342                          NULL, NULL, NULL, NULL, TRUE);
343     exit(0);
344   }
345
346   if (strcmp(opt->longName, "passphrase-change") == 0) {
347     /* Change the passphrase of the private key file */
348     silc_cipher_register_default();
349     silc_pkcs_register_default();
350     silc_hash_register_default();
351     silc_hmac_register_default();
352     silc_change_private_key_passphrase(arg, NULL, NULL);
353     exit(0);
354   }
355
356   if (strcmp(opt->longName, "show-key") == 0) {
357     /* Dump the key */
358     silc_cipher_register_default();
359     silc_pkcs_register_default();
360     silc_hash_register_default();
361     silc_hmac_register_default();
362     silc_show_public_key_file((char *)arg);
363     exit(0);
364   }
365 }
366
367 /* Called to indicate the client library has stopped. */
368
369 static void
370 silc_stopped(SilcClient client, void *context)
371 {
372   SILC_LOG_DEBUG(("Client library has stopped"));
373   if (idletag != -1)
374     g_source_remove(idletag);
375 }
376
377 static void sig_gui_quit(SILC_SERVER_REC *server, const char *msg)
378 {
379   silc_client_stop(silc_client, silc_stopped, NULL);
380 }
381
382 /* Called to indicate the client library is running. */
383
384 static void
385 silc_running(SilcClient client, void *context)
386 {
387   SILC_LOG_DEBUG(("Client library is running"));
388 }
389
390 static void sig_init_finished(void)
391 {
392   /* Check ~/.silc directory and public and private keys */
393   if (!silc_client_check_silc_dir()) {
394     sleep(1);
395     exit(1);
396     return;
397   }
398
399   /* Load public and private key */
400   if (!silc_client_load_keys(silc_client)) {
401     sleep(1);
402     exit(1);
403     return;
404   }
405
406   /* Initialize the SILC client */
407   if (!silc_client_init(silc_client, settings_get_str("user_name"),
408                         opt_hostname ? opt_hostname : silc_net_localhost(),
409                         settings_get_str("real_name"), silc_running, NULL)) {
410     sleep(1);
411     exit(1);
412     return;
413   }
414
415   silc_log_set_callback(SILC_LOG_INFO, silc_log_misc, NULL);
416   silc_log_set_callback(SILC_LOG_WARNING, silc_log_misc, NULL);
417   silc_log_set_callback(SILC_LOG_ERROR, silc_log_misc, NULL);
418   silc_log_set_callback(SILC_LOG_FATAL, silc_log_misc, NULL);
419
420   silc_hash_alloc("sha1", &sha1hash);
421
422   /* register SILC scheduler */
423   idletag = g_timeout_add(5, (GSourceFunc) my_silc_scheduler, NULL);
424 }
425
426 /* Init SILC. Called from src/fe-text/silc.c */
427
428 void silc_core_init(void)
429 {
430   static struct poptOption silc_options[] = {
431     { NULL, '\0', POPT_ARG_CALLBACK, (void *)&silc_opt_callback, '\0', NULL },
432     { "list-ciphers", 0, POPT_ARG_NONE, NULL, 0,
433       "List supported ciphers", NULL },
434     { "list-hash-funcs", 0, POPT_ARG_NONE, NULL, 0,
435       "List supported hash functions", NULL },
436     { "list-hmacs", 0, POPT_ARG_NONE, NULL, 0,
437       "List supported HMACs", NULL },
438     { "list-pkcs", 0, POPT_ARG_NONE, NULL, 0,
439       "List supported PKCSs", NULL },
440 #ifdef SILC_DEBUG
441     { "debug", 'd', POPT_ARG_STRING, NULL, 0,
442       "Enable debugging", "STRING" },
443 #endif /* SILC_DEBUG */
444     { "create-key-pair", 'C', POPT_ARG_NONE, NULL, 0,
445       "Create new public key pair", NULL },
446     { "pkcs", 0, POPT_ARG_STRING, &opt_pkcs, 0,
447       "Set the PKCS of the public key pair (-C)", "PKCS" },
448     { "bits", 0, POPT_ARG_INT, &opt_bits, 0,
449       "Set the length of the public key pair (-C)", "VALUE" },
450     { "passphrase-change", 'P', POPT_ARG_STRING, NULL, 0,
451       "Change the passphrase of private key file", "FILE" },
452     { "show-key", 'S', POPT_ARG_STRING, NULL, 0,
453       "Show the contents of the public key", "FILE" },
454     { NULL, '\0', 0, NULL }
455   };
456
457   CHAT_PROTOCOL_REC *rec;
458   SilcClientParams params;
459   const char *def_cipher, *def_hash, *def_hmac;
460
461   args_register(silc_options);
462
463   /* Settings */
464   settings_add_bool("server", "skip_motd", FALSE);
465   settings_add_str("server", "alternate_nick", NULL);
466   settings_add_bool("server", "use_auto_addr", FALSE);
467   settings_add_str("server", "auto_bind_ip", "");
468   settings_add_str("server", "auto_public_ip", "");
469   settings_add_int("server", "auto_bind_port", 0);
470   settings_add_str("server", "crypto_default_cipher", SILC_DEFAULT_CIPHER);
471   settings_add_str("server", "crypto_default_hash", SILC_DEFAULT_HASH);
472   settings_add_str("server", "crypto_default_hmac", SILC_DEFAULT_HMAC);
473   settings_add_int("server", "key_exchange_timeout_secs", 120);
474   settings_add_int("server", "key_exchange_rekey_secs", 3600);
475   settings_add_bool("server", "key_exchange_rekey_pfs", FALSE);
476   settings_add_int("server", "connauth_request_secs", 2);
477   settings_add_int("server", "heartbeat", 300);
478   settings_add_bool("server", "ignore_message_signatures", FALSE);
479   settings_add_str("server", "session_filename", "session.$chatnet");
480   settings_add_bool("server", "sign_channel_messages", FALSE);
481   settings_add_bool("server", "sign_private_messages", FALSE);
482
483   /* Requested Attributes settings */
484   settings_add_bool("silc", "attr_allow", TRUE);
485   settings_add_str("silc", "attr_vcard", "");
486   settings_add_str("silc", "attr_services", "");
487   settings_add_str("silc", "attr_status_mood", "NORMAL");
488   settings_add_str("silc", "attr_status_text", "");
489   settings_add_str("silc", "attr_status_message", NULL);
490   settings_add_str("silc", "attr_preferred_language", "");
491   settings_add_str("silc", "attr_preferred_contact", "CHAT");
492   settings_add_bool("silc", "attr_timezone", TRUE);
493   settings_add_str("silc", "attr_geolocation", "");
494   settings_add_str("silc", "attr_device_info", NULL);
495   settings_add_str("silc", "attr_public_keys", "");
496
497 #ifdef SILC_DEBUG
498   settings_add_bool("debug", "debug", FALSE);
499   settings_add_str("debug", "debug_string", "");
500 #endif
501
502   signal_add("setup changed", (SIGNAL_FUNC) sig_setup_changed);
503   signal_add("irssi init finished", (SIGNAL_FUNC) sig_init_finished);
504   signal_add("gui exit", (SIGNAL_FUNC) sig_gui_quit);
505
506   silc_init_userinfo();
507
508   silc_log_set_callback(SILC_LOG_INFO, silc_log_stderr, NULL);
509   silc_log_set_callback(SILC_LOG_WARNING, silc_log_stderr, NULL);
510   silc_log_set_callback(SILC_LOG_ERROR, silc_log_stderr, NULL);
511   silc_log_set_callback(SILC_LOG_FATAL, silc_log_stderr, NULL);
512
513   /* Initialize client parameters */
514   memset(&params, 0, sizeof(params));
515   strcat(params.nickname_format, "%n@%h%a");
516   params.connauth_request_secs = settings_get_int("connauth_request_secs");
517
518   /* Allocate SILC client */
519   silc_client = silc_client_alloc(&ops, &params, NULL, silc_version_string);
520
521   /* Get the ciphers and stuff from config file */
522   def_cipher = settings_get_str("crypto_default_cipher");
523   def_hash = settings_get_str("crypto_default_hash");
524   def_hmac = settings_get_str("crypto_default_hmac");
525   silc_register_cipher(silc_client, def_cipher);
526   silc_register_hash(silc_client, def_hash);
527   silc_register_hmac(silc_client, def_hmac);
528   silc_pkcs_register_default();
529
530   /* Register SILC to the irssi */
531   rec = g_new0(CHAT_PROTOCOL_REC, 1);
532   rec->name = "SILC";
533   rec->fullname = "Secure Internet Live Conferencing";
534   rec->chatnet = "silcnet";
535   rec->create_chatnet = create_chatnet;
536   rec->create_server_setup = create_server_setup;
537   rec->create_channel_setup = create_channel_setup;
538   rec->create_server_connect = create_server_connect;
539   rec->destroy_server_connect = destroy_server_connect;
540   rec->server_init_connect = silc_server_init_connect;
541   rec->server_connect = silc_server_connect;
542   rec->channel_create = (CHANNEL_REC *(*) (SERVER_REC *, const char *,
543                                            const char *, int))
544     silc_channel_create;
545   rec->query_create = (QUERY_REC *(*) (const char *, const char *, int))
546     silc_query_create;
547
548   chat_protocol_register(rec);
549   g_free(rec);
550
551   silc_queue_init();
552   silc_server_init();
553   silc_channels_init();
554   silc_queries_init();
555   silc_expandos_init();
556   silc_lag_init();
557   silc_chatnets_init();
558
559   module_register("silc", "core");
560 }
561
562 /* Deinit SILC. Called from src/fe-text/silc.c */
563
564 void silc_core_deinit(void)
565 {
566   if (idletag != -1)
567     g_source_remove(idletag);
568
569   signal_emit("chat protocol deinit", 1,
570         chat_protocol_find("SILC"));
571   signal_remove("setup changed", (SIGNAL_FUNC) sig_setup_changed);
572   signal_remove("irssi init finished", (SIGNAL_FUNC) sig_init_finished);
573   signal_remove("gui exit", (SIGNAL_FUNC) sig_gui_quit);
574
575   silc_queue_deinit();
576   silc_server_deinit();
577   silc_channels_deinit();
578   silc_queries_deinit();
579   silc_expandos_deinit();
580   silc_lag_deinit();
581   silc_chatnets_deinit();
582
583   chat_protocol_unregister("SILC");
584
585   silc_pkcs_private_key_free(irssi_privkey);
586   silc_pkcs_public_key_free(irssi_pubkey);
587   silc_client_free(silc_client);
588 }