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