updates.
[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 "version.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_checkpid(SilcServer silcd)
106 {
107   if (silcd->config->pidfile && silcd->config->pidfile->pid_file) {
108     int oldpid;
109     char *buf;
110     uint32 buf_len;
111
112     SILC_LOG_DEBUG(("Checking for another silcd running"));
113     buf = silc_file_readfile(silcd->config->pidfile->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->pidfile->pid_file);
125       exit(1);
126     }
127   }
128 }
129
130 static void got_hup(int z)
131 {
132   /* First, reset all log files (they might have been deleted) */
133   silc_log_reset_all();
134   silc_log_flush_all();
135 }
136
137 static void stop_server(int z)
138 {
139   SILC_LOG_DEBUG(("Start"));
140
141   /* Flush log files */
142   silc_log_flush_all();
143
144   /* Gracefully stop the server */
145   /*  silc_server_stop(silcd); */
146   /* XXX do this for now since doing graceful exit now can remove
147      the scheduler underneath the server too early and crash it. */
148   exit(0);
149 }
150
151 int main(int argc, char **argv)
152 {
153   int ret, opt, option_index;
154   char *config_file = NULL;
155   bool foreground = FALSE;
156   struct sigaction sa;
157
158   /* Parse command line arguments */
159   if (argc > 1) {
160     while ((opt = getopt_long(argc, argv, "cf:d:hFVC:",
161                               long_opts, &option_index)) != EOF) {
162       switch(opt)
163         {
164         case 'h':
165           silc_usage();
166           break;
167         case 'V':
168           printf("SILCd Secure Internet Live Conferencing daemon, "
169                  "version %s (base: SILC Toolkit %s)\n",
170                  silc_dist_version, silc_version);
171           printf("(c) 1997 - 2001 Pekka Riikonen "
172                  "<priikone@silcnet.org>\n");
173           exit(0);
174           break;
175         case 'd':
176 #ifdef SILC_DEBUG
177           silc_debug = TRUE;
178           silc_debug_hexdump = TRUE;
179           silc_log_set_debug_string(optarg);
180           foreground = TRUE;
181           silc_log_quick = TRUE;
182 #else
183           fprintf(stdout,
184                   "Run-time debugging is not enabled. To enable it recompile\n"
185                   "the server with --enable-debug configuration option.\n");
186 #endif
187           break;
188         case 'f':
189           config_file = strdup(optarg);
190           break;
191         case 'F':
192           foreground = TRUE;
193           break;
194
195           /*
196            * Key management options
197            */
198         case 'C':
199           opt_create_keypair = TRUE;
200           if (optarg)
201             opt_keypath = strdup(optarg);
202           break;
203         case 10:
204           if (optarg)
205             opt_pkcs = strdup(optarg);
206           break;
207         case 11:
208           if (optarg)
209             opt_bits = atoi(optarg);
210           break;
211         case 12:
212           if (optarg)
213             opt_identifier = strdup(optarg);
214           break;
215
216         default:
217           silc_usage();
218           break;
219         }
220     }
221   }
222
223   if (opt_create_keypair == TRUE) {
224     /* Create new key pair and exit */
225     silc_cipher_register_default();
226     silc_pkcs_register_default();
227     silc_hash_register_default();
228     silc_hmac_register_default();
229     silc_server_create_key_pair(opt_pkcs, opt_bits, opt_keypath,
230                                 opt_identifier, NULL, NULL);
231     exit(0);
232   }
233
234   /* Default configuration file */
235   if (!config_file)
236     config_file = strdup(SILC_SERVER_CONFIG_FILE);
237
238   /* Create SILC Server object */
239   ret = silc_server_alloc(&silcd);
240   if (ret == FALSE)
241     goto fail;
242
243   /* Read configuration files */
244   silcd->config = silc_server_config_alloc(config_file);
245   if (silcd->config == NULL)
246     goto fail;
247
248   /* Check for another silcd running */
249   silc_checkpid(silcd);
250
251   /* Initialize the server */
252   ret = silc_server_init(silcd);
253   if (ret == FALSE)
254     goto fail;
255
256   /* Ignore SIGPIPE */
257   sa.sa_handler = SIG_IGN;
258   sa.sa_flags = 0;
259   sigemptyset(&sa.sa_mask);
260   sigaction(SIGPIPE, &sa, NULL);
261   sa.sa_handler = got_hup;
262   sigaction(SIGHUP, &sa, NULL);
263   sa.sa_handler = stop_server;
264   sigaction(SIGTERM, &sa, NULL);
265   sa.sa_handler = stop_server;
266   sigaction(SIGINT, &sa, 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->pidfile && silcd->config->pidfile->pid_file) {
274     char buf[10];
275     unlink(silcd->config->pidfile->pid_file);
276     snprintf(buf, sizeof(buf) - 1, "%d\n", getpid());
277     silc_file_writefile(silcd->config->pidfile->pid_file, 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   /* The server was stopped, free it now */
288   silc_server_free(silcd);
289
290   /* Flush the logging system */
291   silc_log_flush_all();
292
293   exit(0);
294  fail:
295   exit(1);
296 }
297
298 /* Returns identifier string for public key generation. */
299
300 static char *silc_server_create_identifier()
301 {
302   char *username = NULL, *realname = NULL;
303   char hostname[256], email[256];
304   
305   /* Get realname */
306   realname = silc_get_real_name();
307
308   /* Get hostname */
309   memset(hostname, 0, sizeof(hostname));
310   gethostname(hostname, sizeof(hostname));
311
312   /* Get username (mandatory) */
313   username = silc_get_username();
314   if (!username)
315     return NULL;
316
317   /* Create default email address, whether it is right or not */
318   snprintf(email, sizeof(email), "%s@%s", username, hostname);
319
320   return silc_pkcs_encode_identifier(username, hostname, realname, email,
321                                      NULL, NULL);
322 }
323
324 /* Creates new public key and private key pair. This is used only
325    when user wants to create new key pair from command line. */
326
327 static int 
328 silc_server_create_key_pair(char *pkcs_name, int bits, char *path,
329                             char *identifier, 
330                             SilcPublicKey *ret_pub_key,
331                             SilcPrivateKey *ret_prv_key)
332 {
333   SilcPKCS pkcs;
334   SilcPublicKey pub_key;
335   SilcPrivateKey prv_key;
336   SilcRng rng;
337   unsigned char *key;
338   uint32 key_len;
339   char pkfile[256], prvfile[256];
340
341   if (!pkcs_name || !path)
342     return FALSE;
343
344   if (!silc_pkcs_is_supported(pkcs_name)) {
345     fprintf(stderr, "Unsupported PKCS `%s'", pkcs_name);
346     return FALSE;
347   }
348
349   if (!bits)
350     bits = 1024;
351
352   if (!identifier)
353     identifier = silc_server_create_identifier();
354
355   rng = silc_rng_alloc();
356   silc_rng_init(rng);
357   silc_rng_global_init(rng);
358
359   snprintf(pkfile, sizeof(pkfile) - 1, "%s%s", path,
360            SILC_SERVER_PUBLIC_KEY_NAME);
361   snprintf(prvfile, sizeof(prvfile) - 1, "%s%s", path,
362            SILC_SERVER_PRIVATE_KEY_NAME);
363
364   /* Generate keys */
365   silc_pkcs_alloc(pkcs_name, &pkcs);
366   pkcs->pkcs->init(pkcs->context, bits, rng);
367
368   /* Save public key into file */
369   key = silc_pkcs_get_public_key(pkcs, &key_len);
370   pub_key = silc_pkcs_public_key_alloc(pkcs->pkcs->name, identifier,
371                                        key, key_len);
372   silc_pkcs_save_public_key(pkfile, pub_key, SILC_PKCS_FILE_PEM);
373   if (ret_pub_key)
374     *ret_pub_key = pub_key;
375   else
376     silc_pkcs_public_key_free(pub_key);
377
378   memset(key, 0, sizeof(key_len));
379   silc_free(key);
380
381   /* Save private key into file */
382   key = silc_pkcs_get_private_key(pkcs, &key_len);
383   prv_key = silc_pkcs_private_key_alloc(pkcs->pkcs->name, key, key_len);
384   silc_pkcs_save_private_key(prvfile, prv_key, NULL, SILC_PKCS_FILE_BIN);
385   if (ret_prv_key)
386     *ret_prv_key = prv_key;
387   else
388     silc_pkcs_private_key_free(prv_key);
389
390   printf("Public key has been saved into `%s'\n", pkfile);
391   printf("Private key has been saved into `%s'\n", prvfile);
392
393   memset(key, 0, sizeof(key_len));
394   silc_free(key);
395
396   silc_rng_free(rng);
397   silc_pkcs_free(pkcs);
398
399   return TRUE;
400 }