Improved signals support in scheduler.
[silc.git] / apps / silcd / silcd.c
1 /*
2
3   silcd.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2002 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  * Created: Wed Mar 19 00:17:12 1997
22  *
23  * This is the main program for the SILC daemon. This parses command
24  * line arguments and creates the server object.
25  */
26 /* $Id$ */
27
28 #include "serverincludes.h"
29 #include "server_internal.h"
30 #include "silcversion.h"
31
32 /* For now, we'll have this one server context global for this module. */
33 static SilcServer silcd;
34
35 static void silc_usage();
36 static char *silc_server_create_identifier();
37 static int
38 silc_server_create_key_pair(char *pkcs_name, int bits, char *path,
39                             char *identifier,
40                             SilcPublicKey *ret_pub_key,
41                             SilcPrivateKey *ret_prv_key);
42
43 /* Long command line options */
44 static struct option long_opts[] =
45 {
46   { "config-file", 1, NULL, 'f' },
47   { "debug", 1, NULL, 'd' },
48   { "help", 0, NULL, 'h' },
49   { "foreground", 0, NULL, 'F' },
50   { "version", 0, NULL,'V' },
51
52   /* Key management options */
53   { "create-key-pair", 1, NULL, 'C' },
54   { "pkcs", 1, NULL, 10 },
55   { "bits", 1, NULL, 11 },
56   { "identifier", 1, NULL, 12 },
57
58   { NULL, 0, NULL, 0 }
59 };
60
61 /* Command line option variables */
62 static bool opt_create_keypair = FALSE;
63 static char *opt_keypath = NULL;
64 static char *opt_pkcs = "rsa";
65 static char *opt_identifier = NULL;
66 static int opt_bits = 1024;
67
68 /* Prints out the usage of silc client */
69
70 static void silc_usage()
71 {
72   printf("\
73 Usage: silcd [options]\n\
74 \n\
75   Generic Options:\n\
76   -f  --config-file=FILE        Alternate configuration file\n\
77   -d  --debug=string            Enable debugging (Implies --foreground)\n\
78   -h  --help                    Display this message\n\
79   -F  --foreground              Dont fork\n\
80   -V  --version                 Display version\n\
81 \n\
82   Key Management Options:\n\
83   -C, --create-key-pair=PATH    Create new public key pair\n\
84       --pkcs=PKCS               Set the PKCS of the public key pair\n\
85       --bits=VALUE              Set length of the public key pair\n\
86       --identifier=IDENTIFIER   Public key identifier\n\
87 \n\
88       The public key identifier may be of the following format:\n\
89 \n\
90       UN=<username>, HN=<hostname or IP>, RN=<real name>, E=<email>,\n\
91       O=<organization>, C=<country>\n\
92 \n\
93       The UN and HN must be provided, the others are optional.  If the\n\
94       --identifier option is not used an identifier will be created for\n\
95       the public key automatically.\n\
96 \n\
97       Example identifier: \"UN=foobar, HN=foo.bar.com, RN=Foo T. Bar, \n\
98                            E=foo@bar.com, C=FI\"\n\
99 \n");
100   exit(0);
101 }
102
103 /* Dies if a *valid* pid file exists already */
104
105 static void silc_server_checkpid(SilcServer silcd)
106 {
107   if (silcd->config->server_info->pid_file) {
108     int oldpid;
109     char *buf;
110     SilcUInt32 buf_len;
111
112     SILC_LOG_DEBUG(("Checking for another silcd running"));
113     buf = silc_file_readfile(silcd->config->server_info->pid_file, &buf_len);
114     if (!buf)
115       return;
116     oldpid = atoi(buf);
117     silc_free(buf);
118     if (oldpid <= 0)
119       return;
120     kill(oldpid, SIGCHLD); /* this signal does nothing, check if alive */
121     if (errno != ESRCH) {
122       fprintf(stderr, "\nI detected another daemon running with the same pid file.\n");
123       fprintf(stderr, "Please change the config file, or erase the %s\n",
124         silcd->config->server_info->pid_file);
125       exit(1);
126     }
127   }
128 }
129
130 static void signal_handler(int sig)
131 {
132   /* Mark the signal to be caller after this signal is over. */
133   silc_schedule_signal_call(silcd->schedule, sig);
134 }
135
136 SILC_TASK_CALLBACK(got_hup)
137 {
138   /* First, reset all log files (they might have been deleted) */
139   silc_log_reset_all();
140   silc_log_flush_all();
141 }
142
143 SILC_TASK_CALLBACK(stop_server)
144 {
145   /* Stop scheduler, the program will stop eventually after noticing
146      that the scheduler is down. */
147   silc_schedule_stop(silcd->schedule); 
148 }
149
150 int main(int argc, char **argv)
151 {
152   int ret, opt, option_index;
153   char *config_file = NULL;
154   bool foreground = FALSE;
155   struct sigaction sa;
156
157   /* Parse command line arguments */
158   if (argc > 1) {
159     while ((opt = getopt_long(argc, argv, "cf:d:hFVC:",
160                               long_opts, &option_index)) != EOF) {
161       switch(opt)
162         {
163         case 'h':
164           silc_usage();
165           break;
166         case 'V':
167           printf("SILCd Secure Internet Live Conferencing daemon, "
168                  "version %s (base: SILC Toolkit %s)\n",
169                  silc_dist_version, silc_version);
170           printf("(c) 1997 - 2002 Pekka Riikonen "
171                  "<priikone@silcnet.org>\n");
172           exit(0);
173           break;
174         case 'd':
175 #ifdef SILC_DEBUG
176           silc_debug = TRUE;
177           silc_debug_hexdump = TRUE;
178           silc_log_set_debug_string(optarg);
179           foreground = TRUE;
180           silc_log_quick = TRUE;
181 #else
182           fprintf(stdout,
183                   "Run-time debugging is not enabled. To enable it recompile\n"
184                   "the server with --enable-debug configuration option.\n");
185 #endif
186           break;
187         case 'f':
188           config_file = strdup(optarg);
189           break;
190         case 'F':
191           foreground = TRUE;
192           break;
193
194           /*
195            * Key management options
196            */
197         case 'C':
198           opt_create_keypair = TRUE;
199           if (optarg)
200             opt_keypath = strdup(optarg);
201           break;
202         case 10:
203           if (optarg)
204             opt_pkcs = strdup(optarg);
205           break;
206         case 11:
207           if (optarg)
208             opt_bits = atoi(optarg);
209           break;
210         case 12:
211           if (optarg)
212             opt_identifier = strdup(optarg);
213           break;
214
215         default:
216           silc_usage();
217           break;
218         }
219     }
220   }
221
222   if (opt_create_keypair == TRUE) {
223     /* Create new key pair and exit */
224     silc_cipher_register_default();
225     silc_pkcs_register_default();
226     silc_hash_register_default();
227     silc_hmac_register_default();
228     silc_server_create_key_pair(opt_pkcs, opt_bits, opt_keypath,
229                                 opt_identifier, NULL, NULL);
230     exit(0);
231   }
232
233   /* Default configuration file */
234   if (!config_file)
235     config_file = strdup(SILC_SERVER_CONFIG_FILE);
236
237   /* Create SILC Server object */
238   ret = silc_server_alloc(&silcd);
239   if (ret == FALSE)
240     goto fail;
241
242   /* Read configuration files */
243   silcd->config = silc_server_config_alloc(config_file);
244   if (silcd->config == NULL)
245     goto fail;
246
247   /* Check for another silcd running */
248   silc_server_checkpid(silcd);
249
250   /* Initialize the server */
251   ret = silc_server_init(silcd);
252   if (ret == FALSE)
253     goto fail;
254
255   /* Ignore SIGPIPE */
256   sa.sa_handler = SIG_IGN;
257   sa.sa_flags = 0;
258   sigemptyset(&sa.sa_mask);
259   sigaction(SIGPIPE, &sa, NULL);
260   sa.sa_handler = signal_handler;
261   sigaction(SIGHUP, &sa, NULL);
262   sigaction(SIGTERM, &sa, NULL);
263   sigaction(SIGINT, &sa, NULL);
264   silc_schedule_signal_register(silcd->schedule, SIGHUP, got_hup, NULL);
265   silc_schedule_signal_register(silcd->schedule, SIGTERM, stop_server, NULL);
266   silc_schedule_signal_register(silcd->schedule, SIGINT, stop_server, NULL);
267
268   /* Before running the server, fork to background. */
269   if (!foreground)
270     silc_server_daemonise(silcd);
271
272   /* If set, write pid to file */
273   if (silcd->config->server_info->pid_file) {
274     char buf[10], *pidfile = silcd->config->server_info->pid_file;
275     unlink(pidfile);
276     snprintf(buf, sizeof(buf) - 1, "%d\n", getpid());
277     silc_file_writefile(pidfile, buf, strlen(buf));
278   }
279
280   /* Drop root. */
281   silc_server_drop(silcd);
282
283   /* Run the server. When this returns the server has been stopped
284      and we will exit. */
285   silc_server_run(silcd);
286   
287   /* Stop the server and free it. */
288   silc_server_stop(silcd);
289   silc_server_free(silcd);
290
291   /* Flush the logging system */
292   silc_log_flush_all();
293
294   exit(0);
295  fail:
296   exit(1);
297 }
298
299 /* Returns identifier string for public key generation. */
300
301 static char *silc_server_create_identifier()
302 {
303   char *username = NULL, *realname = NULL;
304   char hostname[256], email[256];
305   
306   /* Get realname */
307   realname = silc_get_real_name();
308
309   /* Get hostname */
310   memset(hostname, 0, sizeof(hostname));
311   gethostname(hostname, sizeof(hostname));
312
313   /* Get username (mandatory) */
314   username = silc_get_username();
315   if (!username)
316     return NULL;
317
318   /* Create default email address, whether it is right or not */
319   snprintf(email, sizeof(email), "%s@%s", username, hostname);
320
321   return silc_pkcs_encode_identifier(username, hostname, realname, email,
322                                      NULL, NULL);
323 }
324
325 /* Creates new public key and private key pair. This is used only
326    when user wants to create new key pair from command line. */
327
328 static int 
329 silc_server_create_key_pair(char *pkcs_name, int bits, char *path,
330                             char *identifier, 
331                             SilcPublicKey *ret_pub_key,
332                             SilcPrivateKey *ret_prv_key)
333 {
334   SilcPKCS pkcs;
335   SilcPublicKey pub_key;
336   SilcPrivateKey prv_key;
337   SilcRng rng;
338   unsigned char *key;
339   SilcUInt32 key_len;
340   char pkfile[256], prvfile[256];
341
342   if (!pkcs_name || !path)
343     return FALSE;
344
345   if (!silc_pkcs_is_supported(pkcs_name)) {
346     fprintf(stderr, "Unsupported PKCS `%s'", pkcs_name);
347     return FALSE;
348   }
349
350   if (!bits)
351     bits = 1024;
352
353   if (!identifier)
354     identifier = silc_server_create_identifier();
355
356   rng = silc_rng_alloc();
357   silc_rng_init(rng);
358   silc_rng_global_init(rng);
359
360   snprintf(pkfile, sizeof(pkfile) - 1, "%s%s", path,
361            SILC_SERVER_PUBLIC_KEY_NAME);
362   snprintf(prvfile, sizeof(prvfile) - 1, "%s%s", path,
363            SILC_SERVER_PRIVATE_KEY_NAME);
364
365   /* Generate keys */
366   silc_pkcs_alloc(pkcs_name, &pkcs);
367   silc_pkcs_generate_key(pkcs, bits, rng);
368
369   /* Save public key into file */
370   key = silc_pkcs_get_public_key(pkcs, &key_len);
371   pub_key = silc_pkcs_public_key_alloc(pkcs->pkcs->name, identifier,
372                                        key, key_len);
373   silc_pkcs_save_public_key(pkfile, pub_key, SILC_PKCS_FILE_PEM);
374   if (ret_pub_key)
375     *ret_pub_key = pub_key;
376   else
377     silc_pkcs_public_key_free(pub_key);
378
379   memset(key, 0, sizeof(key_len));
380   silc_free(key);
381
382   /* Save private key into file */
383   key = silc_pkcs_get_private_key(pkcs, &key_len);
384   prv_key = silc_pkcs_private_key_alloc(pkcs->pkcs->name, key, key_len);
385   silc_pkcs_save_private_key(prvfile, prv_key, NULL, SILC_PKCS_FILE_BIN);
386   if (ret_prv_key)
387     *ret_prv_key = prv_key;
388   else
389     silc_pkcs_private_key_free(prv_key);
390
391   printf("Public key has been saved into `%s'\n", pkfile);
392   printf("Private key has been saved into `%s'\n", prvfile);
393
394   memset(key, 0, sizeof(key_len));
395   silc_free(key);
396
397   silc_rng_free(rng);
398   silc_pkcs_free(pkcs);
399
400   return TRUE;
401 }