Merge commit 'origin/silc.1.1.branch'
[silc.git] / lib / silcclient / client_prvmsg.c
index 36d7bbe43a7eaffd76fe308eb7980b50da6a9867..1f7eaf019d90a79dc514eee760b5bdbdf977cad4 100644 (file)
@@ -1,10 +1,10 @@
 /*
 
-  client_prvmsg.c 
+  client_prvmsg.c
 
   Author: Pekka Riikonen <priikone@silcnet.org>
 
-  Copyright (C) 1997 - 2002 Pekka Riikonen
+  Copyright (C) 1997 - 2007 Pekka Riikonen
 
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
 
 */
 /* $Id$ */
-/* This file includes the private message sending and receiving routines
-   and private message key handling routines. */
 
-#include "silcincludes.h"
+#include "silc.h"
 #include "silcclient.h"
 #include "client_internal.h"
 
-/* Sends private message to remote client. If private message key has
-   not been set with this client then the message will be encrypted using
-   normal session keys. Private messages are special packets in SILC
-   network hence we need this own function for them. This is similiar
-   to silc_client_packet_send_to_channel except that we send private
-   message. The `data' is the private message. If the `force_send' is
-   TRUE the packet is sent immediately. */
+/************************** Private Message Send ****************************/
 
-void silc_client_send_private_message(SilcClient client,
-                                     SilcClientConnection conn,
-                                     SilcClientEntry client_entry,
-                                     SilcMessageFlags flags,
-                                     unsigned char *data, 
-                                     SilcUInt32 data_len, 
-                                     bool force_send)
+typedef struct {
+  SilcClient client;
+  SilcClientConnection conn;
+  SilcClientEntry client_entry;
+} *SilcClientPrvmsgContext;
+
+/* Message payload encoding callback */
+
+static void silc_client_send_private_message_final(SilcBuffer message,
+                                                  void *context)
 {
-  SilcSocketConnection sock;
-  SilcBuffer buffer;
-  SilcPacketContext packetdata;
-  const SilcBufferStruct packet;
-  SilcCipher cipher;
-  SilcHmac hmac;
-  int block_len;
-
-  assert(client && conn && client_entry);
-  sock = conn->sock;
-  SILC_LOG_DEBUG(("Sending private message"));
+  SilcClientPrvmsgContext p = context;
+
+  /* Send the private message packet */
+  if (message)
+    silc_packet_send_ext(p->conn->stream, SILC_PACKET_PRIVATE_MESSAGE,
+                        p->client_entry->internal.send_key ?
+                        SILC_PACKET_FLAG_PRIVMSG_KEY : 0,
+                        0, NULL, SILC_ID_CLIENT, &p->client_entry->id,
+                        silc_buffer_datalen(message), NULL, NULL);
+
+  silc_client_unref_client(p->client, p->conn, p->client_entry);
+  silc_free(p);
+}
 
-  /* Encode private message payload */
-  buffer = silc_message_payload_encode(flags, data, data_len,
-                                      !client_entry->send_key ? FALSE :
-                                      !client_entry->generated,
-                                      TRUE, client_entry->send_key,
-                                      client_entry->hmac_send,
-                                      client->rng, NULL, client->private_key,
-                                      client->sha1hash);
-
-  /* If we don't have private message specific key then private messages
-     are just as any normal packet thus call normal packet sending.  If
-     the key exist then the encryption process is a bit different and
-     will be done in the rest of this function. */
-  if (!client_entry->send_key) {
-    silc_client_packet_send(client, sock, SILC_PACKET_PRIVATE_MESSAGE,
-                           client_entry->id, SILC_ID_CLIENT, NULL, NULL,
-                           buffer->data, buffer->len, force_send);
-    goto out;
-  }
+/* Sends private message to remote client. */
 
-  /* We have private message specific key */
-
-  /* Get data used in the encryption */
-  cipher = conn->internal->send_key;
-  hmac = conn->internal->hmac_send;
-  block_len = silc_cipher_get_block_len(cipher);
-
-  /* Set the packet context pointers. */
-  data = buffer->data;
-  data_len = buffer->len;
-  packetdata.flags = SILC_PACKET_FLAG_PRIVMSG_KEY;
-  packetdata.type = SILC_PACKET_PRIVATE_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 = silc_id_id2str(client_entry->id, SILC_ID_CLIENT);
-  packetdata.dst_id_len = silc_id_get_len(client_entry->id, SILC_ID_CLIENT);
-  packetdata.dst_id_type = SILC_ID_CLIENT;
-  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;
+SilcBool silc_client_send_private_message(SilcClient client,
+                                         SilcClientConnection conn,
+                                         SilcClientEntry client_entry,
+                                         SilcMessageFlags flags,
+                                         SilcHash hash,
+                                         unsigned char *data,
+                                         SilcUInt32 data_len)
+{
+  SilcClientPrvmsgContext p;
+  SilcID sid, rid;
+
+  if (silc_unlikely(!client || !conn || !client_entry))
+    return FALSE;
+  if (silc_unlikely(flags & SILC_MESSAGE_FLAG_SIGNED && !hash)) {
+    SILC_LOG_ERROR(("Cannot send signed message without hash, missing "
+                   "arguments"));
+    return FALSE;
   }
+  if (silc_unlikely(conn->internal->disconnected))
+    return FALSE;
 
-  /* Encrypt the header and padding of the packet. */
-  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_DEBUG(("Sending private message"));
 
-  SILC_LOG_HEXDUMP(("Private message packet, len %d", packet.len),
-                  packet.data, packet.len);
+  sid.type = SILC_ID_CLIENT;
+  sid.u.client_id = conn->local_entry->id;
+  rid.type = SILC_ID_CLIENT;
+  rid.u.client_id = client_entry->id;
 
-  /* Now actually send the packet */
-  silc_client_packet_send_real(client, sock, force_send);
+  p = silc_calloc(1, sizeof(*p));
+  if (!p)
+    return FALSE;
 
-  /* 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);
+  p->client = client;
+  p->conn = conn;
+  p->client_entry = silc_client_ref_client(client, conn, client_entry);
 
-  silc_free(packetdata.dst_id);
+  /* Encode private message payload */
+  silc_message_payload_encode(flags, data, data_len,
+                             (!client_entry->internal.send_key ? FALSE :
+                              !client_entry->internal.generated),
+                             TRUE, client_entry->internal.send_key,
+                             client_entry->internal.hmac_send,
+                             client->rng, NULL, conn->private_key,
+                             hash, &sid, &rid, NULL,
+                             silc_client_send_private_message_final, p);
 
- out:
-  silc_buffer_free(buffer);
-}     
-
-static void silc_client_private_message_cb(SilcClient client,
-                                          SilcClientConnection conn,
-                                          SilcClientEntry *clients,
-                                          SilcUInt32 clients_count,
-                                          void *context)
-{
-  SilcPacketContext *packet = (SilcPacketContext *)context;
+  return TRUE;
+}
 
-  if (!clients) {
-    silc_packet_context_free(packet);
-    return;
-  }
+/************************* Private Message Receive **************************/
 
-  silc_client_private_message(client, conn->sock, packet);
-  silc_packet_context_free(packet);
+/* Client resolving callback.  Continues with the private message processing */
+
+static void silc_client_private_message_resolved(SilcClient client,
+                                                SilcClientConnection conn,
+                                                SilcStatus status,
+                                                SilcDList clients,
+                                                void *context)
+{
+  /* If no client found, ignore the private message, a silent error */
+  if (!clients)
+    silc_fsm_next(context, silc_client_private_message_error);
+
+  /* Continue processing the private message packet */
+  SILC_FSM_CALL_CONTINUE(context);
 }
 
-/* Private message received. This processes the private message and
-   finally displays it on the screen. */
+/* Private message received. */
 
-void silc_client_private_message(SilcClient client, 
-                                SilcSocketConnection sock, 
-                                SilcPacketContext *packet)
+SILC_FSM_STATE(silc_client_private_message)
 {
-  SilcClientConnection conn = (SilcClientConnection)sock->user_data;
+  SilcClientConnection conn = fsm_context;
+  SilcClient client = conn->client;
+  SilcPacket packet = state_context;
   SilcMessagePayload payload = NULL;
-  SilcClientID *remote_id = NULL;
-  SilcClientEntry remote_client;
+  SilcClientID remote_id;
+  SilcClientEntry remote_client = NULL;
   SilcMessageFlags flags;
   unsigned char *message;
   SilcUInt32 message_len;
-  SilcCipher cipher = NULL;
-  SilcHmac hmac = NULL;
 
-  if (packet->src_id_type != SILC_ID_CLIENT)
-    goto out;
+  SILC_LOG_DEBUG(("Received private message"));
 
-  remote_id = silc_id_str2id(packet->src_id, packet->src_id_len, 
-                            SILC_ID_CLIENT);
-  if (!remote_id)
-    goto out;
-
-  /* Check whether we know this client already */
-  remote_client = silc_client_get_client_by_id(client, conn, remote_id);
-  if (!remote_client || !remote_client->nickname) {
-    if (remote_client) {
-      if (remote_client->status & SILC_CLIENT_STATUS_RESOLVING) {
-       remote_client->status &= ~SILC_CLIENT_STATUS_RESOLVING;
-       goto out;
-      }
-      remote_client->status |= SILC_CLIENT_STATUS_RESOLVING;
-      remote_client->resolve_cmd_ident = conn->cmd_ident + 1;
-    }
-
-    /* Resolve the client info */
-    silc_client_get_client_by_id_resolve(client, conn, remote_id, NULL,
-                                        silc_client_private_message_cb,
-                                        silc_packet_context_dup(packet));
-    return;
+  if (silc_unlikely(packet->src_id_type != SILC_ID_CLIENT)) {
+    /** Invalid packet */
+    silc_fsm_next(fsm, silc_client_private_message_error);
+    return SILC_FSM_CONTINUE;
   }
 
-  cipher = remote_client->receive_key;
-  hmac = remote_client->hmac_receive;
-  if (packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY && !cipher && !hmac) {
-    silc_free(remote_id);
-    return;
+  if (silc_unlikely(!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_private_message_error);
+    return SILC_FSM_CONTINUE;
   }
 
-  /* Parse the payload and decrypt it also if private message key is set */
-  payload = silc_message_payload_parse(packet->buffer->data,
-                                      packet->buffer->len, TRUE,
-                                      !remote_client->generated,
-                                      cipher, hmac);
-  if (!payload) {
-    silc_free(remote_id);
-    return;
+  /* Check whether we know this client already */
+  remote_client = silc_client_get_client_by_id(client, conn, &remote_id);
+  if (!remote_client || !remote_client->nickname[0]) {
+    /** Resolve client info */
+    silc_client_unref_client(client, conn, remote_client);
+    SILC_FSM_CALL(silc_client_get_client_by_id_resolve(
+                                        client, conn, &remote_id, NULL,
+                                        silc_client_private_message_resolved,
+                                        fsm));
+    /* NOT REACHED */
   }
 
-  flags = silc_message_get_flags(payload);
+  if (silc_unlikely(packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY &&
+                   !remote_client->internal.receive_key &&
+                   !remote_client->internal.hmac_receive))
+    goto out;
+
+  /* Parse the payload and decrypt it also if private message key is set */
+  payload =
+    silc_message_payload_parse(silc_buffer_datalen(&packet->buffer),
+                              TRUE, !remote_client->internal.generated,
+                              remote_client->internal.receive_key,
+                              remote_client->internal.hmac_receive,
+                              packet->src_id, packet->src_id_len,
+                              packet->dst_id, packet->dst_id_len,
+                              NULL, FALSE, NULL);
+  if (silc_unlikely(!payload))
+    goto out;
 
   /* Pass the private message to application */
+  flags = silc_message_get_flags(payload);
   message = silc_message_get_data(payload, &message_len);
   client->internal->ops->private_message(client, conn, remote_client, payload,
                                         flags, message, message_len);
 
   /* See if we are away (gone). If we are away we will reply to the
      sender with the set away message. */
-  if (conn->internal->away && conn->internal->away->away &&
+  if (conn->internal->away_message &&
       !(flags & SILC_MESSAGE_FLAG_NOREPLY)) {
     /* If it's me, ignore */
-    if (SILC_ID_CLIENT_COMPARE(remote_id, conn->local_id))
+    if (SILC_ID_CLIENT_COMPARE(&remote_id, conn->local_id))
       goto out;
 
     /* Send the away message */
     silc_client_send_private_message(client, conn, remote_client,
                                     SILC_MESSAGE_FLAG_AUTOREPLY |
-                                    SILC_MESSAGE_FLAG_NOREPLY,
-                                    conn->internal->away->away,
-                                    strlen(conn->internal->away->away), TRUE);
+                                    SILC_MESSAGE_FLAG_NOREPLY, NULL,
+                                    conn->internal->away_message,
+                                    strlen(conn->internal->away_message));
   }
 
  out:
+  /** Packet processed */
+  silc_packet_free(packet);
+  silc_client_unref_client(client, conn, remote_client);
   if (payload)
     silc_message_payload_free(payload);
-  silc_free(remote_id);
+  return SILC_FSM_FINISH;
+}
+
+/* Private message error. */
+
+SILC_FSM_STATE(silc_client_private_message_error)
+{
+  SilcPacket packet = state_context;
+  silc_packet_free(packet);
+  return SILC_FSM_FINISH;
+}
+
+/* Initialize private message waiter for the `conn' connection. */
+
+SilcBool silc_client_private_message_wait_init(SilcClient client,
+                                              SilcClientConnection conn,
+                                              SilcClientEntry client_entry)
+{
+  SilcID id;
+
+  if (client_entry->internal.prv_waiter)
+    return TRUE;
+
+  /* We want SILC_PACKET_PRIVATE_MESSAGE packets from this source ID. */
+  id.type = SILC_ID_CLIENT;
+  id.u.client_id = client_entry->id;
+
+  client_entry->internal.prv_waiter =
+    silc_packet_wait_init(conn->stream, &id, SILC_PACKET_PRIVATE_MESSAGE, -1);
+  if (!client_entry->internal.prv_waiter)
+    return FALSE;
+
+  return TRUE;
+}
+
+/* Uninitializes private message waiter. */
+
+void silc_client_private_message_wait_uninit(SilcClient client,
+                                            SilcClientConnection conn,
+                                            SilcClientEntry client_entry)
+{
+  if (!client_entry->internal.prv_waiter)
+    return;
+  silc_packet_wait_uninit(client_entry->internal.prv_waiter, conn->stream);
+  client_entry->internal.prv_waiter = NULL;
 }
 
-/* Function that actually employes the received private message key */
+/* Blocks the calling process or thread until private message has been
+   received from the specified client. */
+
+SilcBool silc_client_private_message_wait(SilcClient client,
+                                         SilcClientConnection conn,
+                                         SilcClientEntry client_entry,
+                                         SilcMessagePayload *payload)
+{
+  SilcPacket packet;
+
+  if (!client_entry->internal.prv_waiter)
+    return FALSE;
+
+  /* Block until private message arrives */
+  do {
+    if ((silc_packet_wait(client_entry->internal.prv_waiter, 0, &packet)) < 0)
+      return FALSE;
+
+    /* Parse the payload and decrypt it also if private message key is set */
+    *payload =
+      silc_message_payload_parse(silc_buffer_data(&packet->buffer),
+                                silc_buffer_len(&packet->buffer),
+                                TRUE, !client_entry->internal.generated,
+                                client_entry->internal.receive_key,
+                                client_entry->internal.hmac_receive,
+                                packet->src_id, packet->src_id_len,
+                                packet->dst_id, packet->dst_id_len,
+                                NULL, FALSE, NULL);
+    if (!(*payload)) {
+      silc_packet_free(packet);
+      continue;
+    }
+
+    break;
+  } while (1);
+
+  silc_packet_free(packet);
+  return TRUE;
+}
+
+/*************************** Private Message Key ****************************/
+
+/* Sends private message key request.  Sender of this packet is initiator
+   when setting the private message key. */
+
+static SilcBool
+silc_client_send_private_message_key_request(SilcClient client,
+                                            SilcClientConnection conn,
+                                            SilcClientEntry client_entry)
+{
+  const char *cipher, *hmac;
+
+  SILC_LOG_DEBUG(("Sending private message key request"));
+
+  cipher = silc_cipher_get_name(client_entry->internal.send_key);
+  hmac = silc_hmac_get_name(client_entry->internal.hmac_send);
+
+  /* Send the packet */
+  return silc_packet_send_va_ext(conn->stream,
+                                SILC_PACKET_PRIVATE_MESSAGE_KEY,
+                                0, 0, NULL, SILC_ID_CLIENT,
+                                &client_entry->id, NULL, NULL,
+                                SILC_STR_UI_SHORT(strlen(cipher)),
+                                SILC_STR_DATA(cipher, strlen(cipher)),
+                                SILC_STR_UI_SHORT(strlen(hmac)),
+                                SILC_STR_DATA(hmac, strlen(hmac)),
+                                SILC_STR_END);
+}
+
+/* Client resolving callback.  Here we simply mark that we are the responder
+   side of this private message key request.  */
 
 static void silc_client_private_message_key_cb(SilcClient client,
                                               SilcClientConnection conn,
-                                              SilcClientEntry *clients,
-                                              SilcUInt32 clients_count,
+                                              SilcStatus status,
+                                              SilcDList clients,
                                               void *context)
 {
-  SilcPacketContext *packet = (SilcPacketContext *)context;
-  unsigned char *key;
-  SilcUInt16 key_len;
+  SilcFSMThread thread = context;
+  SilcPacket packet = silc_fsm_get_state_context(thread);
   unsigned char *cipher = NULL, *hmac = NULL;
+  SilcClientEntry client_entry;
   int ret;
 
-  if (!clients)
-    goto out;
+  if (!clients) {
+    silc_packet_free(packet);
+    silc_fsm_finish(thread);
+    return;
+  }
 
   /* Parse the private message key payload */
-  ret = silc_buffer_unformat(packet->buffer,
-                            SILC_STR_UI16_NSTRING(&key, &key_len),
+  ret = silc_buffer_unformat(&packet->buffer,
                             SILC_STR_UI16_STRING_ALLOC(&cipher),
                             SILC_STR_UI16_STRING_ALLOC(&hmac),
                             SILC_STR_END);
   if (!ret)
     goto out;
 
-  if (key_len > packet->buffer->len)
-    goto out;
+  /* Mark that we are responder */
+  client_entry = silc_dlist_get(clients);
+  client_entry->internal.prv_resp = TRUE;
 
-  /* Now take the key in use */
-  if (!silc_client_add_private_message_key(client, conn, clients[0],
-                                          cipher, hmac, key, key_len,
-                                          FALSE, TRUE))
-    goto out;
-
-  /* Print some info for application */
-  client->internal->ops->say(
-                    client, conn, SILC_CLIENT_MESSAGE_AUDIT, 
-                    "Received private message key from %s%s%s %s%s%s", 
-                    clients[0]->nickname,
-                    clients[0]->server ? "@" : "",
-                    clients[0]->server ? clients[0]->server : "",
-                    clients[0]->username ? "(" : "",
-                    clients[0]->username ? clients[0]->username : "",
-                    clients[0]->username ? ")" : "");
+  /* XXX we should notify application that remote wants to set up the
+     static key.  And we should tell if we already have key with remote.
+     Application should return status telling whether to delete the key
+     or not. */
 
  out:
   silc_free(cipher);
   silc_free(hmac);
-  silc_packet_context_free(packet);
+  silc_packet_free(packet);
+  silc_fsm_finish(thread);
 }
 
-/* Processes incoming Private Message Key payload. The libary always
-   accepts the key and takes it into use. */
+/* Processes incoming Private Message Key payload to indicate that the
+   sender whishes to set up a static private message key. */
 
-void silc_client_private_message_key(SilcClient client,
-                                    SilcSocketConnection sock,
-                                    SilcPacketContext *packet)
+SILC_FSM_STATE(silc_client_private_message_key)
 {
-  SilcClientID *remote_id;
-
-  if (packet->src_id_type != SILC_ID_CLIENT)
-    return;
+  SilcClientConnection conn = fsm_context;
+  SilcClient client = conn->client;
+  SilcPacket packet = state_context;
+  SilcClientID remote_id;
+
+  if (packet->src_id_type != SILC_ID_CLIENT) {
+    silc_packet_free(packet);
+    return SILC_FSM_FINISH;
+  }
 
-  remote_id = silc_id_str2id(packet->src_id, packet->src_id_len, 
-                            SILC_ID_CLIENT);
-  if (!remote_id)
-    return;
+  if (!silc_id_str2id(packet->src_id, packet->src_id_len, SILC_ID_CLIENT,
+                     &remote_id, sizeof(remote_id))) {
+    silc_packet_free(packet);
+    return SILC_FSM_FINISH;
+  }
 
-  silc_client_get_client_by_id_resolve(client, sock->user_data, remote_id,
-                                      NULL,
+  /* Always resolve the remote client.  The actual packet is processed
+     in the resolving callback. */
+  SILC_FSM_CALL(silc_client_get_client_by_id_resolve(
+                                      client, conn, &remote_id, NULL,
                                       silc_client_private_message_key_cb,
-                                      silc_packet_context_dup(packet));
-  silc_free(remote_id);
+                                      fsm));
 }
 
-/* Adds private message key to the client library. The key will be used to
-   encrypt all private message between the client and the remote client
-   indicated by the `client_entry'. If the `key' is NULL and the boolean
-   value `generate_key' is TRUE the library will generate random key.
-   The `key' maybe for example pre-shared-key, passphrase or similar.
-   The `cipher' and `hmac' MAY be provided but SHOULD be NULL to assure
-   that the requirements of the SILC protocol are met. The API, however,
-   allows to allocate any cipher and HMAC.
-
-   If `responder' is TRUE then the sending and receiving keys will be
-   set according the client being the receiver of the private key.  If
-   FALSE the client is being the sender (or negotiator) of the private
-   key.
-
-   It is not necessary to set key for normal private message usage. If the
-   key is not set then the private messages are encrypted using normal
-   session keys. Setting the private key, however, increases the security. 
-
-   Returns FALSE if the key is already set for the `client_entry', TRUE
-   otherwise. */
-
-bool silc_client_add_private_message_key(SilcClient client,
-                                        SilcClientConnection conn,
-                                        SilcClientEntry client_entry,
-                                        const char *cipher,
-                                        const char *hmac,
-                                        unsigned char *key,
-                                        SilcUInt32 key_len,
-                                        bool generate_key,
-                                        bool responder)
+/* Adds new private message key to `client_entry'.  If we are setting this
+   before receiving request for it from `client_entry' we will send the
+   request to the client.  Otherwise, we are responder side. */
+
+SilcBool silc_client_add_private_message_key(SilcClient client,
+                                            SilcClientConnection conn,
+                                            SilcClientEntry client_entry,
+                                            const char *cipher,
+                                            const char *hmac,
+                                            unsigned char *key,
+                                            SilcUInt32 key_len)
 {
-  unsigned char private_key[32];
-  SilcUInt32 len;
-  int i;
-  SilcSKEKeyMaterial *keymat;
+  SilcSKEKeyMaterial keymat;
+  SilcBool ret;
 
-  assert(client && client_entry);
+  if (!client || !client_entry)
+    return FALSE;
 
   /* Return FALSE if key already set */
-  if (client_entry->send_key && client_entry->receive_key)
+  if (client_entry->internal.send_key && client_entry->internal.receive_key)
     return FALSE;
 
   if (!cipher)
@@ -366,82 +428,47 @@ bool silc_client_add_private_message_key(SilcClient client,
   if (!silc_hmac_is_supported(hmac))
     return FALSE;
 
-  /* Generate key if not provided */
-  if (generate_key == TRUE) {
-    len = 32;
-    for (i = 0; i < len; i++)
-      private_key[i] = silc_rng_get_byte_fast(client->rng);
-    key = private_key;
-    key_len = len;
-    client_entry->generated = TRUE;
-  }
-
   /* Save the key */
-  client_entry->key = silc_memdup(key, key_len);
-  client_entry->key_len = key_len;
+  client_entry->internal.key = silc_memdup(key, key_len);
+  client_entry->internal.key_len = key_len;
 
   /* Produce the key material as the protocol defines */
-  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,
+                                             conn->internal->sha1hash);
+  if (!keymat)
     return FALSE;
 
-  /* Allocate the cipher and HMAC */
-  silc_cipher_alloc(cipher, &client_entry->send_key);
-  silc_cipher_alloc(cipher, &client_entry->receive_key);
-  silc_hmac_alloc(hmac, NULL, &client_entry->hmac_send);
-  silc_hmac_alloc(hmac, NULL, &client_entry->hmac_receive);
-
-  /* Set the keys */
-  if (responder == TRUE) {
-    silc_cipher_set_key(client_entry->send_key, keymat->receive_enc_key,
-                       keymat->enc_key_len);
-    silc_cipher_set_iv(client_entry->send_key, keymat->receive_iv);
-    silc_cipher_set_key(client_entry->receive_key, keymat->send_enc_key,
-                       keymat->enc_key_len);
-    silc_cipher_set_iv(client_entry->receive_key, keymat->send_iv);
-    silc_hmac_set_key(client_entry->hmac_send, keymat->receive_hmac_key,
-                     keymat->hmac_key_len);
-    silc_hmac_set_key(client_entry->hmac_receive, keymat->send_hmac_key,
-                     keymat->hmac_key_len);
-  } else {
-    silc_cipher_set_key(client_entry->send_key, keymat->send_enc_key,
-                       keymat->enc_key_len);
-    silc_cipher_set_iv(client_entry->send_key, keymat->send_iv);
-    silc_cipher_set_key(client_entry->receive_key, keymat->receive_enc_key,
-                       keymat->enc_key_len);
-    silc_cipher_set_iv(client_entry->receive_key, keymat->receive_iv);
-    silc_hmac_set_key(client_entry->hmac_send, keymat->send_hmac_key,
-                     keymat->hmac_key_len);
-    silc_hmac_set_key(client_entry->hmac_receive, keymat->receive_hmac_key,
-                     keymat->hmac_key_len);
-  }
+  /* Set the key into use */
+  ret = silc_client_add_private_message_key_ske(client, conn, client_entry,
+                                               cipher, hmac, keymat);
+  client_entry->internal.generated = FALSE;
 
   /* Free the key material */
   silc_ske_free_key_material(keymat);
 
-  return TRUE;
+  /* If we are setting the key without a request from the remote client,
+     we will send request to remote. */
+  if (!client_entry->internal.prv_resp)
+    silc_client_send_private_message_key_request(client, conn, client_entry);
+
+  return ret;
 }
 
 /* Same as above but takes the key material from the SKE key material
-   structure. This structure is received if the application uses the
-   silc_client_send_key_agreement to negotiate the key material. The
-   `cipher' and `hmac' SHOULD be provided as it is negotiated also in
-   the SKE protocol. */
-
-bool silc_client_add_private_message_key_ske(SilcClient client,
-                                            SilcClientConnection conn,
-                                            SilcClientEntry client_entry,
-                                            const char *cipher,
-                                            const char *hmac,
-                                            SilcSKEKeyMaterial *key,
-                                            bool responder)
+   structure. */
+
+SilcBool silc_client_add_private_message_key_ske(SilcClient client,
+                                                SilcClientConnection conn,
+                                                SilcClientEntry client_entry,
+                                                const char *cipher,
+                                                const char *hmac,
+                                                SilcSKEKeyMaterial keymat)
 {
-  assert(client && client_entry);
+  if (!client || !client_entry)
+    return FALSE;
 
   /* Return FALSE if key already set */
-  if (client_entry->send_key && client_entry->receive_key)
+  if (client_entry->internal.send_key && client_entry->internal.receive_key)
     return FALSE;
 
   if (!cipher)
@@ -455,123 +482,82 @@ bool silc_client_add_private_message_key_ske(SilcClient client,
   if (!silc_hmac_is_supported(hmac))
     return FALSE;
 
-  client_entry->generated = TRUE;
+  client_entry->internal.generated = TRUE;
 
   /* Allocate the cipher and HMAC */
-  silc_cipher_alloc(cipher, &client_entry->send_key);
-  silc_cipher_alloc(cipher, &client_entry->receive_key);
-  silc_hmac_alloc(hmac, NULL, &client_entry->hmac_send);
-  silc_hmac_alloc(hmac, NULL, &client_entry->hmac_receive);
+  if (!silc_cipher_alloc(cipher, &client_entry->internal.send_key))
+    return FALSE;
+  if (!silc_cipher_alloc(cipher, &client_entry->internal.receive_key))
+    return FALSE;
+  if (!silc_hmac_alloc(hmac, NULL, &client_entry->internal.hmac_send))
+    return FALSE;
+  if (!silc_hmac_alloc(hmac, NULL, &client_entry->internal.hmac_receive))
+    return FALSE;
 
   /* Set the keys */
-  if (responder == TRUE) {
-    silc_cipher_set_key(client_entry->send_key, key->receive_enc_key,
-                       key->enc_key_len);
-    silc_cipher_set_iv(client_entry->send_key, key->receive_iv);
-    silc_cipher_set_key(client_entry->receive_key, key->send_enc_key,
-                       key->enc_key_len);
-    silc_cipher_set_iv(client_entry->receive_key, key->send_iv);
-    silc_hmac_set_key(client_entry->hmac_send, key->receive_hmac_key,
-                     key->hmac_key_len);
-    silc_hmac_set_key(client_entry->hmac_receive, key->send_hmac_key,
-                     key->hmac_key_len);
+  if (client_entry->internal.prv_resp) {
+    silc_cipher_set_key(client_entry->internal.send_key,
+                       keymat->receive_enc_key,
+                       keymat->enc_key_len, TRUE);
+    silc_cipher_set_iv(client_entry->internal.send_key,
+                      keymat->receive_iv);
+    silc_cipher_set_key(client_entry->internal.receive_key,
+                       keymat->send_enc_key,
+                       keymat->enc_key_len, FALSE);
+    silc_cipher_set_iv(client_entry->internal.receive_key, keymat->send_iv);
+    silc_hmac_set_key(client_entry->internal.hmac_send,
+                     keymat->receive_hmac_key,
+                     keymat->hmac_key_len);
+    silc_hmac_set_key(client_entry->internal.hmac_receive,
+                     keymat->send_hmac_key,
+                     keymat->hmac_key_len);
   } else {
-    silc_cipher_set_key(client_entry->send_key, key->send_enc_key,
-                       key->enc_key_len);
-    silc_cipher_set_iv(client_entry->send_key, key->send_iv);
-    silc_cipher_set_key(client_entry->receive_key, key->receive_enc_key,
-                       key->enc_key_len);
-    silc_cipher_set_iv(client_entry->receive_key, key->receive_iv);
-    silc_hmac_set_key(client_entry->hmac_send, key->send_hmac_key,
-                     key->hmac_key_len);
-    silc_hmac_set_key(client_entry->hmac_receive, key->receive_hmac_key,
-                     key->hmac_key_len);
+    silc_cipher_set_key(client_entry->internal.send_key,
+                       keymat->send_enc_key,
+                       keymat->enc_key_len, TRUE);
+    silc_cipher_set_iv(client_entry->internal.send_key,
+                      keymat->send_iv);
+    silc_cipher_set_key(client_entry->internal.receive_key,
+                       keymat->receive_enc_key,
+                       keymat->enc_key_len, FALSE);
+    silc_cipher_set_iv(client_entry->internal.receive_key, keymat->receive_iv);
+    silc_hmac_set_key(client_entry->internal.hmac_send,
+                     keymat->send_hmac_key,
+                     keymat->hmac_key_len);
+    silc_hmac_set_key(client_entry->internal.hmac_receive,
+                     keymat->receive_hmac_key,
+                     keymat->hmac_key_len);
   }
 
   return TRUE;
 }
 
-/* Sends private message key payload to the remote client indicated by
-   the `client_entry'. If the `force_send' is TRUE the packet is sent
-   immediately. Returns FALSE if error occurs, TRUE otherwise. The
-   application should call this function after setting the key to the
-   client.
-
-   Note that the key sent using this function is sent to the remote client
-   through the SILC network. The packet is protected using normal session
-   keys. */
-
-bool silc_client_send_private_message_key(SilcClient client,
-                                        SilcClientConnection conn,
-                                        SilcClientEntry client_entry,
-                                        bool force_send)
-{
-  SilcSocketConnection sock;
-  SilcBuffer buffer;
-  int cipher_len, hmac_len;
-  const char *cipher, *hmac;
-
-  assert(client && conn && client_entry);
-
-  sock = conn->sock;
-  if (!client_entry->send_key || !client_entry->key)
-    return FALSE;
-
-  SILC_LOG_DEBUG(("Sending private message key"));
-
-  cipher = silc_cipher_get_name(client_entry->send_key);
-  cipher_len = strlen(cipher);
-  hmac = silc_hmac_get_name(client_entry->hmac_send);
-  hmac_len = strlen(hmac);
-
-  /* Create private message key payload */
-  buffer = silc_buffer_alloc(2 + client_entry->key_len);
-  silc_buffer_pull_tail(buffer, SILC_BUFFER_END(buffer));
-  silc_buffer_format(buffer,
-                    SILC_STR_UI_SHORT(client_entry->key_len),
-                    SILC_STR_UI_XNSTRING(client_entry->key, 
-                                         client_entry->key_len),
-                    SILC_STR_UI_SHORT(cipher_len),
-                    SILC_STR_UI_XNSTRING(cipher,
-                                         cipher_len),
-                    SILC_STR_UI_SHORT(hmac_len),
-                    SILC_STR_UI_XNSTRING(hmac,
-                                         hmac_len),
-                    SILC_STR_END);
-
-  /* Send the packet */
-  silc_client_packet_send(client, sock, SILC_PACKET_PRIVATE_MESSAGE_KEY,
-                         client_entry->id, SILC_ID_CLIENT, NULL, NULL,
-                         buffer->data, buffer->len, force_send);
-  silc_free(buffer);
-
-  return TRUE;
-}
-
 /* Removes the private message from the library. The key won't be used
    after this to protect the private messages with the remote `client_entry'
    client. Returns FALSE on error, TRUE otherwise. */
 
-bool silc_client_del_private_message_key(SilcClient client,
-                                       SilcClientConnection conn,
-                                       SilcClientEntry client_entry)
+SilcBool silc_client_del_private_message_key(SilcClient client,
+                                            SilcClientConnection conn,
+                                            SilcClientEntry client_entry)
 {
-  assert(client && client_entry);
+  if (!client || !client_entry)
+    return FALSE;
 
-  if (!client_entry->send_key && !client_entry->receive_key)
+  if (!client_entry->internal.send_key && !client_entry->internal.receive_key)
     return FALSE;
 
-  silc_cipher_free(client_entry->send_key);
-  silc_cipher_free(client_entry->receive_key);
+  silc_cipher_free(client_entry->internal.send_key);
+  silc_cipher_free(client_entry->internal.receive_key);
 
-  if (client_entry->key) {
-    memset(client_entry->key, 0, client_entry->key_len);
-    silc_free(client_entry->key);
+  if (client_entry->internal.key) {
+    memset(client_entry->internal.key, 0, client_entry->internal.key_len);
+    silc_free(client_entry->internal.key);
   }
 
-  client_entry->send_key = NULL;
-  client_entry->receive_key = NULL;
-  client_entry->key = NULL;
+  client_entry->internal.send_key = NULL;
+  client_entry->internal.receive_key = NULL;
+  client_entry->internal.key = NULL;
+  client_entry->internal.prv_resp = FALSE;
 
   return TRUE;
 }
@@ -579,7 +565,7 @@ bool silc_client_del_private_message_key(SilcClient client,
 /* Returns array of set private message keys associated to the connection
    `conn'. Returns allocated SilcPrivateMessageKeys array and the array
    count to the `key_count' argument. The array must be freed by the caller
-   by calling the silc_client_free_private_message_keys function. Note: 
+   by calling the silc_client_free_private_message_keys function. Note:
    the keys returned in the array is in raw format. It might not be desired
    to show the keys as is. The application might choose not to show the keys
    at all or to show the fingerprints of the keys. */
@@ -591,38 +577,42 @@ silc_client_list_private_message_keys(SilcClient client,
 {
   SilcPrivateMessageKeys keys;
   SilcUInt32 count = 0;
+  SilcList list;
   SilcIDCacheEntry id_cache;
-  SilcIDCacheList list;
   SilcClientEntry entry;
 
-  assert(client && conn);
-
-  if (!silc_idcache_get_all(conn->internal->client_cache, &list))
+  if (!client || !conn)
     return NULL;
 
-  if (!silc_idcache_list_count(list)) {
-    silc_idcache_list_free(list);
+  silc_mutex_lock(conn->internal->lock);
+  if (!silc_idcache_get_all(conn->internal->client_cache, &list)) {
+    silc_mutex_unlock(conn->internal->lock);
     return NULL;
   }
 
-  keys = silc_calloc(silc_idcache_list_count(list), sizeof(*keys));
-
-  silc_idcache_list_first(list, &id_cache);
-  while (id_cache) {
-    entry = (SilcClientEntry)id_cache->context;
+  keys = silc_calloc(silc_list_count(list), sizeof(*keys));
+  if (!keys) {
+    silc_mutex_unlock(conn->internal->lock);
+    return NULL;
+  }
 
-    if (entry->send_key) {
+  silc_list_start(list);
+  while ((id_cache = silc_list_get(list))) {
+    entry = id_cache->context;
+    if (entry->internal.send_key) {
       keys[count].client_entry = entry;
-      keys[count].cipher = (char *)silc_cipher_get_name(entry->send_key);
-      keys[count].key = entry->generated == FALSE ? entry->key : NULL;
-      keys[count].key_len = entry->generated == FALSE ? entry->key_len : 0;
+      keys[count].cipher = (char *)silc_cipher_get_name(entry->internal.
+                                                       send_key);
+      keys[count].key = (entry->internal.generated == FALSE ?
+                        entry->internal.key : NULL);
+      keys[count].key_len = (entry->internal.generated == FALSE ?
+                            entry->internal.key_len : 0);
       count++;
     }
-
-    if (!silc_idcache_list_next(list, &id_cache))
-      break;
   }
 
+  silc_mutex_unlock(conn->internal->lock);
+
   if (key_count)
     *key_count = count;
 
@@ -638,31 +628,43 @@ void silc_client_free_private_message_keys(SilcPrivateMessageKeys keys,
   silc_free(keys);
 }
 
+/* Return private message key from the client entry. */
+
+SilcBool
+silc_client_private_message_key_is_set(SilcClient client,
+                                      SilcClientConnection conn,
+                                      SilcClientEntry client_entry)
+{
+  return client_entry->internal.send_key != NULL;
+}
+
 /* Sets away `message'.  The away message may be set when the client's
    mode is changed to SILC_UMODE_GONE and the client whishes to reply
    to anyone who sends private message.  The `message' will be sent
    automatically back to the the client who send private message.  If
    away message is already set this replaces the old message with the
-   new one.  If `message' is NULL the old away message is removed. 
+   new one.  If `message' is NULL the old away message is removed.
    The sender may freely free the memory of the `message'. */
 
-void silc_client_set_away_message(SilcClient client,
-                                 SilcClientConnection conn,
-                                 char *message)
+SilcBool silc_client_set_away_message(SilcClient client,
+                                     SilcClientConnection conn,
+                                     char *message)
 {
-  assert(client && conn);
+  if (!client || !conn)
+    return FALSE;
 
-  if (!message && conn->internal->away) {
-    silc_free(conn->internal->away->away);
-    silc_free(conn->internal->away);
-    conn->internal->away = NULL;
+  if (!message) {
+    silc_free(conn->internal->away_message);
+    conn->internal->away_message = NULL;
+    return TRUE;
   }
 
-  if (message) {
-    if (!conn->internal->away)
-      conn->internal->away = silc_calloc(1, sizeof(*conn->internal->away));
-    if (conn->internal->away->away)
-      silc_free(conn->internal->away->away);
-    conn->internal->away->away = strdup(message);
-  }
+  if (conn->internal->away_message)
+    silc_free(conn->internal->away_message);
+
+  conn->internal->away_message = strdup(message);
+  if (!conn->internal->away_message)
+    return FALSE;
+
+  return TRUE;
 }