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