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