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