Integer type name change.
[silc.git] / lib / silccore / silcpacket.c
index 7054f600f6764145d6c3e6ab1ce2d2d4dcd19dfe..7f72922b5d6c4aac3de4ecbde37d0dfaa933c16e 100644 (file)
@@ -1,16 +1,15 @@
 /*
 
-  silcpacket.c
+  silcpacket.c 
 
-  Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
+  Author: Pekka Riikonen <priikone@silcnet.org>
 
-  Copyright (C) 1997 - 2000 Pekka Riikonen
+  Copyright (C) 1997 - 2001 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
-  the Free Software Foundation; either version 2 of the License, or
-  (at your option) any later version.
-  
+  the Free Software Foundation; version 2 of the License.
+
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 ******************************************************************************/
 
-/* Writes data from encrypted buffer to the socket connection. If the
-   data cannot be written at once, it will be written later with a timeout. 
-   The data is written from the data section of the buffer, not from head
-   or tail section. This automatically pulls the data section towards end
-   after writing the data. */
-
-int silc_packet_write(int sock, SilcBuffer src)
-{
-  int ret = 0;
-
-  SILC_LOG_DEBUG(("Writing data to socket %d", sock));
-
-  if (src->len > 0) {
-    ret = write(sock, src->data, src->len);
-    if (ret < 0) {
-      if (errno == EAGAIN) {
-       SILC_LOG_DEBUG(("Could not write immediately, will do it later"));
-       return -2;
-      }
-      SILC_LOG_ERROR(("Cannot write to socket: %s", strerror(errno)));
-      return -1;
-    }
-
-    silc_buffer_pull(src, ret);
-  }
-
-  SILC_LOG_DEBUG(("Wrote data %d bytes", ret));
-
-  return ret;
-}
-
 /* Actually sends the packet. This flushes the connections outgoing data
    buffer. If data is sent directly to the network this returns the bytes
    written, if error occured this returns -1 and if the data could not
@@ -69,8 +37,15 @@ int silc_packet_write(int sock, SilcBuffer src)
    later time. If `force_send' is TRUE this attempts to write the data
    directly to the network, if FALSE, this returns -2. */
 
-int silc_packet_send(SilcSocketConnection sock, int force_send)
+int silc_packet_send(SilcSocketConnection sock, bool force_send)
 {
+  SILC_LOG_DEBUG(("Sending packet to %s:%d [%s]", sock->hostname,
+                 sock->port,  
+                 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
+                  sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
+                  sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
+                  "Router")));
+
   /* Send now if forced to do so */
   if (force_send == TRUE) {
     int ret;
@@ -78,10 +53,11 @@ int silc_packet_send(SilcSocketConnection sock, int force_send)
     SILC_LOG_DEBUG(("Forcing packet send, packet sent immediately"));
 
     /* Write to network */
-    ret = silc_packet_write(sock->sock, sock->outbuf);
+    ret = silc_socket_write(sock);
 
     if (ret == -1) {
-      SILC_LOG_ERROR(("Error sending packet, dropped"));
+      SILC_LOG_ERROR(("Error sending packet, dropped: %s", 
+                      strerror(errno)));
     }
     if (ret != -2)
       return ret;
@@ -101,34 +77,37 @@ int silc_packet_send(SilcSocketConnection sock, int force_send)
    other process of HMAC computing and encryption is needed this function
    cannot be used. */
 
-void silc_packet_encrypt(SilcCipher cipher, SilcHmac hmac, 
-                        SilcBuffer buffer, unsigned int len)
+void silc_packet_encrypt(SilcCipher cipher, SilcHmac hmac, SilcUInt32 sequence,
+                        SilcBuffer buffer, SilcUInt32 len)
 {
   unsigned char mac[32];
-
-  if (cipher) {
-    SILC_LOG_DEBUG(("Encrypting packet, cipher %s, len %d (%d)", 
-                   cipher->cipher->name, len, len - 2));
-  }
+  SilcUInt32 mac_len;
 
   /* Compute HMAC. This assumes that HMAC is created from the entire
      data area thus this uses the length found in buffer, not the length
      sent as argument. */
   if (hmac) {
-    silc_hmac_make(hmac, buffer->data, buffer->len, mac);
-    silc_buffer_put_tail(buffer, mac, hmac->hash->hash->hash_len);
+    unsigned char psn[4];
+
+    silc_hmac_init(hmac);
+    SILC_PUT32_MSB(sequence, psn);
+    silc_hmac_update(hmac, psn, 4);
+    silc_hmac_update(hmac, buffer->data, buffer->len);
+    silc_hmac_final(hmac, mac, &mac_len);
+    silc_buffer_put_tail(buffer, mac, mac_len);
     memset(mac, 0, sizeof(mac));
   }
 
-  /* Encrypt the data area of the packet. 2 bytes of the packet
-     are not encrypted. */
-  if (cipher)
-    cipher->cipher->encrypt(cipher->context, buffer->data + 2, 
-                           buffer->data + 2, len - 2, cipher->iv);
+  /* Encrypt the data area of the packet. */
+  if (cipher) {
+    SILC_LOG_DEBUG(("Encrypting packet, cipher %s, len %d", 
+                   cipher->cipher->name, len));
+    silc_cipher_encrypt(cipher, buffer->data, buffer->data, len, cipher->iv);
+  }
 
   /* Pull the HMAC into the visible data area in the buffer */
   if (hmac)
-    silc_buffer_pull_tail(buffer, hmac->hash->hash->hash_len);
+    silc_buffer_pull_tail(buffer, mac_len);
 }
 
 /* Assembles a new packet to be ready for send out. The buffer sent as
@@ -154,32 +133,35 @@ void silc_packet_encrypt(SilcCipher cipher, SilcHmac hmac,
    ^                                   ^
    Start of assembled packet
 
-   Packet construct is as follows (* = won't be encrypted):
+   Packet construct is as follows:
 
-   x bytes       SILC Header
-      2 bytes     Payload length  (*)
+   n bytes       SILC Header
+      2 bytes     Payload length
       1 byte      Flags
       1 byte      Packet type
+      1 byte      Padding length
+      1 byte      RESERVED
+      1 bytes     Source ID Length
+      1 bytes     Destination ID Length
       1 byte      Source ID Type
-      2 bytes     Source ID Length
-      x bytes     Source ID
+      n bytes     Source ID
       1 byte      Destination ID Type
-      2 bytes     Destination ID Length
-      x bytes     Destination ID
+      n bytes     Destination ID
 
    1 - 16 bytes    Padding
 
-   x bytes        Data payload
+   n bytes        Data payload
 
    All fields in the packet will be authenticated by MAC. The MAC is
-   not computed here, it must be computed differently before encrypting
+   not computed here, it must be computed separately before encrypting
    the packet.
 
 */
 
-void silc_packet_assemble(SilcPacketContext *ctx)
+void silc_packet_assemble(SilcPacketContext *ctx, SilcCipher cipher)
 {
   unsigned char tmppad[SILC_PACKET_MAX_PADLEN];
+  int block_len = cipher ? silc_cipher_get_block_len(cipher) : 0;
   int i;
 
   SILC_LOG_DEBUG(("Assembling outgoing packet"));
@@ -192,11 +174,13 @@ void silc_packet_assemble(SilcPacketContext *ctx)
       ctx->src_id_len + ctx->dst_id_len;
 
   /* Calculate the length of the padding. The padding is calculated from
-     the data that will be encrypted. As protocol states 3 first bytes
-     of the packet are not encrypted they are not included in the
-     padding calculation. */
-  if (!ctx->padlen)
-    ctx->padlen = SILC_PACKET_PADLEN(ctx->truelen);
+     the data that will be encrypted. */
+  if (!ctx->padlen) {
+    if (ctx->long_pad)
+      ctx->padlen = SILC_PACKET_PADLEN_MAX(ctx->truelen);
+    else
+      ctx->padlen = SILC_PACKET_PADLEN(ctx->truelen, block_len);
+  }
 
   /* Put the start of the data section to the right place. */
   silc_buffer_push(ctx->buffer, SILC_PACKET_HEADER_LEN + 
@@ -204,7 +188,8 @@ void silc_packet_assemble(SilcPacketContext *ctx)
 
   /* Get random padding */
 #if 1
-  for (i = 0; i < ctx->padlen; i++) tmppad[i] = silc_rng_get_byte(ctx->rng);
+  for (i = 0; i < ctx->padlen; i++) tmppad[i] = 
+                                     silc_rng_global_get_byte_fast();
 #else
   /* XXX: For testing - to be removed */
   memset(tmppad, 65, sizeof(tmppad));
@@ -216,8 +201,10 @@ void silc_packet_assemble(SilcPacketContext *ctx)
                     SILC_STR_UI_SHORT(ctx->truelen),
                     SILC_STR_UI_CHAR(ctx->flags),
                     SILC_STR_UI_CHAR(ctx->type),
-                    SILC_STR_UI_SHORT(ctx->src_id_len),
-                    SILC_STR_UI_SHORT(ctx->dst_id_len),
+                    SILC_STR_UI_CHAR(ctx->padlen),
+                    SILC_STR_UI_CHAR(0),
+                    SILC_STR_UI_CHAR(ctx->src_id_len),
+                    SILC_STR_UI_CHAR(ctx->dst_id_len),
                     SILC_STR_UI_CHAR(ctx->src_id_type),
                     SILC_STR_UI_XNSTRING(ctx->src_id, ctx->src_id_len),
                     SILC_STR_UI_CHAR(ctx->dst_id_type),
@@ -237,9 +224,9 @@ void silc_packet_assemble(SilcPacketContext *ctx)
    outgoing buffer in SilcSocketConnection object. */
 
 void silc_packet_send_prepare(SilcSocketConnection sock,
-                             unsigned int header_len,
-                             unsigned int padlen,
-                             unsigned int data_len)
+                             SilcUInt32 header_len,
+                             SilcUInt32 padlen,
+                             SilcUInt32 data_len)
 {
   int totlen, oldlen;
 
@@ -250,7 +237,10 @@ void silc_packet_send_prepare(SilcSocketConnection sock,
     /* Allocate new buffer. This is done only once per connection. */
     SILC_LOG_DEBUG(("Allocating outgoing data buffer"));
     
-    sock->outbuf = silc_buffer_alloc(SILC_PACKET_DEFAULT_SIZE);
+    if (totlen > SILC_PACKET_DEFAULT_SIZE)
+      sock->outbuf = silc_buffer_alloc(totlen);
+    else
+      sock->outbuf = silc_buffer_alloc(SILC_PACKET_DEFAULT_SIZE);
     silc_buffer_pull_tail(sock->outbuf, totlen);
     silc_buffer_pull(sock->outbuf, header_len + padlen);
   } else {
@@ -258,10 +248,12 @@ void silc_packet_send_prepare(SilcSocketConnection sock,
       /* There is some pending data in the buffer. */
 
       /* Allocate more space if needed */
-      if ((sock->outbuf->end - sock->outbuf->tail) < data_len) {
+      if ((sock->outbuf->end - sock->outbuf->tail) < 
+         (totlen + 20)) {
        SILC_LOG_DEBUG(("Reallocating outgoing data buffer"));
        sock->outbuf = silc_buffer_realloc(sock->outbuf, 
-                                          sock->outbuf->truelen + totlen);
+                                          sock->outbuf->truelen +
+                                          (totlen * 2));
       }
 
       oldlen = sock->outbuf->len;
@@ -270,6 +262,15 @@ void silc_packet_send_prepare(SilcSocketConnection sock,
     } else {
       /* Buffer is free for use */
       silc_buffer_clear(sock->outbuf);
+
+      /* Allocate more space if needed */
+      if ((sock->outbuf->end - sock->outbuf->tail) < (totlen + 20)) {
+       SILC_LOG_DEBUG(("Reallocating outgoing data buffer"));
+       sock->outbuf = silc_buffer_realloc(sock->outbuf, 
+                                          sock->outbuf->truelen + 
+                                          (totlen * 2));
+      }
+
       silc_buffer_pull_tail(sock->outbuf, totlen);
       silc_buffer_pull(sock->outbuf, header_len + padlen);
     }
@@ -282,192 +283,189 @@ void silc_packet_send_prepare(SilcSocketConnection sock,
 
 ******************************************************************************/
 
-/* Reads data from the socket connection into the incoming data buffer.
-   However, this does not parse the packet, it only reads some amount from
-   the network. If there are more data available that can be read at a time
-   the rest of the data will be read later with a timeout and only after
-   that the packet is ready to be parsed. 
+static int silc_packet_decrypt(SilcCipher cipher, SilcHmac hmac, 
+                              SilcUInt32 sequence, SilcBuffer buffer, 
+                              bool normal);
 
-   The destination buffer sent as argument must be initialized before 
-   calling this function, and, the data section and the start of the tail
-   section must be same. Ie. we add the read data to the tail section of
-   the buffer hence the data section is the start of the buffer.
-
-   This returns amount of bytes read or -1 on error or -2 on case where
-   all of the data could not be read at once. */
+/* Receives packet from network and reads the data into connection's
+   incoming data buffer. If the data was read directly this returns the
+   read bytes, if error occured this returns -1, if the data could not
+   be read directly at this time this returns -2 in which case the data
+   should be read again at some later time, or If EOF occured this returns
+   0. */
 
-int silc_packet_read(int sock, SilcBuffer dest)
+int silc_packet_receive(SilcSocketConnection sock)
 {
-  int len = 0;
-  unsigned char buf[SILC_PACKET_READ_SIZE];
-
-  SILC_LOG_DEBUG(("Reading data from socket %d", sock));
-
-  /* Read the data from the socket. */
-  len = read(sock, buf, sizeof(buf));
-  if (len < 0) {
-    if (errno == EAGAIN || errno == EINTR) {
-      SILC_LOG_DEBUG(("Could not read immediately, will do it later"));
-      return -2;
-    }
-    SILC_LOG_ERROR(("Cannot read from socket: %d", strerror(errno)));
-    return -1;
-  }
-
-  if (!len)
-    return 0;
-
-  /* Insert the data to the buffer. If the data doesn't fit to the 
-     buffer space is allocated for the buffer. */
-  /* XXX: This may actually be bad thing as if there is pending data in
-     the buffer they will be lost! */
-  if (dest) {
-
-    /* If the data doesn't fit we just have to allocate a whole new 
-       data area */
-    if (dest->truelen <= len) {
-
-      /* Free the old buffer */
-      memset(dest->head, 'F', dest->truelen);
-      silc_free(dest->head);
-
-      /* Allocate new data area */
-      len += SILC_PACKET_DEFAULT_SIZE;
-      dest->data = silc_calloc(len, sizeof(char));
-      dest->truelen = len;
-      dest->len = 0;
-      dest->head = dest->data;
-      dest->data = dest->data;
-      dest->tail = dest->data;
-      dest->end = dest->data + dest->truelen;
-      len -= SILC_PACKET_DEFAULT_SIZE;
-    }
+  int ret;
 
-    silc_buffer_put_tail(dest, buf, len);
-    silc_buffer_pull_tail(dest, len);
-  }
+  SILC_LOG_DEBUG(("Receiving packet from %s:%d [%s]", sock->hostname,
+                 sock->port, 
+                 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
+                  sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
+                  sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
+                  "Router")));
 
-  SILC_LOG_DEBUG(("Read %d bytes", len));
+  /* Read some data from connection */
+  ret = silc_socket_read(sock);
 
-  return len;
+  return ret;
 }
 
-/* Processes the received data. This checks the received data and 
-   calls parser callback that handles the actual packet decryption
-   and parsing. If more than one packet was received this calls the
-   parser multiple times. The parser callback will get context
-   SilcPacketParserContext that includes the packet and the `context'
-   sent to this function. */
-
-void silc_packet_receive_process(SilcSocketConnection sock,
+/* Processes and decrypts the incmoing data, and calls parser callback
+   for each received packet that will handle the actual packet parsing.
+   If more than one packet was received this calls the parser multiple
+   times.  The parser callback will get context SilcPacketParserContext
+   that includes the packet and the `parser_context' sent to this
+   function. 
+   
+   The `local_is_router' indicates whether the caller is router server
+   in which case the receiving process of a certain packet types may
+   be special.  Normal server and client must set it to FALSE.  The
+   SilcPacketParserContext will indicate also whether the received
+   packet was normal or special packet. */
+
+bool silc_packet_receive_process(SilcSocketConnection sock,
+                                bool local_is_router,
                                 SilcCipher cipher, SilcHmac hmac,
+                                SilcUInt32 sequence,
                                 SilcPacketParserCallback parser,
-                                void *context)
+                                void *parser_context)
 {
   SilcPacketParserContext *parse_ctx;
-  int packetlen, paddedlen, count, mac_len = 0;
+  int packetlen, paddedlen, mac_len = 0;
+  bool cont = TRUE;
 
-  /* We need at least 2 bytes of data to be able to start processing
-     the packet. */
-  if (sock->inbuf->len < 2)
-    return;
+  /* Do not process for disconnected connection */
+  if (SILC_IS_DISCONNECTED(sock))
+    return TRUE;
+
+  if (sock->inbuf->len < SILC_PACKET_MIN_HEADER_LEN)
+    return TRUE;
 
   if (hmac)
-    mac_len = hmac->hash->hash->hash_len;
+    mac_len = silc_hmac_len(hmac);
 
   /* Parse the packets from the data */
-  count = 0;
-  while (sock->inbuf->len > 0) {
+  while (sock->inbuf->len > 0 && cont) {
+
+    if (sock->inbuf->len < SILC_PACKET_MIN_HEADER_LEN) {
+      SILC_LOG_DEBUG(("Partial packet in queue, waiting for the rest"));
+      return TRUE;
+    }
+
+    /* Decrypt first 16 bytes of the packet */
+    if (!SILC_IS_INBUF_PENDING(sock) && cipher)
+      silc_cipher_decrypt(cipher, sock->inbuf->data, sock->inbuf->data, 
+                         SILC_PACKET_MIN_HEADER_LEN, cipher->iv);
+
+    /* Get packet lenght and full packet length with padding */
     SILC_PACKET_LENGTH(sock->inbuf, packetlen, paddedlen);
-    paddedlen += 2;
-    count++;
 
+    /* Sanity checks */
     if (packetlen < SILC_PACKET_MIN_LEN) {
       SILC_LOG_DEBUG(("Received invalid packet, dropped"));
-      return;
+      silc_buffer_clear(sock->inbuf);
+      return FALSE;
     }
 
     if (sock->inbuf->len < paddedlen + mac_len) {
-      SILC_LOG_DEBUG(("Received partial packet, waiting for the rest"));
-      return;
+      SILC_LOG_DEBUG(("Received partial packet, waiting for the rest"
+                     "(%d < %d)", sock->inbuf->len, paddedlen + mac_len));
+      SILC_SET_INBUF_PENDING(sock);
+      return TRUE;
     }
 
+    SILC_UNSET_INBUF_PENDING(sock);
     parse_ctx = silc_calloc(1, sizeof(*parse_ctx));
     parse_ctx->packet = silc_packet_context_alloc();
     parse_ctx->packet->buffer = silc_buffer_alloc(paddedlen + mac_len);
+    parse_ctx->packet->type = sock->inbuf->data[3];
+    parse_ctx->packet->padlen = sock->inbuf->data[4];
+    parse_ctx->packet->sequence = sequence++;
     parse_ctx->sock = sock;
-    parse_ctx->cipher = cipher;
-    parse_ctx->hmac = hmac;
-    parse_ctx->context = context;
+    parse_ctx->context = parser_context;
 
     silc_buffer_pull_tail(parse_ctx->packet->buffer, 
                          SILC_BUFFER_END(parse_ctx->packet->buffer));
     silc_buffer_put(parse_ctx->packet->buffer, sock->inbuf->data, 
-                   paddedlen + mac_len);
-
-    SILC_LOG_HEXDUMP(("Incoming packet, len %d", 
-                     parse_ctx->packet->buffer->len),
-                    parse_ctx->packet->buffer->data, 
-                    parse_ctx->packet->buffer->len);
+                   paddedlen + mac_len);
+
+    SILC_LOG_HEXDUMP(("Incoming packet (%d) (%dB decrypted), len %d", 
+                     sequence - 1, SILC_PACKET_MIN_HEADER_LEN, 
+                     paddedlen + mac_len),
+                    sock->inbuf->data, paddedlen + mac_len);
+
+    /* Check whether this is normal or special packet */
+    if (local_is_router) {
+      if (sock->inbuf->data[3] == SILC_PACKET_PRIVATE_MESSAGE &&
+         (sock->inbuf->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY))
+       parse_ctx->normal = FALSE;
+      else if (sock->inbuf->data[3] != SILC_PACKET_CHANNEL_MESSAGE || 
+              (sock->inbuf->data[3] == SILC_PACKET_CHANNEL_MESSAGE &&
+               sock->type == SILC_SOCKET_TYPE_ROUTER))
+       parse_ctx->normal = TRUE;
+    } else {
+      if (sock->inbuf->data[3] == SILC_PACKET_PRIVATE_MESSAGE &&
+         (sock->inbuf->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY))
+       parse_ctx->normal = FALSE;
+      else if (sock->inbuf->data[3] != SILC_PACKET_CHANNEL_MESSAGE)
+       parse_ctx->normal = TRUE;
+    }
 
-    /* Call the parser */
-    if (parser)
-      (*parser)(parse_ctx);
+    /* Decrypt rest of the packet */
+    if (cipher)
+      if (silc_packet_decrypt(cipher, hmac, parse_ctx->packet->sequence, 
+                             parse_ctx->packet->buffer, 
+                             parse_ctx->normal) == -1) {
+       SILC_LOG_WARNING(("Packet decryption failed %s:%d [%s]", 
+                         sock->hostname, sock->port,
+                         (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
+                          sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
+                          sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
+                          "Router")));
+      }
 
     /* Pull the packet from inbuf thus we'll get the next one
        in the inbuf. */
-    silc_buffer_pull(sock->inbuf, paddedlen);
-    if (hmac)
-      silc_buffer_pull(sock->inbuf, mac_len);
-  }
+    silc_buffer_pull(sock->inbuf, paddedlen + mac_len);
 
-  silc_buffer_clear(sock->inbuf);
-}
-
-/* Receives packet from network and reads the data into connection's
-   incoming data buffer. If the data was read directly this returns the
-   read bytes, if error occured this returns -1, if the data could not
-   be read directly at this time this returns -2 in which case the data
-   should be read again at some later time, or If EOF occured this returns
-   0. */
-
-int silc_packet_receive(SilcSocketConnection sock)
-{
-  int ret;
-
-  /* Allocate the incoming data buffer if not done already. */
-  if (!sock->inbuf)
-    sock->inbuf = silc_buffer_alloc(SILC_PACKET_DEFAULT_SIZE);
-  
-  /* Read some data from connection */
-  ret = silc_packet_read(sock->sock, sock->inbuf);
-
-  /* Error */
-  if (ret == -1) {
-    SILC_LOG_ERROR(("Error reading packet, dropped"));
+    /* Call the parser */
+    cont = (*parser)(parse_ctx, parser_context);
   }
 
-  return ret;
+  if (cont == FALSE && sock->inbuf->len > 0)
+    return TRUE;
+
+  SILC_LOG_DEBUG(("Clearing inbound buffer"));
+  silc_buffer_clear(sock->inbuf);
+  return TRUE;
 }
 
 /* Checks MAC in the packet. Returns TRUE if MAC is Ok. This is called
    after packet has been totally decrypted and parsed. */
 
-static int silc_packet_check_mac(SilcHmac hmac, SilcBuffer buffer)
+static int silc_packet_check_mac(SilcHmac hmac, SilcBuffer buffer,
+                                SilcUInt32 sequence)
 {
   /* Check MAC */
   if (hmac) {
-    unsigned char mac[32];
+    unsigned char mac[32], psn[4];
+    SilcUInt32 mac_len;
     
     SILC_LOG_DEBUG(("Verifying MAC"));
 
     /* Compute HMAC of packet */
+
     memset(mac, 0, sizeof(mac));
-    silc_hmac_make(hmac, buffer->data, buffer->len, mac);
+    silc_hmac_init(hmac);
+    SILC_PUT32_MSB(sequence, psn);
+    silc_hmac_update(hmac, psn, 4);
+    silc_hmac_update(hmac, buffer->data, buffer->len);
+    silc_hmac_final(hmac, mac, &mac_len);
 
     /* Compare the HMAC's (buffer->tail has the packet's HMAC) */
-    if (memcmp(mac, buffer->tail, hmac->hash->hash->hash_len)) {
-      SILC_LOG_DEBUG(("MAC failed"));
+    if (memcmp(buffer->tail, mac, mac_len)) {
+      SILC_LOG_ERROR(("MAC failed"));
       return FALSE;
     }
     
@@ -490,8 +488,8 @@ static int silc_packet_decrypt_rest(SilcCipher cipher, SilcHmac hmac,
 
     /* Pull MAC from packet before decryption */
     if (hmac) {
-      if ((buffer->len - hmac->hash->hash->hash_len) > SILC_PACKET_MIN_LEN) {
-       silc_buffer_push_tail(buffer, hmac->hash->hash->hash_len);
+      if ((buffer->len - silc_hmac_len(hmac)) > SILC_PACKET_MIN_LEN) {
+       silc_buffer_push_tail(buffer, silc_hmac_len(hmac));
       } else {
        SILC_LOG_DEBUG(("Bad MAC length in packet, packet dropped"));
        return FALSE;
@@ -501,11 +499,10 @@ static int silc_packet_decrypt_rest(SilcCipher cipher, SilcHmac hmac,
     SILC_LOG_DEBUG(("Decrypting rest of the packet"));
 
     /* Decrypt rest of the packet */
-    silc_buffer_pull(buffer, SILC_PACKET_MIN_HEADER_LEN - 2);
-    cipher->cipher->decrypt(cipher->context, buffer->data + 2,
-                           buffer->data + 2, buffer->len - 2,
-                           cipher->iv);
-    silc_buffer_push(buffer, SILC_PACKET_MIN_HEADER_LEN - 2);
+    silc_buffer_pull(buffer, SILC_PACKET_MIN_HEADER_LEN);
+    silc_cipher_decrypt(cipher, buffer->data, buffer->data, buffer->len, 
+                       cipher->iv);
+    silc_buffer_push(buffer, SILC_PACKET_MIN_HEADER_LEN);
 
     SILC_LOG_HEXDUMP(("Fully decrypted packet, len %d", buffer->len),
                     buffer->data, buffer->len);
@@ -526,12 +523,12 @@ static int silc_packet_decrypt_rest_special(SilcCipher cipher,
 {
   /* Decrypt rest of the header plus padding */
   if (cipher) {
-    unsigned short truelen, len1, len2, padlen;
+    SilcUInt16 len;
 
     /* Pull MAC from packet before decryption */
     if (hmac) {
-      if ((buffer->len - hmac->hash->hash->hash_len) > SILC_PACKET_MIN_LEN) {
-       silc_buffer_push_tail(buffer, hmac->hash->hash->hash_len);
+      if ((buffer->len - silc_hmac_len(hmac)) > SILC_PACKET_MIN_LEN) {
+       silc_buffer_push_tail(buffer, silc_hmac_len(hmac));
       } else {
        SILC_LOG_DEBUG(("Bad MAC length in packet, packet dropped"));
        return FALSE;
@@ -540,18 +537,22 @@ static int silc_packet_decrypt_rest_special(SilcCipher cipher,
   
     SILC_LOG_DEBUG(("Decrypting rest of the header"));
 
-    SILC_GET16_MSB(len1, &buffer->data[4]);
-    SILC_GET16_MSB(len2, &buffer->data[6]);
-
-    truelen = SILC_PACKET_HEADER_LEN + len1 + len2;
-    padlen = SILC_PACKET_PADLEN(truelen);
-    len1 = (truelen + padlen) - (SILC_PACKET_MIN_HEADER_LEN - 2);
+    /* padding length + src id len + dst id len + header length - 16
+       bytes already decrypted, gives the rest of the encrypted packet */
+    len = (((SilcUInt8)buffer->data[4] + (SilcUInt8)buffer->data[6] + 
+          (SilcUInt8)buffer->data[7] + SILC_PACKET_HEADER_LEN) -
+          SILC_PACKET_MIN_HEADER_LEN);
 
-    silc_buffer_pull(buffer, SILC_PACKET_MIN_HEADER_LEN - 2);
-    cipher->cipher->decrypt(cipher->context, buffer->data + 2,
-                           buffer->data + 2, len1 - 2,
-                           cipher->iv);
-    silc_buffer_push(buffer, SILC_PACKET_MIN_HEADER_LEN - 2);
+    silc_buffer_pull(buffer, SILC_PACKET_MIN_HEADER_LEN);
+    if (len > buffer->len) {
+      SILC_LOG_DEBUG(("Garbage in header of packet, bad packet length, "
+                     "packet dropped"));
+      return FALSE;
+    }
+    silc_cipher_decrypt(cipher, buffer->data, buffer->data, len, cipher->iv);
+    silc_buffer_push(buffer, SILC_PACKET_MIN_HEADER_LEN);
+    SILC_LOG_HEXDUMP(("packet, len %d", buffer->len), 
+                    buffer->data, buffer->len);
   }
 
   return TRUE;
@@ -563,45 +564,39 @@ static int silc_packet_decrypt_rest_special(SilcCipher cipher,
    the HMAC of the packet. If any other special or customized decryption
    processing is required this function cannot be used. This returns
    -1 on error, 0 when packet is normal packet and 1 when the packet
-   is special and requires special processing. */
-
-int silc_packet_decrypt(SilcCipher cipher, SilcHmac hmac,
-                       SilcBuffer buffer, SilcPacketContext *packet)
-{
-#if 0
-  SILC_LOG_DEBUG(("Decrypting packet, cipher %s, len %d (%d)", 
-                 cipher->cipher->name, len, len - 2));
-#endif
+   is special and requires special processing. 
 
-  /* Decrypt start of the packet header */
-  if (cipher)
-    cipher->cipher->decrypt(cipher->context, buffer->data + 2,
-                           buffer->data + 2, SILC_PACKET_MIN_HEADER_LEN - 2,
-                           cipher->iv);
+   The `check_packet' is a callback funtion that this function will 
+   call.  The callback relates to the checking whether the packet is
+   normal packet or special packet and how it should be processed.  If
+   the callback return TRUE the packet is normal and FALSE if the packet
+   is special and requires special procesing. */
 
+static int silc_packet_decrypt(SilcCipher cipher, SilcHmac hmac,
+                              SilcUInt32 sequence, SilcBuffer buffer, 
+                              bool normal)
+{
   /* If the packet type is not any special type lets decrypt rest
      of the packet here. */
-  if ((buffer->data[3] == SILC_PACKET_PRIVATE_MESSAGE &&
-      !(buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY)) ||
-      buffer->data[3] != SILC_PACKET_CHANNEL_MESSAGE) {
-
+  if (normal == TRUE) {
     /* Normal packet, decrypt rest of the packet */
     if (!silc_packet_decrypt_rest(cipher, hmac, buffer))
       return -1;
 
     /* Check MAC */
-    if (!silc_packet_check_mac(hmac, buffer))
-      return FALSE;
+    if (!silc_packet_check_mac(hmac, buffer, sequence))
+      return -1;
 
     return 0;
   } else {
     /* Packet requires special handling, decrypt rest of the header.
        This only decrypts. */
-    silc_packet_decrypt_rest_special(cipher, hmac, buffer);
+    if (!silc_packet_decrypt_rest_special(cipher, hmac, buffer))
+      return -1;
 
     /* Check MAC */
-    if (!silc_packet_check_mac(hmac, buffer))
-      return FALSE;
+    if (!silc_packet_check_mac(hmac, buffer, sequence))
+      return -1;
 
     return 1;
   }
@@ -613,10 +608,11 @@ int silc_packet_decrypt(SilcCipher cipher, SilcHmac hmac,
    function returns the type of the packet. The data section of the 
    buffer is parsed, not head or tail sections. */
 
-SilcPacketType silc_packet_parse(SilcPacketContext *ctx)
+SilcPacketType silc_packet_parse(SilcPacketContext *ctx, SilcCipher cipher)
 {
   SilcBuffer buffer = ctx->buffer;
-  int len;
+  SilcUInt8 tmp;
+  int len, ret;
 
   SILC_LOG_DEBUG(("Parsing incoming packet"));
 
@@ -631,29 +627,34 @@ SilcPacketType silc_packet_parse(SilcPacketContext *ctx)
                             SILC_STR_UI_SHORT(&ctx->truelen),
                             SILC_STR_UI_CHAR(&ctx->flags),
                             SILC_STR_UI_CHAR(&ctx->type),
-                            SILC_STR_UI_SHORT(&ctx->src_id_len),
-                            SILC_STR_UI_SHORT(&ctx->dst_id_len),
+                            SILC_STR_UI_CHAR(&ctx->padlen),
+                            SILC_STR_UI_CHAR(&tmp),
+                            SILC_STR_UI_CHAR(&ctx->src_id_len),
+                            SILC_STR_UI_CHAR(&ctx->dst_id_len),
                             SILC_STR_UI_CHAR(&ctx->src_id_type),
                             SILC_STR_END);
+  if (len == -1 || tmp != 0)
+    return SILC_PACKET_NONE;
 
   if (ctx->src_id_len > SILC_PACKET_MAX_ID_LEN ||
       ctx->dst_id_len > SILC_PACKET_MAX_ID_LEN) {
-    SILC_LOG_ERROR(("Bad ID lengths in packet"));
+    SILC_LOG_ERROR(("Bad ID lengths in packet (%d and %d)",
+                   ctx->src_id_len, ctx->dst_id_len));
     return SILC_PACKET_NONE;
   }
 
-  /* Calculate length of padding in packet */
-  ctx->padlen = SILC_PACKET_PADLEN(ctx->truelen);
-
   silc_buffer_pull(buffer, len);
-  silc_buffer_unformat(buffer, 
-                      SILC_STR_UI_XNSTRING_ALLOC(&ctx->src_id,
-                                                 ctx->src_id_len),
-                      SILC_STR_UI_CHAR(&ctx->dst_id_type),
-                      SILC_STR_UI_XNSTRING_ALLOC(&ctx->dst_id,
-                                                 ctx->dst_id_len),
-                      SILC_STR_UI_XNSTRING(NULL, ctx->padlen),
-                      SILC_STR_END);
+  ret = silc_buffer_unformat(buffer, 
+                            SILC_STR_UI_XNSTRING_ALLOC(&ctx->src_id,
+                                                       ctx->src_id_len),
+                            SILC_STR_UI_CHAR(&ctx->dst_id_type),
+                            SILC_STR_UI_XNSTRING_ALLOC(&ctx->dst_id,
+                                                       ctx->dst_id_len),
+                            SILC_STR_UI_XNSTRING(NULL, ctx->padlen),
+                            SILC_STR_END);
+  if (ret == -1)
+    return SILC_PACKET_NONE;
+
   silc_buffer_push(buffer, len);
 
   SILC_LOG_HEXDUMP(("parsed packet, len %d", ctx->buffer->len), 
@@ -674,10 +675,12 @@ SilcPacketType silc_packet_parse(SilcPacketContext *ctx)
    the header in a way that it does not take the data area into account
    and parses the header and padding area only. */
 
-SilcPacketType silc_packet_parse_special(SilcPacketContext *ctx)
+SilcPacketType silc_packet_parse_special(SilcPacketContext *ctx,
+                                        SilcCipher cipher)
 {
   SilcBuffer buffer = ctx->buffer;
-  int len, tmplen;
+  SilcUInt8 tmp;
+  int len, ret;
 
   SILC_LOG_DEBUG(("Parsing incoming packet"));
 
@@ -692,32 +695,38 @@ SilcPacketType silc_packet_parse_special(SilcPacketContext *ctx)
                             SILC_STR_UI_SHORT(&ctx->truelen),
                             SILC_STR_UI_CHAR(&ctx->flags),
                             SILC_STR_UI_CHAR(&ctx->type),
-                            SILC_STR_UI_SHORT(&ctx->src_id_len),
-                            SILC_STR_UI_SHORT(&ctx->dst_id_len),
+                            SILC_STR_UI_CHAR(&ctx->padlen),
+                            SILC_STR_UI_CHAR(&tmp),
+                            SILC_STR_UI_CHAR(&ctx->src_id_len),
+                            SILC_STR_UI_CHAR(&ctx->dst_id_len),
                             SILC_STR_UI_CHAR(&ctx->src_id_type),
                             SILC_STR_END);
+  if (len == -1 || tmp != 0) {
+    SILC_LOG_ERROR(("Malformed packet header, packet dropped"));
+    return SILC_PACKET_NONE;
+  }
 
   if (ctx->src_id_len > SILC_PACKET_MAX_ID_LEN ||
       ctx->dst_id_len > SILC_PACKET_MAX_ID_LEN) {
-    SILC_LOG_ERROR(("Bad ID lengths in packet"));
+    SILC_LOG_ERROR(("Bad ID lengths in packet (%d and %d)",
+                   ctx->src_id_len, ctx->dst_id_len));
     return SILC_PACKET_NONE;
   }
 
-  /* Calculate length of padding in packet. As this is special packet
-     the data area is not used in the padding calculation as it won't
-     be decrypted by the caller. */
-  tmplen = SILC_PACKET_HEADER_LEN + ctx->src_id_len + ctx->dst_id_len;
-  ctx->padlen = SILC_PACKET_PADLEN(tmplen);
-
   silc_buffer_pull(buffer, len);
-  silc_buffer_unformat(buffer, 
-                      SILC_STR_UI_XNSTRING_ALLOC(&ctx->src_id,
-                                                 ctx->src_id_len),
-                      SILC_STR_UI_CHAR(&ctx->dst_id_type),
-                      SILC_STR_UI_XNSTRING_ALLOC(&ctx->dst_id,
-                                                 ctx->dst_id_len),
-                      SILC_STR_UI_XNSTRING(NULL, ctx->padlen),
-                      SILC_STR_END);
+  ret = silc_buffer_unformat(buffer, 
+                            SILC_STR_UI_XNSTRING_ALLOC(&ctx->src_id,
+                                                       ctx->src_id_len),
+                            SILC_STR_UI_CHAR(&ctx->dst_id_type),
+                            SILC_STR_UI_XNSTRING_ALLOC(&ctx->dst_id,
+                                                       ctx->dst_id_len),
+                            SILC_STR_UI_XNSTRING(NULL, ctx->padlen),
+                            SILC_STR_END);
+  if (ret == -1) {
+    SILC_LOG_ERROR(("Malformed packet header, packet dropped"));
+    return SILC_PACKET_NONE;
+  }
+
   silc_buffer_push(buffer, len);
 
   SILC_LOG_HEXDUMP(("parsed packet, len %d", ctx->buffer->len), 
@@ -734,7 +743,7 @@ SilcPacketType silc_packet_parse_special(SilcPacketContext *ctx)
 
 /* Allocate packet context */
 
-SilcPacketContext *silc_packet_context_alloc()
+SilcPacketContext *silc_packet_context_alloc(void)
 {
   SilcPacketContext *ctx = silc_calloc(1, sizeof(*ctx));
   ctx->users++;
@@ -746,6 +755,8 @@ SilcPacketContext *silc_packet_context_alloc()
 SilcPacketContext *silc_packet_context_dup(SilcPacketContext *ctx)
 {
   ctx->users++;
+  SILC_LOG_DEBUG(("Packet context %p refcnt %d->%d", ctx, ctx->users - 1,
+                 ctx->users));
   return ctx;
 }
 
@@ -755,6 +766,8 @@ SilcPacketContext *silc_packet_context_dup(SilcPacketContext *ctx)
 void silc_packet_context_free(SilcPacketContext *ctx)
 {
   ctx->users--;
+  SILC_LOG_DEBUG(("Packet context %p refcnt %d->%d", ctx, ctx->users + 1,
+                 ctx->users));
   if (ctx->users < 1)
     {
       if (ctx->buffer)