Added SilcIDListData structure and added it to ClientEntry and
[silc.git] / apps / silcd / server.c
1 /*
2
3   server.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 /*
21  * This is the actual SILC server than handles everything relating to
22  * servicing the SILC connections. This is also a SILC router as a router 
23  * is also normal server.
24  */
25 /* $Id$ */
26
27 #include "serverincludes.h"
28 #include "server_internal.h"
29
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_router);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_timeout_remote);
41
42 extern char *server_version;
43
44 /* Allocates a new SILC server object. This has to be done before the server
45    can be used. After allocation one must call silc_server_init to initialize
46    the server. The new allocated server object is returned to the new_server
47    argument. */
48
49 int silc_server_alloc(SilcServer *new_server)
50 {
51   SilcServer server;
52
53   SILC_LOG_DEBUG(("Allocating new server object"));
54
55   server = silc_calloc(1, sizeof(*server));
56   server->server_type = SILC_SERVER;
57   server->standalone = TRUE;
58   server->local_list = silc_calloc(1, sizeof(*server->local_list));
59   server->global_list = silc_calloc(1, sizeof(*server->global_list));
60 #ifdef SILC_SIM
61   server->sim = silc_dlist_init();
62 #endif
63
64   *new_server = server;
65
66   return TRUE;
67 }
68
69 /* Free's the SILC server object. This is called at the very end before
70    the program ends. */
71
72 void silc_server_free(SilcServer server)
73 {
74   if (server) {
75     SilcSimContext *sim;
76
77     if (server->local_list)
78       silc_free(server->local_list);
79     if (server->global_list)
80       silc_free(server->global_list);
81     if (server->rng)
82       silc_rng_free(server->rng);
83
84     while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
85       silc_dlist_del(server->sim, sim);
86       silc_sim_free(sim);
87     }
88     silc_dlist_uninit(server->sim);
89
90     if (server->params)
91       silc_free(server->params);
92
93     silc_math_primegen_uninit(); /* XXX */
94     silc_free(server);
95   }
96 }
97
98 /* Initializes the entire SILC server. This is called always before running
99    the server. This is called only once at the initialization of the program.
100    This binds the server to its listenning port. After this function returns 
101    one should call silc_server_run to start the server. This returns TRUE 
102    when everything is ok to run the server. Configuration file must be
103    read and parsed before calling this. */
104
105 int silc_server_init(SilcServer server)
106 {
107   int *sock = NULL, sock_count = 0, i;
108   SilcServerID *id;
109   SilcServerEntry id_entry;
110
111   SILC_LOG_DEBUG(("Initializing server"));
112   assert(server);
113   assert(server->config);
114
115   /* XXX After server is made as Silc Server Library this can be given
116      as argument, for now this is hard coded */
117   server->params = silc_calloc(1, sizeof(*server->params));
118   server->params->retry_count = SILC_SERVER_RETRY_COUNT;
119   server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
120   server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
121   server->params->retry_keep_trying = FALSE;
122   server->params->protocol_timeout = 60;
123
124   /* Set log files where log message should be saved. */
125   server->config->server = server;
126   silc_config_server_setlogfiles(server->config);
127  
128   /* Register all configured ciphers, PKCS and hash functions. */
129   silc_config_server_register_ciphers(server->config);
130   silc_config_server_register_pkcs(server->config);
131   silc_config_server_register_hashfuncs(server->config);
132
133   /* Initialize random number generator for the server. */
134   server->rng = silc_rng_alloc();
135   silc_rng_init(server->rng);
136   silc_math_primegen_init(); /* XXX */
137
138   /* Initialize hash functions for server to use */
139   silc_hash_alloc("md5", &server->md5hash);
140   silc_hash_alloc("sha1", &server->sha1hash);
141
142   /* Initialize none cipher */
143   silc_cipher_alloc("none", &server->none_cipher);
144
145   /* XXXXX Generate RSA key pair */
146   {
147     unsigned char *public_key;
148     unsigned char *private_key;
149     unsigned int pk_len, prv_len;
150     struct stat st;
151
152     if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
153
154       if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
155         SILC_LOG_ERROR(("Could not create RSA key pair"));
156         goto err0;
157       }
158       
159       if (server->pkcs->pkcs->init(server->pkcs->context, 
160                                    1024, server->rng) == FALSE) {
161         SILC_LOG_ERROR(("Could not generate RSA key pair"));
162         goto err0;
163       }
164       
165       public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
166                                                       &pk_len);
167       private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
168                                                         &prv_len);
169       
170       SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
171       SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
172       
173       server->public_key = 
174         silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
175                                    public_key, pk_len);
176       server->private_key = 
177         silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
178       
179       /* XXX Save keys */
180       silc_pkcs_save_public_key("pubkey.pub", server->public_key,
181                                 SILC_PKCS_FILE_PEM);
182       silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
183                                  SILC_PKCS_FILE_BIN);
184
185       memset(public_key, 0, pk_len);
186       memset(private_key, 0, prv_len);
187       silc_free(public_key);
188       silc_free(private_key);
189     } else {
190       silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
191                                 SILC_PKCS_FILE_PEM);
192       silc_pkcs_load_private_key("privkey.prv", &server->private_key,
193                                  SILC_PKCS_FILE_BIN);
194     }
195   }
196
197   /* Create a listening server. Note that our server can listen on
198      multiple ports. All listeners are created here and now. */
199   /* XXX Still check this whether to use server_info or listen_port. */
200   sock_count = 0;
201   while(server->config->listen_port) {
202     int tmp;
203
204     tmp = silc_net_create_server(server->config->listen_port->port,
205                                  server->config->listen_port->host);
206     if (tmp < 0)
207       goto err0;
208
209     sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
210     sock[sock_count] = tmp;
211     server->config->listen_port = server->config->listen_port->next;
212     sock_count++;
213   }
214
215   /* Initialize ID caches */
216   server->local_list->clients = silc_idcache_alloc(0);
217   server->local_list->servers = silc_idcache_alloc(0);
218   server->local_list->channels = silc_idcache_alloc(0);
219
220   /* XXX for now these are allocated for normal server as well as these
221      hold some global information that the server has fetched from its
222      router. For router these are used as they are supposed to be used
223      on router. The XXX can be remoevd later if this is the way we are
224      going to do this in the normal server as well. */
225   server->global_list->clients = silc_idcache_alloc(0);
226   server->global_list->servers = silc_idcache_alloc(0);
227   server->global_list->channels = silc_idcache_alloc(0);
228
229   /* Allocate the entire socket list that is used in server. Eventually 
230      all connections will have entry in this table (it is a table of 
231      pointers to the actual object that is allocated individually 
232      later). */
233   server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
234                                 sizeof(*server->sockets));
235
236   for (i = 0; i < sock_count; i++) {
237     SilcSocketConnection newsocket = NULL;
238
239     /* Set socket to non-blocking mode */
240     silc_net_set_socket_nonblock(sock[i]);
241     server->sock = sock[i];
242     
243     /* Create a Server ID for the server. */
244     silc_id_create_server_id(sock[i], server->rng, &id);
245     if (!id) {
246       goto err0;
247     }
248     
249     server->id = id;
250     server->id_type = SILC_ID_SERVER;
251     server->server_name = server->config->server_info->server_name;
252
253     /* Add ourselves to the server list. We don't have a router yet 
254        beacuse we haven't established a route yet. It will be done later. 
255        For now, NULL is sent as router. This allocates new entry to
256        the ID list. */
257     id_entry = 
258       silc_idlist_add_server(server->local_list,
259                              server->config->server_info->server_name,
260                              server->server_type, server->id, NULL, NULL);
261     if (!id_entry) {
262       SILC_LOG_ERROR(("Could not add ourselves to cache"));
263       goto err0;
264     }
265     
266     /* Add ourselves also to the socket table. The entry allocated above
267        is sent as argument for fast referencing in the future. */
268     silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry, 
269                       &newsocket);
270     if (!newsocket)
271       goto err0;
272
273     server->sockets[sock[i]] = newsocket;
274
275     /* Put the allocated socket pointer also to the entry allocated above 
276        for fast back-referencing to the socket list. */
277     id_entry->connection = (void *)server->sockets[sock[i]];
278     server->id_entry = id_entry;
279   }
280
281   /* Register the task queues. In SILC we have by default three task queues. 
282      One task queue for non-timeout tasks which perform different kind of 
283      I/O on file descriptors, timeout task queue for timeout tasks, and,
284      generic non-timeout task queue whose tasks apply to all connections. */
285   silc_task_queue_alloc(&server->io_queue, TRUE);
286   if (!server->io_queue) {
287     goto err0;
288   }
289   silc_task_queue_alloc(&server->timeout_queue, TRUE);
290   if (!server->timeout_queue) {
291     goto err1;
292   }
293   silc_task_queue_alloc(&server->generic_queue, TRUE);
294   if (!server->generic_queue) {
295     goto err1;
296   }
297
298   /* Register protocols */
299   silc_server_protocols_register();
300
301   /* Initialize the scheduler */
302   silc_schedule_init(&server->io_queue, &server->timeout_queue, 
303                      &server->generic_queue, 
304                      SILC_SERVER_MAX_CONNECTIONS);
305   
306   /* Add the first task to the queue. This is task that is executed by
307      timeout. It expires as soon as the caller calls silc_server_run. This
308      task performs authentication protocol and key exchange with our
309      primary router. */
310   silc_task_register(server->timeout_queue, sock[0], 
311                      silc_server_connect_to_router,
312                      (void *)server, 0, 1,
313                      SILC_TASK_TIMEOUT,
314                      SILC_TASK_PRI_NORMAL);
315
316   /* Add listener task to the queue. This task receives new connections to the 
317      server. This task remains on the queue until the end of the program. */
318   silc_task_register(server->io_queue, sock[0],
319                      silc_server_accept_new_connection,
320                      (void *)server, 0, 0, 
321                      SILC_TASK_FD,
322                      SILC_TASK_PRI_NORMAL);
323   server->listenning = TRUE;
324
325   /* If server connections has been configured then we must be router as
326      normal server cannot have server connections, only router connections. */
327   if (server->config->servers)
328     server->server_type = SILC_ROUTER;
329
330   SILC_LOG_DEBUG(("Server initialized"));
331
332   /* We are done here, return succesfully */
333   return TRUE;
334
335   silc_task_queue_free(server->timeout_queue);
336  err1:
337   silc_task_queue_free(server->io_queue);
338  err0:
339   for (i = 0; i < sock_count; i++)
340     silc_net_close_server(sock[i]);
341
342   return FALSE;
343 }
344
345 /* Stops the SILC server. This function is used to shutdown the server. 
346    This is usually called after the scheduler has returned. After stopping 
347    the server one should call silc_server_free. */
348
349 void silc_server_stop(SilcServer server)
350 {
351   SILC_LOG_DEBUG(("Stopping server"));
352
353   /* Stop the scheduler, although it might be already stopped. This
354      doesn't hurt anyone. This removes all the tasks and task queues,
355      as well. */
356   silc_schedule_stop();
357   silc_schedule_uninit();
358
359   silc_server_protocols_unregister();
360
361   SILC_LOG_DEBUG(("Server stopped"));
362 }
363
364 /* The heart of the server. This runs the scheduler thus runs the server. */
365
366 void silc_server_run(SilcServer server)
367 {
368   SILC_LOG_DEBUG(("Running server"));
369
370   /* Start the scheduler, the heart of the SILC server. When this returns
371      the program will be terminated. */
372   silc_schedule();
373 }
374
375 /* Timeout callback that will be called to retry connecting to remote
376    router. This is used by both normal and router server. This will wait
377    before retrying the connecting. The timeout is generated by exponential
378    backoff algorithm. */
379
380 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
381 {
382   SilcServerConnection sconn = (SilcServerConnection)context;
383   SilcServer server = sconn->server;
384
385   SILC_LOG_INFO(("Retrying connecting to a router"));
386
387   /* Calculate next timeout */
388   if (sconn->retry_count >= 1) {
389     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
390     if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
391       sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
392   } else {
393     sconn->retry_timeout = server->params->retry_interval_min;
394   }
395   sconn->retry_count++;
396   sconn->retry_timeout = sconn->retry_timeout +
397     silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
398
399   /* If we've reached max retry count, give up. */
400   if (sconn->retry_count > server->params->retry_count && 
401       server->params->retry_keep_trying == FALSE) {
402     SILC_LOG_ERROR(("Could not connect to router, giving up"));
403     return;
404   }
405
406   /* Wait one before retrying */
407   silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
408                      context, sconn->retry_timeout, 
409                      server->params->retry_interval_min_usec,
410                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
411 }
412
413 /* Generic routine to use connect to a router. */
414
415 SILC_TASK_CALLBACK(silc_server_connect_router)
416 {    
417   SilcServerConnection sconn = (SilcServerConnection)context;
418   SilcServer server = sconn->server;
419   SilcSocketConnection newsocket;
420   SilcProtocol protocol;
421   SilcServerKEInternalContext *proto_ctx;
422   int sock;
423
424   /* Connect to remote host */
425   sock = silc_net_create_connection(sconn->remote_port, 
426                                     sconn->remote_host);
427   if (sock < 0) {
428     SILC_LOG_ERROR(("Could not connect to router"));
429     silc_task_register(server->timeout_queue, fd, 
430                        silc_server_connect_to_router_retry,
431                        context, 0, 1, SILC_TASK_TIMEOUT, 
432                        SILC_TASK_PRI_NORMAL);
433     return;
434   }
435
436   /* Set socket options */
437   silc_net_set_socket_nonblock(sock);
438   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
439
440   /* Create socket connection for the connection. Even though we
441      know that we are connecting to a router we will mark the socket
442      to be unknown connection until we have executed authentication
443      protocol. */
444   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
445   server->sockets[sock] = newsocket;
446   newsocket->hostname = sconn->remote_host;
447   newsocket->port = sconn->remote_port;
448   sconn->sock = newsocket;
449
450   /* Allocate internal protocol context. This is sent as context
451      to the protocol. */
452   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
453   proto_ctx->server = (void *)server;
454   proto_ctx->context = (void *)sconn;
455   proto_ctx->sock = newsocket;
456   proto_ctx->rng = server->rng;
457   proto_ctx->responder = FALSE;
458       
459   /* Perform key exchange protocol. silc_server_connect_to_router_second
460      will be called after the protocol is finished. */
461   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
462                       &protocol, proto_ctx,
463                       silc_server_connect_to_router_second);
464   newsocket->protocol = protocol;
465       
466   /* Register a timeout task that will be executed if the protocol
467      is not executed within set limit. */
468   proto_ctx->timeout_task = 
469     silc_task_register(server->timeout_queue, sock, 
470                        silc_server_timeout_remote,
471                        server, server->params->protocol_timeout,
472                        server->params->protocol_timeout_usec,
473                        SILC_TASK_TIMEOUT,
474                        SILC_TASK_PRI_LOW);
475
476   /* Register the connection for network input and output. This sets
477      that scheduler will listen for incoming packets for this connection 
478      and sets that outgoing packets may be sent to this connection as 
479      well. However, this doesn't set the scheduler for outgoing traffic,
480      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
481      later when outgoing data is available. */
482   context = (void *)server;
483   SILC_REGISTER_CONNECTION_FOR_IO(sock);
484   
485   /* Run the protocol */
486   protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
487 }
488   
489 /* This function connects to our primary router or if we are a router this
490    establishes all our primary routes. This is called at the start of the
491    server to do authentication and key exchange with our router - called
492    from schedule. */
493
494 SILC_TASK_CALLBACK(silc_server_connect_to_router)
495 {
496   SilcServer server = (SilcServer)context;
497   SilcServerConnection sconn;
498
499   SILC_LOG_DEBUG(("Connecting to router(s)"));
500
501   /* If we are normal SILC server we need to connect to our cell's
502      router. */
503   if (server->server_type == SILC_SERVER) {
504     SILC_LOG_DEBUG(("We are normal server"));
505
506     /* Create connection to the router, if configured. */
507     if (server->config->routers) {
508
509       /* Allocate connection object for hold connection specific stuff. */
510       sconn = silc_calloc(1, sizeof(*sconn));
511       sconn->server = server;
512       sconn->remote_host = server->config->routers->host;
513       sconn->remote_port = server->config->routers->port;
514
515       silc_task_register(server->timeout_queue, fd, 
516                          silc_server_connect_router,
517                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
518                          SILC_TASK_PRI_NORMAL);
519       return;
520     }
521   }
522
523   /* If we are a SILC router we need to establish all of our primary
524      routes. */
525   if (server->server_type == SILC_ROUTER) {
526     SilcConfigServerSectionServerConnection *ptr;
527
528     SILC_LOG_DEBUG(("We are router"));
529
530     /* Create the connections to all our routes */
531     ptr = server->config->routers;
532     while (ptr) {
533
534       SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
535                       ptr->initiator ? "Initiator" : "Responder",
536                       ptr->host, ptr->port));
537
538       if (ptr->initiator) {
539         /* Allocate connection object for hold connection specific stuff. */
540         sconn = silc_calloc(1, sizeof(*sconn));
541         sconn->server = server;
542         sconn->remote_host = ptr->host;
543         sconn->remote_port = ptr->port;
544
545         silc_task_register(server->timeout_queue, fd, 
546                            silc_server_connect_router,
547                            (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
548                            SILC_TASK_PRI_NORMAL);
549       }
550
551       if (!ptr->next)
552         return;
553
554       ptr = ptr->next;
555     }
556   }
557
558   SILC_LOG_DEBUG(("No router(s), server will be standalone"));
559   
560   /* There wasn't a configured router, we will continue but we don't
561      have a connection to outside world.  We will be standalone server. */
562   server->standalone = TRUE;
563 }
564
565 /* Second part of connecting to router(s). Key exchange protocol has been
566    executed and now we will execute authentication protocol. */
567
568 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
569 {
570   SilcProtocol protocol = (SilcProtocol)context;
571   SilcServerKEInternalContext *ctx = 
572     (SilcServerKEInternalContext *)protocol->context;
573   SilcServer server = (SilcServer)ctx->server;
574   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
575   SilcSocketConnection sock = NULL;
576   SilcServerConnAuthInternalContext *proto_ctx;
577
578   SILC_LOG_DEBUG(("Start"));
579
580   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
581     /* Error occured during protocol */
582     silc_protocol_free(protocol);
583     if (ctx->packet)
584       silc_buffer_free(ctx->packet);
585     if (ctx->ske)
586       silc_ske_free(ctx->ske);
587     if (ctx->dest_id)
588       silc_free(ctx->dest_id);
589     silc_free(ctx);
590     sock->protocol = NULL;
591     silc_server_disconnect_remote(server, sock, "Server closed connection: "
592                                   "Key exchange failed");
593     return;
594   }
595   
596   /* Allocate internal context for the authentication protocol. This
597      is sent as context for the protocol. */
598   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
599   proto_ctx->server = (void *)server;
600   proto_ctx->context = (void *)sconn;
601   proto_ctx->sock = sock = server->sockets[fd];
602   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
603   proto_ctx->dest_id_type = ctx->dest_id_type;
604   proto_ctx->dest_id = ctx->dest_id;
605
606   /* Resolve the authentication method used in this connection */
607   proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
608   if (server->config->routers) {
609     SilcConfigServerSectionServerConnection *conn = NULL;
610
611     /* Check if we find a match from user configured connections */
612     conn = silc_config_server_find_router_conn(server->config,
613                                                sock->hostname,
614                                                sock->port);
615     if (conn) {
616       /* Match found. Use the configured authentication method */
617       proto_ctx->auth_meth = conn->auth_meth;
618       if (conn->auth_data) {
619         proto_ctx->auth_data = strdup(conn->auth_data);
620         proto_ctx->auth_data_len = strlen(conn->auth_data);
621       }
622     } else {
623       /* No match found. */
624       /* XXX */
625     }
626   } else {
627     /* XXX */
628   }
629
630   /* Free old protocol as it is finished now */
631   silc_protocol_free(protocol);
632   if (ctx->packet)
633     silc_buffer_free(ctx->packet);
634   silc_free(ctx);
635   sock->protocol = NULL;
636
637   /* Allocate the authentication protocol. This is allocated here
638      but we won't start it yet. We will be receiving party of this
639      protocol thus we will wait that connecting party will make
640      their first move. */
641   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
642                       &sock->protocol, proto_ctx, 
643                       silc_server_connect_to_router_final);
644
645   /* Register timeout task. If the protocol is not executed inside
646      this timelimit the connection will be terminated. Currently
647      this is 15 seconds and is hard coded limit (XXX). */
648   proto_ctx->timeout_task = 
649     silc_task_register(server->timeout_queue, sock->sock, 
650                        silc_server_timeout_remote,
651                        (void *)server, 15, 0,
652                        SILC_TASK_TIMEOUT,
653                        SILC_TASK_PRI_LOW);
654
655   /* Run the protocol */
656   sock->protocol->execute(server->timeout_queue, 0, 
657                           sock->protocol, sock->sock, 0, 0);
658 }
659
660 /* Finalizes the connection to router. Registers a server task to the
661    queue so that we can accept new connections. */
662
663 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
664 {
665   SilcProtocol protocol = (SilcProtocol)context;
666   SilcServerConnAuthInternalContext *ctx = 
667     (SilcServerConnAuthInternalContext *)protocol->context;
668   SilcServer server = (SilcServer)ctx->server;
669   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
670   SilcSocketConnection sock = ctx->sock;
671   SilcServerEntry id_entry;
672   SilcBuffer packet;
673   unsigned char *id_string;
674
675   SILC_LOG_DEBUG(("Start"));
676
677   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
678     /* Error occured during protocol */
679     if (ctx->dest_id)
680       silc_free(ctx->dest_id);
681     silc_server_disconnect_remote(server, sock, "Server closed connection: "
682                                   "Authentication failed");
683     goto out;
684   }
685
686   /* Add a task to the queue. This task receives new connections to the 
687      server. This task remains on the queue until the end of the program. */
688   if (!server->listenning) {
689     silc_task_register(server->io_queue, server->sock, 
690                        silc_server_accept_new_connection,
691                        (void *)server, 0, 0, 
692                        SILC_TASK_FD,
693                        SILC_TASK_PRI_NORMAL);
694     server->listenning = TRUE;
695   }
696
697   /* Send NEW_SERVER packet to the router. We will become registered
698      to the SILC network after sending this packet. */
699   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
700   packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN + 
701                              strlen(server->server_name));
702   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
703   silc_buffer_format(packet,
704                      SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
705                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
706                      SILC_STR_UI_SHORT(strlen(server->server_name)),
707                      SILC_STR_UI_XNSTRING(server->server_name,
708                                           strlen(server->server_name)),
709                      SILC_STR_END);
710
711   /* Send the packet */
712   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
713                           packet->data, packet->len, TRUE);
714   silc_buffer_free(packet);
715   silc_free(id_string);
716
717   SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
718
719   /* Add the connected router to local server list */
720   server->standalone = FALSE;
721   id_entry = silc_idlist_add_server(server->local_list, 
722                                     sock->hostname ? sock->hostname : sock->ip,
723                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
724   if (!id_entry) {
725     if (ctx->dest_id)
726       silc_free(ctx->dest_id);
727     silc_server_disconnect_remote(server, sock, "Server closed connection: "
728                                   "Authentication failed");
729     goto out;
730   }
731
732   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
733   silc_free(sock->user_data);
734   sock->user_data = (void *)id_entry;
735   sock->type = SILC_SOCKET_TYPE_ROUTER;
736   server->id_entry->router = id_entry;
737
738  out:
739   /* Free the temporary connection data context */
740   if (sconn)
741     silc_free(sconn);
742
743   /* Free the protocol object */
744   silc_protocol_free(protocol);
745   if (ctx->packet)
746     silc_buffer_free(ctx->packet);
747   if (ctx->ske)
748     silc_ske_free(ctx->ske);
749   silc_free(ctx);
750   sock->protocol = NULL;
751 }
752
753 /* Accepts new connections to the server. Accepting new connections are
754    done in three parts to make it async. */
755
756 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
757 {
758   SilcServer server = (SilcServer)context;
759   SilcSocketConnection newsocket;
760   SilcServerKEInternalContext *proto_ctx;
761   int sock;
762
763   SILC_LOG_DEBUG(("Accepting new connection"));
764
765   sock = silc_net_accept_connection(server->sock);
766   if (sock < 0) {
767     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
768     return;
769   }
770
771   /* Check max connections */
772   if (sock > SILC_SERVER_MAX_CONNECTIONS) {
773     if (server->config->redirect) {
774       /* XXX Redirecting connection to somewhere else now?? */
775       /*silc_server_send_notify("Server is full, trying to redirect..."); */
776     } else {
777       SILC_LOG_ERROR(("Refusing connection, server is full"));
778     }
779     return;
780   }
781
782   /* Set socket options */
783   silc_net_set_socket_nonblock(sock);
784   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
785
786   /* We don't create a ID yet, since we don't know what type of connection
787      this is yet. But, we do add the connection to the socket table. */
788   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
789   server->sockets[sock] = newsocket;
790
791   /* XXX This MUST be done async as this will block the entire server
792      process. Either we have to do our own resolver stuff or in the future
793      we can use threads. */
794   /* Perform mandatory name and address lookups for the remote host. */
795   silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
796   if (!newsocket->ip || !newsocket->hostname) {
797     SILC_LOG_DEBUG(("IP lookup/DNS lookup failed"));
798     SILC_LOG_ERROR(("IP lookup/DNS lookup failed"));
799     return;
800   }
801
802   SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
803                  newsocket->ip));
804
805   /* Allocate internal context for key exchange protocol. This is
806      sent as context for the protocol. */
807   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
808   proto_ctx->server = context;
809   proto_ctx->sock = newsocket;
810   proto_ctx->rng = server->rng;
811   proto_ctx->responder = TRUE;
812
813   /* Prepare the connection for key exchange protocol. We allocate the
814      protocol but will not start it yet. The connector will be the
815      initiator of the protocol thus we will wait for initiation from 
816      there before we start the protocol. */
817   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
818                       &newsocket->protocol, proto_ctx, 
819                       silc_server_accept_new_connection_second);
820
821   /* Register a timeout task that will be executed if the connector
822      will not start the key exchange protocol within 60 seconds. For
823      now, this is a hard coded limit. After 60 secs the connection will
824      be closed if the key exchange protocol has not been started. */
825   proto_ctx->timeout_task = 
826     silc_task_register(server->timeout_queue, newsocket->sock, 
827                        silc_server_timeout_remote,
828                        context, 60, 0,
829                        SILC_TASK_TIMEOUT,
830                        SILC_TASK_PRI_LOW);
831
832   /* Register the connection for network input and output. This sets
833      that scheduler will listen for incoming packets for this connection 
834      and sets that outgoing packets may be sent to this connection as well.
835      However, this doesn't set the scheduler for outgoing traffic, it
836      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
837      later when outgoing data is available. */
838   SILC_REGISTER_CONNECTION_FOR_IO(sock);
839 }
840
841 /* Second part of accepting new connection. Key exchange protocol has been
842    performed and now it is time to do little connection authentication
843    protocol to figure out whether this connection is client or server
844    and whether it has right to access this server (especially server
845    connections needs to be authenticated). */
846
847 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
848 {
849   SilcProtocol protocol = (SilcProtocol)context;
850   SilcServerKEInternalContext *ctx = 
851     (SilcServerKEInternalContext *)protocol->context;
852   SilcServer server = (SilcServer)ctx->server;
853   SilcSocketConnection sock = NULL;
854   SilcServerConnAuthInternalContext *proto_ctx;
855
856   SILC_LOG_DEBUG(("Start"));
857
858   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
859     /* Error occured during protocol */
860     silc_protocol_free(protocol);
861     if (ctx->packet)
862       silc_buffer_free(ctx->packet);
863     if (ctx->ske)
864       silc_ske_free(ctx->ske);
865     if (ctx->dest_id)
866       silc_free(ctx->dest_id);
867     silc_free(ctx);
868     if (sock)
869       sock->protocol = NULL;
870     silc_server_disconnect_remote(server, sock, "Server closed connection: "
871                                   "Key exchange failed");
872     return;
873   }
874
875   /* Allocate internal context for the authentication protocol. This
876      is sent as context for the protocol. */
877   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
878   proto_ctx->server = (void *)server;
879   proto_ctx->sock = sock = server->sockets[fd];
880   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
881   proto_ctx->responder = TRUE;
882   proto_ctx->dest_id_type = ctx->dest_id_type;
883   proto_ctx->dest_id = ctx->dest_id;
884
885   /* Free old protocol as it is finished now */
886   silc_protocol_free(protocol);
887   if (ctx->packet)
888     silc_buffer_free(ctx->packet);
889   silc_free(ctx);
890   sock->protocol = NULL;
891
892   /* Allocate the authentication protocol. This is allocated here
893      but we won't start it yet. We will be receiving party of this
894      protocol thus we will wait that connecting party will make
895      their first move. */
896   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
897                       &sock->protocol, proto_ctx, 
898                       silc_server_accept_new_connection_final);
899
900   /* Register timeout task. If the protocol is not executed inside
901      this timelimit the connection will be terminated. Currently
902      this is 60 seconds and is hard coded limit (XXX). */
903   proto_ctx->timeout_task = 
904     silc_task_register(server->timeout_queue, sock->sock, 
905                        silc_server_timeout_remote,
906                        (void *)server, 60, 0,
907                        SILC_TASK_TIMEOUT,
908                        SILC_TASK_PRI_LOW);
909 }
910
911 /* Final part of accepting new connection. The connection has now
912    been authenticated and keys has been exchanged. We also know whether
913    this is client or server connection. */
914
915 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
916 {
917   SilcProtocol protocol = (SilcProtocol)context;
918   SilcServerConnAuthInternalContext *ctx = 
919     (SilcServerConnAuthInternalContext *)protocol->context;
920   SilcServer server = (SilcServer)ctx->server;
921   SilcSocketConnection sock = ctx->sock;
922   void *id_entry = NULL;
923
924   SILC_LOG_DEBUG(("Start"));
925
926   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
927     /* Error occured during protocol */
928     silc_protocol_free(protocol);
929     if (ctx->packet)
930       silc_buffer_free(ctx->packet);
931     if (ctx->ske)
932       silc_ske_free(ctx->ske);
933     if (ctx->dest_id)
934       silc_free(ctx->dest_id);
935     silc_free(ctx);
936     if (sock)
937       sock->protocol = NULL;
938     silc_server_disconnect_remote(server, sock, "Server closed connection: "
939                                   "Authentication failed");
940     return;
941   }
942
943   sock->type = ctx->conn_type;
944   switch(sock->type) {
945   case SILC_SOCKET_TYPE_CLIENT:
946     {
947       SilcClientEntry client;
948
949       SILC_LOG_DEBUG(("Remote host is client"));
950       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
951                      sock->ip));
952
953       /* Add the client to the client ID cache. The nickname and Client ID
954          and other information is created after we have received NEW_CLIENT
955          packet from client. */
956       client = silc_idlist_add_client(server->local_list, 
957                                       NULL, NULL, NULL, NULL, NULL, sock);
958       if (!client) {
959         SILC_LOG_ERROR(("Could not add new client to cache"));
960         silc_free(sock->user_data);
961         break;
962       }
963
964       id_entry = (void *)client;
965       break;
966     }
967   case SILC_SOCKET_TYPE_SERVER:
968   case SILC_SOCKET_TYPE_ROUTER:
969     {
970       SilcServerEntry new_server;
971
972       SILC_LOG_DEBUG(("Remote host is %s", 
973                       sock->type == SILC_SOCKET_TYPE_SERVER ? 
974                       "server" : "router"));
975       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
976                      sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ? 
977                      "server" : "router"));
978
979       /* Add the server into server cache. The server name and Server ID
980          is updated after we have received NEW_SERVER packet from the
981          server. */
982       new_server = 
983         silc_idlist_add_server(server->local_list, NULL,
984                                sock->type == SILC_SOCKET_TYPE_SERVER ?
985                                SILC_SERVER : SILC_ROUTER, NULL, NULL, sock);
986       if (!new_server) {
987         SILC_LOG_ERROR(("Could not add new server to cache"));
988         silc_free(sock->user_data);
989         break;
990       }
991
992       id_entry = (void *)new_server;
993       
994       /* There is connection to other server now, if it is router then
995          we will have connection to outside world.  If we are router but
996          normal server connected to us then we will remain standalone,
997          if we are standlone. */
998       if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
999         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1000         server->standalone = FALSE;
1001         if (!server->id_entry->router)
1002           server->id_entry->router = id_entry;
1003       }
1004       break;
1005     }
1006   default:
1007     break;
1008   }
1009
1010   /* Add the common data structure to the ID entry. */
1011   if (id_entry)
1012     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1013       
1014   /* Add to sockets internal pointer for fast referencing */
1015   silc_free(sock->user_data);
1016   sock->user_data = id_entry;
1017
1018   /* Connection has been fully established now. Everything is ok. */
1019   SILC_LOG_DEBUG(("New connection authenticated"));
1020
1021   silc_protocol_free(protocol);
1022   if (ctx->packet)
1023     silc_buffer_free(ctx->packet);
1024   if (ctx->ske)
1025     silc_ske_free(ctx->ske);
1026   if (ctx->dest_id)
1027     silc_free(ctx->dest_id);
1028   silc_free(ctx);
1029   sock->protocol = NULL;
1030 }
1031
1032 /* Internal routine that sends packet or marks packet to be sent. This
1033    is used directly only in special cases. Normal cases should use
1034    silc_server_packet_send. Returns < 0 error. */
1035
1036 static int silc_server_packet_send_real(SilcServer server,
1037                                         SilcSocketConnection sock,
1038                                         int force_send)
1039 {
1040   int ret;
1041
1042   /* Send the packet */
1043   ret = silc_packet_send(sock, force_send);
1044   if (ret != -2)
1045     return ret;
1046
1047   /* Mark that there is some outgoing data available for this connection. 
1048      This call sets the connection both for input and output (the input
1049      is set always and this call keeps the input setting, actually). 
1050      Actual data sending is performed by silc_server_packet_process. */
1051   SILC_SET_CONNECTION_FOR_OUTPUT(sock->sock);
1052
1053   /* Mark to socket that data is pending in outgoing buffer. This flag
1054      is needed if new data is added to the buffer before the earlier
1055      put data is sent to the network. */
1056   SILC_SET_OUTBUF_PENDING(sock);
1057
1058   return 0;
1059 }
1060
1061 typedef struct {
1062   SilcPacketContext *packetdata;
1063   SilcServer server;
1064   SilcSocketConnection sock;
1065   SilcCipher cipher;
1066   SilcHmac hmac;
1067 } SilcServerInternalPacket;
1068
1069 /* This function is used to read packets from network and send packets to
1070    network. This is usually a generic task. */
1071
1072 SILC_TASK_CALLBACK(silc_server_packet_process)
1073 {
1074   SilcServer server = (SilcServer)context;
1075   SilcSocketConnection sock = server->sockets[fd];
1076   SilcIDListData idata;
1077   SilcCipher cipher = NULL;
1078   SilcHmac hmac = NULL;
1079   int ret;
1080
1081   SILC_LOG_DEBUG(("Processing packet"));
1082
1083   /* Packet sending */
1084   if (type == SILC_TASK_WRITE) {
1085     SILC_LOG_DEBUG(("Writing data to connection"));
1086
1087     if (sock->outbuf->data - sock->outbuf->head)
1088       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1089
1090     ret = silc_server_packet_send_real(server, sock, TRUE);
1091
1092     /* If returned -2 could not write to connection now, will do
1093        it later. */
1094     if (ret == -2)
1095       return;
1096     
1097     /* The packet has been sent and now it is time to set the connection
1098        back to only for input. When there is again some outgoing data 
1099        available for this connection it will be set for output as well. 
1100        This call clears the output setting and sets it only for input. */
1101     SILC_SET_CONNECTION_FOR_INPUT(fd);
1102     SILC_UNSET_OUTBUF_PENDING(sock);
1103
1104     silc_buffer_clear(sock->outbuf);
1105     return;
1106   }
1107
1108   /* Packet receiving */
1109   SILC_LOG_DEBUG(("Reading data from connection"));
1110
1111   /* Read some data from connection */
1112   ret = silc_packet_receive(sock);
1113   if (ret < 0)
1114     return;
1115     
1116   /* EOF */
1117   if (ret == 0) {
1118     SILC_LOG_DEBUG(("Read EOF"));
1119       
1120     /* If connection is disconnecting already we will finally
1121        close the connection */
1122     if (SILC_IS_DISCONNECTING(sock)) {
1123       if (sock->user_data)
1124         silc_server_free_sock_user_data(server, sock);
1125       silc_server_close_connection(server, sock);
1126       return;
1127     }
1128       
1129     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1130
1131     if (sock->user_data)
1132       silc_server_free_sock_user_data(server, sock);
1133     silc_server_close_connection(server, sock);
1134     return;
1135   }
1136
1137   /* If connection is disconnecting or disconnected we will ignore
1138      what we read. */
1139   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1140     SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1141     return;
1142   }
1143
1144   /* Get keys and stuff from ID entry */
1145   idata = (SilcIDListData)sock->user_data;
1146   if (idata) {
1147     idata->last_receive = time(NULL);
1148     cipher = idata->receive_key;
1149     hmac = idata->hmac;
1150   }
1151  
1152   /* Process the packet. This will call the parser that will then
1153      decrypt and parse the packet. */
1154   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1155                               server);
1156 }
1157
1158 /* Parses whole packet, received earlier. */
1159
1160 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1161 {
1162   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1163   SilcServer server = (SilcServer)parse_ctx->context;
1164   SilcSocketConnection sock = parse_ctx->sock;
1165   SilcPacketContext *packet = parse_ctx->packet;
1166   SilcBuffer buffer = packet->buffer;
1167   int ret;
1168
1169   SILC_LOG_DEBUG(("Start"));
1170
1171   /* Decrypt the received packet */
1172   ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac, 
1173                             buffer, packet);
1174   if (ret < 0)
1175     goto out;
1176
1177   if (ret == 0) {
1178     /* Parse the packet. Packet type is returned. */
1179     ret = silc_packet_parse(packet);
1180   } else {
1181     /* Parse the packet header in special way as this is "special"
1182        packet type. */
1183     ret = silc_packet_parse_special(packet);
1184   }
1185
1186   if (ret == SILC_PACKET_NONE)
1187     goto out;
1188   
1189   /* Parse the incoming packet type */
1190   silc_server_packet_parse_type(server, sock, packet);
1191
1192  out:
1193   silc_buffer_clear(sock->inbuf);
1194   if (packet->src_id)
1195     silc_free(packet->src_id);
1196   if (packet->dst_id)
1197     silc_free(packet->dst_id);
1198   silc_free(packet);
1199   silc_free(parse_ctx);
1200 }
1201
1202 /* Parser callback called by silc_packet_receive_process. This merely
1203    registers timeout that will handle the actual parsing whem appropriate. */
1204
1205 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1206 {
1207   SilcServer server = (SilcServer)parser_context->context;
1208   SilcSocketConnection sock = parser_context->sock;
1209
1210   switch (sock->type) {
1211   case SILC_SOCKET_TYPE_CLIENT:
1212   case SILC_SOCKET_TYPE_UNKNOWN:
1213     /* Parse the packet with timeout */
1214     silc_task_register(server->timeout_queue, sock->sock,
1215                        silc_server_packet_parse_real,
1216                        (void *)parser_context, 0, 100000,
1217                        SILC_TASK_TIMEOUT,
1218                        SILC_TASK_PRI_NORMAL);
1219     break;
1220   case SILC_SOCKET_TYPE_SERVER:
1221   case SILC_SOCKET_TYPE_ROUTER:
1222     /* Packets from servers are parsed as soon as possible */
1223     silc_task_register(server->timeout_queue, sock->sock,
1224                        silc_server_packet_parse_real,
1225                        (void *)parser_context, 0, 1,
1226                        SILC_TASK_TIMEOUT,
1227                        SILC_TASK_PRI_NORMAL);
1228     break;
1229   default:
1230     return;
1231   }
1232 }
1233
1234 /* Parses the packet type and calls what ever routines the packet type
1235    requires. This is done for all incoming packets. */
1236
1237 void silc_server_packet_parse_type(SilcServer server, 
1238                                    SilcSocketConnection sock,
1239                                    SilcPacketContext *packet)
1240 {
1241   SilcBuffer buffer = packet->buffer;
1242   SilcPacketType type = packet->type;
1243
1244   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1245
1246   /* Parse the packet type */
1247   switch(type) {
1248   case SILC_PACKET_DISCONNECT:
1249     SILC_LOG_DEBUG(("Disconnect packet"));
1250     break;
1251   case SILC_PACKET_SUCCESS:
1252     /*
1253      * Success received for something. For now we can have only
1254      * one protocol for connection executing at once hence this
1255      * success message is for whatever protocol is executing currently.
1256      */
1257     SILC_LOG_DEBUG(("Success packet"));
1258     if (sock->protocol) {
1259       sock->protocol->execute(server->timeout_queue, 0,
1260                               sock->protocol, sock->sock, 0, 0);
1261     }
1262     break;
1263   case SILC_PACKET_FAILURE:
1264     /*
1265      * Failure received for something. For now we can have only
1266      * one protocol for connection executing at once hence this
1267      * failure message is for whatever protocol is executing currently.
1268      */
1269     SILC_LOG_DEBUG(("Failure packet"));
1270     if (sock->protocol) {
1271       /* XXX Audit the failure type */
1272       sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1273       sock->protocol->execute(server->timeout_queue, 0,
1274                               sock->protocol, sock->sock, 0, 0);
1275     }
1276     break;
1277   case SILC_PACKET_REJECT:
1278     SILC_LOG_DEBUG(("Reject packet"));
1279     return;
1280     break;
1281
1282     /* 
1283      * Channel packets
1284      */
1285   case SILC_PACKET_CHANNEL_MESSAGE:
1286     /*
1287      * Received channel message. Channel messages are special packets
1288      * (although probably most common ones) hence they are handled
1289      * specially.
1290      */
1291     SILC_LOG_DEBUG(("Channel Message packet"));
1292     silc_server_channel_message(server, sock, packet);
1293     break;
1294
1295   case SILC_PACKET_CHANNEL_KEY:
1296     /*
1297      * Received key for channel. As channels are created by the router
1298      * the keys are as well. We will distribute the key to all of our
1299      * locally connected clients on the particular channel. Router
1300      * never receives this channel and thus is ignored.
1301      */
1302     SILC_LOG_DEBUG(("Channel Key packet"));
1303     silc_server_channel_key(server, sock, packet);
1304     break;
1305
1306     /*
1307      * Command packets
1308      */
1309   case SILC_PACKET_COMMAND:
1310     /*
1311      * Recived command. Allocate command context and execute the command.
1312      */
1313     SILC_LOG_DEBUG(("Command packet"));
1314     silc_server_command_process(server, sock, packet);
1315     break;
1316
1317   case SILC_PACKET_COMMAND_REPLY:
1318     /*
1319      * Received command reply packet. Servers never send commands thus
1320      * they don't receive command reply packets either, except in cases
1321      * where server has forwarded command packet coming from client. 
1322      * This must be the case here or we will ignore the packet.
1323      */
1324     SILC_LOG_DEBUG(("Command Reply packet"));
1325     silc_server_packet_relay_command_reply(server, sock, packet);
1326     break;
1327
1328     /*
1329      * Private Message packets
1330      */
1331   case SILC_PACKET_PRIVATE_MESSAGE:
1332     /*
1333      * Received private message packet. The packet is coming from either
1334      * client or server.
1335      */
1336     SILC_LOG_DEBUG(("Private Message packet"));
1337     silc_server_private_message(server, sock, packet);
1338     break;
1339
1340   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1341     break;
1342
1343     /*
1344      * Key Exchange protocol packets
1345      */
1346   case SILC_PACKET_KEY_EXCHANGE:
1347     SILC_LOG_DEBUG(("KE packet"));
1348     if (sock->protocol && sock->protocol->protocol->type 
1349         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1350
1351       SilcServerKEInternalContext *proto_ctx = 
1352         (SilcServerKEInternalContext *)sock->protocol->context;
1353
1354       proto_ctx->packet = buffer;
1355
1356       /* Let the protocol handle the packet */
1357       sock->protocol->execute(server->timeout_queue, 0, 
1358                               sock->protocol, sock->sock, 0, 100000);
1359     } else {
1360       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1361                       "protocol active, packet dropped."));
1362
1363       /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1364     }
1365     break;
1366
1367   case SILC_PACKET_KEY_EXCHANGE_1:
1368     SILC_LOG_DEBUG(("KE 1 packet"));
1369     if (sock->protocol && sock->protocol->protocol->type 
1370         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1371
1372       SilcServerKEInternalContext *proto_ctx = 
1373         (SilcServerKEInternalContext *)sock->protocol->context;
1374
1375       if (proto_ctx->packet)
1376         silc_buffer_free(proto_ctx->packet);
1377
1378       proto_ctx->packet = buffer;
1379       proto_ctx->dest_id_type = packet->src_id_type;
1380       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1381
1382       /* Let the protocol handle the packet */
1383       sock->protocol->execute(server->timeout_queue, 0, 
1384                               sock->protocol, sock->sock,
1385                               0, 100000);
1386     } else {
1387       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1388                       "protocol active, packet dropped."));
1389     }
1390     break;
1391
1392   case SILC_PACKET_KEY_EXCHANGE_2:
1393     SILC_LOG_DEBUG(("KE 2 packet"));
1394     if (sock->protocol && sock->protocol->protocol->type 
1395         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1396
1397       SilcServerKEInternalContext *proto_ctx = 
1398         (SilcServerKEInternalContext *)sock->protocol->context;
1399
1400       if (proto_ctx->packet)
1401         silc_buffer_free(proto_ctx->packet);
1402
1403       proto_ctx->packet = buffer;
1404       proto_ctx->dest_id_type = packet->src_id_type;
1405       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1406
1407       /* Let the protocol handle the packet */
1408       sock->protocol->execute(server->timeout_queue, 0, 
1409                               sock->protocol, sock->sock,
1410                               0, 100000);
1411     } else {
1412       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1413                       "protocol active, packet dropped."));
1414     }
1415     break;
1416
1417   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1418     /* If we receive this packet we will send to the other end information
1419        about our mandatory authentication method for the connection. 
1420        This packet maybe received at any time. */
1421
1422     /*
1423      * Connection Authentication protocol packets
1424      */
1425   case SILC_PACKET_CONNECTION_AUTH:
1426     /* Start of the authentication protocol. We receive here the 
1427        authentication data and will verify it. */
1428     SILC_LOG_DEBUG(("Connection auth packet"));
1429     if (sock->protocol && sock->protocol->protocol->type 
1430         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1431
1432       SilcServerConnAuthInternalContext *proto_ctx = 
1433         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1434
1435       proto_ctx->packet = buffer;
1436
1437       /* Let the protocol handle the packet */
1438       sock->protocol->execute(server->timeout_queue, 0, 
1439                               sock->protocol, sock->sock, 0, 0);
1440     } else {
1441       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1442                       "protocol active, packet dropped."));
1443     }
1444     break;
1445
1446   case SILC_PACKET_NEW_ID:
1447     /*
1448      * Received New ID packet. This includes some new ID that has been
1449      * created. It may be for client, server or channel. This is the way
1450      * to distribute information about new registered entities in the
1451      * SILC network.
1452      */
1453     SILC_LOG_DEBUG(("New ID packet"));
1454     silc_server_new_id(server, sock, packet);
1455     break;
1456
1457   case SILC_PACKET_NEW_CLIENT:
1458     /*
1459      * Received new client packet. This includes client information that
1460      * we will use to create initial client ID. After creating new
1461      * ID we will send it to the client.
1462      */
1463     SILC_LOG_DEBUG(("New Client packet"));
1464     silc_server_new_client(server, sock, packet);
1465     break;
1466
1467   case SILC_PACKET_NEW_SERVER:
1468     /*
1469      * Received new server packet. This includes Server ID and some other
1470      * information that we may save. This is received after server has 
1471      * connected to us.
1472      */
1473     SILC_LOG_DEBUG(("New Server packet"));
1474     silc_server_new_server(server, sock, packet);
1475     break;
1476
1477   case SILC_PACKET_NEW_CHANNEL:
1478     break;
1479
1480   case SILC_PACKET_NEW_CHANNEL_USER:
1481     break;
1482
1483   case SILC_PACKET_NEW_CHANNEL_LIST:
1484     break;
1485
1486   case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1487     break;
1488
1489   case SILC_PACKET_REPLACE_ID:
1490     /*
1491      * Received replace ID packet. This sends the old ID that is to be
1492      * replaced with the new one included into the packet. Client must not
1493      * send this packet.
1494      */
1495     SILC_LOG_DEBUG(("Replace ID packet"));
1496     silc_server_replace_id(server, sock, packet);
1497     break;
1498
1499   case SILC_PACKET_REMOVE_ID:
1500     break;
1501
1502   case SILC_PACKET_REMOVE_CHANNEL_USER:
1503     /*
1504      * Received packet to remove user from a channel. Routers notify other
1505      * routers about a user leaving a channel.
1506      */
1507     SILC_LOG_DEBUG(("Remove Channel User packet"));
1508     silc_server_remove_channel_user(server, sock, packet);
1509     break;
1510
1511   default:
1512     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1513     break;
1514   }
1515   
1516 }
1517
1518 /* Assembles a new packet to be sent out to network. This doesn't actually
1519    send the packet but creates the packet and fills the outgoing data
1520    buffer and marks the packet ready to be sent to network. However, If 
1521    argument force_send is TRUE the packet is sent immediately and not put 
1522    to queue. Normal case is that the packet is not sent immediately. */
1523
1524 void silc_server_packet_send(SilcServer server,
1525                              SilcSocketConnection sock, 
1526                              SilcPacketType type, 
1527                              SilcPacketFlags flags,
1528                              unsigned char *data, 
1529                              unsigned int data_len,
1530                              int force_send)
1531 {
1532   void *dst_id = NULL;
1533   SilcIdType dst_id_type = SILC_ID_NONE;
1534
1535   if (!sock)
1536     return;
1537
1538   /* Get data used in the packet sending, keys and stuff */
1539   switch(sock->type) {
1540   case SILC_SOCKET_TYPE_CLIENT:
1541     dst_id = ((SilcClientEntry)sock->user_data)->id;
1542     dst_id_type = SILC_ID_CLIENT;
1543     break;
1544   case SILC_SOCKET_TYPE_SERVER:
1545   case SILC_SOCKET_TYPE_ROUTER:
1546     dst_id = ((SilcServerEntry)sock->user_data)->id;
1547     dst_id_type = SILC_ID_SERVER;
1548     break;
1549   default:
1550     break;
1551   }
1552
1553   silc_server_packet_send_dest(server, sock, type, flags, dst_id,
1554                                dst_id_type, data, data_len, force_send);
1555 }
1556
1557 /* Assembles a new packet to be sent out to network. This doesn't actually
1558    send the packet but creates the packet and fills the outgoing data
1559    buffer and marks the packet ready to be sent to network. However, If 
1560    argument force_send is TRUE the packet is sent immediately and not put 
1561    to queue. Normal case is that the packet is not sent immediately. 
1562    Destination information is sent as argument for this function. */
1563
1564 void silc_server_packet_send_dest(SilcServer server,
1565                                   SilcSocketConnection sock, 
1566                                   SilcPacketType type, 
1567                                   SilcPacketFlags flags,
1568                                   void *dst_id,
1569                                   SilcIdType dst_id_type,
1570                                   unsigned char *data, 
1571                                   unsigned int data_len,
1572                                   int force_send)
1573 {
1574   SilcPacketContext packetdata;
1575   SilcIDListData idata;
1576   SilcCipher cipher = NULL;
1577   SilcHmac hmac = NULL;
1578   unsigned char *dst_id_data = NULL;
1579   unsigned int dst_id_len = 0;
1580
1581   SILC_LOG_DEBUG(("Sending packet, type %d", type));
1582
1583   /* Get data used in the packet sending, keys and stuff */
1584   idata = (SilcIDListData)sock->user_data;
1585
1586   if (dst_id) {
1587     dst_id_data = silc_id_id2str(dst_id, dst_id_type);
1588     dst_id_len = silc_id_get_len(dst_id_type);
1589   }
1590
1591   /* Set the packet context pointers */
1592   packetdata.type = type;
1593   packetdata.flags = flags;
1594   packetdata.src_id = silc_id_id2str(server->id, server->id_type);
1595   packetdata.src_id_len = SILC_ID_SERVER_LEN;
1596   packetdata.src_id_type = server->id_type;
1597   packetdata.dst_id = dst_id_data;
1598   packetdata.dst_id_len = dst_id_len;
1599   packetdata.dst_id_type = dst_id_type;
1600   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
1601     packetdata.src_id_len + dst_id_len;
1602   packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1603   packetdata.rng = server->rng;
1604
1605   /* Prepare outgoing data buffer for packet sending */
1606   silc_packet_send_prepare(sock, 
1607                            SILC_PACKET_HEADER_LEN +
1608                            packetdata.src_id_len + 
1609                            packetdata.dst_id_len,
1610                            packetdata.padlen,
1611                            data_len);
1612
1613   SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
1614
1615   packetdata.buffer = sock->outbuf;
1616
1617   /* Put the data to the buffer */
1618   if (data && data_len)
1619     silc_buffer_put(sock->outbuf, data, data_len);
1620
1621   /* Create the outgoing packet */
1622   silc_packet_assemble(&packetdata);
1623
1624   if (idata) {
1625     cipher = idata->send_key;
1626     hmac = idata->hmac;
1627   }
1628
1629   /* Encrypt the packet */
1630   silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1631
1632   SILC_LOG_HEXDUMP(("Outgoing packet, len %d", sock->outbuf->len),
1633                    sock->outbuf->data, sock->outbuf->len);
1634
1635   /* Now actually send the packet */
1636   silc_server_packet_send_real(server, sock, force_send);
1637
1638   if (packetdata.src_id)
1639     silc_free(packetdata.src_id);
1640   if (packetdata.dst_id)
1641     silc_free(packetdata.dst_id);
1642 }
1643
1644 /* Forwards packet. Packets sent with this function will be marked as
1645    forwarded (in the SILC header flags) so that the receiver knows that
1646    we have forwarded the packet to it. Forwarded packets are handled
1647    specially by the receiver as they are not destined to the receiver
1648    originally. However, the receiver knows this because the forwarded
1649    flag has been set (and the flag is authenticated). */
1650
1651 void silc_server_packet_forward(SilcServer server,
1652                                 SilcSocketConnection sock,
1653                                 unsigned char *data, unsigned int data_len,
1654                                 int force_send)
1655 {
1656   SilcIDListData idata;
1657   SilcCipher cipher = NULL;
1658   SilcHmac hmac = NULL;
1659
1660   SILC_LOG_DEBUG(("Forwarding packet"));
1661
1662   /* Get data used in the packet sending, keys and stuff */
1663   idata = (SilcIDListData)sock->user_data;
1664
1665   /* Prepare outgoing data buffer for packet sending */
1666   silc_packet_send_prepare(sock, 0, 0, data_len);
1667
1668   /* Mungle the packet flags and add the FORWARDED flag */
1669   if (data)
1670     data[2] |= (unsigned char)SILC_PACKET_FLAG_FORWARDED;
1671
1672   /* Put the data to the buffer */
1673   if (data && data_len)
1674     silc_buffer_put(sock->outbuf, data, data_len);
1675
1676   if (idata) {
1677     cipher = idata->send_key;
1678     hmac = idata->hmac;
1679   }
1680
1681   /* Encrypt the packet */
1682   silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1683
1684   SILC_LOG_HEXDUMP(("Forwarded packet, len %d", sock->outbuf->len),
1685                    sock->outbuf->data, sock->outbuf->len);
1686
1687   /* Now actually send the packet */
1688   silc_server_packet_send_real(server, sock, force_send);
1689 }
1690
1691 /* Internal routine to actually create the channel packet and send it
1692    to network. This is common function in channel message sending. If
1693    `channel_message' is TRUE this encrypts the message as it is strictly
1694    a channel message. If FALSE normal encryption process is used. */
1695
1696 static void
1697 silc_server_packet_send_to_channel_real(SilcServer server,
1698                                         SilcSocketConnection sock,
1699                                         SilcPacketContext *packet,
1700                                         SilcCipher cipher,
1701                                         SilcHmac hmac,
1702                                         unsigned char *data,
1703                                         unsigned int data_len,
1704                                         int channel_message,
1705                                         int force_send)
1706 {
1707   packet->truelen = data_len + SILC_PACKET_HEADER_LEN + 
1708     packet->src_id_len + packet->dst_id_len;
1709
1710   /* Prepare outgoing data buffer for packet sending */
1711   silc_packet_send_prepare(sock, 
1712                            SILC_PACKET_HEADER_LEN +
1713                            packet->src_id_len + 
1714                            packet->dst_id_len,
1715                            packet->padlen,
1716                            data_len);
1717
1718   packet->buffer = sock->outbuf;
1719
1720   /* Put the data to buffer, assemble and encrypt the packet. The packet
1721      is encrypted with normal session key shared with the client. */
1722   silc_buffer_put(sock->outbuf, data, data_len);
1723   silc_packet_assemble(packet);
1724   if (channel_message)
1725     silc_packet_encrypt(cipher, hmac, sock->outbuf, SILC_PACKET_HEADER_LEN + 
1726                         packet->src_id_len + packet->dst_id_len +
1727                         packet->padlen);
1728   else
1729     silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
1730     
1731   SILC_LOG_HEXDUMP(("Channel packet, len %d", sock->outbuf->len),
1732                    sock->outbuf->data, sock->outbuf->len);
1733
1734   /* Now actually send the packet */
1735   silc_server_packet_send_real(server, sock, force_send);
1736 }
1737
1738 /* This routine is used by the server to send packets to channel. The 
1739    packet sent with this function is distributed to all clients on
1740    the channel. Usually this is used to send notify messages to the
1741    channel, things like notify about new user joining to the channel. */
1742
1743 void silc_server_packet_send_to_channel(SilcServer server,
1744                                         SilcChannelEntry channel,
1745                                         SilcPacketType type,
1746                                         unsigned char *data,
1747                                         unsigned int data_len,
1748                                         int force_send)
1749 {
1750   SilcSocketConnection sock = NULL;
1751   SilcPacketContext packetdata;
1752   SilcClientEntry client = NULL;
1753   SilcServerEntry *routed = NULL;
1754   SilcChannelClientEntry chl;
1755   SilcIDListData idata;
1756   unsigned int routed_count = 0;
1757
1758   /* This doesn't send channel message packets */
1759   if (type == SILC_PACKET_CHANNEL_MESSAGE)
1760     return;
1761   
1762   SILC_LOG_DEBUG(("Sending packet to channel"));
1763
1764   /* Set the packet context pointers. */
1765   packetdata.flags = 0;
1766   packetdata.type = type;
1767   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
1768   packetdata.src_id_len = SILC_ID_SERVER_LEN;
1769   packetdata.src_id_type = SILC_ID_SERVER;
1770   packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1771   packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1772   packetdata.dst_id_type = SILC_ID_CHANNEL;
1773   packetdata.rng = server->rng;
1774   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
1775     packetdata.src_id_len + packetdata.dst_id_len;
1776   packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
1777
1778   /* If there are global users in the channel we will send the message
1779      first to our router for further routing. */
1780   if (server->server_type == SILC_SERVER && !server->standalone &&
1781       channel->global_users) {
1782     SilcServerEntry router;
1783
1784     /* Get data used in packet header encryption, keys and stuff. */
1785     router = server->id_entry->router;
1786     sock = (SilcSocketConnection)router->connection;
1787     idata = (SilcIDListData)router;
1788     
1789     SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1790
1791     silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1792                                             idata->send_key, idata->hmac, 
1793                                             data, data_len, FALSE, force_send);
1794   }
1795
1796   /* Send the message to clients on the channel's client list. */
1797   silc_list_start(channel->user_list);
1798   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1799     client = chl->client;
1800
1801     /* If client has router set it is not locally connected client and
1802        we will route the message to the router set in the client. */
1803     if (client && client->router && server->server_type == SILC_ROUTER) {
1804       int k;
1805
1806       /* Check if we have sent the packet to this route already */
1807       for (k = 0; k < routed_count; k++)
1808         if (routed[k] == client->router)
1809           break;
1810       if (k < routed_count)
1811         continue;
1812
1813       /* Get data used in packet header encryption, keys and stuff. */
1814       sock = (SilcSocketConnection)client->router->connection;
1815       idata = (SilcIDListData)client->router;
1816
1817       /* Send the packet */
1818       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1819                                               idata->send_key, idata->hmac, 
1820                                               data, data_len, FALSE, 
1821                                               force_send);
1822
1823       /* We want to make sure that the packet is routed to same router
1824          only once. Mark this route as sent route. */
1825       k = routed_count;
1826       routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
1827       routed[k] = client->router;
1828       routed_count++;
1829
1830       continue;
1831     }
1832
1833     /* Send to locally connected client */
1834     if (client) {
1835
1836       /* Get data used in packet header encryption, keys and stuff. */
1837       sock = (SilcSocketConnection)client->connection;
1838       idata = (SilcIDListData)client;
1839
1840       /* Send the packet */
1841       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1842                                               idata->send_key, idata->hmac, 
1843                                               data, data_len, FALSE, 
1844                                               force_send);
1845     }
1846   }
1847
1848   if (routed_count)
1849     silc_free(routed);
1850   silc_free(packetdata.src_id);
1851   silc_free(packetdata.dst_id);
1852 }
1853
1854 /* This routine is explicitly used to relay messages to some channel.
1855    Packets sent with this function we have received earlier and are
1856    totally encrypted. This just sends the packet to all clients on
1857    the channel. If the sender of the packet is someone on the channel 
1858    the message will not be sent to that client. The SILC Packet header
1859    is encrypted with the session key shared between us and the client.
1860    MAC is also computed before encrypting the header. Rest of the
1861    packet will be untouched. */
1862
1863 void silc_server_packet_relay_to_channel(SilcServer server,
1864                                          SilcSocketConnection sender_sock,
1865                                          SilcChannelEntry channel,
1866                                          void *sender, 
1867                                          SilcIdType sender_type,
1868                                          unsigned char *data,
1869                                          unsigned int data_len,
1870                                          int force_send)
1871 {
1872   int found = FALSE;
1873   SilcSocketConnection sock = NULL;
1874   SilcPacketContext packetdata;
1875   SilcClientEntry client = NULL;
1876   SilcServerEntry *routed = NULL;
1877   SilcChannelClientEntry chl;
1878   unsigned int routed_count = 0;
1879   SilcIDListData idata;
1880
1881   SILC_LOG_DEBUG(("Relaying packet to channel"));
1882
1883   /* Set the packet context pointers. */
1884   packetdata.flags = 0;
1885   packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
1886   packetdata.src_id = silc_id_id2str(sender, sender_type);
1887   packetdata.src_id_len = silc_id_get_len(sender_type);
1888   packetdata.src_id_type = sender_type;
1889   packetdata.dst_id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
1890   packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1891   packetdata.dst_id_type = SILC_ID_CHANNEL;
1892   packetdata.rng = server->rng;
1893   packetdata.padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
1894                                           packetdata.src_id_len +
1895                                           packetdata.dst_id_len));
1896
1897   /* If there are global users in the channel we will send the message
1898      first to our router for further routing. */
1899   if (server->server_type == SILC_SERVER && !server->standalone &&
1900       channel->global_users) {
1901     SilcServerEntry router;
1902
1903     router = server->id_entry->router;
1904
1905     /* Check that the sender is not our router. */
1906     if (sender_sock != (SilcSocketConnection)router->connection) {
1907
1908       /* Get data used in packet header encryption, keys and stuff. */
1909       sock = (SilcSocketConnection)router->connection;
1910       idata = (SilcIDListData)router;
1911
1912       SILC_LOG_DEBUG(("Sending channel message to router for routing"));
1913
1914       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1915                                               idata->send_key, idata->hmac, 
1916                                               data, data_len, TRUE, 
1917                                               force_send);
1918     }
1919   }
1920
1921   /* Send the message to clients on the channel's client list. */
1922   silc_list_start(channel->user_list);
1923   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1924     client = chl->client;
1925
1926     if (client) {
1927
1928       /* If sender is one on the channel do not send it the packet. */
1929       if (!found && !SILC_ID_CLIENT_COMPARE(client->id, sender)) {
1930         found = TRUE;
1931         continue;
1932       }
1933
1934       /* If the client has set router it means that it is not locally
1935          connected client and we will route the packet further. */
1936       if (server->server_type == SILC_ROUTER && client->router) {
1937         int k;
1938
1939         /* Sender maybe server as well so we want to make sure that
1940            we won't send the message to the server it came from. */
1941         if (!found && !SILC_ID_SERVER_COMPARE(client->router->id, sender)) {
1942           found = TRUE;
1943           continue;
1944         }
1945
1946         /* Check if we have sent the packet to this route already */
1947         for (k = 0; k < routed_count; k++)
1948           if (routed[k] == client->router)
1949             break;
1950         if (k < routed_count)
1951           continue;
1952         
1953         /* Get data used in packet header encryption, keys and stuff. */
1954         sock = (SilcSocketConnection)client->router->connection;
1955         idata = (SilcIDListData)client->router;
1956
1957         /* Send the packet */
1958         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1959                                                 idata->send_key, idata->hmac, 
1960                                                 data, data_len, TRUE, 
1961                                                 force_send);
1962         
1963         /* We want to make sure that the packet is routed to same router
1964            only once. Mark this route as sent route. */
1965         k = routed_count;
1966         routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
1967         routed[k] = client->router;
1968         routed_count++;
1969         
1970         continue;
1971       }
1972
1973       /* XXX Check client's mode on the channel. */
1974
1975       /* Get data used in packet header encryption, keys and stuff. */
1976       sock = (SilcSocketConnection)client->connection;
1977       idata = (SilcIDListData)client;
1978
1979       SILC_LOG_DEBUG(("Sending packet to client %s", 
1980                       sock->hostname ? sock->hostname : sock->ip));
1981
1982       /* Send the packet */
1983       silc_server_packet_send_to_channel_real(server, sock, &packetdata,
1984                                               idata->send_key, idata->hmac, 
1985                                               data, data_len, TRUE, 
1986                                               force_send);
1987     }
1988   }
1989
1990   silc_free(packetdata.src_id);
1991   silc_free(packetdata.dst_id);
1992 }
1993
1994 /* This function is used to send packets strictly to all local clients
1995    on a particular channel.  This is used for example to distribute new
1996    channel key to all our locally connected clients on the channel. 
1997    The packets are always encrypted with the session key shared between
1998    the client, this means these are not _to the channel_ but _to the client_
1999    on the channel. */
2000
2001 void silc_server_packet_send_local_channel(SilcServer server,
2002                                            SilcChannelEntry channel,
2003                                            SilcPacketType type,
2004                                            SilcPacketFlags flags,
2005                                            unsigned char *data,
2006                                            unsigned int data_len,
2007                                            int force_send)
2008 {
2009   SilcClientEntry client;
2010   SilcChannelClientEntry chl;
2011   SilcSocketConnection sock = NULL;
2012
2013   SILC_LOG_DEBUG(("Start"));
2014
2015   /* Send the message to clients on the channel's client list. */
2016   silc_list_start(channel->user_list);
2017   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2018     client = chl->client;
2019
2020     if (client) {
2021       sock = (SilcSocketConnection)client->connection;
2022
2023       /* Send the packet to the client */
2024       silc_server_packet_send_dest(server, sock, type, flags, client->id,
2025                                    SILC_ID_CLIENT, data, data_len,
2026                                    force_send);
2027     }
2028   }
2029 }
2030
2031 /* Relays received command reply packet to the correct destination. The
2032    destination must be one of our locally connected client or the packet
2033    will be ignored. This is called when server has forwarded one of
2034    client's command request to router and router has now replied to the 
2035    command. */
2036
2037 void silc_server_packet_relay_command_reply(SilcServer server,
2038                                             SilcSocketConnection sock,
2039                                             SilcPacketContext *packet)
2040 {
2041   SilcBuffer buffer = packet->buffer;
2042   SilcClientEntry client;
2043   SilcClientID *id;
2044   SilcSocketConnection dst_sock;
2045   SilcIDListData idata;
2046
2047   SILC_LOG_DEBUG(("Start"));
2048
2049   /* Source must be server or router */
2050   if (packet->src_id_type != SILC_ID_SERVER &&
2051       sock->type != SILC_SOCKET_TYPE_ROUTER)
2052     goto out;
2053
2054   /* Destination must be client */
2055   if (packet->dst_id_type != SILC_ID_CLIENT)
2056     goto out;
2057
2058   /* Execute command reply locally for the command */
2059   silc_server_command_reply_process(server, sock, buffer);
2060
2061   id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2062
2063   /* Destination must be one of ours */
2064   client = silc_idlist_find_client_by_id(server->local_list, id);
2065   if (!client) {
2066     silc_free(id);
2067     goto out;
2068   }
2069
2070   /* Relay the packet to the client */
2071
2072   dst_sock = (SilcSocketConnection)client->connection;
2073   silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
2074                    + packet->dst_id_len + packet->padlen);
2075
2076   silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2077   silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2078
2079   idata = (SilcIDListData)client;
2080
2081   /* Encrypt packet */
2082   silc_packet_encrypt(idata->send_key, idata->hmac, dst_sock->outbuf, 
2083                       buffer->len);
2084     
2085   /* Send the packet */
2086   silc_server_packet_send_real(server, dst_sock, FALSE);
2087
2088   silc_free(id);
2089
2090  out:
2091   silc_buffer_free(buffer);
2092 }
2093
2094 /* Closes connection to socket connection */
2095
2096 void silc_server_close_connection(SilcServer server,
2097                                   SilcSocketConnection sock)
2098 {
2099
2100   SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
2101
2102   /* We won't listen for this connection anymore */
2103   silc_schedule_unset_listen_fd(sock->sock);
2104
2105   /* Unregister all tasks */
2106   silc_task_unregister_by_fd(server->io_queue, sock->sock);
2107   silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
2108
2109   /* Close the actual connection */
2110   silc_net_close_connection(sock->sock);
2111   server->sockets[sock->sock] = NULL;
2112   silc_socket_free(sock);
2113 }
2114
2115 /* Sends disconnect message to remote connection and disconnects the 
2116    connection. */
2117
2118 void silc_server_disconnect_remote(SilcServer server,
2119                                    SilcSocketConnection sock,
2120                                    const char *fmt, ...)
2121 {
2122   va_list ap;
2123   unsigned char buf[4096];
2124
2125   memset(buf, 0, sizeof(buf));
2126   va_start(ap, fmt);
2127   vsprintf(buf, fmt, ap);
2128   va_end(ap);
2129
2130   SILC_LOG_DEBUG(("Disconnecting remote host"));
2131
2132   /* Notify remote end that the conversation is over. The notify message
2133      is tried to be sent immediately. */
2134   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
2135                           buf, strlen(buf), TRUE);
2136
2137   /* Mark the connection to be disconnected */
2138   SILC_SET_DISCONNECTED(sock);
2139   silc_server_close_connection(server, sock);
2140 }
2141
2142 /* Free's user_data pointer from socket connection object. As this 
2143    pointer maybe anything we wil switch here to find the correct
2144    data type and free it the way it needs to be free'd. */
2145
2146 void silc_server_free_sock_user_data(SilcServer server, 
2147                                      SilcSocketConnection sock)
2148 {
2149   SILC_LOG_DEBUG(("Start"));
2150
2151   switch(sock->type) {
2152   case SILC_SOCKET_TYPE_CLIENT:
2153     {
2154       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2155
2156       /* Remove client from all channels */
2157       silc_server_remove_from_channels(server, sock, user_data);
2158
2159       /* XXX must take some info to history before freeing */
2160
2161       /* Free the client entry and everything in it */
2162       silc_idlist_del_data(user_data);
2163       silc_idlist_del_client(server->local_list, user_data);
2164       break;
2165     }
2166   case SILC_SOCKET_TYPE_SERVER:
2167   case SILC_SOCKET_TYPE_ROUTER:
2168     {
2169
2170       break;
2171     }
2172     break;
2173   default:
2174     {
2175       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2176
2177       silc_idlist_del_data(user_data);
2178       silc_free(user_data);
2179       break;
2180     }
2181   }
2182
2183   sock->user_data = NULL;
2184 }
2185
2186 /* Removes client from all channels it has joined. This is used when
2187    client connection is disconnected. If the client on a channel
2188    is last, the channel is removed as well. */
2189
2190 void silc_server_remove_from_channels(SilcServer server, 
2191                                       SilcSocketConnection sock,
2192                                       SilcClientEntry client)
2193 {
2194   SilcChannelEntry channel;
2195   SilcChannelClientEntry chl;
2196   SilcBuffer chidp, clidp;
2197
2198   SILC_LOG_DEBUG(("Start"));
2199
2200   if (!client || !client->id)
2201     return;
2202
2203   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2204
2205   /* Remove the client from all channels. The client is removed from
2206      the channels' user list. */
2207   silc_list_start(client->channels);
2208   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2209     channel = chl->channel;
2210     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2211
2212     /* Remove from list */
2213     silc_list_del(client->channels, chl);
2214
2215     /* If this client is last one on the channel the channel
2216        is removed all together. */
2217     if (silc_list_count(channel->user_list) < 2) {
2218
2219       /* However, if the channel has marked global users then the 
2220          channel is not created locally, and this does not remove the
2221          channel globally from SILC network, in this case we will
2222          notify that this client has left the channel. */
2223       if (channel->global_users)
2224         silc_server_send_notify_to_channel(server, channel,
2225                                            SILC_NOTIFY_TYPE_SIGNOFF, 1,
2226                                            clidp->data, clidp->len);
2227       
2228       silc_idlist_del_channel(server->local_list, channel);
2229       continue;
2230     }
2231
2232     /* Remove from list */
2233     silc_list_del(channel->user_list, chl);
2234     silc_free(chl);
2235
2236     /* Send notify to channel about client leaving SILC and thus
2237        the entire channel. */
2238     silc_server_send_notify_to_channel(server, channel,
2239                                        SILC_NOTIFY_TYPE_SIGNOFF, 1,
2240                                        clidp->data, clidp->len);
2241     silc_buffer_free(chidp);
2242   }
2243
2244   silc_buffer_free(clidp);
2245 }
2246
2247 /* Removes client from one channel. This is used for example when client
2248    calls LEAVE command to remove itself from the channel. Returns TRUE
2249    if channel still exists and FALSE if the channel is removed when
2250    last client leaves the channel. If `notify' is FALSE notify messages
2251    are not sent. */
2252
2253 int silc_server_remove_from_one_channel(SilcServer server, 
2254                                         SilcSocketConnection sock,
2255                                         SilcChannelEntry channel,
2256                                         SilcClientEntry client,
2257                                         int notify)
2258 {
2259   SilcChannelEntry ch;
2260   SilcChannelClientEntry chl;
2261   SilcBuffer clidp;
2262
2263   SILC_LOG_DEBUG(("Start"));
2264
2265   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2266
2267   /* Remove the client from the channel. The client is removed from
2268      the channel's user list. */
2269   silc_list_start(client->channels);
2270   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2271     if (chl->channel != channel)
2272       continue;
2273
2274     ch = chl->channel;
2275
2276     /* Remove from list */
2277     silc_list_del(client->channels, chl);
2278
2279     /* If this client is last one on the channel the channel
2280        is removed all together. */
2281     if (silc_list_count(channel->user_list) < 2) {
2282       /* Notify about leaving client if this channel has global users,
2283          ie. the channel is not created locally. */
2284       if (notify && channel->global_users)
2285         silc_server_send_notify_to_channel(server, channel,
2286                                            SILC_NOTIFY_TYPE_LEAVE, 1,
2287                                            clidp->data, clidp->len);
2288       
2289       silc_idlist_del_channel(server->local_list, channel);
2290       silc_buffer_free(clidp);
2291       return FALSE;
2292     }
2293
2294     /* Remove from list */
2295     silc_list_del(channel->user_list, chl);
2296     silc_free(chl);
2297
2298     /* Send notify to channel about client leaving the channel */
2299     if (notify)
2300       silc_server_send_notify_to_channel(server, channel,
2301                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2302                                          clidp->data, clidp->len);
2303     break;
2304   }
2305
2306   silc_buffer_free(clidp);
2307   return TRUE;
2308 }
2309
2310 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
2311    This works because we assure that the user list on the channel is
2312    always in up to date thus we can only check the channel list from 
2313    `client' which is faster than checking the user list from `channel'. */
2314
2315 int silc_server_client_on_channel(SilcClientEntry client,
2316                                   SilcChannelEntry channel)
2317 {
2318   SilcChannelClientEntry chl;
2319
2320   if (!client || !channel)
2321     return FALSE;
2322
2323   silc_list_start(client->channels);
2324   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2325     if (chl->channel == channel)
2326       return TRUE;
2327
2328   return FALSE;
2329 }
2330
2331 /* Timeout callback. This is called if connection is idle or for some
2332    other reason is not responding within some period of time. This 
2333    disconnects the remote end. */
2334
2335 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2336 {
2337   SilcServerConnection sconn = (SilcServerConnection)context;
2338   SilcSocketConnection sock = sconn->server->sockets[fd];
2339
2340   silc_server_disconnect_remote(sconn->server, sock, 
2341                                 "Server closed connection: "
2342                                 "Connection timeout");
2343 }
2344
2345 /* Internal routine used to send (relay, route) private messages to some
2346    destination. If the private message key does not exist then the message
2347    is re-encrypted, otherwise we just pass it along. */
2348
2349 static void 
2350 silc_server_private_message_send_internal(SilcServer server,
2351                                           SilcSocketConnection dst_sock,
2352                                           SilcCipher cipher,
2353                                           SilcHmac hmac,
2354                                           SilcPacketContext *packet)
2355 {
2356   SilcBuffer buffer = packet->buffer;
2357
2358   /* Send and re-encrypt if private messge key does not exist */
2359   if ((packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) == FALSE) {
2360
2361     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
2362                      + packet->dst_id_len + packet->padlen);
2363     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2364     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2365     
2366     /* Re-encrypt packet */
2367     silc_packet_encrypt(cipher, hmac, dst_sock->outbuf, buffer->len);
2368     
2369     /* Send the packet */
2370     silc_server_packet_send_real(server, dst_sock, FALSE);
2371
2372   } else {
2373     /* Key exist so just send it */
2374     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
2375                      + packet->dst_id_len + packet->padlen);
2376     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
2377     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
2378     silc_server_packet_send_real(server, dst_sock, FALSE);
2379   }
2380 }
2381
2382 /* Received private message. This resolves the destination of the message 
2383    and sends the packet. This is used by both server and router.  If the
2384    destination is our locally connected client this sends the packet to
2385    the client. This may also send the message for further routing if
2386    the destination is not in our server (or router). */
2387
2388 void silc_server_private_message(SilcServer server,
2389                                  SilcSocketConnection sock,
2390                                  SilcPacketContext *packet)
2391 {
2392   SilcBuffer buffer = packet->buffer;
2393   SilcClientID *id;
2394   SilcServerEntry router;
2395   SilcSocketConnection dst_sock;
2396   SilcClientEntry client;
2397   SilcIDListData idata;
2398
2399   SILC_LOG_DEBUG(("Start"));
2400
2401   if (!packet->dst_id) {
2402     SILC_LOG_ERROR(("Bad Client ID in private message packet, dropped"));
2403     goto err;
2404   }
2405
2406   /* Decode destination Client ID */
2407   id = silc_id_str2id(packet->dst_id, SILC_ID_CLIENT);
2408   if (!id) {
2409     SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
2410     goto err;
2411   }
2412
2413   /* If the destination belongs to our server we don't have to route
2414      the message anywhere but to send it to the local destination. */
2415   client = silc_idlist_find_client_by_id(server->local_list, id);
2416   if (client) {
2417     /* It exists, now deliver the message to the destination */
2418     dst_sock = (SilcSocketConnection)client->connection;
2419
2420     /* If we are router and the client has router then the client is in
2421        our cell but not directly connected to us. */
2422     if (server->server_type == SILC_ROUTER && client->router) {
2423       /* We are of course in this case the client's router thus the real
2424          "router" of the client is the server who owns the client. Thus
2425          we will send the packet to that server. */
2426       router = (SilcServerEntry)dst_sock->user_data;
2427       idata = (SilcIDListData)router;
2428       //      assert(client->router == server->id_entry);
2429
2430       silc_server_private_message_send_internal(server, dst_sock,
2431                                                 idata->send_key,
2432                                                 idata->hmac,
2433                                                 packet);
2434       goto out;
2435     }
2436
2437     /* Seems that client really is directly connected to us */
2438     idata = (SilcIDListData)client;
2439     silc_server_private_message_send_internal(server, dst_sock, 
2440                                               idata->send_key,
2441                                               idata->hmac, packet);
2442     goto out;
2443   }
2444
2445   /* Destination belongs to someone not in this server. If we are normal
2446      server our action is to send the packet to our router. */
2447   if (server->server_type == SILC_SERVER && !server->standalone) {
2448     router = server->id_entry->router;
2449
2450     /* Send to primary route */
2451     if (router) {
2452       dst_sock = (SilcSocketConnection)router->connection;
2453       idata = (SilcIDListData)router;
2454       silc_server_private_message_send_internal(server, dst_sock, 
2455                                                 idata->send_key,
2456                                                 idata->hmac, packet);
2457     }
2458     goto out;
2459   }
2460
2461   /* We are router and we will perform route lookup for the destination 
2462      and send the message to fastest route. */
2463   if (server->server_type == SILC_ROUTER && !server->standalone) {
2464     dst_sock = silc_server_get_route(server, id, SILC_ID_CLIENT);
2465     router = (SilcServerEntry)dst_sock->user_data;
2466     idata = (SilcIDListData)router;
2467
2468     /* Get fastest route and send packet. */
2469     if (router)
2470       silc_server_private_message_send_internal(server, dst_sock, 
2471                                                 idata->send_key,
2472                                                 idata->hmac, packet);
2473
2474     goto out;
2475   }
2476
2477  err:
2478   silc_server_send_error(server, sock, 
2479                          "No such nickname: Private message not sent");
2480  out:
2481   silc_buffer_free(buffer);
2482 }
2483
2484 /* Process received channel message. The message can be originated from
2485    client or server. */
2486
2487 void silc_server_channel_message(SilcServer server,
2488                                  SilcSocketConnection sock,
2489                                  SilcPacketContext *packet)
2490 {
2491   SilcChannelEntry channel = NULL;
2492   SilcChannelClientEntry chl;
2493   SilcChannelID *id = NULL;
2494   void *sender = NULL;
2495   SilcBuffer buffer = packet->buffer;
2496
2497   SILC_LOG_DEBUG(("Processing channel message"));
2498
2499   /* Sanity checks */
2500   if (packet->dst_id_type != SILC_ID_CHANNEL) {
2501     SILC_LOG_ERROR(("Received bad message for channel, dropped"));
2502     SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
2503     goto out;
2504   }
2505
2506   /* Find channel entry */
2507   id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
2508   channel = silc_idlist_find_channel_by_id(server->local_list, id);
2509   if (!channel) {
2510     SILC_LOG_DEBUG(("Could not find channel"));
2511     goto out;
2512   }
2513
2514   /* See that this client is on the channel. If the message is coming
2515      from router we won't do the check as the message is from client that
2516      we don't know about. Also, if the original sender is not client
2517      (as it can be server as well) we don't do the check. */
2518   sender = silc_id_str2id(packet->src_id, packet->src_id_type);
2519   if (sock->type != SILC_SOCKET_TYPE_ROUTER && 
2520       packet->src_id_type == SILC_ID_CLIENT) {
2521     silc_list_start(channel->user_list);
2522     while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2523       if (chl->client && !SILC_ID_CLIENT_COMPARE(chl->client->id, sender))
2524         break;
2525     }
2526     if (chl == SILC_LIST_END)
2527       goto out;
2528   }
2529
2530   /* Distribute the packet to our local clients. This will send the
2531      packet for further routing as well, if needed. */
2532   silc_server_packet_relay_to_channel(server, sock, channel, sender,
2533                                       packet->src_id_type,
2534                                       packet->buffer->data,
2535                                       packet->buffer->len, FALSE);
2536
2537  out:
2538   if (sender)
2539     silc_free(sender);
2540   if (id)
2541     silc_free(id);
2542   silc_buffer_free(buffer);
2543 }
2544
2545 /* Received channel key packet. We distribute the key to all of our locally
2546    connected clients on the channel. */
2547 /* XXX Router must accept this packet and distribute the key to all its
2548    server that has clients on the channel */
2549
2550 void silc_server_channel_key(SilcServer server,
2551                              SilcSocketConnection sock,
2552                              SilcPacketContext *packet)
2553 {
2554   SilcBuffer buffer = packet->buffer;
2555   SilcChannelKeyPayload payload = NULL;
2556   SilcChannelID *id = NULL;
2557   SilcChannelEntry channel;
2558   SilcChannelClientEntry chl;
2559   SilcClientEntry client;
2560   unsigned char *tmp;
2561   unsigned int tmp_len;
2562   char *cipher;
2563
2564   if (packet->src_id_type != SILC_ID_SERVER &&
2565       sock->type != SILC_SOCKET_TYPE_ROUTER)
2566     goto out;
2567
2568   /* Decode channel key payload */
2569   payload = silc_channel_key_payload_parse(buffer);
2570   if (!payload) {
2571     SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2572     goto out;
2573   }
2574
2575   /* Get channel ID */
2576   tmp = silc_channel_key_get_id(payload, &tmp_len);
2577   id = silc_id_payload_parse_id(tmp, tmp_len);
2578   if (!id)
2579     goto out;
2580
2581   /* Get the channel entry */
2582   channel = silc_idlist_find_channel_by_id(server->local_list, id);
2583   if (!channel) {
2584     SILC_LOG_ERROR(("Received key for non-existent channel"));
2585     goto out;
2586   }
2587
2588   /* Save the key for us as well */
2589   tmp = silc_channel_key_get_key(payload, &tmp_len);
2590   if (!tmp)
2591     goto out;
2592   cipher = silc_channel_key_get_cipher(payload, NULL);;
2593   if (!cipher)
2594     goto out;
2595   if (!silc_cipher_alloc(cipher, &channel->channel_key))
2596     goto out;
2597
2598   channel->key_len = tmp_len * 8;
2599   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2600   memcpy(channel->key, tmp, tmp_len);
2601   channel->channel_key->cipher->set_key(channel->channel_key->context, 
2602                                         tmp, tmp_len);
2603
2604   /* Distribute the key to all clients on the channel */
2605   /* XXX Some other sender should be used, I think this is not correct */
2606   silc_list_start(channel->user_list);
2607   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2608     client = chl->client;
2609
2610     if (client)
2611       silc_server_packet_send_dest(server, client->connection,
2612                                    SILC_PACKET_CHANNEL_KEY, 0,
2613                                    client->id, SILC_ID_CLIENT,
2614                                    buffer->data, buffer->len, FALSE);
2615   }
2616
2617  out:
2618   if (id)
2619     silc_free(id);
2620   if (payload)
2621     silc_channel_key_payload_free(payload);
2622   silc_buffer_free(buffer);
2623 }
2624
2625 /* Sends current motd to client */
2626
2627 void silc_server_send_motd(SilcServer server,
2628                            SilcSocketConnection sock)
2629 {
2630   char *motd;
2631   int motd_len;
2632
2633   if (server->config && server->config->motd && 
2634       server->config->motd->motd_file) {
2635
2636     motd = silc_file_read(server->config->motd->motd_file, &motd_len);
2637     if (!motd)
2638       return;
2639
2640     silc_server_send_notify(server, sock, SILC_NOTIFY_TYPE_MOTD, 1,
2641                             motd, motd_len);
2642     silc_free(motd);
2643   }
2644 }
2645
2646 /* Sends error message. Error messages may or may not have any 
2647    implications. */
2648
2649 void silc_server_send_error(SilcServer server,
2650                             SilcSocketConnection sock,
2651                             const char *fmt, ...)
2652 {
2653   va_list ap;
2654   unsigned char buf[4096];
2655
2656   memset(buf, 0, sizeof(buf));
2657   va_start(ap, fmt);
2658   vsprintf(buf, fmt, ap);
2659   va_end(ap);
2660
2661   silc_server_packet_send(server, sock, SILC_PACKET_ERROR, 0, 
2662                           buf, strlen(buf), FALSE);
2663 }
2664
2665 /* Sends notify message. If format is TRUE the variable arguments are
2666    formatted and the formatted string is sent as argument payload. If it is
2667    FALSE then each argument is sent as separate argument and their format
2668    in the argument list must be { argument data, argument length }. */
2669
2670 void silc_server_send_notify(SilcServer server,
2671                              SilcSocketConnection sock,
2672                              SilcNotifyType type,
2673                              unsigned int argc, ...)
2674 {
2675   va_list ap;
2676   SilcBuffer packet;
2677
2678   va_start(ap, argc);
2679
2680   packet = silc_notify_payload_encode(type, argc, ap);
2681   silc_server_packet_send(server, sock, SILC_PACKET_NOTIFY, 0, 
2682                           packet->data, packet->len, FALSE);
2683   silc_buffer_free(packet);
2684 }
2685
2686 /* Sends notify message destined to specific entity. */
2687
2688 void silc_server_send_notify_dest(SilcServer server,
2689                                   SilcSocketConnection sock,
2690                                   void *dest_id,
2691                                   SilcIdType dest_id_type,
2692                                   SilcNotifyType type,
2693                                   unsigned int argc, ...)
2694 {
2695   va_list ap;
2696   SilcBuffer packet;
2697
2698   va_start(ap, argc);
2699
2700   packet = silc_notify_payload_encode(type, argc, ap);
2701   silc_server_packet_send_dest(server, sock, SILC_PACKET_NOTIFY, 0, 
2702                                dest_id, dest_id_type,
2703                                packet->data, packet->len, FALSE);
2704   silc_buffer_free(packet);
2705 }
2706
2707 /* Sends notify message to a channel. The notify message sent is 
2708    distributed to all clients on the channel. */
2709
2710 void silc_server_send_notify_to_channel(SilcServer server,
2711                                         SilcChannelEntry channel,
2712                                         SilcNotifyType type,
2713                                         unsigned int argc, ...)
2714 {
2715   va_list ap;
2716   SilcBuffer packet;
2717
2718   va_start(ap, argc);
2719
2720   packet = silc_notify_payload_encode(type, argc, ap);
2721   silc_server_packet_send_to_channel(server, channel, 
2722                                      SILC_PACKET_NOTIFY,
2723                                      packet->data, packet->len, FALSE);
2724   silc_buffer_free(packet);
2725 }
2726
2727 /* Send notify message to all clients the client has joined. It is quaranteed
2728    that the message is sent only once to a client (ie. if a client is joined
2729    on two same channel it will receive only one notify message). Also, this
2730    sends only to local clients (locally connected if we are server, and to
2731    local servers if we are router). */
2732
2733 void silc_server_send_notify_on_channels(SilcServer server,
2734                                          SilcClientEntry client,
2735                                          SilcNotifyType type,
2736                                          unsigned int argc, ...)
2737 {
2738   int k;
2739   SilcSocketConnection sock = NULL;
2740   SilcPacketContext packetdata;
2741   SilcClientEntry c;
2742   SilcClientEntry *sent_clients = NULL;
2743   unsigned int sent_clients_count = 0;
2744   SilcServerEntry *routed = NULL;
2745   unsigned int routed_count = 0;
2746   SilcChannelEntry channel;
2747   SilcChannelClientEntry chl, chl2;
2748   SilcIDListData idata;
2749   SilcBuffer packet;
2750   unsigned char *data;
2751   unsigned int data_len;
2752   int force_send = FALSE;
2753   va_list ap;
2754
2755   if (!silc_list_count(client->channels))
2756     return;
2757
2758   va_start(ap, argc);
2759   packet = silc_notify_payload_encode(type, argc, ap);
2760   data = packet->data;
2761   data_len = packet->len;
2762
2763   /* Set the packet context pointers. */
2764   packetdata.flags = 0;
2765   packetdata.type = SILC_PACKET_NOTIFY;
2766   packetdata.src_id = silc_id_id2str(server->id, SILC_ID_SERVER);
2767   packetdata.src_id_len = SILC_ID_SERVER_LEN;
2768   packetdata.src_id_type = SILC_ID_SERVER;
2769   packetdata.rng = server->rng;
2770
2771   silc_list_start(client->channels);
2772   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2773     channel = chl->channel;
2774
2775     /* Send the message to all clients on the channel's client list. */
2776     silc_list_start(channel->user_list);
2777     while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2778       c = chl2->client;
2779       
2780       /* Check if we have sent the packet to this client already */
2781       for (k = 0; k < sent_clients_count; k++)
2782         if (sent_clients[k] == c)
2783           break;
2784       if (k < sent_clients_count)
2785         continue;
2786
2787       /* If we are router and if this client has router set it is not
2788          locally connected client and we will route the message to the
2789          router set in the client. */
2790       if (c && c->router && server->server_type == SILC_ROUTER) {
2791         /* Check if we have sent the packet to this route already */
2792         for (k = 0; k < routed_count; k++)
2793           if (routed[k] == c->router)
2794             break;
2795         if (k < routed_count)
2796           continue;
2797         
2798         /* Get data used in packet header encryption, keys and stuff. */
2799         sock = (SilcSocketConnection)c->router->connection;
2800         idata = (SilcIDListData)c->router;
2801         
2802         packetdata.dst_id = silc_id_id2str(c->router->id, SILC_ID_SERVER);
2803         packetdata.dst_id_len = SILC_ID_SERVER_LEN;
2804         packetdata.dst_id_type = SILC_ID_SERVER;
2805         packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
2806           packetdata.src_id_len + packetdata.dst_id_len;
2807         packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2808
2809         /* Send the packet */
2810         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2811                                                 idata->send_key, idata->hmac, 
2812                                                 data, data_len, FALSE, 
2813                                                 force_send);
2814         
2815         silc_free(packetdata.dst_id);
2816
2817         /* We want to make sure that the packet is routed to same router
2818            only once. Mark this route as sent route. */
2819         k = routed_count;
2820         routed = silc_realloc(routed, sizeof(*routed) * (k + 1));
2821         routed[k] = c->router;
2822         routed_count++;
2823
2824         continue;
2825       }
2826
2827       /* Send to locally connected client */
2828       if (c) {
2829         
2830         /* Get data used in packet header encryption, keys and stuff. */
2831         sock = (SilcSocketConnection)c->connection;
2832         idata = (SilcIDListData)c;
2833         
2834         packetdata.dst_id = silc_id_id2str(c->id, SILC_ID_CLIENT);
2835         packetdata.dst_id_len = SILC_ID_CLIENT_LEN;
2836         packetdata.dst_id_type = SILC_ID_CLIENT;
2837         packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
2838           packetdata.src_id_len + packetdata.dst_id_len;
2839         packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
2840
2841         /* Send the packet */
2842         silc_server_packet_send_to_channel_real(server, sock, &packetdata,
2843                                                 idata->send_key, idata->hmac, 
2844                                                 data, data_len, FALSE, 
2845                                                 force_send);
2846
2847         silc_free(packetdata.dst_id);
2848
2849         /* Make sure that we send the notify only once per client. */
2850         sent_clients = silc_realloc(sent_clients, sizeof(*sent_clients) * 
2851                                     (sent_clients_count + 1));
2852         sent_clients[sent_clients_count] = c;
2853         sent_clients_count++;
2854       }
2855     }
2856   }
2857
2858   if (routed_count)
2859     silc_free(routed);
2860   if (sent_clients_count)
2861     silc_free(sent_clients);
2862   silc_free(packetdata.src_id);
2863 }
2864
2865 /* Sends New ID Payload to remote end. The packet is used to distribute
2866    information about new registered clients, servers, channel etc. usually
2867    to routers so that they can keep these information up to date. 
2868    If the argument `broadcast' is TRUE then the packet is sent as
2869    broadcast packet. */
2870
2871 void silc_server_send_new_id(SilcServer server,
2872                              SilcSocketConnection sock,
2873                              int broadcast,
2874                              void *id, SilcIdType id_type, 
2875                              unsigned int id_len)
2876 {
2877   SilcBuffer idp;
2878
2879   idp = silc_id_payload_encode(id, id_type);
2880   silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 
2881                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
2882                           idp->data, idp->len, FALSE);
2883   silc_buffer_free(idp);
2884 }
2885
2886 /* Sends Replace ID payload to remote end. This is used to replace old
2887    ID with new ID sent in the packet.  This is called for example when
2888    user changes nickname and we create new ID for the user.  If the 
2889    argument `broadcast' is TRUE then the packet is sent as
2890    broadcast packet. */
2891 /* XXX It would be expected that the new id is same type as the old
2892    ID. :) */
2893
2894 void silc_server_send_replace_id(SilcServer server,
2895                                  SilcSocketConnection sock,
2896                                  int broadcast,
2897                                  void *old_id, SilcIdType old_id_type,
2898                                  unsigned int old_id_len,
2899                                  void *new_id, SilcIdType new_id_type,
2900                                  unsigned int new_id_len)
2901 {
2902   SilcBuffer packet;
2903   unsigned char *oid;
2904   unsigned char *nid;
2905
2906   oid = silc_id_id2str(old_id, old_id_type);
2907   if (!oid)
2908     return;
2909
2910   nid = silc_id_id2str(new_id, new_id_type);
2911   if (!nid)
2912     return;
2913
2914   packet = silc_buffer_alloc(2 + 2 + 2 + 2 + old_id_len + new_id_len);
2915   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2916   silc_buffer_format(packet,
2917                      SILC_STR_UI_SHORT(old_id_type),
2918                      SILC_STR_UI_SHORT(old_id_len),
2919                      SILC_STR_UI_XNSTRING(oid, old_id_len),
2920                      SILC_STR_UI_SHORT(new_id_type),
2921                      SILC_STR_UI_SHORT(new_id_len),
2922                      SILC_STR_UI_XNSTRING(nid, new_id_len),
2923                      SILC_STR_END);
2924
2925   silc_server_packet_send(server, sock, SILC_PACKET_REPLACE_ID, 
2926                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
2927                           packet->data, packet->len, FALSE);
2928   silc_free(oid);
2929   silc_free(nid);
2930   silc_buffer_free(packet);
2931 }
2932
2933 /* This function is used to send Remove Channel User payload. This may sent
2934    by server but is usually used only by router to notify other routers that
2935    user has left a channel. Normal server sends this packet to its router
2936    to notify that the router should not hold a record about this client
2937    on a channel anymore. Router distributes it further to other routers. */
2938
2939 void silc_server_send_remove_channel_user(SilcServer server,
2940                                           SilcSocketConnection sock,
2941                                           int broadcast,
2942                                           void *client_id, void *channel_id)
2943 {
2944   SilcBuffer packet;
2945   unsigned char *clid, *chid;
2946
2947   clid = silc_id_id2str(client_id, SILC_ID_CLIENT);
2948   if (!clid)
2949     return;
2950
2951   chid = silc_id_id2str(channel_id, SILC_ID_CHANNEL);
2952   if (!chid)
2953     return;
2954
2955   packet = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN + SILC_ID_CHANNEL_LEN);
2956   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2957   silc_buffer_format(packet,
2958                      SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
2959                      SILC_STR_UI_XNSTRING(clid, SILC_ID_CLIENT_LEN),
2960                      SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2961                      SILC_STR_UI_XNSTRING(chid, SILC_ID_CHANNEL_LEN),
2962                      SILC_STR_END);
2963
2964   silc_server_packet_send(server, sock, SILC_PACKET_REMOVE_CHANNEL_USER, 
2965                           broadcast ? SILC_PACKET_FLAG_BROADCAST : 0, 
2966                           packet->data, packet->len, FALSE);
2967   silc_free(clid);
2968   silc_free(chid);
2969   silc_buffer_free(packet);
2970 }
2971
2972 /* Received packet to replace a ID. This checks that the requested ID
2973    exists and replaces it with the new one. */
2974
2975 void silc_server_replace_id(SilcServer server,
2976                             SilcSocketConnection sock,
2977                             SilcPacketContext *packet)
2978 {
2979   SilcBuffer buffer = packet->buffer;
2980   unsigned char *old_id = NULL, *new_id = NULL;
2981   SilcIdType old_id_type, new_id_type;
2982   unsigned short old_id_len, new_id_len;
2983   void *id = NULL, *id2 = NULL;
2984
2985   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2986       packet->src_id_type == SILC_ID_CLIENT)
2987     return;
2988
2989   SILC_LOG_DEBUG(("Replacing ID"));
2990
2991   silc_buffer_unformat(buffer,
2992                        SILC_STR_UI_SHORT(&old_id_type),
2993                        SILC_STR_UI16_NSTRING_ALLOC(&old_id, &old_id_len),
2994                        SILC_STR_UI_SHORT(&new_id_type),
2995                        SILC_STR_UI16_NSTRING_ALLOC(&new_id, &new_id_len),
2996                        SILC_STR_END);
2997
2998   if (old_id_type != new_id_type)
2999     goto out;
3000
3001   if (old_id_len != silc_id_get_len(old_id_type) ||
3002       new_id_len != silc_id_get_len(new_id_type))
3003     goto out;
3004
3005   id = silc_id_str2id(old_id, old_id_type);
3006   if (!id)
3007     goto out;
3008
3009   id2 = silc_id_str2id(new_id, new_id_type);
3010   if (!id2)
3011     goto out;
3012
3013   /* Replace the old ID */
3014   switch(old_id_type) {
3015   case SILC_ID_CLIENT:
3016     if (silc_idlist_replace_client_id(server->local_list, id, id2) == NULL)
3017       if (server->server_type == SILC_ROUTER)
3018         silc_idlist_replace_client_id(server->global_list, id, id2);
3019     break;
3020
3021   case SILC_ID_SERVER:
3022     if (silc_idlist_replace_server_id(server->local_list, id, id2) == NULL)
3023       if (server->server_type == SILC_ROUTER)
3024         silc_idlist_replace_server_id(server->global_list, id, id2);
3025     break;
3026
3027   case SILC_ID_CHANNEL:
3028     /* XXX Hmm... Basically this cannot occur. Channel ID's cannot be
3029        re-generated. */
3030     silc_free(id2);
3031     break;
3032
3033   default:
3034     silc_free(id2);
3035     break;
3036   }
3037
3038  out:
3039   if (id)
3040     silc_free(id);
3041   if (old_id)
3042     silc_free(old_id);
3043   if (new_id)
3044     silc_free(new_id);
3045 }
3046
3047 /* Creates new channel. */
3048
3049 SilcChannelEntry silc_server_new_channel(SilcServer server, 
3050                                          SilcServerID *router_id,
3051                                          char *cipher, char *channel_name)
3052 {
3053   int i, channel_len, key_len;
3054   SilcChannelID *channel_id;
3055   SilcChannelEntry entry;
3056   SilcCipher key;
3057   unsigned char channel_key[32], *id_string;
3058   SilcBuffer packet;
3059
3060   SILC_LOG_DEBUG(("Creating new channel"));
3061
3062   /* Create channel key */
3063   for (i = 0; i < 32; i++)
3064     channel_key[i] = silc_rng_get_byte(server->rng);
3065
3066   if (!cipher)
3067     cipher = "twofish";
3068
3069   /* Allocate keys */
3070   key_len = 16;
3071   silc_cipher_alloc(cipher, &key);
3072   key->cipher->set_key(key->context, channel_key, key_len);
3073
3074   channel_name = strdup(channel_name);
3075
3076   /* Create the channel */
3077   silc_id_create_channel_id(router_id, server->rng, &channel_id);
3078   entry = silc_idlist_add_channel(server->local_list, channel_name, 
3079                                   SILC_CHANNEL_MODE_NONE, channel_id, 
3080                                   NULL, key);
3081   if (!entry) {
3082     silc_free(channel_name);
3083     return NULL;
3084   }
3085
3086   entry->key = silc_calloc(key_len, sizeof(*entry->key));
3087   entry->key_len = key_len * 8;
3088   memcpy(entry->key, channel_key, key_len);
3089   memset(channel_key, 0, sizeof(channel_key));
3090
3091   /* Notify other routers about the new channel. We send the packet
3092      to our primary route. */
3093   if (server->standalone == FALSE) {
3094     channel_len = strlen(channel_name);
3095     id_string = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3096     packet = silc_buffer_alloc(2 + SILC_ID_CHANNEL_LEN);
3097
3098     silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
3099     silc_buffer_format(packet,
3100                        SILC_STR_UI_SHORT(channel_len),
3101                        SILC_STR_UI_XNSTRING(channel_name, channel_len),
3102                        SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3103                        SILC_STR_UI_XNSTRING(id_string, SILC_ID_CHANNEL_LEN),
3104                        SILC_STR_END);
3105
3106     /* Send the packet to our router. */
3107     silc_server_packet_send(server, (SilcSocketConnection) 
3108                             server->id_entry->router->connection,
3109                             SILC_PACKET_NEW_CHANNEL_USER, 0, 
3110                             packet->data, packet->len, TRUE);
3111     
3112     silc_free(id_string);
3113     silc_buffer_free(packet);
3114   }
3115
3116   return entry;
3117 }
3118
3119 /* Create new client. This processes incoming NEW_CLIENT packet and creates
3120    Client ID for the client. Client becomes registered after calling this
3121    functions. */
3122
3123 SilcClientEntry silc_server_new_client(SilcServer server,
3124                                        SilcSocketConnection sock,
3125                                        SilcPacketContext *packet)
3126 {
3127   SilcBuffer buffer = packet->buffer;
3128   SilcClientEntry client;
3129   SilcIDCacheEntry cache;
3130   SilcClientID *client_id;
3131   SilcBuffer reply;
3132   SilcIDListData idata;
3133   char *username = NULL, *realname = NULL, *id_string;
3134
3135   SILC_LOG_DEBUG(("Creating new client"));
3136
3137   if (sock->type != SILC_SOCKET_TYPE_CLIENT)
3138     return NULL;
3139
3140   /* Take client entry */
3141   client = (SilcClientEntry)sock->user_data;
3142   idata = (SilcIDListData)client;
3143
3144   /* Fetch the old client cache entry so that we can update it. */
3145   if (!silc_idcache_find_by_context(server->local_list->clients,
3146                                     sock->user_data, &cache)) {
3147     SILC_LOG_ERROR(("Lost client's cache entry - bad thing"));
3148     return NULL;
3149   }
3150
3151   /* Parse incoming packet */
3152   silc_buffer_unformat(buffer,
3153                        SILC_STR_UI16_STRING_ALLOC(&username),
3154                        SILC_STR_UI16_STRING_ALLOC(&realname),
3155                        SILC_STR_END);
3156
3157   /* Create Client ID */
3158   silc_id_create_client_id(server->id, server->rng, server->md5hash,
3159                            username, &client_id);
3160
3161   /* Update client entry */
3162   idata->registered = TRUE;
3163   client->nickname = strdup(username);
3164   client->username = username;
3165   client->userinfo = realname;
3166   client->id = client_id;
3167
3168   /* Update the cache entry */
3169   cache->id = (void *)client_id;
3170   cache->type = SILC_ID_CLIENT;
3171   cache->data = username;
3172   silc_idcache_sort_by_data(server->local_list->clients);
3173
3174   /* Notify our router about new client on the SILC network */
3175   if (!server->standalone)
3176     silc_server_send_new_id(server, (SilcSocketConnection) 
3177                             server->id_entry->router->connection, 
3178                             server->server_type == SILC_SERVER ? TRUE : FALSE,
3179                             client->id, SILC_ID_CLIENT, SILC_ID_CLIENT_LEN);
3180   
3181   /* Send the new client ID to the client. */
3182   id_string = silc_id_id2str(client->id, SILC_ID_CLIENT);
3183   reply = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN);
3184   silc_buffer_pull_tail(reply, SILC_BUFFER_END(reply));
3185   silc_buffer_format(reply,
3186                      SILC_STR_UI_SHORT(SILC_ID_CLIENT),
3187                      SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
3188                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_CLIENT_LEN),
3189                      SILC_STR_END);
3190   silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 0, 
3191                           reply->data, reply->len, FALSE);
3192   silc_free(id_string);
3193   silc_buffer_free(reply);
3194
3195   /* Send some nice info to the client */
3196   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3197                           ("Welcome to the SILC Network %s@%s",
3198                            username, sock->hostname));
3199   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3200                           ("Your host is %s, running version %s",
3201                            server->config->server_info->server_name,
3202                            server_version));
3203   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3204                           ("Your connection is secured with %s cipher, "
3205                            "key length %d bits",
3206                            idata->send_key->cipher->name,
3207                            idata->send_key->cipher->key_len));
3208   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
3209                           ("Your current nickname is %s",
3210                            client->nickname));
3211
3212   /* Send motd */
3213   silc_server_send_motd(server, sock);
3214
3215   return client;
3216 }
3217
3218 /* Create new server. This processes incoming NEW_SERVER packet and
3219    saves the received Server ID. The server is our locally connected
3220    server thus we save all the information and save it to local list. 
3221    This funtion can be used by both normal server and router server.
3222    If normal server uses this it means that its router has connected
3223    to the server. If router uses this it means that one of the cell's
3224    servers is connected to the router. */
3225
3226 SilcServerEntry silc_server_new_server(SilcServer server,
3227                                        SilcSocketConnection sock,
3228                                        SilcPacketContext *packet)
3229 {
3230   SilcBuffer buffer = packet->buffer;
3231   SilcServerEntry new_server;
3232   SilcIDCacheEntry cache;
3233   SilcServerID *server_id;
3234   SilcIDListData idata;
3235   unsigned char *server_name, *id_string;
3236   unsigned short id_len;
3237
3238   SILC_LOG_DEBUG(("Creating new server"));
3239
3240   if (sock->type != SILC_SOCKET_TYPE_SERVER &&
3241       sock->type != SILC_SOCKET_TYPE_ROUTER)
3242     return NULL;
3243
3244   /* Take server entry */
3245   new_server = (SilcServerEntry)sock->user_data;
3246   idata = (SilcIDListData)new_server;
3247
3248   /* Fetch the old server cache entry so that we can update it. */
3249   if (!silc_idcache_find_by_context(server->local_list->servers,
3250                                     sock->user_data, &cache)) {
3251     SILC_LOG_ERROR(("Lost server's cache entry - bad thing"));
3252     return NULL;
3253   }
3254
3255   /* Parse the incoming packet */
3256   silc_buffer_unformat(buffer,
3257                        SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
3258                        SILC_STR_UI16_STRING_ALLOC(&server_name),
3259                        SILC_STR_END);
3260
3261   if (id_len > buffer->len) {
3262     silc_free(id_string);
3263     silc_free(server_name);
3264     return NULL;
3265   }
3266
3267   /* Get Server ID */
3268   server_id = silc_id_str2id(id_string, SILC_ID_SERVER);
3269   silc_free(id_string);
3270
3271   /* Update client entry */
3272   idata->registered = TRUE;
3273   new_server->server_name = server_name;
3274   new_server->id = server_id;
3275
3276   /* Update the cache entry */
3277   cache->id = (void *)server_id;
3278   cache->type = SILC_ID_SERVER;
3279   cache->data = server_name;
3280   silc_idcache_sort_by_data(server->local_list->servers);
3281
3282   /* Distribute the information about new server in the SILC network
3283      to our router. If we are normal server we won't send anything
3284      since this connection must be our router connection. */
3285   if (server->server_type == SILC_ROUTER && !server->standalone &&
3286       server->id_entry->router->connection != sock)
3287     silc_server_send_new_id(server, server->id_entry->router->connection,
3288                             TRUE, new_server->id, SILC_ID_SERVER, 
3289                             SILC_ID_SERVER_LEN);
3290
3291   return new_server;
3292 }
3293
3294 /* Processes incoming New ID Payload. New ID Payload is used to distribute
3295    information about newly registered clients, servers and created 
3296    channels. */
3297
3298 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
3299                         SilcPacketContext *packet)
3300 {
3301   SilcBuffer buffer = packet->buffer;
3302   SilcIDList id_list;
3303   SilcServerEntry tmpserver, router;
3304   SilcSocketConnection router_sock;
3305   SilcIDPayload idp;
3306   SilcIdType id_type;
3307   void *id, *tmpid;
3308
3309   SILC_LOG_DEBUG(("Processing new ID"));
3310
3311   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3312       server->server_type == SILC_SERVER ||
3313       packet->src_id_type != SILC_ID_SERVER)
3314     return;
3315
3316   idp = silc_id_payload_parse(buffer);
3317   if (!idp)
3318     return;
3319
3320   id_type = silc_id_payload_get_type(idp);
3321
3322   /* Normal server cannot have other normal server connections */
3323   if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER)
3324     goto out;
3325
3326   id = silc_id_payload_get_id(idp);
3327   if (!id)
3328     goto out;
3329
3330   /* If the packet is originated from the one who sent it to us we know
3331      that the ID belongs to our cell, unless the sender was router. */
3332   tmpid = silc_id_str2id(packet->src_id, SILC_ID_SERVER);
3333   tmpserver = (SilcServerEntry)sock->user_data;
3334
3335   if (!SILC_ID_SERVER_COMPARE(tmpid, tmpserver->id) &&
3336       sock->type == SILC_SOCKET_TYPE_SERVER) {
3337     id_list = server->local_list;
3338     router_sock = sock;
3339     router = sock->user_data;
3340     /*    router = server->id_entry; */
3341   } else {
3342     id_list = server->global_list;
3343     router_sock = (SilcSocketConnection)server->id_entry->router->connection;
3344     router = server->id_entry->router;
3345   }
3346
3347   silc_free(tmpid);
3348
3349   switch(id_type) {
3350   case SILC_ID_CLIENT:
3351     {
3352       SilcClientEntry idlist;
3353
3354       /* Add the client to our local list. We are router and we keep
3355          cell specific local database of all clients in the cell. */
3356       idlist = silc_idlist_add_client(id_list, NULL, NULL, NULL,
3357                                       id, router, router_sock);
3358     }
3359     break;
3360
3361   case SILC_ID_SERVER:
3362     {
3363       SilcServerEntry idlist;
3364
3365       /* Add the server to our local list. We are router and we keep
3366          cell specific local database of all servers in the cell. */
3367       idlist = silc_idlist_add_server(id_list, NULL, 0, id, router, 
3368                                       router_sock);
3369     }
3370     break;
3371
3372   case SILC_ID_CHANNEL:
3373     /* Add the channel to our local list. We are router and we keep
3374        cell specific local database of all channels in the cell. */
3375     silc_idlist_add_channel(id_list, NULL, 0, id, router, NULL);
3376     break;
3377
3378   default:
3379     break;
3380   }
3381
3382  out:
3383   silc_id_payload_free(idp);
3384 }
3385
3386 /* Received packet to remove a user from a channel. Routers notify other
3387    routers that user has left a channel. Client must not send this packet. 
3388    Normal server may send this packet but ignores if it receives one. */
3389
3390 void silc_server_remove_channel_user(SilcServer server,
3391                                      SilcSocketConnection sock,
3392                                      SilcPacketContext *packet)
3393 {
3394   SilcBuffer buffer = packet->buffer;
3395   unsigned char *tmp1 = NULL, *tmp2 = NULL;
3396   SilcClientID *client_id = NULL;
3397   SilcChannelID *channel_id = NULL;
3398   SilcChannelEntry channel;
3399   SilcClientEntry client;
3400
3401   SILC_LOG_DEBUG(("Removing user from channel"));
3402
3403   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3404       server->server_type == SILC_SERVER)
3405     return;
3406
3407   silc_buffer_unformat(buffer,
3408                        SILC_STR_UI16_STRING_ALLOC(&tmp1),
3409                        SILC_STR_UI16_STRING_ALLOC(&tmp2),
3410                        SILC_STR_END);
3411
3412   if (!tmp1 || !tmp2)
3413     goto out;
3414
3415   client_id = silc_id_str2id(tmp1, SILC_ID_CLIENT);
3416   channel_id = silc_id_str2id(tmp2, SILC_ID_CHANNEL);
3417   if (!client_id || !channel_id)
3418     goto out;
3419
3420   /* XXX routers should check server->global_list as well */
3421   /* Get channel entry */
3422   channel = silc_idlist_find_channel_by_id(server->local_list, channel_id);
3423   if (!channel)
3424     goto out;
3425   
3426   /* XXX routers should check server->global_list as well */
3427   /* Get client entry */
3428   client = silc_idlist_find_client_by_id(server->local_list, client_id);
3429   if (!client)
3430     goto out;
3431
3432   /* Remove from channel */
3433   silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
3434
3435  out:
3436   if (tmp1)
3437     silc_free(tmp1);
3438   if (tmp2)
3439     silc_free(tmp2);
3440   if (client_id)
3441     silc_free(client_id);
3442   if (channel_id)
3443     silc_free(channel_id);
3444 }