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