Client library rewrites.
[silc.git] / lib / silcclient / client_channel.c
index 7587d07d27a9451fd5f2e54de2c4e8a37a5abce1..c843b63b9c3a558350f69e362efac5e73ed61336 100644 (file)
 
 */
 /* $Id$ */
-/* This file includes channel message sending and receiving routines,
-   channel key receiving and setting, and channel private key handling
-   routines. */
 
 #include "silc.h"
 #include "silcclient.h"
 #include "client_internal.h"
 
-/* Sends packet to the `channel'. Packet to channel is always encrypted
-   differently from "normal" packets. SILC header of the packet is
-   encrypted with the next receiver's key and the rest of the packet is
-   encrypted with the channel specific key. Padding and HMAC is computed
-   with the next receiver's key. The `data' is the channel message. If
-   the `force_send' is TRUE then the packet is sent immediately. */
+/************************** Channel Message Send ****************************/
+
+/* Sends channel message to `channel'. */
 
 SilcBool silc_client_send_channel_message(SilcClient client,
-                                     SilcClientConnection conn,
-                                     SilcChannelEntry channel,
-                                     SilcChannelPrivateKey key,
-                                     SilcMessageFlags flags,
-                                     unsigned char *data,
-                                     SilcUInt32 data_len,
-                                     SilcBool force_send)
+                                         SilcClientConnection conn,
+                                         SilcChannelEntry channel,
+                                         SilcChannelPrivateKey key,
+                                         SilcMessageFlags flags,
+                                         SilcHash hash,
+                                         unsigned char *data,
+                                         SilcUInt32 data_len)
 {
-  SilcSocketConnection sock;
-  SilcBuffer payload;
-  SilcPacketContext packetdata;
-  const SilcBufferStruct packet;
+  SilcChannelUser chu;
+  SilcBuffer buffer;
   SilcCipher cipher;
   SilcHmac hmac;
-  unsigned char *id_string;
-  int block_len;
-  SilcChannelUser chu;
-  SilcBool ret = FALSE;
+  SilcBool ret;
 
-  assert(client && conn && channel);
-  sock = conn->sock;
-  SILC_LOG_DEBUG(("Sending packet to channel"));
+  SILC_LOG_DEBUG(("Sending channel message"));
+
+  if (!client || !conn || !channel)
+    return FALSE;
+  if (flags & SILC_MESSAGE_FLAG_SIGNED && !hash)
+    return FALSE;
 
   chu = silc_client_on_channel(channel, conn->local_entry);
   if (!chu) {
-    SILC_LOG_ERROR(("Cannot send message to channel we are not joined"));
+    client->internal->ops->say(conn->client, conn,
+                              SILC_CLIENT_MESSAGE_AUDIT,
+                              "Cannot talk to channel: not joined");
     return FALSE;
   }
 
@@ -73,36 +67,37 @@ SilcBool silc_client_send_channel_message(SilcClient client,
     return FALSE;
 
   /* Take the key to be used */
-  if (channel->private_keys) {
+  if (channel->internal.private_keys) {
     if (key) {
       /* Use key application specified */
       cipher = key->cipher;
       hmac = key->hmac;
     } else if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY &&
-              channel->curr_key) {
+              channel->internal.curr_key) {
       /* Use current private key */
-      cipher = channel->curr_key->cipher;
-      hmac = channel->curr_key->hmac;
+      cipher = channel->internal.curr_key->cipher;
+      hmac = channel->internal.curr_key->hmac;
     } else if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY &&
-              !channel->curr_key && channel->private_keys) {
+              !channel->internal.curr_key &&
+              channel->internal.private_keys) {
       /* Use just some private key since we don't know what to use
         and private keys are set. */
-      silc_dlist_start(channel->private_keys);
-      key = silc_dlist_get(channel->private_keys);
+      silc_dlist_start(channel->internal.private_keys);
+      key = silc_dlist_get(channel->internal.private_keys);
       cipher = key->cipher;
       hmac = key->hmac;
 
       /* Use this key as current private key */
-      channel->curr_key = key;
+      channel->internal.curr_key = key;
     } else {
       /* Use normal channel key generated by the server */
-      cipher = channel->channel_key;
-      hmac = channel->hmac;
+      cipher = channel->internal.channel_key;
+      hmac = channel->internal.hmac;
     }
   } else {
     /* Use normal channel key generated by the server */
-    cipher = channel->channel_key;
-    hmac = channel->hmac;
+    cipher = channel->internal.channel_key;
+    hmac = channel->internal.hmac;
   }
 
   if (!cipher || !hmac) {
@@ -110,198 +105,136 @@ SilcBool silc_client_send_channel_message(SilcClient client,
     return FALSE;
   }
 
-  block_len = silc_cipher_get_block_len(cipher);
-
   /* Encode the message payload. This also encrypts the message payload. */
-  payload = silc_message_payload_encode(flags, data, data_len, TRUE, FALSE,
-                                       cipher, hmac, client->rng, NULL,
-                                       client->private_key, client->sha1hash);
-  if (!payload) {
+  buffer = silc_message_payload_encode(flags, data, data_len, TRUE, FALSE,
+                                      cipher, hmac, client->rng, NULL,
+                                      conn->private_key, hash, NULL);
+  if (!buffer) {
     SILC_LOG_ERROR(("Error encoding channel message"));
     return FALSE;
   }
 
-  /* Get data used in packet header encryption, keys and stuff. */
-  cipher = conn->internal->send_key;
-  hmac = conn->internal->hmac_send;
-  id_string = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
-
-  /* Set the packet context pointers. The destination ID is always
-     the Channel ID of the channel. Server and router will handle the
-     distribution of the packet. */
-  data = payload->data;
-  data_len = payload->len;
-  packetdata.flags = 0;
-  packetdata.type = SILC_PACKET_CHANNEL_MESSAGE;
-  packetdata.src_id = conn->local_id_data;
-  packetdata.src_id_len = silc_id_get_len(conn->local_id, SILC_ID_CLIENT);
-  packetdata.src_id_type = SILC_ID_CLIENT;
-  packetdata.dst_id = id_string;
-  packetdata.dst_id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
-  packetdata.dst_id_type = SILC_ID_CHANNEL;
-  data_len = SILC_PACKET_DATALEN(data_len, SILC_PACKET_HEADER_LEN +
-                                packetdata.src_id_len +
-                                packetdata.dst_id_len);
-  packetdata.truelen = data_len + SILC_PACKET_HEADER_LEN +
-    packetdata.src_id_len + packetdata.dst_id_len;
-  SILC_PACKET_PADLEN((SILC_PACKET_HEADER_LEN +
-                     packetdata.src_id_len +
-                     packetdata.dst_id_len), block_len, packetdata.padlen);
-
-  /* Create the outgoing packet */
-  if (!silc_packet_assemble(&packetdata, client->rng, cipher, hmac, sock,
-                            data, data_len, (const SilcBuffer)&packet)) {
-    SILC_LOG_ERROR(("Error assembling packet"));
-    goto out;
-  }
-
-  /* Encrypt the header and padding of the packet. This is encrypted
-     with normal session key shared with our server. */
-  silc_packet_encrypt(cipher, hmac, conn->internal->psn_send++,
-                     (SilcBuffer)&packet, SILC_PACKET_HEADER_LEN +
-                     packetdata.src_id_len + packetdata.dst_id_len +
-                     packetdata.padlen);
-
-  SILC_LOG_HEXDUMP(("Packet to channel, len %d", packet.len),
-                   packet.data, packet.len);
-
-  /* Now actually send the packet */
-  silc_client_packet_send_real(client, sock, force_send);
-
-  /* Check for mandatory rekey */
-  if (conn->internal->psn_send == SILC_CLIENT_REKEY_THRESHOLD)
-    silc_schedule_task_add(client->schedule, sock->sock,
-                          silc_client_rekey_callback, sock, 0, 1,
-                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
-
-  ret = TRUE;
-
- out:
-  silc_buffer_free(payload);
-  silc_free(id_string);
+  /* Send the channel message */
+  ret = silc_packet_send_ext(conn->stream, SILC_PACKET_CHANNEL_MESSAGE, 0,
+                            0, NULL, SILC_ID_CHANNEL, &channel->id,
+                            silc_buffer_datalen(buffer), NULL, NULL);
 
+  silc_buffer_free(buffer);
   return ret;
 }
 
-typedef struct {
-  SilcMessagePayload payload;
-  SilcChannelID *channel_id;
-  SilcChannelPrivateKey key;
-} *SilcChannelClientResolve;
-
-static void silc_client_channel_message_cb(SilcClient client,
-                                          SilcClientConnection conn,
-                                          SilcClientEntry *clients,
-                                          SilcUInt32 clients_count,
-                                          void *context)
-{
-  SilcChannelClientResolve res = (SilcChannelClientResolve)context;
-
-  if (clients_count == 1) {
-    SilcChannelEntry channel;
-    unsigned char *message;
-    SilcUInt32 message_len;
-
-    channel = silc_client_get_channel_by_id(client, conn, res->channel_id);
-    if (!channel)
-      goto out;
-
-    /* If this client is not on channel, add it there since it clearly
-       is there. */
-    if (!silc_client_on_channel(channel, clients[0])) {
-      SilcChannelUser chu = silc_calloc(1, sizeof(*chu));
-      chu->client = clients[0];
-      chu->channel = channel;
-      silc_hash_table_add(channel->user_list, clients[0], chu);
-      silc_hash_table_add(clients[0]->channels, channel, chu);
-    }
+/************************* Channel Message Receive **************************/
 
-    message = silc_message_get_data(res->payload, &message_len);
+/* Client resolving callback.  Continues with the channel message processing */
 
-    /* Pass the message to application */
-    client->internal->ops->channel_message(
-                           client, conn, clients[0], channel, res->payload,
-                           res->key, silc_message_get_flags(res->payload),
-                           message, message_len);
-  }
+static void silc_client_channel_message_resolved(SilcClient client,
+                                                SilcClientConnection conn,
+                                                SilcStatus status,
+                                                SilcDList clients,
+                                                void *context)
+{
+  /* If no client found, ignore the channel message, a silent error */
+  if (!clients)
+    silc_fsm_next(context, silc_client_channel_message_error);
 
- out:
-  silc_message_payload_free(res->payload);
-  silc_free(res->channel_id);
-  silc_free(res);
+  /* Continue processing the channel message packet */
+  SILC_FSM_CALL_CONTINUE(context);
 }
 
-/* Process received message to a channel (or from a channel, really). This
-   decrypts the channel message with channel specific key and parses the
-   message payload. Finally it displays the message on the screen. */
+/* Process received channel message */
 
-void silc_client_channel_message(SilcClient client,
-                                SilcSocketConnection sock,
-                                SilcPacketContext *packet)
+SILC_FSM_STATE(silc_client_channel_message)
 {
-  SilcClientConnection conn = (SilcClientConnection)sock->user_data;
-  SilcBuffer buffer = packet->buffer;
+  SilcClientConnection conn = fsm_context;
+  SilcClient client = conn->client;
+  SilcPacket packet = state_context;
+  SilcBuffer buffer = &packet->buffer;
   SilcMessagePayload payload = NULL;
-  SilcChannelID *id = NULL;
   SilcChannelEntry channel;
   SilcClientEntry client_entry;
-  SilcClientID *client_id = NULL;
+  SilcClientID remote_id;
+  SilcChannelID channel_id;
   unsigned char *message;
   SilcUInt32 message_len;
   SilcChannelPrivateKey key = NULL;
 
   SILC_LOG_DEBUG(("Received channel message"));
 
-  /* Sanity checks */
-  if (packet->dst_id_type != SILC_ID_CHANNEL)
-    goto out;
+  if (packet->dst_id_type != SILC_ID_CHANNEL) {
+    /** Invalid packet */
+    silc_fsm_next(fsm, silc_client_channel_message_error);
+    return SILC_FSM_CONTINUE;
+  }
 
-  client_id = silc_id_str2id(packet->src_id, packet->src_id_len,
-                            SILC_ID_CLIENT);
-  if (!client_id)
-    goto out;
-  id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CHANNEL);
-  if (!id)
-    goto out;
+  if (!silc_id_str2id(packet->src_id, packet->src_id_len, SILC_ID_CLIENT,
+                     &remote_id, sizeof(remote_id))) {
+    /** Invalid source ID */
+    silc_fsm_next(fsm, silc_client_channel_message_error);
+    return SILC_FSM_CONTINUE;
+  }
 
-  /* Find the channel entry from channels on this connection */
-  channel = silc_client_get_channel_by_id(client, conn, id);
-  if (!channel)
-    goto out;
+  /* Get sender client entry */
+  client_entry = silc_client_get_client_by_id(client, conn, &remote_id);
+  if (!client_entry || !client_entry->nickname[0]) {
+    /** Resolve client info */
+    silc_client_unref_client(client, conn, client_entry);
+    SILC_FSM_CALL(silc_client_get_client_by_id_resolve(
+                                        client, conn, &remote_id, NULL,
+                                        silc_client_channel_message_resolved,
+                                        fsm));
+    /* NOT REACHED */
+  }
+
+  if (!silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CHANNEL,
+                     &channel_id, sizeof(channel_id))) {
+    /** Invalid destination ID */
+    silc_fsm_next(fsm, silc_client_channel_message_error);
+    return SILC_FSM_CONTINUE;
+  }
+
+  /* Find the channel */
+  channel = silc_client_get_channel_by_id(client, conn, &channel_id);
+  if (!channel) {
+    /** Unknown channel */
+    silc_fsm_next(fsm, silc_client_channel_message_error);
+    return SILC_FSM_CONTINUE;
+  }
 
   /* If there is no channel private key then just decrypt the message
      with the channel key. If private keys are set then just go through
      all private keys and check what decrypts correctly. */
-  if (!channel->private_keys) {
+  if (!channel->internal.private_keys) {
     /* Parse the channel message payload. This also decrypts the payload */
-    payload = silc_message_payload_parse(buffer->data, buffer->len, FALSE,
-                                        FALSE, channel->channel_key,
-                                        channel->hmac);
+    payload = silc_message_payload_parse(silc_buffer_data(buffer),
+                                        silc_buffer_len(buffer), FALSE,
+                                        FALSE, channel->internal.channel_key,
+                                        channel->internal.hmac, NULL,
+                                        FALSE, NULL);
 
     /* If decryption failed and we have just performed channel key rekey
        we will use the old key in decryption. If that fails too then we
        cannot do more and will drop the packet. */
     if (!payload) {
-      SilcCipher key;
+      SilcCipher cipher;
       SilcHmac hmac;
-      int i;
 
-      if (!channel->old_channel_keys ||
-         !silc_dlist_count(channel->old_channel_keys))
+      if (!channel->internal.old_channel_keys ||
+         !silc_dlist_count(channel->internal.old_channel_keys))
        goto out;
 
       SILC_LOG_DEBUG(("Attempting to decrypt with old channel key(s)"));
 
-      silc_dlist_end(channel->old_channel_keys);
-      silc_dlist_end(channel->old_hmacs);
-      for (i = 0; i < silc_dlist_count(channel->old_channel_keys); i++) {
-       key = silc_dlist_get(channel->old_channel_keys);
-       hmac = silc_dlist_get(channel->old_hmacs);
-       if (!key || !hmac)
+      silc_dlist_end(channel->internal.old_channel_keys);
+      silc_dlist_end(channel->internal.old_hmacs);
+      while ((cipher = silc_dlist_get(channel->internal.old_channel_keys))) {
+       hmac = silc_dlist_get(channel->internal.old_hmacs);
+       if (!hmac)
          break;
 
-       payload = silc_message_payload_parse(buffer->data, buffer->len,
-                                            FALSE, FALSE, key, hmac);
+       payload = silc_message_payload_parse(silc_buffer_data(buffer),
+                                            silc_buffer_len(buffer),
+                                            FALSE, FALSE, cipher, hmac,
+                                            NULL, FALSE, NULL);
        if (payload)
          break;
       }
@@ -309,21 +242,24 @@ void silc_client_channel_message(SilcClient client,
        goto out;
     }
   } else {
-    /* If the private key mode, however is not set on the channel then
-       try the actual channel key first before trying private keys. */
+    /* If the private key mode is not set on the channel then try the actual
+       channel key first before trying private keys. */
     if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY))
-      payload = silc_message_payload_parse(buffer->data, buffer->len, FALSE,
-                                          FALSE, channel->channel_key,
-                                          channel->hmac);
+      payload = silc_message_payload_parse(silc_buffer_data(buffer),
+                                          silc_buffer_len(buffer),
+                                          FALSE, FALSE,
+                                          channel->internal.channel_key,
+                                          channel->internal.hmac, NULL,
+                                          FALSE, NULL);
 
     if (!payload) {
-      silc_dlist_start(channel->private_keys);
-      while ((key = silc_dlist_get(channel->private_keys))
-            != SILC_LIST_END) {
+      silc_dlist_start(channel->internal.private_keys);
+      while ((key = silc_dlist_get(channel->internal.private_keys))) {
        /* Parse the message payload. This also decrypts the payload */
-       payload = silc_message_payload_parse(buffer->data, buffer->len,
-                                            FALSE, FALSE,
-                                            key->cipher, key->hmac);
+       payload = silc_message_payload_parse(silc_buffer_data(buffer),
+                                            silc_buffer_len(buffer),
+                                            FALSE, FALSE, key->cipher,
+                                            key->hmac, NULL, FALSE, NULL);
        if (payload)
          break;
       }
@@ -332,23 +268,6 @@ void silc_client_channel_message(SilcClient client,
     }
   }
 
-  /* Find client entry */
-  client_entry = silc_client_get_client_by_id(client, conn, client_id);
-  if (!client_entry || !client_entry->nickname ||
-      !silc_client_on_channel(channel, client_entry)) {
-    /* Resolve the client info */
-    SilcChannelClientResolve res = silc_calloc(1, sizeof(*res));
-    res->payload = payload;
-    res->channel_id = id;
-    res->key = key;
-    silc_client_get_client_by_id_resolve(client, conn, client_id, NULL,
-                                        silc_client_channel_message_cb,
-                                        res);
-    payload = NULL;
-    id = NULL;
-    goto out;
-  }
-
   message = silc_message_get_data(payload, &message_len);
 
   /* Pass the message to application */
@@ -358,12 +277,24 @@ void silc_client_channel_message(SilcClient client,
                             message, message_len);
 
  out:
-  silc_free(id);
-  silc_free(client_id);
+  silc_client_unref_client(client, conn, client_entry);
+  silc_client_unref_channel(client, conn, channel);
   if (payload)
     silc_message_payload_free(payload);
+  return SILC_FSM_FINISH;
+}
+
+/* Channel message error. */
+
+SILC_FSM_STATE(silc_client_channel_message_error)
+{
+  SilcPacket packet = state_context;
+  silc_packet_free(packet);
+  return SILC_FSM_FINISH;
 }
 
+/******************************* Channel Key ********************************/
+
 /* Timeout callback that is called after a short period of time after the
    new channel key has been created.  This removes the first channel key
    in the list. */
@@ -374,171 +305,162 @@ SILC_TASK_CALLBACK(silc_client_save_channel_key_rekey)
   SilcCipher key;
   SilcHmac hmac;
 
-  if (channel->old_channel_keys) {
-    silc_dlist_start(channel->old_channel_keys);
-    key = silc_dlist_get(channel->old_channel_keys);
+  if (channel->internal.old_channel_keys) {
+    silc_dlist_start(channel->internal.old_channel_keys);
+    key = silc_dlist_get(channel->internal.old_channel_keys);
     if (key) {
-      silc_dlist_del(channel->old_channel_keys, key);
+      silc_dlist_del(channel->internal.old_channel_keys, key);
       silc_cipher_free(key);
     }
   }
 
-  if (channel->old_hmacs) {
-    silc_dlist_start(channel->old_hmacs);
-    hmac = silc_dlist_get(channel->old_hmacs);
+  if (channel->internal.old_hmacs) {
+    silc_dlist_start(channel->internal.old_hmacs);
+    hmac = silc_dlist_get(channel->internal.old_hmacs);
     if (hmac) {
-      silc_dlist_del(channel->old_hmacs, hmac);
+      silc_dlist_del(channel->internal.old_hmacs, hmac);
       silc_hmac_free(hmac);
     }
   }
 }
 
-/* Saves channel key from encoded `key_payload'. This is used when we
-   receive Channel Key Payload and when we are processing JOIN command
-   reply. */
+/* Saves channel key from encoded `key_payload'. This is used when we receive
+   Channel Key Payload and when we are processing JOIN command reply. */
 
-void silc_client_save_channel_key(SilcClient client,
-                                 SilcClientConnection conn,
-                                 SilcBuffer key_payload,
-                                 SilcChannelEntry channel)
+SilcBool silc_client_save_channel_key(SilcClient client,
+                                     SilcClientConnection conn,
+                                     SilcBuffer key_payload,
+                                     SilcChannelEntry channel)
 {
   unsigned char *id_string, *key, *cipher, *hmac, hash[SILC_HASH_MAXLEN];
   SilcUInt32 tmp_len;
-  SilcChannelID *id;
+  SilcChannelID id;
   SilcChannelKeyPayload payload;
 
-  payload = silc_channel_key_payload_parse(key_payload->data,
-                                          key_payload->len);
+  payload = silc_channel_key_payload_parse(silc_buffer_data(key_payload),
+                                          silc_buffer_len(key_payload));
   if (!payload)
-    return;
+    return FALSE;
 
   id_string = silc_channel_key_get_id(payload, &tmp_len);
   if (!id_string) {
     silc_channel_key_payload_free(payload);
-    return;
+    return FALSE;
   }
 
-  id = silc_id_str2id(id_string, tmp_len, SILC_ID_CHANNEL);
-  if (!id) {
+  if (!silc_id_str2id(id_string, tmp_len, SILC_ID_CHANNEL, &id, sizeof(id))) {
     silc_channel_key_payload_free(payload);
-    return;
+    return FALSE;
   }
 
   /* Find channel. */
   if (!channel) {
-    channel = silc_client_get_channel_by_id(client, conn, id);
-    if (!channel)
-      goto out;
+    channel = silc_client_get_channel_by_id(client, conn, &id);
+    if (!channel) {
+      silc_channel_key_payload_free(payload);
+      return FALSE;
+    }
+  } else {
+    silc_client_ref_channel(client, conn, channel);
   }
 
-  hmac = (channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) :
-         SILC_DEFAULT_HMAC);
-
   /* Save the old key for a short period of time so that we can decrypt
      channel message even after the rekey if some client would be sending
      messages with the old key after the rekey. */
-  if (!channel->old_channel_keys)
-    channel->old_channel_keys = silc_dlist_init();
-  if (!channel->old_hmacs)
-    channel->old_hmacs = silc_dlist_init();
-  silc_dlist_add(channel->old_channel_keys, channel->channel_key);
-  silc_dlist_add(channel->old_hmacs, channel->hmac);
-  silc_schedule_task_add(client->schedule, 0,
-                        silc_client_save_channel_key_rekey, channel,
-                        10, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
-
-  /* Free the old channel key data */
-  silc_free(channel->key);
+  if (!channel->internal.old_channel_keys)
+    channel->internal.old_channel_keys = silc_dlist_init();
+  if (!channel->internal.old_hmacs)
+    channel->internal.old_hmacs = silc_dlist_init();
+  if (channel->internal.old_channel_keys && channel->internal.old_hmacs) {
+    silc_dlist_add(channel->internal.old_channel_keys,
+                  channel->internal.channel_key);
+    silc_dlist_add(channel->internal.old_hmacs, channel->internal.hmac);
+    silc_schedule_task_add_timeout(client->schedule,
+                                  silc_client_save_channel_key_rekey,
+                                  channel, 15, 0);
+  }
 
-  /* Save the key */
-  key = silc_channel_key_get_key(payload, &tmp_len);
+  /* Get channel cipher */
   cipher = silc_channel_key_get_cipher(payload, NULL);
-  channel->key_len = tmp_len * 8;
-  channel->key = silc_memdup(key, tmp_len);
-
-  if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
+  if (!silc_cipher_alloc(cipher, &channel->internal.channel_key)) {
     client->internal->ops->say(
                           conn->client, conn,
                           SILC_CLIENT_MESSAGE_AUDIT,
                           "Cannot talk to channel: unsupported cipher %s",
                           cipher);
-    goto out;
+    silc_client_unref_channel(client, conn, channel);
+    silc_channel_key_payload_free(payload);
+    return FALSE;
   }
 
   /* Set the cipher key */
-  silc_cipher_set_key(channel->channel_key, key, channel->key_len);
+  key = silc_channel_key_get_key(payload, &tmp_len);
+  silc_cipher_set_key(channel->internal.channel_key, key, tmp_len * 8);
 
-  /* Generate HMAC key from the channel key data and set it */
-  silc_hmac_alloc(hmac, NULL, &channel->hmac);
-  silc_hash_make(silc_hmac_get_hash(channel->hmac), key, tmp_len, hash);
-  silc_hmac_set_key(channel->hmac, hash,
-                   silc_hash_len(silc_hmac_get_hash(channel->hmac)));
+  /* Get channel HMAC */
+  hmac = (channel->internal.hmac ?
+         (char *)silc_hmac_get_name(channel->internal.hmac) :
+         SILC_DEFAULT_HMAC);
+  if (!silc_hmac_alloc(hmac, NULL, &channel->internal.hmac)) {
+    client->internal->ops->say(
+                          conn->client, conn,
+                          SILC_CLIENT_MESSAGE_AUDIT,
+                          "Cannot talk to channel: unsupported HMAC %s",
+                          hmac);
+    silc_client_unref_channel(client, conn, channel);
+    silc_channel_key_payload_free(payload);
+    return FALSE;
+  }
+
+  /* Set HMAC key */
+  silc_hash_make(silc_hmac_get_hash(channel->internal.hmac), key,
+                tmp_len, hash);
+  silc_hmac_set_key(channel->internal.hmac, hash,
+                   silc_hash_len(silc_hmac_get_hash(channel->internal.hmac)));
   memset(hash, 0, sizeof(hash));
 
- out:
-  silc_free(id);
-  silc_channel_key_payload_free(payload);
+  silc_client_unref_channel(client, conn, channel);
+
+  return TRUE;
 }
 
-/* Processes received key for channel. The received key will be used
-   to protect the traffic on the channel for now on. Client must receive
-   the key to the channel before talking on the channel is possible.
-   This is the key that server has generated, this is not the channel
-   private key, it is entirely local setting. */
+/* Received channel key packet.  The key will replace old channel key. */
 
-void silc_client_receive_channel_key(SilcClient client,
-                                    SilcSocketConnection sock,
-                                    SilcBuffer packet)
+SILC_FSM_STATE(silc_client_channel_key)
 {
-  SILC_LOG_DEBUG(("Received key for channel"));
+  SilcClientConnection conn = fsm_context;
+  SilcClient client = conn->client;
+  SilcPacket packet = state_context;
+
+  SILC_LOG_DEBUG(("Received channel key"));
 
   /* Save the key */
-  silc_client_save_channel_key(client, sock->user_data, packet, NULL);
+  silc_client_save_channel_key(client, conn, &packet->buffer, NULL);
+  silc_packet_free(packet);
+
+  return SILC_FSM_FINISH;
 }
 
-/* Adds private key for channel. When channel has private key then the
-   messages are encrypted using that key. All clients on the channel must
-   also know the key in order to decrypt the messages. However, it is
-   possible to have several private keys per one channel. In this case
-   only some of the clients on the channel may know the one key and only
-   some the other key.
-
-   If `cipher' and/or `hmac' is NULL then default values will be used
-   (aes-256-cbc for cipher and hmac-sha1-96 for hmac).
-
-   The private key for channel is optional. If it is not set then the
-   channel messages are encrypted using the channel key generated by the
-   server. However, setting the private key (or keys) for the channel
-   significantly adds security. If more than one key is set the library
-   will automatically try all keys at the message decryption phase. Note:
-   setting many keys slows down the decryption phase as all keys has to
-   be tried in order to find the correct decryption key. However, setting
-   a few keys does not have big impact to the decryption performace.
-
-   NOTE: that this is entirely local setting. The key set using this function
-   is not sent to the network at any phase.
-
-   NOTE: If the key material was originated by the SKE protocol (using
-   silc_client_send_key_agreement) then the `key' MUST be the
-   key->send_enc_key as this is dictated by the SILC protocol. However,
-   currently it is not expected that the SKE key material would be used
-   as channel private key. However, this API allows it. */
+/**************************** Channel Private Key ***************************/
+
+/* Add new channel private key */
 
 SilcBool silc_client_add_channel_private_key(SilcClient client,
-                                        SilcClientConnection conn,
-                                        SilcChannelEntry channel,
-                                        const char *name,
-                                        char *cipher,
-                                        char *hmac,
-                                        unsigned char *key,
-                                        SilcUInt32 key_len,
-                                        SilcChannelPrivateKey *ret_key)
+                                            SilcClientConnection conn,
+                                            SilcChannelEntry channel,
+                                            const char *name,
+                                            char *cipher,
+                                            char *hmac,
+                                            unsigned char *key,
+                                            SilcUInt32 key_len,
+                                            SilcChannelPrivateKey *ret_key)
 {
   SilcChannelPrivateKey entry;
   unsigned char hash[SILC_HASH_MAXLEN];
-  SilcSKEKeyMaterial *keymat;
+  SilcSKEKeyMaterial keymat;
 
-  assert(client && channel);
+  if (!client || !conn || !channel)
+    return FALSE;
 
   if (!cipher)
     cipher = SILC_DEFAULT_CIPHER;
@@ -547,43 +469,58 @@ SilcBool silc_client_add_channel_private_key(SilcClient client,
 
   if (!silc_cipher_is_supported(cipher))
     return FALSE;
-
   if (!silc_hmac_is_supported(hmac))
     return FALSE;
 
+  if (!channel->internal.private_keys) {
+    channel->internal.private_keys = silc_dlist_init();
+    if (!channel->internal.private_keys)
+      return FALSE;
+  }
+
   /* Produce the key material */
-  keymat = silc_calloc(1, sizeof(*keymat));
-  if (silc_ske_process_key_material_data(key, key_len, 16, 256, 16,
-                                        client->sha1hash, keymat)
-      != SILC_SKE_STATUS_OK)
+  keymat = silc_ske_process_key_material_data(key, key_len, 16, 256, 16,
+                                             client->sha1hash);
+  if (!keymat)
     return FALSE;
 
-  if (!channel->private_keys)
-    channel->private_keys = silc_dlist_init();
-
   /* Save the key */
   entry = silc_calloc(1, sizeof(*entry));
+  if (!entry) {
+    silc_ske_free_key_material(keymat);
+    return FALSE;
+  }
   entry->name = name ? strdup(name) : NULL;
-  entry->key = silc_memdup(keymat->send_enc_key, keymat->enc_key_len / 8);
-  entry->key_len = keymat->enc_key_len / 8;
 
   /* Allocate the cipher and set the key*/
-  silc_cipher_alloc(cipher, &entry->cipher);
-  silc_cipher_set_key(entry->cipher, entry->key, keymat->enc_key_len);
+  if (!silc_cipher_alloc(cipher, &entry->cipher)) {
+    silc_free(entry);
+    silc_free(entry->name);
+    silc_ske_free_key_material(keymat);
+    return FALSE;
+  }
+  silc_cipher_set_key(entry->cipher, keymat->send_enc_key,
+                     keymat->enc_key_len);
 
   /* Generate HMAC key from the channel key data and set it */
-  silc_hmac_alloc(hmac, NULL, &entry->hmac);
-  silc_hash_make(silc_hmac_get_hash(entry->hmac), entry->key,
-                entry->key_len, hash);
+  if (!silc_hmac_alloc(hmac, NULL, &entry->hmac)) {
+    silc_free(entry);
+    silc_free(entry->name);
+    silc_cipher_free(entry->cipher);
+    silc_ske_free_key_material(keymat);
+    return FALSE;
+  }
+  silc_hash_make(silc_hmac_get_hash(entry->hmac), keymat->send_enc_key,
+                keymat->enc_key_len / 8, hash);
   silc_hmac_set_key(entry->hmac, hash,
                    silc_hash_len(silc_hmac_get_hash(entry->hmac)));
   memset(hash, 0, sizeof(hash));
 
   /* Add to the private keys list */
-  silc_dlist_add(channel->private_keys, entry);
+  silc_dlist_add(channel->internal.private_keys, entry);
 
-  if (!channel->curr_key)
-    channel->curr_key = entry;
+  if (!channel->internal.curr_key)
+    channel->internal.curr_key = entry;
 
   /* Free the key material */
   silc_ske_free_key_material(keymat);
@@ -604,26 +541,25 @@ SilcBool silc_client_del_channel_private_keys(SilcClient client,
 {
   SilcChannelPrivateKey entry;
 
-  assert(client && channel);
+  if (!client || !conn || !channel)
+    return FALSE;
 
-  if (!channel->private_keys)
+  if (!channel->internal.private_keys)
     return FALSE;
 
-  silc_dlist_start(channel->private_keys);
-  while ((entry = silc_dlist_get(channel->private_keys)) != SILC_LIST_END) {
-    silc_dlist_del(channel->private_keys, entry);
-    memset(entry->key, 0, entry->key_len);
-    silc_free(entry->key);
+  silc_dlist_start(channel->internal.private_keys);
+  while ((entry = silc_dlist_get(channel->internal.private_keys))) {
+    silc_dlist_del(channel->internal.private_keys, entry);
     silc_free(entry->name);
     silc_cipher_free(entry->cipher);
     silc_hmac_free(entry->hmac);
     silc_free(entry);
   }
 
-  channel->curr_key = NULL;
+  channel->internal.curr_key = NULL;
 
-  silc_dlist_uninit(channel->private_keys);
-  channel->private_keys = NULL;
+  silc_dlist_uninit(channel->internal.private_keys);
+  channel->internal.private_keys = NULL;
 
   return TRUE;
 }
@@ -635,38 +571,38 @@ SilcBool silc_client_del_channel_private_keys(SilcClient client,
    returns FALSE on error, TRUE otherwise. */
 
 SilcBool silc_client_del_channel_private_key(SilcClient client,
-                                       SilcClientConnection conn,
-                                       SilcChannelEntry channel,
-                                       SilcChannelPrivateKey key)
+                                            SilcClientConnection conn,
+                                            SilcChannelEntry channel,
+                                            SilcChannelPrivateKey key)
 {
   SilcChannelPrivateKey entry;
 
-  assert(client && channel);
+  if (!client || !conn || !channel)
+    return FALSE;
 
-  if (!channel->private_keys)
+  if (!channel->internal.private_keys)
     return FALSE;
 
-  silc_dlist_start(channel->private_keys);
-  while ((entry = silc_dlist_get(channel->private_keys)) != SILC_LIST_END) {
-    if (entry == key) {
-      if (channel->curr_key == entry)
-       channel->curr_key = NULL;
-
-      silc_dlist_del(channel->private_keys, entry);
-      memset(entry->key, 0, entry->key_len);
-      silc_free(entry->key);
-      silc_free(entry->name);
-      silc_cipher_free(entry->cipher);
-      silc_hmac_free(entry->hmac);
-      silc_free(entry);
-
-      if (silc_dlist_count(channel->private_keys) == 0) {
-       silc_dlist_uninit(channel->private_keys);
-       channel->private_keys = NULL;
-      }
+  silc_dlist_start(channel->internal.private_keys);
+  while ((entry = silc_dlist_get(channel->internal.private_keys))) {
+    if (entry != key)
+      continue;
+
+    if (channel->internal.curr_key == entry)
+      channel->internal.curr_key = NULL;
+
+    silc_dlist_del(channel->internal.private_keys, entry);
+    silc_free(entry->name);
+    silc_cipher_free(entry->cipher);
+    silc_hmac_free(entry->hmac);
+    silc_free(entry);
 
-      return TRUE;
+    if (silc_dlist_count(channel->internal.private_keys) == 0) {
+      silc_dlist_uninit(channel->internal.private_keys);
+      channel->internal.private_keys = NULL;
     }
+
+    return TRUE;
   }
 
   return FALSE;
@@ -678,39 +614,28 @@ SilcBool silc_client_del_channel_private_key(SilcClient client,
    used to delete the specific key by giving the pointer as argument to the
    function silc_client_del_channel_private_key. */
 
-SilcChannelPrivateKey *
-silc_client_list_channel_private_keys(SilcClient client,
-                                     SilcClientConnection conn,
-                                     SilcChannelEntry channel,
-                                     SilcUInt32 *key_count)
+SilcDList silc_client_list_channel_private_keys(SilcClient client,
+                                               SilcClientConnection conn,
+                                               SilcChannelEntry channel)
 {
-  SilcChannelPrivateKey *keys = NULL, entry;
-  SilcUInt32 count = 0;
+  SilcChannelPrivateKey entry;
+  SilcDList list;
 
-  assert(client && channel);
+  if (!client || !conn || !channel)
+    return FALSE;
 
-  if (!channel->private_keys)
+  if (!channel->internal.private_keys)
     return NULL;
 
-  silc_dlist_start(channel->private_keys);
-  while ((entry = silc_dlist_get(channel->private_keys)) != SILC_LIST_END) {
-    keys = silc_realloc(keys, sizeof(*keys) * (count + 1));
-    keys[count] = entry;
-    count++;
-  }
-
-  if (key_count)
-    *key_count = count;
-
-  return keys;
-}
+  list = silc_dlist_init();
+  if (!list)
+    return NULL;
 
-/* Frees the SilcChannelPrivateKey array. */
+  silc_dlist_start(channel->internal.private_keys);
+  while ((entry = silc_dlist_get(channel->internal.private_keys)))
+    silc_dlist_add(list, entry);
 
-void silc_client_free_channel_private_keys(SilcChannelPrivateKey *keys,
-                                          SilcUInt32 key_count)
-{
-  silc_free(keys);
+  return list;
 }
 
 /* Sets the `key' to be used as current channel private key on the
@@ -722,10 +647,13 @@ void silc_client_current_channel_private_key(SilcClient client,
                                             SilcChannelEntry channel,
                                             SilcChannelPrivateKey key)
 {
-  assert(client && channel);
-  channel->curr_key = key;
+  if (!channel)
+    return;
+  channel->internal.curr_key = key;
 }
 
+/***************************** Utility routines *****************************/
+
 /* Returns the SilcChannelUser entry if the `client_entry' is joined on the
    channel indicated by the `channel'. NULL if client is not joined on
    the channel. */
@@ -741,3 +669,64 @@ SilcChannelUser silc_client_on_channel(SilcChannelEntry channel,
 
   return NULL;
 }
+
+/* Adds client to channel */
+
+SilcBool silc_client_add_to_channel(SilcChannelEntry channel,
+                                   SilcClientEntry client_entry,
+                                   SilcUInt32 cumode)
+{
+  SilcChannelUser chu;
+
+  if (silc_client_on_channel(channel, client_entry))
+    return FALSE;
+
+  chu = silc_calloc(1, sizeof(*chu));
+  if (!chu)
+    return FALSE;
+
+  chu->client = client_entry;
+  chu->channel = channel;
+  chu->mode = cumode;
+  silc_hash_table_add(channel->user_list, client_entry, chu);
+  silc_hash_table_add(client_entry->channels, channel, chu);
+
+  return TRUE;
+}
+
+/* Removes client from a channel */
+
+SilcBool silc_client_remove_from_channel(SilcChannelEntry channel,
+                                        SilcClientEntry client_entry)
+{
+  SilcChannelUser chu;
+
+  chu = silc_client_on_channel(channel, client_entry);
+  if (!chu)
+    return FALSE;
+
+  silc_hash_table_del(chu->client->channels, chu->channel);
+  silc_hash_table_del(chu->channel->user_list, chu->client);
+  silc_free(chu);
+
+  return TRUE;
+}
+
+/* Removes a client entry from all channels it has joined. */
+
+void silc_client_remove_from_channels(SilcClient client,
+                                     SilcClientConnection conn,
+                                     SilcClientEntry client_entry)
+{
+  SilcHashTableList htl;
+  SilcChannelUser chu;
+
+  silc_hash_table_list(client_entry->channels, &htl);
+  while (silc_hash_table_get(&htl, NULL, (void *)&chu)) {
+    silc_hash_table_del(chu->client->channels, chu->channel);
+    silc_hash_table_del(chu->channel->user_list, chu->client);
+    silc_free(chu);
+  }
+
+  silc_hash_table_list_reset(&htl);
+}