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