updates
[silc.git] / lib / silcclient / client.c
1 /*
2
3   client.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 /* $Id$ */
21
22 #include "clientlibincludes.h"
23
24 /* Static task callback prototypes */
25 SILC_TASK_CALLBACK(silc_client_connect_to_server_start);
26 SILC_TASK_CALLBACK(silc_client_connect_to_server_second);
27 SILC_TASK_CALLBACK(silc_client_connect_to_server_final);
28 SILC_TASK_CALLBACK(silc_client_packet_process);
29 SILC_TASK_CALLBACK(silc_client_packet_parse_real);
30
31 static void silc_client_packet_parse(SilcPacketParserContext *parser_context);
32 static void silc_client_packet_parse_type(SilcClient client, 
33                                           SilcSocketConnection sock,
34                                           SilcPacketContext *packet);
35
36 /* Allocates new client object. This has to be done before client may
37    work. After calling this one must call silc_client_init to initialize
38    the client. The `application' is application specific user data pointer
39    and caller must free it. */
40
41 SilcClient silc_client_alloc(SilcClientOperations *ops, void *application)
42 {
43   SilcClient new_client;
44
45   new_client = silc_calloc(1, sizeof(*new_client));
46   new_client->application = application;
47   new_client->ops = ops;
48
49   return new_client;
50 }
51
52 /* Free's client object */
53
54 void silc_client_free(SilcClient client)
55 {
56   if (client) {
57     silc_free(client);
58   }
59 }
60
61 /* Initializes the client. This makes all the necessary steps to make
62    the client ready to be run. One must call silc_client_run to run the
63    client. */
64
65 int silc_client_init(SilcClient client)
66 {
67   SILC_LOG_DEBUG(("Initializing client"));
68
69   /* Initialize hash functions for client to use */
70   silc_hash_alloc("md5", &client->md5hash);
71   silc_hash_alloc("sha1", &client->sha1hash);
72
73   /* Initialize none cipher */
74   silc_cipher_alloc("none", &client->none_cipher);
75
76   /* Initialize random number generator */
77   client->rng = silc_rng_alloc();
78   silc_rng_init(client->rng);
79   silc_math_primegen_init(); /* XXX */
80
81   /* Register protocols */
82   silc_client_protocols_register();
83
84   /* Initialize the scheduler */
85   silc_schedule_init(&client->io_queue, &client->timeout_queue, 
86                      &client->generic_queue, 5000);
87
88   return TRUE;
89 }
90
91 /* Stops the client. This is called to stop the client and thus to stop
92    the program. */
93
94 void silc_client_stop(SilcClient client)
95 {
96   SILC_LOG_DEBUG(("Stopping client"));
97
98   /* Stop the scheduler, although it might be already stopped. This
99      doesn't hurt anyone. This removes all the tasks and task queues,
100      as well. */
101   silc_schedule_stop();
102   silc_schedule_uninit();
103
104   silc_client_protocols_unregister();
105
106   SILC_LOG_DEBUG(("Client stopped"));
107 }
108
109 /* Runs the client. */
110
111 void silc_client_run(SilcClient client)
112 {
113   SILC_LOG_DEBUG(("Running client"));
114
115   /* Start the scheduler, the heart of the SILC client. When this returns
116      the program will be terminated. */
117   silc_schedule();
118 }
119
120 /* Allocates and adds new connection to the client. This adds the allocated
121    connection to the connection table and returns a pointer to it. A client
122    can have multiple connections to multiple servers. Every connection must
123    be added to the client using this function. User data `context' may
124    be sent as argument. */
125
126 SilcClientConnection silc_client_add_connection(SilcClient client,
127                                                 char *hostname,
128                                                 int port,
129                                                 void *context)
130 {
131   SilcClientConnection conn;
132   int i;
133
134   conn = silc_calloc(1, sizeof(*conn));
135
136   /* Initialize ID caches */
137   conn->client_cache = silc_idcache_alloc(0);
138   conn->channel_cache = silc_idcache_alloc(0);
139   conn->server_cache = silc_idcache_alloc(0);
140   conn->client = client;
141   conn->remote_host = strdup(hostname);
142   conn->remote_port = port;
143   conn->context = context;
144
145   /* Add the connection to connections table */
146   for (i = 0; i < client->conns_count; i++)
147     if (client->conns && !client->conns[i]) {
148       client->conns[i] = conn;
149       return conn;
150     }
151
152   client->conns = silc_realloc(client->conns, sizeof(*client->conns)
153                                * (client->conns_count + 1));
154   client->conns[client->conns_count] = conn;
155   client->conns_count++;
156
157   return conn;
158 }
159
160 /* Removes connection from client. */
161
162 void silc_client_del_connection(SilcClient client, SilcClientConnection conn)
163 {
164   int i;
165
166   for (i = 0; i < client->conns_count; i++)
167     if (client->conns[i] == conn) {
168       silc_free(conn);
169       client->conns[i] = NULL;
170     }
171 }
172
173 /* Internal context for connection process. This is needed as we
174    doing asynchronous connecting. */
175 typedef struct {
176   SilcClient client;
177   SilcClientConnection conn;
178   SilcTask task;
179   int sock;
180   char *host;
181   int port;
182   int tries;
183 } SilcClientInternalConnectContext;
184
185 static int 
186 silc_client_connect_to_server_internal(SilcClientInternalConnectContext *ctx)
187 {
188   int sock;
189
190   /* XXX In the future we should give up this non-blocking connect all
191      together and use threads instead. */
192   /* Create connection to server asynchronously */
193   sock = silc_net_create_connection_async(ctx->port, ctx->host);
194   if (sock < 0)
195     return -1;
196
197   /* Register task that will receive the async connect and will
198      read the result. */
199   ctx->task = silc_task_register(ctx->client->io_queue, sock, 
200                                  silc_client_connect_to_server_start,
201                                  (void *)ctx, 0, 0, 
202                                  SILC_TASK_FD,
203                                  SILC_TASK_PRI_NORMAL);
204   silc_task_reset_iotype(ctx->task, SILC_TASK_WRITE);
205   silc_schedule_set_listen_fd(sock, ctx->task->iomask);
206
207   ctx->sock = sock;
208
209   return sock;
210 }
211
212 /* Connects to remote server. This is the main routine used to connect
213    to SILC server. Returns -1 on error and the created socket otherwise. 
214    The `context' is user context that is saved into the SilcClientConnection
215    that is created after the connection is created. */
216
217 int silc_client_connect_to_server(SilcClient client, int port,
218                                   char *host, void *context)
219 {
220   SilcClientInternalConnectContext *ctx;
221   SilcClientConnection conn;
222   int sock;
223
224   SILC_LOG_DEBUG(("Connecting to port %d of server %s",
225                   port, host));
226
227   conn = silc_client_add_connection(client, host, port, context);
228
229   client->ops->say(client, conn, 
230                    "Connecting to port %d of server %s", port, host);
231
232   /* Allocate internal context for connection process. This is
233      needed as we are doing async connecting. */
234   ctx = silc_calloc(1, sizeof(*ctx));
235   ctx->client = client;
236   ctx->conn = conn;
237   ctx->host = strdup(host);
238   ctx->port = port;
239   ctx->tries = 0;
240
241   /* Do the actual connecting process */
242   sock = silc_client_connect_to_server_internal(ctx);
243   if (sock == -1)
244     silc_client_del_connection(client, conn);
245   return sock;
246 }
247
248 /* Start SILC Key Exchange (SKE) protocol to negotiate shared secret
249    key material between client and server.  This function can be called
250    directly if application is performing its own connecting and does not
251    use the connecting provided by this library. */
252
253 int silc_client_start_key_exchange(SilcClient client,
254                                    SilcClientConnection conn,
255                                    int fd)
256 {
257   SilcProtocol protocol;
258   SilcClientKEInternalContext *proto_ctx;
259   void *context;
260
261   /* Allocate new socket connection object */
262   silc_socket_alloc(fd, SILC_SOCKET_TYPE_SERVER, (void *)conn, &conn->sock);
263   if (conn->sock == NULL) {
264     client->ops->say(client, conn, 
265                      "Error: Could not allocate connection socket");
266     return FALSE;
267   }
268
269   conn->nickname = strdup(client->username);
270   conn->sock->hostname = conn->remote_host;
271   conn->sock->port = conn->remote_port;
272
273   /* Allocate internal Key Exchange context. This is sent to the
274      protocol as context. */
275   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
276   proto_ctx->client = (void *)client;
277   proto_ctx->sock = conn->sock;
278   proto_ctx->rng = client->rng;
279   proto_ctx->responder = FALSE;
280
281   /* Perform key exchange protocol. silc_client_connect_to_server_final
282      will be called after the protocol is finished. */
283   silc_protocol_alloc(SILC_PROTOCOL_CLIENT_KEY_EXCHANGE, 
284                       &protocol, (void *)proto_ctx,
285                       silc_client_connect_to_server_second);
286   if (!protocol) {
287     client->ops->say(client, conn, 
288                      "Error: Could not start authentication protocol");
289     return FALSE;
290   }
291   conn->sock->protocol = protocol;
292
293   /* Register the connection for network input and output. This sets
294      that scheduler will listen for incoming packets for this connection 
295      and sets that outgoing packets may be sent to this connection as well.
296      However, this doesn't set the scheduler for outgoing traffic, it will 
297      be set separately by calling SILC_CLIENT_SET_CONNECTION_FOR_OUTPUT,
298      later when outgoing data is available. */
299   context = (void *)client;
300   SILC_CLIENT_REGISTER_CONNECTION_FOR_IO(fd);
301
302   /* Execute the protocol */
303   protocol->execute(client->timeout_queue, 0, protocol, fd, 0, 0);
304   return TRUE;
305 }
306
307 /* Start of the connection to the remote server. This is called after
308    succesful TCP/IP connection has been established to the remote host. */
309
310 SILC_TASK_CALLBACK(silc_client_connect_to_server_start)
311 {
312   SilcClientInternalConnectContext *ctx =
313     (SilcClientInternalConnectContext *)context;
314   SilcClient client = ctx->client;
315   SilcClientConnection conn = ctx->conn;
316   int opt, opt_len = sizeof(opt);
317
318   SILC_LOG_DEBUG(("Start"));
319
320   /* Check the socket status as it might be in error */
321   getsockopt(fd, SOL_SOCKET, SO_ERROR, &opt, &opt_len);
322   if (opt != 0) {
323     if (ctx->tries < 2) {
324       /* Connection failed but lets try again */
325       client->ops->say(client, conn, "Could not connect to server %s: %s",
326                        ctx->host, strerror(opt));
327       client->ops->say(client, conn, 
328                        "Connecting to port %d of server %s resumed", 
329                        ctx->port, ctx->host);
330
331       /* Unregister old connection try */
332       silc_schedule_unset_listen_fd(fd);
333       silc_net_close_connection(fd);
334       silc_task_unregister(client->io_queue, ctx->task);
335
336       /* Try again */
337       silc_client_connect_to_server_internal(ctx);
338       ctx->tries++;
339     } else {
340       /* Connection failed and we won't try anymore */
341       client->ops->say(client, conn, "Could not connect to server %s: %s",
342                        ctx->host, strerror(opt));
343       silc_schedule_unset_listen_fd(fd);
344       silc_net_close_connection(fd);
345       silc_task_unregister(client->io_queue, ctx->task);
346       silc_free(ctx);
347
348       /* Notify application of failure */
349       client->ops->connect(client, conn, FALSE);
350       silc_client_del_connection(client, conn);
351     }
352     return;
353   }
354
355   silc_schedule_unset_listen_fd(fd);
356   silc_task_unregister(client->io_queue, ctx->task);
357   silc_free(ctx);
358
359   if (!silc_client_start_key_exchange(client, conn, fd)) {
360     silc_net_close_connection(fd);
361     client->ops->connect(client, conn, FALSE);
362   }
363 }
364
365 /* Second part of the connecting to the server. This executed 
366    authentication protocol. */
367
368 SILC_TASK_CALLBACK(silc_client_connect_to_server_second)
369 {
370   SilcProtocol protocol = (SilcProtocol)context;
371   SilcClientKEInternalContext *ctx = 
372     (SilcClientKEInternalContext *)protocol->context;
373   SilcClient client = (SilcClient)ctx->client;
374   SilcSocketConnection sock = NULL;
375   SilcClientConnAuthInternalContext *proto_ctx;
376
377   SILC_LOG_DEBUG(("Start"));
378
379   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
380     /* Error occured during protocol */
381     SILC_LOG_DEBUG(("Error during KE protocol"));
382     silc_protocol_free(protocol);
383     if (ctx->ske)
384       silc_ske_free(ctx->ske);
385     if (ctx->dest_id)
386       silc_free(ctx->dest_id);
387     ctx->sock->protocol = NULL;
388
389     /* Notify application of failure */
390     client->ops->connect(client, ctx->sock->user_data, FALSE);
391     silc_free(ctx);
392     return;
393   }
394
395   /* Allocate internal context for the authentication protocol. This
396      is sent as context for the protocol. */
397   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
398   proto_ctx->client = (void *)client;
399   proto_ctx->sock = sock = ctx->sock;
400   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
401   proto_ctx->dest_id_type = ctx->dest_id_type;
402   proto_ctx->dest_id = ctx->dest_id;
403
404   /* Resolve the authentication method to be used in this connection */
405   if (!client->ops->get_auth_method(client, sock->user_data, sock->hostname,
406                                     sock->port, &proto_ctx->auth_meth,
407                                     &proto_ctx->auth_data, 
408                                     &proto_ctx->auth_data_len))
409     {
410       /* XXX do AUTH_REQUEST resolcing with server */
411       proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_NONE;
412     }
413
414   /* Free old protocol as it is finished now */
415   silc_protocol_free(protocol);
416   if (ctx->packet)
417     silc_buffer_free(ctx->packet);
418   silc_free(ctx);
419   /* silc_free(ctx->keymat....); */
420   sock->protocol = NULL;
421
422   /* Allocate the authentication protocol. This is allocated here
423      but we won't start it yet. We will be receiving party of this
424      protocol thus we will wait that connecting party will make
425      their first move. */
426   silc_protocol_alloc(SILC_PROTOCOL_CLIENT_CONNECTION_AUTH, 
427                       &sock->protocol, (void *)proto_ctx, 
428                       silc_client_connect_to_server_final);
429
430   /* Execute the protocol */
431   sock->protocol->execute(client->timeout_queue, 0, sock->protocol, fd, 0, 0);
432 }
433
434 /* Finalizes the connection to the remote SILC server. This is called
435    after authentication protocol has been completed. This send our
436    user information to the server to receive our client ID from
437    server. */
438
439 SILC_TASK_CALLBACK(silc_client_connect_to_server_final)
440 {
441   SilcProtocol protocol = (SilcProtocol)context;
442   SilcClientConnAuthInternalContext *ctx = 
443     (SilcClientConnAuthInternalContext *)protocol->context;
444   SilcClient client = (SilcClient)ctx->client;
445   SilcClientConnection conn = (SilcClientConnection)ctx->sock->user_data;
446   SilcBuffer packet;
447
448   SILC_LOG_DEBUG(("Start"));
449
450   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
451     /* Error occured during protocol */
452     SILC_LOG_DEBUG(("Error during authentication protocol"));
453     silc_protocol_free(protocol);
454     if (ctx->auth_data)
455       silc_free(ctx->auth_data);
456     if (ctx->ske)
457       silc_ske_free(ctx->ske);
458     if (ctx->dest_id)
459       silc_free(ctx->dest_id);
460     conn->sock->protocol = NULL;
461
462     /* Notify application of failure */
463     client->ops->connect(client, ctx->sock->user_data, FALSE);
464     silc_free(ctx);
465     return;
466   }
467
468   /* Send NEW_CLIENT packet to the server. We will become registered
469      to the SILC network after sending this packet and we will receive
470      client ID from the server. */
471   packet = silc_buffer_alloc(2 + 2 + strlen(client->username) + 
472                              strlen(client->realname));
473   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
474   silc_buffer_format(packet,
475                      SILC_STR_UI_SHORT(strlen(client->username)),
476                      SILC_STR_UI_XNSTRING(client->username,
477                                           strlen(client->username)),
478                      SILC_STR_UI_SHORT(strlen(client->realname)),
479                      SILC_STR_UI_XNSTRING(client->realname,
480                                           strlen(client->realname)),
481                      SILC_STR_END);
482
483   /* Send the packet */
484   silc_client_packet_send(client, ctx->sock, SILC_PACKET_NEW_CLIENT,
485                           NULL, 0, NULL, NULL, 
486                           packet->data, packet->len, TRUE);
487   silc_buffer_free(packet);
488
489   /* Save remote ID. */
490   conn->remote_id = ctx->dest_id;
491   conn->remote_id_data = silc_id_id2str(ctx->dest_id, SILC_ID_SERVER);
492   conn->remote_id_data_len = SILC_ID_SERVER_LEN;
493
494   /* Notify application of successful connection */
495   client->ops->connect(client, conn, TRUE);
496
497   silc_protocol_free(protocol);
498   if (ctx->auth_data)
499     silc_free(ctx->auth_data);
500   if (ctx->ske)
501     silc_ske_free(ctx->ske);
502   if (ctx->dest_id)
503     silc_free(ctx->dest_id);
504   silc_free(ctx);
505   conn->sock->protocol = NULL;
506 }
507
508 /* Internal routine that sends packet or marks packet to be sent. This
509    is used directly only in special cases. Normal cases should use
510    silc_server_packet_send. Returns < 0 on error. */
511
512 static int silc_client_packet_send_real(SilcClient client,
513                                         SilcSocketConnection sock,
514                                         int force_send)
515 {
516   int ret;
517
518   /* Send the packet */
519   ret = silc_packet_send(sock, force_send);
520   if (ret != -2)
521     return ret;
522
523   /* Mark that there is some outgoing data available for this connection. 
524      This call sets the connection both for input and output (the input
525      is set always and this call keeps the input setting, actually). 
526      Actual data sending is performed by silc_client_packet_process. */
527   SILC_CLIENT_SET_CONNECTION_FOR_OUTPUT(sock->sock);
528
529   /* Mark to socket that data is pending in outgoing buffer. This flag
530      is needed if new data is added to the buffer before the earlier
531      put data is sent to the network. */
532   SILC_SET_OUTBUF_PENDING(sock);
533
534   return 0;
535 }
536
537 /* Packet processing callback. This is used to send and receive packets
538    from network. This is generic task. */
539
540 SILC_TASK_CALLBACK(silc_client_packet_process)
541 {
542   SilcClient client = (SilcClient)context;
543   SilcSocketConnection sock = NULL;
544   SilcClientConnection conn;
545   int ret;
546
547   SILC_LOG_DEBUG(("Processing packet"));
548
549   SILC_CLIENT_GET_SOCK(client, fd, sock);
550   if (sock == NULL)
551     return;
552
553   conn = (SilcClientConnection)sock->user_data;
554
555   /* Packet sending */
556   if (type == SILC_TASK_WRITE) {
557     SILC_LOG_DEBUG(("Writing data to connection"));
558
559     if (sock->outbuf->data - sock->outbuf->head)
560       silc_buffer_push(sock->outbuf, 
561                        sock->outbuf->data - sock->outbuf->head);
562
563     ret = silc_client_packet_send_real(client, sock, TRUE);
564
565     /* If returned -2 could not write to connection now, will do
566        it later. */
567     if (ret == -2)
568       return;
569     
570     /* The packet has been sent and now it is time to set the connection
571        back to only for input. When there is again some outgoing data 
572        available for this connection it will be set for output as well. 
573        This call clears the output setting and sets it only for input. */
574     SILC_CLIENT_SET_CONNECTION_FOR_INPUT(fd);
575     SILC_UNSET_OUTBUF_PENDING(sock);
576
577     silc_buffer_clear(sock->outbuf);
578     return;
579   }
580
581   /* Packet receiving */
582   if (type == SILC_TASK_READ) {
583     SILC_LOG_DEBUG(("Reading data from connection"));
584
585     /* Read data from network */
586     ret = silc_packet_receive(sock);
587     if (ret < 0)
588       return;
589     
590     /* EOF */
591     if (ret == 0) {
592       SILC_LOG_DEBUG(("Read EOF"));
593
594       /* If connection is disconnecting already we will finally
595          close the connection */
596       if (SILC_IS_DISCONNECTING(sock)) {
597         client->ops->disconnect(client, conn);
598         silc_client_close_connection(client, sock);
599         return;
600       }
601       
602       client->ops->say(client, conn, "Connection closed: premature EOF");
603       SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
604       client->ops->disconnect(client, conn);
605       silc_client_close_connection(client, sock);
606       return;
607     }
608
609     /* Process the packet. This will call the parser that will then
610        decrypt and parse the packet. */
611     silc_packet_receive_process(sock, conn->receive_key, conn->hmac,
612                                 silc_client_packet_parse, client);
613   }
614 }
615
616 /* Parses whole packet, received earlier. */
617
618 SILC_TASK_CALLBACK(silc_client_packet_parse_real)
619 {
620   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
621   SilcClient client = (SilcClient)parse_ctx->context;
622   SilcPacketContext *packet = parse_ctx->packet;
623   SilcBuffer buffer = packet->buffer;
624   SilcSocketConnection sock = parse_ctx->sock;
625   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
626   int ret;
627
628   SILC_LOG_DEBUG(("Start"));
629
630   /* Decrypt the received packet */
631   ret = silc_packet_decrypt(conn->receive_key, conn->hmac, buffer, packet);
632   if (ret < 0)
633     goto out;
634
635   if (ret == 0) {
636     /* Parse the packet. Packet type is returned. */
637     ret = silc_packet_parse(packet);
638   } else {
639     /* Parse the packet header in special way as this is "special"
640        packet type. */
641     ret = silc_packet_parse_special(packet);
642   }
643
644   if (ret == SILC_PACKET_NONE)
645     goto out;
646
647   /* Parse the incoming packet type */
648   silc_client_packet_parse_type(client, sock, packet);
649
650  out:
651   silc_buffer_clear(buffer);
652   if (packet->src_id)
653     silc_free(packet->src_id);
654   if (packet->dst_id)
655     silc_free(packet->dst_id);
656   silc_free(packet);
657   silc_free(parse_ctx);
658 }
659
660 /* Parser callback called by silc_packet_receive_process. Thie merely
661    registers timeout that will handle the actual parsing when appropriate. */
662
663 void silc_client_packet_parse(SilcPacketParserContext *parser_context)
664 {
665   SilcClient client = (SilcClient)parser_context->context;
666
667   /* Parse the packet */
668   silc_task_register(client->timeout_queue, parser_context->sock->sock, 
669                      silc_client_packet_parse_real,
670                      (void *)parser_context, 0, 1, 
671                      SILC_TASK_TIMEOUT,
672                      SILC_TASK_PRI_NORMAL);
673 }
674   
675 /* Parses the packet type and calls what ever routines the packet type
676    requires. This is done for all incoming packets. */
677
678 void silc_client_packet_parse_type(SilcClient client, 
679                                    SilcSocketConnection sock,
680                                    SilcPacketContext *packet)
681 {
682   SilcBuffer buffer = packet->buffer;
683   SilcPacketType type = packet->type;
684
685   SILC_LOG_DEBUG(("Parsing packet type %d", type));
686
687   /* Parse the packet type */
688   switch(type) {
689   case SILC_PACKET_DISCONNECT:
690     silc_client_disconnected_by_server(client, sock, buffer);
691     break;
692   case SILC_PACKET_SUCCESS:
693     /*
694      * Success received for something. For now we can have only
695      * one protocol for connection executing at once hence this
696      * success message is for whatever protocol is executing currently.
697      */
698     if (sock->protocol) {
699       sock->protocol->execute(client->timeout_queue, 0,
700                               sock->protocol, sock->sock, 0, 0);
701     }
702     break;
703   case SILC_PACKET_FAILURE:
704     /*
705      * Failure received for some protocol. Set the protocol state to 
706      * error and call the protocol callback. This fill cause error on
707      * protocol and it will call the final callback.
708      */
709     if (sock->protocol) {
710       sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
711       sock->protocol->execute(client->timeout_queue, 0,
712                               sock->protocol, sock->sock, 0, 0);
713
714       /* XXX We have only two protocols currently thus we know what this
715          failure indication is. */
716       if (buffer->len >= 4) {
717         unsigned int failure;
718
719         SILC_GET32_MSB(failure, buffer->data);
720
721         /* Notify application */
722         client->ops->failure(client, sock->user_data, sock->protocol,
723                              (void *)failure);
724       }
725     }
726     break;
727   case SILC_PACKET_REJECT:
728     break;
729
730   case SILC_PACKET_NOTIFY:
731     /*
732      * Received notify message 
733      */
734     silc_client_notify_by_server(client, sock, packet);
735     break;
736
737   case SILC_PACKET_ERROR:
738     /*
739      * Received error message
740      */
741     silc_client_error_by_server(client, sock, buffer);
742     break;
743
744   case SILC_PACKET_CHANNEL_MESSAGE:
745     /*
746      * Received message to (from, actually) a channel
747      */
748     silc_client_channel_message(client, sock, packet);
749     break;
750   case SILC_PACKET_CHANNEL_KEY:
751     /*
752      * Received key for a channel. By receiving this key the client will be
753      * able to talk to the channel it has just joined. This can also be
754      * a new key for existing channel as keys expire peridiocally.
755      */
756     silc_client_receive_channel_key(client, sock, buffer);
757     break;
758
759   case SILC_PACKET_PRIVATE_MESSAGE:
760     /*
761      * Received private message
762      */
763     silc_client_private_message(client, sock, packet);
764     break;
765   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
766     /*
767      * Received private message key
768      */
769     break;
770
771   case SILC_PACKET_COMMAND_REPLY:
772     /*
773      * Recived reply for a command
774      */
775     silc_client_command_reply_process(client, sock, packet);
776     break;
777
778   case SILC_PACKET_KEY_EXCHANGE:
779     if (sock->protocol) {
780       SilcClientKEInternalContext *proto_ctx = 
781         (SilcClientKEInternalContext *)sock->protocol->context;
782
783       proto_ctx->packet = buffer;
784       proto_ctx->dest_id_type = packet->src_id_type;
785       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
786
787       /* Let the protocol handle the packet */
788       sock->protocol->execute(client->timeout_queue, 0,
789                               sock->protocol, sock->sock, 0, 0);
790     } else {
791       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
792                       "protocol active, packet dropped."));
793
794       /* XXX Trigger KE protocol?? Rekey actually! */
795     }
796     break;
797
798   case SILC_PACKET_KEY_EXCHANGE_1:
799     if (sock->protocol) {
800
801     } else {
802       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
803                       "protocol active, packet dropped."));
804     }
805     break;
806   case SILC_PACKET_KEY_EXCHANGE_2:
807     if (sock->protocol) {
808       SilcClientKEInternalContext *proto_ctx = 
809         (SilcClientKEInternalContext *)sock->protocol->context;
810
811       if (proto_ctx->packet)
812         silc_buffer_free(proto_ctx->packet);
813
814       proto_ctx->packet = buffer;
815       proto_ctx->dest_id_type = packet->src_id_type;
816       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
817
818       /* Let the protocol handle the packet */
819       sock->protocol->execute(client->timeout_queue, 0,
820                               sock->protocol, sock->sock, 0, 0);
821     } else {
822       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
823                       "protocol active, packet dropped."));
824     }
825     break;
826
827   case SILC_PACKET_NEW_ID:
828     {
829       /*
830        * Received new ID from server. This packet is received at
831        * the connection to the server.  New ID is also received when 
832        * user changes nickname but in that case the new ID is received
833        * as command reply and not as this packet type.
834        */
835       SilcIDPayload idp;
836
837       idp = silc_id_payload_parse(buffer);
838       if (silc_id_payload_get_type(idp) != SILC_ID_CLIENT)
839         break;
840
841       silc_client_receive_new_id(client, sock, idp);
842       silc_id_payload_free(idp);
843       break;
844     }
845
846   default:
847     SILC_LOG_DEBUG(("Incorrect packet type %d, packet dropped", type));
848     break;
849   }
850 }
851
852 /* Sends packet. This doesn't actually send the packet instead it assembles
853    it and marks it to be sent. However, if force_send is TRUE the packet
854    is sent immediately. if dst_id, cipher and hmac are NULL those parameters
855    will be derived from sock argument. Otherwise the valid arguments sent
856    are used. */
857
858 void silc_client_packet_send(SilcClient client, 
859                              SilcSocketConnection sock,
860                              SilcPacketType type, 
861                              void *dst_id,
862                              SilcIdType dst_id_type,
863                              SilcCipher cipher,
864                              SilcHmac hmac,
865                              unsigned char *data, 
866                              unsigned int data_len, 
867                              int force_send)
868 {
869   SilcPacketContext packetdata;
870
871   SILC_LOG_DEBUG(("Sending packet, type %d", type));
872
873   /* Get data used in the packet sending, keys and stuff */
874   if ((!cipher || !hmac || !dst_id) && sock->user_data) {
875     if (!cipher && ((SilcClientConnection)sock->user_data)->send_key)
876       cipher = ((SilcClientConnection)sock->user_data)->send_key;
877
878     if (!hmac && ((SilcClientConnection)sock->user_data)->hmac)
879       hmac = ((SilcClientConnection)sock->user_data)->hmac;
880
881     if (!dst_id && ((SilcClientConnection)sock->user_data)->remote_id) {
882       dst_id = ((SilcClientConnection)sock->user_data)->remote_id;
883       dst_id_type = SILC_ID_SERVER;
884     }
885   }
886
887   /* Set the packet context pointers */
888   packetdata.flags = 0;
889   packetdata.type = type;
890   if (((SilcClientConnection)sock->user_data)->local_id_data)
891     packetdata.src_id = ((SilcClientConnection)sock->user_data)->local_id_data;
892   else 
893     packetdata.src_id = silc_calloc(SILC_ID_CLIENT_LEN, sizeof(unsigned char));
894   packetdata.src_id_len = SILC_ID_CLIENT_LEN;
895   packetdata.src_id_type = SILC_ID_CLIENT;
896   if (dst_id) {
897     packetdata.dst_id = silc_id_id2str(dst_id, dst_id_type);
898     packetdata.dst_id_len = silc_id_get_len(dst_id_type);
899     packetdata.dst_id_type = dst_id_type;
900   } else {
901     packetdata.dst_id = NULL;
902     packetdata.dst_id_len = 0;
903     packetdata.dst_id_type = SILC_ID_NONE;
904   }
905   packetdata.rng = client->rng;
906   packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN + 
907     packetdata.src_id_len + packetdata.dst_id_len;
908   packetdata.padlen = SILC_PACKET_PADLEN(packetdata.truelen);
909
910   /* Prepare outgoing data buffer for packet sending */
911   silc_packet_send_prepare(sock, 
912                            SILC_PACKET_HEADER_LEN +
913                            packetdata.src_id_len + 
914                            packetdata.dst_id_len,
915                            packetdata.padlen,
916                            data_len);
917
918   SILC_LOG_DEBUG(("Putting data to outgoing buffer, len %d", data_len));
919
920   packetdata.buffer = sock->outbuf;
921
922   /* Put the data to the buffer */
923   if (data && data_len)
924     silc_buffer_put(sock->outbuf, data, data_len);
925
926   /* Create the outgoing packet */
927   silc_packet_assemble(&packetdata);
928
929   /* Encrypt the packet */
930   if (cipher)
931     silc_packet_encrypt(cipher, hmac, sock->outbuf, sock->outbuf->len);
932
933   SILC_LOG_HEXDUMP(("Packet, len %d", sock->outbuf->len),
934                    sock->outbuf->data, sock->outbuf->len);
935
936   /* Now actually send the packet */
937   silc_client_packet_send_real(client, sock, force_send);
938 }
939
940 /* Sends packet to a channel. Packet to channel is always encrypted
941    differently from "normal" packets. SILC header of the packet is 
942    encrypted with the next receiver's key and the rest of the packet is
943    encrypted with the channel specific key. Padding and HMAC is computed
944    with the next receiver's key. */
945
946 void silc_client_packet_send_to_channel(SilcClient client, 
947                                         SilcSocketConnection sock,
948                                         SilcChannelEntry channel,
949                                         unsigned char *data, 
950                                         unsigned int data_len, 
951                                         int force_send)
952 {
953   int i;
954   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
955   SilcBuffer payload;
956   SilcPacketContext packetdata;
957   SilcCipher cipher;
958   SilcHmac hmac;
959   unsigned char *id_string;
960
961   SILC_LOG_DEBUG(("Sending packet to channel"));
962
963   if (!channel || !channel->key) {
964     client->ops->say(client, conn, 
965                      "Cannot talk to channel: key does not exist");
966     return;
967   }
968
969   /* Generate IV */
970   if (!channel->iv)
971     for (i = 0; i < 16; i++) channel->iv[i] = silc_rng_get_byte(client->rng);
972   else
973     silc_hash_make(client->md5hash, channel->iv, 16, channel->iv);
974
975   /* Encode the channel payload */
976   payload = silc_channel_payload_encode(data_len, data, 16, channel->iv, 
977                                         client->rng);
978   if (!payload) {
979     client->ops->say(client, conn, 
980                      "Error: Could not create packet to be sent to channel");
981     return;
982   }
983
984   /* Get data used in packet header encryption, keys and stuff. Rest
985      of the packet (the payload) is, however, encrypted with the 
986      specified channel key. */
987   cipher = conn->send_key;
988   hmac = conn->hmac;
989   id_string = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
990
991   /* Set the packet context pointers. The destination ID is always
992      the Channel ID of the channel. Server and router will handle the
993      distribution of the packet. */
994   packetdata.flags = 0;
995   packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
996   packetdata.src_id = conn->local_id_data;
997   packetdata.src_id_len = SILC_ID_CLIENT_LEN;
998   packetdata.src_id_type = SILC_ID_CLIENT;
999   packetdata.dst_id = id_string;
1000   packetdata.dst_id_len = SILC_ID_CHANNEL_LEN;
1001   packetdata.dst_id_type = SILC_ID_CHANNEL;
1002   packetdata.rng = client->rng;
1003   packetdata.truelen = payload->len + SILC_PACKET_HEADER_LEN + 
1004     packetdata.src_id_len + packetdata.dst_id_len;
1005   packetdata.padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
1006                                           packetdata.src_id_len +
1007                                           packetdata.dst_id_len));
1008
1009   /* Prepare outgoing data buffer for packet sending */
1010   silc_packet_send_prepare(sock, 
1011                            SILC_PACKET_HEADER_LEN +
1012                            packetdata.src_id_len + 
1013                            packetdata.dst_id_len,
1014                            packetdata.padlen,
1015                            payload->len);
1016
1017   packetdata.buffer = sock->outbuf;
1018
1019   /* Encrypt payload of the packet. This is encrypted with the channel key. */
1020   channel->channel_key->cipher->encrypt(channel->channel_key->context,
1021                                         payload->data, payload->data,
1022                                         payload->len - 16, /* -IV_LEN */
1023                                         channel->iv);
1024
1025   /* Put the actual encrypted payload data into the buffer. */
1026   silc_buffer_put(sock->outbuf, payload->data, payload->len);
1027
1028   /* Create the outgoing packet */
1029   silc_packet_assemble(&packetdata);
1030
1031   /* Encrypt the header and padding of the packet. This is encrypted 
1032      with normal session key shared with our server. */
1033   silc_packet_encrypt(cipher, hmac, sock->outbuf, SILC_PACKET_HEADER_LEN + 
1034                       packetdata.src_id_len + packetdata.dst_id_len +
1035                       packetdata.padlen);
1036
1037   SILC_LOG_HEXDUMP(("Packet to channel, len %d", sock->outbuf->len),
1038                    sock->outbuf->data, sock->outbuf->len);
1039
1040   /* Now actually send the packet */
1041   silc_client_packet_send_real(client, sock, force_send);
1042   silc_buffer_free(payload);
1043   silc_free(id_string);
1044 }
1045
1046 /* Sends private message to remote client. If private message key has
1047    not been set with this client then the message will be encrypted using
1048    normal session keys. Private messages are special packets in SILC
1049    network hence we need this own function for them. This is similiar
1050    to silc_client_packet_send_to_channel except that we send private
1051    message. */
1052
1053 void silc_client_packet_send_private_message(SilcClient client,
1054                                              SilcSocketConnection sock,
1055                                              SilcClientEntry client_entry,
1056                                              unsigned char *data, 
1057                                              unsigned int data_len, 
1058                                              int force_send)
1059 {
1060   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1061   SilcBuffer buffer;
1062   SilcPacketContext packetdata;
1063   unsigned int nick_len;
1064   SilcCipher cipher;
1065   SilcHmac hmac;
1066
1067   SILC_LOG_DEBUG(("Sending private message"));
1068
1069   /* Create private message payload */
1070   nick_len = strlen(conn->nickname);
1071   buffer = silc_buffer_alloc(2 + nick_len + data_len);
1072   silc_buffer_pull_tail(buffer, SILC_BUFFER_END(buffer));
1073   silc_buffer_format(buffer,
1074                      SILC_STR_UI_SHORT(nick_len),
1075                      SILC_STR_UI_XNSTRING(conn->nickname,
1076                                           nick_len),
1077                      SILC_STR_UI_XNSTRING(data, data_len),
1078                      SILC_STR_END);
1079
1080   /* If we don't have private message specific key then private messages
1081      are just as any normal packet thus call normal packet sending.  If
1082      the key exist then the encryption process is a bit different and
1083      will be done in the rest of this function. */
1084   if (!client_entry->send_key) {
1085     silc_client_packet_send(client, sock, SILC_PACKET_PRIVATE_MESSAGE,
1086                             client_entry->id, SILC_ID_CLIENT, NULL, NULL,
1087                             buffer->data, buffer->len, force_send);
1088     goto out;
1089   }
1090
1091   /* We have private message specific key */
1092
1093   /* Get data used in the encryption */
1094   cipher = client_entry->send_key;
1095   hmac = conn->hmac;
1096
1097   /* Set the packet context pointers. */
1098   packetdata.flags = 0;
1099   packetdata.type = SILC_PACKET_PRIVATE_MESSAGE;
1100   packetdata.src_id = conn->local_id_data;
1101   packetdata.src_id_len = SILC_ID_CLIENT_LEN;
1102   packetdata.src_id_type = SILC_ID_CLIENT;
1103   if (client_entry)
1104     packetdata.dst_id = silc_id_id2str(client_entry->id, SILC_ID_CLIENT);
1105   else
1106     packetdata.dst_id = conn->local_id_data;
1107   packetdata.dst_id_len = SILC_ID_CLIENT_LEN;
1108   packetdata.dst_id_type = SILC_ID_CLIENT;
1109   packetdata.rng = client->rng;
1110   packetdata.truelen = buffer->len + SILC_PACKET_HEADER_LEN + 
1111     packetdata.src_id_len + packetdata.dst_id_len;
1112   packetdata.padlen = SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
1113                                           packetdata.src_id_len +
1114                                           packetdata.dst_id_len));
1115
1116   /* Prepare outgoing data buffer for packet sending */
1117   silc_packet_send_prepare(sock, 
1118                            SILC_PACKET_HEADER_LEN +
1119                            packetdata.src_id_len + 
1120                            packetdata.dst_id_len,
1121                            packetdata.padlen,
1122                            buffer->len);
1123   
1124   packetdata.buffer = sock->outbuf;
1125
1126   /* Encrypt payload of the packet. Encrypt with private message specific
1127      key if it exist, otherwise with session key. */
1128   cipher->cipher->encrypt(cipher->context, buffer->data, buffer->data,
1129                           buffer->len, cipher->iv);
1130       
1131   /* Put the actual encrypted payload data into the buffer. */
1132   silc_buffer_put(sock->outbuf, buffer->data, buffer->len);
1133
1134   /* Create the outgoing packet */
1135   silc_packet_assemble(&packetdata);
1136
1137   /* Encrypt the header and padding of the packet. */
1138   silc_packet_encrypt(cipher, hmac, sock->outbuf, SILC_PACKET_HEADER_LEN + 
1139                       packetdata.src_id_len + packetdata.dst_id_len +
1140                       packetdata.padlen);
1141
1142   SILC_LOG_HEXDUMP(("Private message packet, len %d", sock->outbuf->len),
1143                    sock->outbuf->data, sock->outbuf->len);
1144
1145   /* Now actually send the packet */
1146   silc_client_packet_send_real(client, sock, force_send);
1147   silc_free(packetdata.dst_id);
1148
1149  out:
1150   silc_free(buffer);
1151 }     
1152
1153 /* Closes connection to remote end. Free's all allocated data except
1154    for some information such as nickname etc. that are valid at all time. */
1155
1156 void silc_client_close_connection(SilcClient client,
1157                                   SilcSocketConnection sock)
1158 {
1159   SilcClientConnection conn;
1160
1161   /* We won't listen for this connection anymore */
1162   silc_schedule_unset_listen_fd(sock->sock);
1163
1164   /* Unregister all tasks */
1165   silc_task_unregister_by_fd(client->io_queue, sock->sock);
1166   silc_task_unregister_by_fd(client->timeout_queue, sock->sock);
1167
1168   /* Close the actual connection */
1169   silc_net_close_connection(sock->sock);
1170
1171   client->ops->say(client, sock->user_data,
1172                    "Closed connection to host %s", sock->hostname ?
1173                    sock->hostname : sock->ip);
1174
1175   /* Free everything */
1176   if (sock->user_data) {
1177     conn = (SilcClientConnection)sock->user_data;
1178
1179     /* XXX Free all client entries and channel entries. */
1180
1181     /* Clear ID caches */
1182     silc_idcache_del_all(conn->client_cache);
1183     silc_idcache_del_all(conn->channel_cache);
1184
1185     /* Free data */
1186     if (conn->remote_host)
1187       silc_free(conn->remote_host);
1188     if (conn->local_id)
1189       silc_free(conn->local_id);
1190     if (conn->local_id_data)
1191       silc_free(conn->local_id_data);
1192     if (conn->send_key)
1193       silc_cipher_free(conn->send_key);
1194     if (conn->receive_key)
1195       silc_cipher_free(conn->receive_key);
1196     if (conn->hmac)
1197       silc_hmac_free(conn->hmac);
1198     if (conn->hmac_key) {
1199       memset(conn->hmac_key, 0, conn->hmac_key_len);
1200       silc_free(conn->hmac_key);
1201     }
1202
1203     conn->sock = NULL;
1204     conn->remote_port = 0;
1205     conn->remote_type = 0;
1206     conn->send_key = NULL;
1207     conn->receive_key = NULL;
1208     conn->hmac = NULL;
1209     conn->hmac_key = NULL;
1210     conn->hmac_key_len = 0;
1211     conn->local_id = NULL;
1212     conn->local_id_data = NULL;
1213     conn->remote_host = NULL;
1214     conn->current_channel = NULL;
1215
1216     silc_client_del_connection(client, conn);
1217   }
1218
1219   if (sock->protocol) {
1220     silc_protocol_free(sock->protocol);
1221     sock->protocol = NULL;
1222   }
1223   silc_socket_free(sock);
1224 }
1225
1226 /* Called when we receive disconnection packet from server. This 
1227    closes our end properly and displays the reason of the disconnection
1228    on the screen. */
1229
1230 void silc_client_disconnected_by_server(SilcClient client,
1231                                         SilcSocketConnection sock,
1232                                         SilcBuffer message)
1233 {
1234   char *msg;
1235
1236   SILC_LOG_DEBUG(("Server disconnected us, sock %d", sock->sock));
1237
1238   msg = silc_calloc(message->len + 1, sizeof(char));
1239   memcpy(msg, message->data, message->len);
1240   client->ops->say(client, sock->user_data, msg);
1241   silc_free(msg);
1242
1243   SILC_SET_DISCONNECTED(sock);
1244   silc_client_close_connection(client, sock);
1245 }
1246
1247 /* Received error message from server. Display it on the screen. 
1248    We don't take any action what so ever of the error message. */
1249
1250 void silc_client_error_by_server(SilcClient client,
1251                                  SilcSocketConnection sock,
1252                                  SilcBuffer message)
1253 {
1254   char *msg;
1255
1256   msg = silc_calloc(message->len + 1, sizeof(char));
1257   memcpy(msg, message->data, message->len);
1258   client->ops->say(client, sock->user_data, msg);
1259   silc_free(msg);
1260 }
1261
1262 /* Called when notify is received and some async operation (such as command)
1263    is required before processing the notify message. This calls again the
1264    silc_client_notify_by_server and reprocesses the original notify packet. */
1265
1266 static void silc_client_notify_by_server_pending(void *context)
1267 {
1268   SilcPacketContext *p = (SilcPacketContext *)context;
1269   silc_client_notify_by_server(p->context, p->sock, p);
1270   if (p->src_id)
1271     silc_free(p->src_id);
1272   if (p->dst_id)
1273     silc_free(p->dst_id);
1274   silc_buffer_free(p->buffer);
1275   silc_free(p);
1276 }
1277
1278 /* Received notify message from server */
1279
1280 void silc_client_notify_by_server(SilcClient client,
1281                                   SilcSocketConnection sock,
1282                                   SilcPacketContext *packet)
1283 {
1284   SilcBuffer buffer = packet->buffer;
1285   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1286   SilcNotifyPayload payload;
1287   SilcNotifyType type;
1288   SilcArgumentPayload args;
1289   int i;
1290
1291   SilcClientID *client_id = NULL;
1292   SilcChannelID *channel_id = NULL;
1293   SilcClientEntry client_entry;
1294   SilcClientEntry client_entry2;
1295   SilcChannelEntry channel;
1296   SilcChannelUser chu;
1297   SilcIDCacheEntry id_cache = NULL;
1298   unsigned char *tmp;
1299   unsigned int tmp_len, mode;
1300
1301   payload = silc_notify_payload_parse(buffer);
1302   type = silc_notify_get_type(payload);
1303   args = silc_notify_get_args(payload);
1304   if (!args)
1305     goto out;
1306
1307   switch(type) {
1308   case SILC_NOTIFY_TYPE_NONE:
1309     /* Notify application */
1310     client->ops->notify(client, conn, type, 
1311                         silc_argument_get_arg_type(args, 1, NULL));
1312     break;
1313
1314   case SILC_NOTIFY_TYPE_INVITE:
1315     /* 
1316      * Someone invited me to a channel. Find Client and Channel entries
1317      * for the application.
1318      */
1319     
1320     /* Get Client ID */
1321     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1322     if (!tmp)
1323       goto out;
1324
1325     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1326
1327     /* Find Client entry and if not found query it */
1328     client_entry = silc_idlist_get_client_by_id(client, conn, client_id, TRUE);
1329     if (!client_entry) {
1330       SilcPacketContext *p = silc_packet_context_dup(packet);
1331       p->context = (void *)client;
1332       p->sock = sock;
1333       silc_client_command_pending(SILC_COMMAND_WHOIS, 
1334                                   silc_client_notify_by_server_pending, p);
1335       goto out;
1336     }
1337
1338     /* Get Channel ID */
1339     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1340     if (!tmp)
1341       goto out;
1342
1343     channel_id = silc_id_payload_parse_id(tmp, tmp_len);
1344
1345     /* XXX Will ALWAYS fail because currently we don't have way to resolve
1346        channel information for channel that we're not joined to. */
1347     /* XXX ways to fix: use (extended) LIST command, or define the channel
1348        name to the notfy type when name resolving is not mandatory. */
1349     /* Find channel entry */
1350     if (!silc_idcache_find_by_id_one(conn->channel_cache, (void *)channel_id,
1351                                      SILC_ID_CHANNEL, &id_cache))
1352       goto out;
1353
1354     channel = (SilcChannelEntry)id_cache->context;
1355
1356     /* Notify application */
1357     client->ops->notify(client, conn, type, client_entry, channel);
1358     break;
1359
1360   case SILC_NOTIFY_TYPE_JOIN:
1361     /*
1362      * Someone has joined to a channel. Get their ID and nickname and
1363      * cache them for later use.
1364      */
1365
1366     /* Get Client ID */
1367     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1368     if (!tmp)
1369       goto out;
1370
1371     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1372
1373     /* Find Client entry and if not found query it */
1374     client_entry = silc_idlist_get_client_by_id(client, conn, client_id, TRUE);
1375     if (!client_entry) {
1376       SilcPacketContext *p = silc_packet_context_dup(packet);
1377       p->context = (void *)client;
1378       p->sock = sock;
1379       silc_client_command_pending(SILC_COMMAND_WHOIS, 
1380                                   silc_client_notify_by_server_pending, p);
1381       goto out;
1382     }
1383
1384     /* Get channel entry */
1385     channel_id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
1386     if (!silc_idcache_find_by_id_one(conn->channel_cache, (void *)channel_id,
1387                                      SILC_ID_CHANNEL, &id_cache))
1388       break;
1389
1390     channel = (SilcChannelEntry)id_cache->context;
1391
1392     /* Add client to channel */
1393     chu = silc_calloc(1, sizeof(*chu));
1394     chu->client = client_entry;
1395     silc_list_add(channel->clients, chu);
1396
1397     /* XXX add support for multiple same nicks on same channel. Check
1398        for them here */
1399
1400     /* Notify application. The channel entry is sent last as this notify
1401        is for channel but application don't know it from the arguments
1402        sent by server. */
1403     client->ops->notify(client, conn, type, client_entry, channel);
1404     break;
1405
1406   case SILC_NOTIFY_TYPE_LEAVE:
1407     /*
1408      * Someone has left a channel. We will remove it from the channel but
1409      * we'll keep it in the cache in case we'll need it later.
1410      */
1411     
1412     /* Get Client ID */
1413     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1414     if (!tmp)
1415       goto out;
1416
1417     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1418
1419     /* Find Client entry */
1420     client_entry = 
1421       silc_idlist_get_client_by_id(client, conn, client_id, FALSE);
1422     if (!client_entry)
1423       goto out;
1424
1425     /* Get channel entry */
1426     channel_id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
1427     if (!silc_idcache_find_by_id_one(conn->channel_cache, (void *)channel_id,
1428                                      SILC_ID_CHANNEL, &id_cache))
1429       break;
1430
1431     channel = (SilcChannelEntry)id_cache->context;
1432
1433     /* Remove client from channel */
1434     silc_list_start(channel->clients);
1435     while ((chu = silc_list_get(channel->clients)) != SILC_LIST_END) {
1436       if (chu->client == client_entry) {
1437         silc_list_del(channel->clients, chu);
1438         silc_free(chu);
1439         break;
1440       }
1441     }
1442
1443     /* Notify application. The channel entry is sent last as this notify
1444        is for channel but application don't know it from the arguments
1445        sent by server. */
1446     client->ops->notify(client, conn, type, client_entry, channel);
1447     break;
1448
1449   case SILC_NOTIFY_TYPE_SIGNOFF:
1450     /*
1451      * Someone left SILC. We'll remove it from all channels and from cache.
1452      */
1453
1454     /* Get Client ID */
1455     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1456     if (!tmp)
1457       goto out;
1458
1459     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1460
1461     /* Find Client entry */
1462     client_entry = 
1463       silc_idlist_get_client_by_id(client, conn, client_id, FALSE);
1464     if (!client_entry)
1465       goto out;
1466
1467     /* Remove from all channels */
1468     silc_client_remove_from_channels(client, conn, client_entry);
1469
1470     /* Remove from cache */
1471     silc_idcache_del_by_id(conn->client_cache, SILC_ID_CLIENT, 
1472                            client_entry->id);
1473
1474     /* Notify application */
1475     client->ops->notify(client, conn, type, client_entry);
1476
1477     /* Free data */
1478     if (client_entry->nickname)
1479       silc_free(client_entry->nickname);
1480     if (client_entry->server)
1481       silc_free(client_entry->server);
1482     if (client_entry->id)
1483       silc_free(client_entry->id);
1484     if (client_entry->send_key)
1485       silc_cipher_free(client_entry->send_key);
1486     if (client_entry->receive_key)
1487       silc_cipher_free(client_entry->receive_key);
1488     break;
1489
1490   case SILC_NOTIFY_TYPE_TOPIC_SET:
1491     /*
1492      * Someone set the topic on a channel.
1493      */
1494
1495     /* Get Client ID */
1496     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1497     if (!tmp)
1498       goto out;
1499
1500     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1501
1502     /* Find Client entry */
1503     client_entry = 
1504       silc_idlist_get_client_by_id(client, conn, client_id, FALSE);
1505     if (!client_entry)
1506       goto out;
1507
1508     /* Get topic */
1509     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1510     if (!tmp)
1511       goto out;
1512
1513     /* Get channel entry */
1514     channel_id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
1515     if (!silc_idcache_find_by_id_one(conn->channel_cache, (void *)channel_id,
1516                                      SILC_ID_CHANNEL, &id_cache))
1517       break;
1518
1519     channel = (SilcChannelEntry)id_cache->context;
1520
1521     /* Notify application. The channel entry is sent last as this notify
1522        is for channel but application don't know it from the arguments
1523        sent by server. */
1524     client->ops->notify(client, conn, type, client_entry, tmp, channel);
1525     break;
1526
1527   case SILC_NOTIFY_TYPE_NICK_CHANGE:
1528     /*
1529      * Someone changed their nickname. If we don't have entry for the new
1530      * ID we will query it and return here after it's done. After we've
1531      * returned we fetch the old entry and free it and notify the 
1532      * application.
1533      */
1534
1535     /* Get new Client ID */
1536     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1537     if (!tmp)
1538       goto out;
1539
1540     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1541
1542     /* Ignore my ID */
1543     if (!SILC_ID_CLIENT_COMPARE(client_id, conn->local_id))
1544       break;
1545
1546     /* Find Client entry and if not found query it */
1547     client_entry2 = 
1548       silc_idlist_get_client_by_id(client, conn, client_id, TRUE);
1549     if (!client_entry2) {
1550       SilcPacketContext *p = silc_packet_context_dup(packet);
1551       p->context = (void *)client;
1552       p->sock = sock;
1553       silc_client_command_pending(SILC_COMMAND_WHOIS, 
1554                                   silc_client_notify_by_server_pending, p);
1555       goto out;
1556     }
1557
1558     /* Get old Client ID */
1559     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1560     if (!tmp)
1561       goto out;
1562
1563     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1564
1565     /* Find old Client entry */
1566     client_entry = 
1567       silc_idlist_get_client_by_id(client, conn, client_id, FALSE);
1568     if (!client_entry)
1569       goto out;
1570
1571     /* Remove the old from cache */
1572     silc_idcache_del_by_id(conn->client_cache, SILC_ID_CLIENT, 
1573                            client_entry->id);
1574
1575     /* Replace old ID entry with new one on all channels. */
1576     silc_client_replace_from_channels(client, conn, client_entry,
1577                                       client_entry2);
1578
1579     /* Notify application */
1580     client->ops->notify(client, conn, type, client_entry, client_entry2);
1581
1582     /* Free data */
1583     if (client_entry->nickname)
1584       silc_free(client_entry->nickname);
1585     if (client_entry->server)
1586       silc_free(client_entry->server);
1587     if (client_entry->id)
1588       silc_free(client_entry->id);
1589     if (client_entry->send_key)
1590       silc_cipher_free(client_entry->send_key);
1591     if (client_entry->receive_key)
1592       silc_cipher_free(client_entry->receive_key);
1593     break;
1594
1595   case SILC_NOTIFY_TYPE_CMODE_CHANGE:
1596     /*
1597      * Someone changed a channel mode
1598      */
1599
1600     /* Get Client ID */
1601     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1602     if (!tmp)
1603       goto out;
1604
1605     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1606
1607     /* Find Client entry */
1608     client_entry = 
1609       silc_idlist_get_client_by_id(client, conn, client_id, FALSE);
1610     if (!client_entry)
1611       goto out;
1612
1613     /* Get the mode */
1614     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1615     if (!tmp)
1616       goto out;
1617
1618     SILC_GET32_MSB(mode, tmp);
1619
1620     /* Get channel entry */
1621     channel_id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
1622     if (!silc_idcache_find_by_id_one(conn->channel_cache, (void *)channel_id,
1623                                      SILC_ID_CHANNEL, &id_cache))
1624       break;
1625
1626     channel = (SilcChannelEntry)id_cache->context;
1627
1628     /* Save the new mode */
1629     channel->mode = mode;
1630
1631     /* Notify application. The channel entry is sent last as this notify
1632        is for channel but application don't know it from the arguments
1633        sent by server. */
1634     client->ops->notify(client, conn, type, client_entry, mode, channel);
1635     break;
1636
1637   case SILC_NOTIFY_TYPE_CUMODE_CHANGE:
1638     /*
1639      * Someone changed user's mode on a channel
1640      */
1641
1642     /* Get Client ID */
1643     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1644     if (!tmp)
1645       goto out;
1646
1647     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1648
1649     /* Find Client entry */
1650     client_entry = 
1651       silc_idlist_get_client_by_id(client, conn, client_id, FALSE);
1652     if (!client_entry)
1653       goto out;
1654
1655     /* Get the mode */
1656     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1657     if (!tmp)
1658       goto out;
1659
1660     SILC_GET32_MSB(mode, tmp);
1661
1662     /* Get target Client ID */
1663     tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1664     if (!tmp)
1665       goto out;
1666
1667     silc_free(client_id);
1668     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1669
1670     /* Find target Client entry */
1671     client_entry2 = 
1672       silc_idlist_get_client_by_id(client, conn, client_id, FALSE);
1673     if (!client_entry2)
1674       goto out;
1675
1676     /* Get channel entry */
1677     channel_id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
1678     if (!silc_idcache_find_by_id_one(conn->channel_cache, (void *)channel_id,
1679                                      SILC_ID_CHANNEL, &id_cache))
1680       break;
1681
1682     channel = (SilcChannelEntry)id_cache->context;
1683
1684     /* Save the mode */
1685     silc_list_start(channel->clients);
1686     while ((chu = silc_list_get(channel->clients)) != SILC_LIST_END) {
1687       if (chu->client == client_entry) {
1688         chu->mode = mode;
1689         break;
1690       }
1691     }
1692
1693     /* Notify application. The channel entry is sent last as this notify
1694        is for channel but application don't know it from the arguments
1695        sent by server. */
1696     client->ops->notify(client, conn, type, client_entry, mode, 
1697                         client_entry2, channel);
1698     break;
1699
1700   case SILC_NOTIFY_TYPE_MOTD:
1701     /*
1702      * Received Message of the day
1703      */
1704
1705     /* Get motd */
1706     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1707     if (!tmp)
1708       goto out;
1709     
1710     /* Notify application */
1711     client->ops->notify(client, conn, type, tmp);
1712     break;
1713     
1714   default:
1715     break;
1716   }
1717
1718  out:
1719   silc_notify_payload_free(payload);
1720   if (client_id)
1721     silc_free(client_id);
1722   if (channel_id)
1723     silc_free(channel_id);
1724 }
1725
1726 /* Processes the received new Client ID from server. Old Client ID is
1727    deleted from cache and new one is added. */
1728
1729 void silc_client_receive_new_id(SilcClient client,
1730                                 SilcSocketConnection sock,
1731                                 SilcIDPayload idp)
1732 {
1733   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1734
1735   /* Delete old ID from ID cache */
1736   silc_idcache_del_by_id(conn->client_cache, SILC_ID_CLIENT, conn->local_id);
1737   
1738   /* Save the new ID */
1739   if (conn->local_id)
1740     silc_free(conn->local_id);
1741   if (conn->local_id_data)
1742     silc_free(conn->local_id_data);
1743
1744   conn->local_id = silc_id_payload_get_id(idp);
1745   conn->local_id_data = silc_id_payload_get_data(idp);
1746   conn->local_id_data_len = silc_id_payload_get_len(idp);;
1747
1748   if (!conn->local_entry)
1749     conn->local_entry = silc_calloc(1, sizeof(*conn->local_entry));
1750
1751   conn->local_entry->nickname = conn->nickname;
1752   if (!conn->local_entry->username) {
1753     conn->local_entry->username = 
1754       silc_calloc(strlen(client->username) + strlen(client->hostname) + 1,
1755                   sizeof(conn->local_entry->username));
1756     sprintf(conn->local_entry->username, "%s@%s", client->username,
1757             client->hostname);
1758   }
1759   conn->local_entry->server = strdup(conn->remote_host);
1760   conn->local_entry->id = conn->local_id;
1761   
1762   /* Put it to the ID cache */
1763   silc_idcache_add(conn->client_cache, conn->nickname, SILC_ID_CLIENT,
1764                    conn->local_id, (void *)conn->local_entry, TRUE);
1765 }
1766
1767 /* Processed received Channel ID for a channel. This is called when client
1768    joins to channel and server replies with channel ID. The ID is cached. */
1769
1770 void silc_client_new_channel_id(SilcClient client,
1771                                 SilcSocketConnection sock,
1772                                 char *channel_name,
1773                                 unsigned int mode, SilcIDPayload idp)
1774 {
1775   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1776   SilcChannelEntry channel;
1777
1778   SILC_LOG_DEBUG(("New channel ID"));
1779
1780   channel = silc_calloc(1, sizeof(*channel));
1781   channel->channel_name = channel_name;
1782   channel->id = silc_id_payload_get_id(idp);
1783   channel->mode = mode;
1784   silc_list_init(channel->clients, struct SilcChannelUserStruct, next);
1785
1786   conn->current_channel = channel;
1787
1788   /* Put it to the ID cache */
1789   silc_idcache_add(conn->channel_cache, channel_name, SILC_ID_CHANNEL,
1790                    (void *)channel->id, (void *)channel, TRUE);
1791 }
1792
1793 /* Processes received key for channel. The received key will be used
1794    to protect the traffic on the channel for now on. Client must receive
1795    the key to the channel before talking on the channel is possible. 
1796    This is the key that server has generated, this is not the channel
1797    private key, it is entirely local setting. */
1798
1799 void silc_client_receive_channel_key(SilcClient client,
1800                                      SilcSocketConnection sock,
1801                                      SilcBuffer packet)
1802 {
1803   unsigned char *id_string, *key, *cipher;
1804   unsigned int tmp_len;
1805   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1806   SilcChannelID *id;
1807   SilcIDCacheEntry id_cache = NULL;
1808   SilcChannelEntry channel;
1809   SilcChannelKeyPayload payload;
1810
1811   SILC_LOG_DEBUG(("Received key for channel"));
1812   
1813   payload = silc_channel_key_payload_parse(packet);
1814   if (!payload)
1815     return;
1816
1817   id_string = silc_channel_key_get_id(payload, &tmp_len);
1818   if (!id_string) {
1819     silc_channel_key_payload_free(payload);
1820     return;
1821   }
1822   id = silc_id_payload_parse_id(id_string, tmp_len);
1823
1824   /* Find channel. */
1825   if (!silc_idcache_find_by_id_one(conn->channel_cache, (void *)id,
1826                                    SILC_ID_CHANNEL, &id_cache))
1827     goto out;
1828     
1829   /* Save the key */
1830   key = silc_channel_key_get_key(payload, &tmp_len);
1831   cipher = silc_channel_key_get_cipher(payload, NULL);
1832
1833   channel = (SilcChannelEntry)id_cache->context;
1834   channel->key_len = tmp_len;
1835   channel->key = silc_calloc(tmp_len, sizeof(*channel->key));
1836   memcpy(channel->key, key, tmp_len);
1837
1838   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
1839     client->ops->say(client, conn,
1840                      "Cannot talk to channel: unsupported cipher %s", cipher);
1841     goto out;
1842   }
1843   channel->channel_key->cipher->set_key(channel->channel_key->context, 
1844                                         key, tmp_len);
1845
1846   /* Client is now joined to the channel */
1847   channel->on_channel = TRUE;
1848
1849  out:
1850   silc_free(id);
1851   silc_channel_key_payload_free(payload);
1852 }
1853
1854 /* Process received message to a channel (or from a channel, really). This
1855    decrypts the channel message with channel specific key and parses the
1856    channel payload. Finally it displays the message on the screen. */
1857
1858 void silc_client_channel_message(SilcClient client, 
1859                                  SilcSocketConnection sock, 
1860                                  SilcPacketContext *packet)
1861 {
1862   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1863   SilcBuffer buffer = packet->buffer;
1864   SilcChannelPayload payload = NULL;
1865   SilcChannelID *id = NULL;
1866   SilcChannelEntry channel;
1867   SilcChannelUser chu;
1868   SilcIDCacheEntry id_cache = NULL;
1869   SilcClientID *client_id = NULL;
1870   int i;
1871   char *nickname;
1872
1873   /* Sanity checks */
1874   if (packet->dst_id_type != SILC_ID_CHANNEL)
1875     goto out;
1876
1877   client_id = silc_id_str2id(packet->src_id, SILC_ID_CLIENT);
1878   id = silc_id_str2id(packet->dst_id, SILC_ID_CHANNEL);
1879
1880   /* Find the channel entry from channels on this connection */
1881   if (!silc_idcache_find_by_id_one(conn->channel_cache, (void *)id,
1882                                    SILC_ID_CHANNEL, &id_cache))
1883     goto out;
1884
1885   channel = (SilcChannelEntry)id_cache->context;
1886
1887   /* Decrypt the channel message payload. Push the IV out of the way,
1888      since it is not encrypted (after pushing buffer->tail has the IV). */
1889   silc_buffer_push_tail(buffer, 16);
1890   channel->channel_key->cipher->decrypt(channel->channel_key->context,
1891                                         buffer->data, buffer->data,
1892                                         buffer->len, buffer->tail);
1893   silc_buffer_pull_tail(buffer, 16);
1894
1895   /* Parse the channel message payload */
1896   payload = silc_channel_payload_parse(buffer);
1897   if (!payload)
1898     goto out;
1899
1900   /* Find nickname */
1901   nickname = "[unknown]";
1902   silc_list_start(channel->clients);
1903   while ((chu = silc_list_get(channel->clients)) != SILC_LIST_END) {
1904     if (!SILC_ID_CLIENT_COMPARE(chu->client->id, client_id)) {
1905       nickname = chu->client->nickname;
1906       break;
1907     }
1908   }
1909
1910   /* Pass the message to application */
1911   client->ops->channel_message(client, conn, nickname,
1912                                channel->channel_name,
1913                                silc_channel_get_data(payload, NULL));
1914
1915  out:
1916   if (id)
1917     silc_free(id);
1918   if (client_id)
1919     silc_free(client_id);
1920   if (payload)
1921     silc_channel_payload_free(payload);
1922 }
1923
1924 /* Private message received. This processes the private message and
1925    finally displays it on the screen. */
1926
1927 void silc_client_private_message(SilcClient client, 
1928                                  SilcSocketConnection sock, 
1929                                  SilcPacketContext *packet)
1930 {
1931   SilcClientConnection conn = (SilcClientConnection)sock->user_data;
1932   SilcBuffer buffer = packet->buffer;
1933   unsigned short nick_len;
1934   unsigned char *nickname, *message;
1935
1936   /* Get nickname */
1937   silc_buffer_unformat(buffer, 
1938                        SILC_STR_UI16_NSTRING_ALLOC(&nickname, &nick_len),
1939                        SILC_STR_END);
1940   silc_buffer_pull(buffer, 2 + nick_len);
1941      
1942   message = silc_calloc(buffer->len + 1, sizeof(char));
1943   memcpy(message, buffer->data, buffer->len);
1944
1945   /* Pass the private message to application */
1946   client->ops->private_message(client, conn, nickname, message);
1947
1948   /* See if we are away (gone). If we are away we will reply to the
1949      sender with the set away message. */
1950   if (conn->away && conn->away->away) {
1951     SilcClientID *remote_id;
1952     SilcClientEntry remote_client;
1953     SilcIDCacheEntry id_cache;
1954
1955     if (packet->src_id_type != SILC_ID_CLIENT)
1956       goto out;
1957
1958     remote_id = silc_id_str2id(packet->src_id, SILC_ID_CLIENT);
1959     if (!remote_id)
1960       goto out;
1961
1962     /* If it's me, ignore */
1963     if (!SILC_ID_CLIENT_COMPARE(remote_id, conn->local_id))
1964       goto out;
1965
1966     /* Check whether we know this client already */
1967     if (!silc_idcache_find_by_id_one(conn->client_cache, remote_id,
1968                                      SILC_ID_CLIENT, &id_cache))
1969       {
1970         /* Allocate client entry */
1971         remote_client = silc_calloc(1, sizeof(*remote_client));
1972         remote_client->id = remote_id;
1973         silc_parse_nickname(nickname, &remote_client->nickname, 
1974                             &remote_client->server, &remote_client->num);
1975
1976         /* Save the client to cache */
1977         silc_idcache_add(conn->client_cache, remote_client->nickname,
1978                          SILC_ID_CLIENT, remote_client->id, remote_client, 
1979                          TRUE);
1980       } else {
1981         silc_free(remote_id);
1982         remote_client = (SilcClientEntry)id_cache->context;
1983       }
1984
1985     /* Send the away message */
1986     silc_client_packet_send_private_message(client, sock, remote_client,
1987                                             conn->away->away,
1988                                             strlen(conn->away->away), TRUE);
1989   }
1990
1991  out:
1992   memset(message, 0, buffer->len);
1993   silc_free(message);
1994   silc_free(nickname);
1995 }
1996
1997 /* Removes a client entry from all channel it has joined. This really is
1998    a performance killer (client_entry should have pointers to channel 
1999    entry list). */
2000
2001 void silc_client_remove_from_channels(SilcClient client,
2002                                       SilcClientConnection conn,
2003                                       SilcClientEntry client_entry)
2004 {
2005   SilcIDCacheEntry id_cache;
2006   SilcIDCacheList list;
2007   SilcChannelEntry channel;
2008   SilcChannelUser chu;
2009   int i;
2010
2011   if (!silc_idcache_find_by_id(conn->channel_cache, SILC_ID_CACHE_ANY,
2012                                SILC_ID_CHANNEL, &list))
2013     return;
2014
2015   silc_idcache_list_first(list, &id_cache);
2016   channel = (SilcChannelEntry)id_cache->context;
2017   
2018   while (channel) {
2019     
2020     /* Remove client from channel */
2021     silc_list_start(channel->clients);
2022     while ((chu = silc_list_get(channel->clients)) != SILC_LIST_END) {
2023       if (chu->client == client_entry) {
2024         silc_list_del(channel->clients, chu);
2025         silc_free(chu);
2026         break;
2027       }
2028     }
2029
2030     if (!silc_idcache_list_next(list, &id_cache))
2031       break;
2032     
2033     channel = (SilcChannelEntry)id_cache->context;
2034   }
2035
2036   silc_idcache_list_free(list);
2037 }
2038
2039 /* Replaces `old' client entries from all channels to `new' client entry.
2040    This can be called for example when nickname changes and old ID entry
2041    is replaced from ID cache with the new one. If the old ID entry is only
2042    updated, then this fucntion needs not to be called. */
2043
2044 void silc_client_replace_from_channels(SilcClient client, 
2045                                        SilcClientConnection conn,
2046                                        SilcClientEntry old,
2047                                        SilcClientEntry new)
2048 {
2049   SilcIDCacheEntry id_cache;
2050   SilcIDCacheList list;
2051   SilcChannelEntry channel;
2052   SilcChannelUser chu;
2053   int i;
2054
2055   if (!silc_idcache_find_by_id(conn->channel_cache, SILC_ID_CACHE_ANY,
2056                                SILC_ID_CHANNEL, &list))
2057     return;
2058
2059   silc_idcache_list_first(list, &id_cache);
2060   channel = (SilcChannelEntry)id_cache->context;
2061   
2062   while (channel) {
2063     
2064     /* Replace client entry */
2065     silc_list_start(channel->clients);
2066     while ((chu = silc_list_get(channel->clients)) != SILC_LIST_END) {
2067       if (chu->client == old) {
2068         chu->client = new;
2069         break;
2070       }
2071     }
2072
2073     if (!silc_idcache_list_next(list, &id_cache))
2074       break;
2075     
2076     channel = (SilcChannelEntry)id_cache->context;
2077   }
2078
2079   silc_idcache_list_free(list);
2080 }
2081
2082 /* Parses mode mask and returns the mode as string. */
2083
2084 char *silc_client_chmode(unsigned int mode)
2085 {
2086   char string[20];
2087
2088   if (!mode)
2089     return NULL;
2090
2091   memset(string, 0, sizeof(string));
2092
2093   if (mode & SILC_CHANNEL_MODE_PRIVATE)
2094     strncat(string, "p", 1);
2095
2096   if (mode & SILC_CHANNEL_MODE_SECRET)
2097     strncat(string, "s", 1);
2098
2099   if (mode & SILC_CHANNEL_MODE_PRIVKEY)
2100     strncat(string, "k", 1);
2101
2102   if (mode & SILC_CHANNEL_MODE_INVITE)
2103     strncat(string, "i", 1);
2104
2105   if (mode & SILC_CHANNEL_MODE_TOPIC)
2106     strncat(string, "t", 1);
2107
2108   if (mode & SILC_CHANNEL_MODE_ULIMIT)
2109     strncat(string, "l", 1);
2110
2111   if (mode & SILC_CHANNEL_MODE_PASSPHRASE)
2112     strncat(string, "a", 1);
2113
2114   /* Rest of mode is ignored */
2115
2116   return strdup(string);
2117 }
2118
2119 /* Parses channel user mode mask and returns te mode as string */
2120
2121 char *silc_client_chumode(unsigned int mode)
2122 {
2123   char string[4];
2124
2125   if (!mode)
2126     return NULL;
2127
2128   memset(string, 0, sizeof(string));
2129
2130   if (mode & SILC_CHANNEL_UMODE_CHANFO)
2131     strncat(string, "f", 1);
2132
2133   if (mode & SILC_CHANNEL_UMODE_CHANOP)
2134     strncat(string, "o", 1);
2135
2136   return strdup(string);
2137 }
2138
2139 /* Parses channel user mode and returns it as special mode character. */
2140
2141 char *silc_client_chumode_char(unsigned int mode)
2142 {
2143   char string[4];
2144
2145   if (!mode)
2146     return NULL;
2147
2148   memset(string, 0, sizeof(string));
2149
2150   if (mode & SILC_CHANNEL_UMODE_CHANFO)
2151     strncat(string, "*", 1);
2152
2153   if (mode & SILC_CHANNEL_UMODE_CHANOP)
2154     strncat(string, "@", 1);
2155
2156   return strdup(string);
2157 }