Handle destroyed stream in packet dispatcher.
[silc.git] / lib / silccore / silcpacket.c
index adce3221a4cc5473a9fa2c30caeee1856772f653..a88bbf63602155309e8e2fe8522bd193c3f473f8 100644 (file)
@@ -151,8 +151,21 @@ do {                                                                       \
                                (s)->stream_context);                   \
 } while(0)
 
-static void silc_packet_dispatch(SilcPacket packet);
+static SilcBool silc_packet_dispatch(SilcPacket packet);
 static void silc_packet_read_process(SilcPacketStream stream);
+static inline SilcBool silc_packet_send_raw(SilcPacketStream stream,
+                                           SilcPacketType type,
+                                           SilcPacketFlags flags,
+                                           SilcIdType src_id_type,
+                                           unsigned char *src_id,
+                                           SilcUInt32 src_id_len,
+                                           SilcIdType dst_id_type,
+                                           unsigned char *dst_id,
+                                           SilcUInt32 dst_id_len,
+                                           const unsigned char *data,
+                                           SilcUInt32 data_len,
+                                           SilcCipher cipher,
+                                           SilcHmac hmac);
 
 /************************ Static utility functions **************************/
 
@@ -166,14 +179,18 @@ SILC_TASK_CALLBACK(silc_packet_stream_inject_packet)
   SILC_LOG_DEBUG(("Injecting packet %p to stream %p", packet, packet->stream));
 
   silc_mutex_lock(stream->lock);
-  silc_packet_dispatch(packet);
+  if (!stream->destroyed)
+    silc_packet_dispatch(packet);
   silc_mutex_unlock(stream->lock);
+  silc_packet_stream_unref(stream);
 }
 
 /* Write data to the stream.  Must be called with ps->lock locked.  Unlocks
-   the lock inside this function. */
+   the lock inside this function, unless no_unlock is TRUE.  Unlocks always
+   in case it returns FALSE. */
 
-static inline SilcBool silc_packet_stream_write(SilcPacketStream ps)
+static inline SilcBool silc_packet_stream_write(SilcPacketStream ps,
+                                               SilcBool no_unlock)
 {
   SilcStream stream;
   SilcBool connected;
@@ -191,17 +208,17 @@ static inline SilcBool silc_packet_stream_write(SilcPacketStream ps)
        i = silc_net_udp_send(stream, ps->remote_udp->remote_ip,
                              ps->remote_udp->remote_port,
                              ps->outbuf.data, silc_buffer_len(&ps->outbuf));
-       if (i == -2) {
+       if (silc_unlikely(i == -2)) {
          /* Error */
          silc_buffer_reset(&ps->outbuf);
-         silc_mutex_unlock(ps->lock);
          SILC_PACKET_CALLBACK_ERROR(ps, SILC_PACKET_ERR_WRITE);
          return FALSE;
        }
 
-       if (i == -1) {
+       if (silc_unlikely(i == -1)) {
          /* Cannot write now, write later. */
-         silc_mutex_unlock(ps->lock);
+         if (!no_unlock)
+           silc_mutex_unlock(ps->lock);
          return TRUE;
        }
 
@@ -210,7 +227,8 @@ static inline SilcBool silc_packet_stream_write(SilcPacketStream ps)
       }
 
       silc_buffer_reset(&ps->outbuf);
-      silc_mutex_unlock(ps->lock);
+      if (!no_unlock)
+       silc_mutex_unlock(ps->lock);
 
       return TRUE;
     }
@@ -220,7 +238,7 @@ static inline SilcBool silc_packet_stream_write(SilcPacketStream ps)
   while (silc_buffer_len(&ps->outbuf) > 0) {
     i = silc_stream_write(stream, ps->outbuf.data,
                          silc_buffer_len(&ps->outbuf));
-    if (i == 0) {
+    if (silc_unlikely(i == 0)) {
       /* EOS */
       silc_buffer_reset(&ps->outbuf);
       silc_mutex_unlock(ps->lock);
@@ -228,7 +246,7 @@ static inline SilcBool silc_packet_stream_write(SilcPacketStream ps)
       return FALSE;
     }
 
-    if (i == -2) {
+    if (silc_unlikely(i == -2)) {
       /* Error */
       silc_buffer_reset(&ps->outbuf);
       silc_mutex_unlock(ps->lock);
@@ -236,9 +254,10 @@ static inline SilcBool silc_packet_stream_write(SilcPacketStream ps)
       return FALSE;
     }
 
-    if (i == -1) {
+    if (silc_unlikely(i == -1)) {
       /* Cannot write now, write later. */
-      silc_mutex_unlock(ps->lock);
+      if (!no_unlock)
+       silc_mutex_unlock(ps->lock);
       return TRUE;
     }
 
@@ -247,7 +266,8 @@ static inline SilcBool silc_packet_stream_write(SilcPacketStream ps)
   }
 
   silc_buffer_reset(&ps->outbuf);
-  silc_mutex_unlock(ps->lock);
+  if (!no_unlock)
+    silc_mutex_unlock(ps->lock);
 
   return TRUE;
 }
@@ -286,7 +306,7 @@ static inline SilcBool silc_packet_stream_read(SilcPacketStream ps,
       ret = silc_net_udp_receive(stream, remote_ip, sizeof(remote_ip),
                                 &remote_port, ps->inbuf.tail,
                                 silc_buffer_taillen(&ps->inbuf));
-      if (ret == -2) {
+      if (silc_unlikely(ret == -2)) {
        /* Error */
        silc_buffer_reset(&ps->inbuf);
        silc_mutex_unlock(ps->lock);
@@ -314,7 +334,7 @@ static inline SilcBool silc_packet_stream_read(SilcPacketStream ps,
 
        silc_mutex_lock(remote->lock);
        if (ret > silc_buffer_taillen(&remote->inbuf))
-         if (!silc_buffer_realloc(&remote->inbuf, ret)) {
+         if (silc_unlikely(!silc_buffer_realloc(&remote->inbuf, ret))) {
            silc_mutex_unlock(remote->lock);
            silc_mutex_unlock(ps->lock);
            SILC_PACKET_CALLBACK_ERROR(ps, SILC_PACKET_ERR_NO_MEMORY);
@@ -334,7 +354,7 @@ static inline SilcBool silc_packet_stream_read(SilcPacketStream ps,
       /* Unknown sender */
       if (!ps->remote_udp) {
        ps->remote_udp = silc_calloc(1, sizeof(*ps->remote_udp));
-       if (!ps->remote_udp) {
+       if (silc_unlikely(!ps->remote_udp)) {
          silc_mutex_unlock(ps->lock);
          SILC_PACKET_CALLBACK_ERROR(ps, SILC_PACKET_ERR_NO_MEMORY);
          return FALSE;
@@ -355,7 +375,7 @@ static inline SilcBool silc_packet_stream_read(SilcPacketStream ps,
   ret = silc_stream_read(ps->stream, ps->inbuf.tail,
                         silc_buffer_taillen(&ps->inbuf));
 
-  if (ret == 0) {
+  if (silc_unlikely(ret == 0)) {
     /* EOS */
     silc_buffer_reset(&ps->inbuf);
     silc_mutex_unlock(ps->lock);
@@ -363,7 +383,7 @@ static inline SilcBool silc_packet_stream_read(SilcPacketStream ps,
     return FALSE;
   }
 
-  if (ret == -2) {
+  if (silc_unlikely(ret == -2)) {
     /* Error */
     silc_buffer_reset(&ps->inbuf);
     silc_mutex_unlock(ps->lock);
@@ -391,7 +411,7 @@ static void silc_packet_stream_io(SilcStream stream, SilcStreamStatus status,
 
   silc_mutex_lock(ps->lock);
 
-  if (ps->destroyed) {
+  if (silc_unlikely(ps->destroyed)) {
     silc_mutex_unlock(ps->lock);
     return;
   }
@@ -401,13 +421,13 @@ static void silc_packet_stream_io(SilcStream stream, SilcStreamStatus status,
   case SILC_STREAM_CAN_WRITE:
     SILC_LOG_DEBUG(("Writing pending data to stream"));
 
-    if (!silc_buffer_headlen(&ps->outbuf)) {
+    if (silc_unlikely(!silc_buffer_headlen(&ps->outbuf))) {
       silc_mutex_unlock(ps->lock);
       return;
     }
 
     /* Write pending data to stream */
-    silc_packet_stream_write(ps);
+    silc_packet_stream_write(ps, FALSE);
     break;
 
   case SILC_STREAM_CAN_READ:
@@ -418,6 +438,7 @@ static void silc_packet_stream_io(SilcStream stream, SilcStreamStatus status,
       return;
 
     /* Now process the data */
+    silc_packet_stream_ref(ps);
     if (!remote) {
       silc_packet_read_process(ps);
       silc_mutex_unlock(ps->lock);
@@ -425,6 +446,7 @@ static void silc_packet_stream_io(SilcStream stream, SilcStreamStatus status,
       silc_packet_read_process(remote);
       silc_mutex_unlock(remote->lock);
     }
+    silc_packet_stream_unref(ps);
     break;
 
   default:
@@ -452,13 +474,13 @@ static SilcPacket silc_packet_alloc(SilcPacketEngine engine)
     silc_mutex_unlock(engine->lock);
 
     packet = silc_calloc(1, sizeof(*packet));
-    if (!packet)
+    if (silc_unlikely(!packet))
       return NULL;
 
     SILC_LOG_DEBUG(("Allocating new packet %p", packet));
 
     tmp = silc_malloc(SILC_PACKET_DEFAULT_SIZE);
-    if (!tmp) {
+    if (silc_unlikely(!tmp)) {
       silc_free(packet);
       return NULL;
     }
@@ -707,6 +729,7 @@ SilcPacketStream silc_packet_stream_add_remote(SilcPacketStream stream,
   if (packet) {
     /* Inject packet to the new stream */
     packet->stream = ps;
+    silc_packet_stream_ref(ps);
     silc_schedule_task_add_timeout(silc_stream_get_schedule(stream->stream),
                                   silc_packet_stream_inject_packet, packet,
                                   0, 0);
@@ -921,6 +944,13 @@ void silc_packet_stream_unlink(SilcPacketStream stream,
   silc_packet_stream_unref(stream);
 }
 
+/* Returns TRUE if stream is UDP stream */
+
+SilcBool silc_packet_stream_is_udp(SilcPacketStream stream)
+{
+  return stream->udp || silc_socket_stream_is_udp(stream->stream, NULL);
+}
+
 /* Return packet sender IP and port for UDP packet stream */
 
 SilcBool silc_packet_get_sender(SilcPacket packet,
@@ -997,104 +1027,97 @@ SilcStream silc_packet_stream_get_stream(SilcPacketStream stream)
   return stream->stream;
 }
 
-/* Set ciphers for packet stream */
+/* Set keys. */
 
-void silc_packet_set_ciphers(SilcPacketStream stream, SilcCipher send,
-                            SilcCipher receive)
+SilcBool silc_packet_set_keys(SilcPacketStream stream, SilcCipher send_key,
+                              SilcCipher receive_key, SilcHmac send_hmac,
+                              SilcHmac receive_hmac, SilcBool rekey)
 {
-  SILC_LOG_DEBUG(("Setting new ciphers to packet stream"));
+  SILC_LOG_DEBUG(("Setting new keys to packet stream %p", stream));
+
+  /* If doing rekey, send REKEY_DONE packet */
+  if (rekey) {
+    /* This will take stream lock. */
+    if (!silc_packet_send_raw(stream, SILC_PACKET_REKEY_DONE, 0,
+                             stream->src_id_type, stream->src_id,
+                             stream->src_id_len, stream->dst_id_type,
+                             stream->dst_id, stream->dst_id_len,
+                             NULL, 0, stream->send_key[0],
+                             stream->send_hmac[0]))
+      return FALSE;
 
-  silc_mutex_lock(stream->lock);
+    /* Write the packet to the stream */
+    if (!silc_packet_stream_write(stream, TRUE))
+      return FALSE;
+  } else {
+    silc_mutex_lock(stream->lock);
+  }
 
-  /* In case IV Included is set, save the old key */
+  /* In case IV Included is set, save the old keys */
   if (stream->iv_included) {
-    if (stream->send_key[1]) {
+    if (stream->send_key[1] && send_key) {
       silc_cipher_free(stream->send_key[1]);
       stream->send_key[1] = stream->send_key[0];
     }
-    if (stream->receive_key[1]) {
+    if (stream->receive_key[1] && receive_key) {
       silc_cipher_free(stream->receive_key[1]);
       stream->receive_key[1] = stream->receive_key[0];
     }
-  } else {
-    if (stream->send_key[0])
-      silc_cipher_free(stream->send_key[0]);
-    if (stream->send_key[1])
-      silc_cipher_free(stream->receive_key[0]);
-  }
-
-  stream->send_key[0] = send;
-  stream->receive_key[0] = receive;
-
-  silc_mutex_unlock(stream->lock);
-}
-
-/* Return current ciphers from packet stream */
-
-SilcBool silc_packet_get_ciphers(SilcPacketStream stream, SilcCipher *send,
-                                SilcCipher *receive)
-{
-  if (!stream->send_key[0] && !stream->receive_key[0])
-    return FALSE;
-
-  silc_mutex_lock(stream->lock);
-
-  if (send)
-    *send = stream->send_key[0];
-  if (receive)
-    *receive = stream->receive_key[0];
-
-  silc_mutex_unlock(stream->lock);
-
-  return TRUE;
-}
-
-/* Set HMACs for packet stream */
-
-void silc_packet_set_hmacs(SilcPacketStream stream, SilcHmac send,
-                          SilcHmac receive)
-{
-  SILC_LOG_DEBUG(("Setting new HMACs to packet stream"));
-
-  silc_mutex_lock(stream->lock);
-
-  /* In case IV Included is set, save the old HMAC */
-  if (stream->iv_included) {
-    if (stream->send_hmac[1]) {
+    if (stream->send_hmac[1] && send_hmac) {
       silc_hmac_free(stream->send_hmac[1]);
       stream->send_hmac[1] = stream->send_hmac[0];
     }
-    if (stream->receive_hmac[1]) {
+    if (stream->receive_hmac[1] && receive_hmac) {
       silc_hmac_free(stream->receive_hmac[1]);
       stream->receive_hmac[1] = stream->receive_hmac[0];
     }
   } else {
-    if (stream->send_hmac[0])
+    if (stream->send_key[0] && send_key)
+      silc_cipher_free(stream->send_key[0]);
+    if (stream->send_key[1] && receive_key)
+      silc_cipher_free(stream->receive_key[0]);
+    if (stream->send_hmac[0] && send_hmac)
       silc_hmac_free(stream->send_hmac[0]);
-    if (stream->receive_hmac[0])
+    if (stream->receive_hmac[0] && receive_hmac)
       silc_hmac_free(stream->receive_hmac[0]);
   }
 
-  stream->send_hmac[0] = send;
-  stream->receive_hmac[0] = receive;
+  /* Set keys */
+  if (send_key)
+    stream->send_key[0] = send_key;
+  if (receive_key)
+    stream->receive_key[0] = receive_key;
+  if (send_hmac)
+    stream->send_hmac[0] = send_hmac;
+  if (receive_hmac)
+    stream->receive_hmac[0] = receive_hmac;
 
   silc_mutex_unlock(stream->lock);
+  return TRUE;
 }
 
-/* Return current HMACs from packet stream */
+/* Return current ciphers from packet stream */
 
-SilcBool silc_packet_get_hmacs(SilcPacketStream stream, SilcHmac *send,
-                              SilcHmac *receive)
+SilcBool silc_packet_get_keys(SilcPacketStream stream,
+                             SilcCipher *send_key,
+                             SilcCipher *receive_key,
+                             SilcHmac *send_hmac,
+                             SilcHmac *receive_hmac)
 {
-  if (!stream->send_hmac[0] && !stream->receive_hmac[0])
+  if (!stream->send_key[0] && !stream->receive_key[0] &&
+      !stream->send_hmac[0] && !stream->receive_hmac[0])
     return FALSE;
 
   silc_mutex_lock(stream->lock);
 
-  if (send)
-    *send = stream->send_hmac[0];
-  if (receive)
-    *receive = stream->receive_hmac[0];
+  if (send_key)
+    *send_key = stream->send_key[0];
+  if (receive_key)
+    *receive_key = stream->receive_key[0];
+  if (send_hmac)
+    *send_hmac = stream->send_hmac[0];
+  if (receive_hmac)
+    *receive_hmac = stream->receive_hmac[0];
 
   silc_mutex_unlock(stream->lock);
 
@@ -1195,10 +1218,10 @@ void silc_packet_free(SilcPacket packet)
 /* Prepare outgoing data buffer for packet sending.  Returns the
    pointer to that buffer into the `packet'. */
 
-static SilcBool silc_packet_send_prepare(SilcPacketStream stream,
-                                        SilcUInt32 totlen,
-                                        SilcHmac hmac,
-                                        SilcBuffer packet)
+static inline SilcBool silc_packet_send_prepare(SilcPacketStream stream,
+                                               SilcUInt32 totlen,
+                                               SilcHmac hmac,
+                                               SilcBuffer packet)
 {
   unsigned char *oldptr;
   unsigned int mac_len = hmac ? silc_hmac_len(hmac) : 0;
@@ -1206,7 +1229,7 @@ static SilcBool silc_packet_send_prepare(SilcPacketStream stream,
   totlen += mac_len;
 
   /* Allocate more space if needed */
-  if (silc_buffer_taillen(&stream->outbuf) < totlen) {
+  if (silc_unlikely(silc_buffer_taillen(&stream->outbuf) < totlen)) {
     if (!silc_buffer_realloc(&stream->outbuf,
                             silc_buffer_truelen(&stream->outbuf) + totlen))
       return FALSE;
@@ -1222,21 +1245,23 @@ static SilcBool silc_packet_send_prepare(SilcPacketStream stream,
   return TRUE;
 }
 
-/* Internal routine to send packet */
-
-static SilcBool silc_packet_send_raw(SilcPacketStream stream,
-                                    SilcPacketType type,
-                                    SilcPacketFlags flags,
-                                    SilcIdType src_id_type,
-                                    unsigned char *src_id,
-                                    SilcUInt32 src_id_len,
-                                    SilcIdType dst_id_type,
-                                    unsigned char *dst_id,
-                                    SilcUInt32 dst_id_len,
-                                    const unsigned char *data,
-                                    SilcUInt32 data_len,
-                                    SilcCipher cipher,
-                                    SilcHmac hmac)
+/* Internal routine to assemble outgoing packet.  Assembles and encryptes
+   the packet.  The silc_packet_stream_write needs to be called to send it
+   after this returns TRUE. */
+
+static inline SilcBool silc_packet_send_raw(SilcPacketStream stream,
+                                           SilcPacketType type,
+                                           SilcPacketFlags flags,
+                                           SilcIdType src_id_type,
+                                           unsigned char *src_id,
+                                           SilcUInt32 src_id_len,
+                                           SilcIdType dst_id_type,
+                                           unsigned char *dst_id,
+                                           SilcUInt32 dst_id_len,
+                                           const unsigned char *data,
+                                           SilcUInt32 data_len,
+                                           SilcCipher cipher,
+                                           SilcHmac hmac)
 {
   unsigned char tmppad[SILC_PACKET_MAX_PADLEN], iv[33], psn[4];
   int block_len = (cipher ? silc_cipher_get_block_len(cipher) : 0);
@@ -1299,8 +1324,8 @@ static SilcBool silc_packet_send_raw(SilcPacketStream stream,
   silc_mutex_lock(stream->lock);
 
   /* Get packet pointer from the outgoing buffer */
-  if (!silc_packet_send_prepare(stream, truelen + padlen + ivlen + psnlen,
-                               hmac, &packet)) {
+  if (silc_unlikely(!silc_packet_send_prepare(stream, truelen + padlen + ivlen
+                                             + psnlen, hmac, &packet))) {
     silc_mutex_unlock(stream->lock);
     return FALSE;
   }
@@ -1326,7 +1351,7 @@ static SilcBool silc_packet_send_raw(SilcPacketStream stream,
                         SILC_STR_DATA(tmppad, padlen),
                         SILC_STR_DATA(data, data_len),
                         SILC_STR_END);
-  if (i < 0) {
+  if (silc_unlikely(i < 0)) {
     silc_mutex_unlock(stream->lock);
     return FALSE;
   }
@@ -1335,10 +1360,11 @@ static SilcBool silc_packet_send_raw(SilcPacketStream stream,
                   silc_buffer_data(&packet), silc_buffer_len(&packet));
 
   /* Encrypt the packet */
-  if (cipher) {
+  if (silc_likely(cipher)) {
     SILC_LOG_DEBUG(("Encrypting packet"));
-    if (!silc_cipher_encrypt(cipher, packet.data + ivlen,
-                            packet.data + ivlen, enclen, NULL)) {
+    if (silc_unlikely(!silc_cipher_encrypt(cipher, packet.data + ivlen,
+                                          packet.data + ivlen, enclen,
+                                          NULL))) {
       SILC_LOG_ERROR(("Packet encryption failed"));
       silc_mutex_unlock(stream->lock);
       return FALSE;
@@ -1346,7 +1372,7 @@ static SilcBool silc_packet_send_raw(SilcPacketStream stream,
   }
 
   /* Compute HMAC */
-  if (hmac) {
+  if (silc_likely(hmac)) {
     SilcUInt32 mac_len;
 
     /* MAC is computed from the entire encrypted packet data, and put
@@ -1359,8 +1385,7 @@ static SilcBool silc_packet_send_raw(SilcPacketStream stream,
     stream->send_psn++;
   }
 
-  /* Write the packet to the stream */
-  return silc_packet_stream_write(stream);
+  return TRUE;
 }
 
 /* Sends a packet */
@@ -1369,16 +1394,21 @@ SilcBool silc_packet_send(SilcPacketStream stream,
                          SilcPacketType type, SilcPacketFlags flags,
                          const unsigned char *data, SilcUInt32 data_len)
 {
-  return silc_packet_send_raw(stream, type, flags,
-                             stream->src_id_type,
-                             stream->src_id,
-                             stream->src_id_len,
-                             stream->dst_id_type,
-                             stream->dst_id,
-                             stream->dst_id_len,
-                             data, data_len,
-                             stream->send_key[0],
-                             stream->send_hmac[0]);
+  SilcBool ret;
+
+  ret = silc_packet_send_raw(stream, type, flags,
+                            stream->src_id_type,
+                            stream->src_id,
+                            stream->src_id_len,
+                            stream->dst_id_type,
+                            stream->dst_id,
+                            stream->dst_id_len,
+                            data, data_len,
+                            stream->send_key[0],
+                            stream->send_hmac[0]);
+
+  /* Write the packet to the stream */
+  return ret ? silc_packet_stream_write(stream, FALSE) : FALSE;
 }
 
 /* Sends a packet, extended routine */
@@ -1392,6 +1422,7 @@ SilcBool silc_packet_send_ext(SilcPacketStream stream,
 {
   unsigned char src_id_data[32], dst_id_data[32];
   SilcUInt32 src_id_len, dst_id_len;
+  SilcBool ret;
 
   if (src_id)
     if (!silc_id_id2str(src_id, src_id_type, src_id_data,
@@ -1402,16 +1433,19 @@ SilcBool silc_packet_send_ext(SilcPacketStream stream,
                        sizeof(dst_id_data), &dst_id_len))
       return FALSE;
 
-  return silc_packet_send_raw(stream, type, flags,
-                             src_id ? src_id_type : stream->src_id_type,
-                             src_id ? src_id_data : stream->src_id,
-                             src_id ? src_id_len : stream->src_id_len,
-                             dst_id ? dst_id_type : stream->dst_id_type,
-                             dst_id ? dst_id_data : stream->dst_id,
-                             dst_id ? dst_id_len : stream->dst_id_len,
-                             data, data_len,
-                             cipher ? cipher : stream->send_key[0],
-                             hmac ? hmac : stream->send_hmac[0]);
+  ret = silc_packet_send_raw(stream, type, flags,
+                            src_id ? src_id_type : stream->src_id_type,
+                            src_id ? src_id_data : stream->src_id,
+                            src_id ? src_id_len : stream->src_id_len,
+                            dst_id ? dst_id_type : stream->dst_id_type,
+                            dst_id ? dst_id_data : stream->dst_id,
+                            dst_id ? dst_id_len : stream->dst_id_len,
+                            data, data_len,
+                            cipher ? cipher : stream->send_key[0],
+                            hmac ? hmac : stream->send_hmac[0]);
+
+  /* Write the packet to the stream */
+  return ret ? silc_packet_stream_write(stream, FALSE) : FALSE;
 }
 
 /* Sends packet after formatting the arguments to buffer */
@@ -1482,7 +1516,7 @@ static inline SilcBool silc_packet_check_mac(SilcHmac hmac,
                                             SilcUInt32 sequence)
 {
   /* Check MAC */
-  if (hmac) {
+  if (silc_likely(hmac)) {
     unsigned char mac[32], psn[4];
     SilcUInt32 mac_len;
 
@@ -1501,7 +1535,7 @@ static inline SilcBool silc_packet_check_mac(SilcHmac hmac,
     silc_hmac_final(hmac, mac, &mac_len);
 
     /* Compare the MAC's */
-    if (memcmp(packet_mac, mac, mac_len)) {
+    if (silc_unlikely(memcmp(packet_mac, mac, mac_len))) {
       SILC_LOG_DEBUG(("MAC failed"));
       return FALSE;
     }
@@ -1520,18 +1554,19 @@ static inline int silc_packet_decrypt(SilcCipher cipher, SilcHmac hmac,
                                      SilcBool normal)
 {
   if (normal == TRUE) {
-    if (cipher) {
+    if (silc_likely(cipher)) {
       /* Decrypt rest of the packet */
       SILC_LOG_DEBUG(("Decrypting the packet"));
-      if (!silc_cipher_decrypt(cipher, buffer->data, buffer->data,
-                              silc_buffer_len(buffer), NULL))
+      if (silc_unlikely(!silc_cipher_decrypt(cipher, buffer->data,
+                                            buffer->data,
+                                            silc_buffer_len(buffer), NULL)))
        return -1;
     }
     return 0;
 
   } else {
     /* Decrypt rest of the header plus padding */
-    if (cipher) {
+    if (silc_likely(cipher)) {
       SilcUInt16 len;
       SilcUInt32 block_len = silc_cipher_get_block_len(cipher);
 
@@ -1545,13 +1580,13 @@ static inline int silc_packet_decrypt(SilcCipher cipher, SilcHmac hmac,
             block_len);
       silc_buffer_pull(buffer, block_len);
 
-      if (len > silc_buffer_len(buffer)) {
+      if (silc_unlikely(len > silc_buffer_len(buffer))) {
        SILC_LOG_ERROR(("Garbage in header of packet, bad packet length, "
                        "packet dropped"));
        return -1;
       }
-      if (!silc_cipher_decrypt(cipher, buffer->data, buffer->data,
-                              len, NULL))
+      if (silc_unlikely(!silc_cipher_decrypt(cipher, buffer->data,
+                                            buffer->data, len, NULL)))
        return -1;
     }
 
@@ -1580,15 +1615,15 @@ static inline SilcBool silc_packet_parse(SilcPacket packet)
                             SILC_STR_UI_CHAR(&dst_id_len),
                             SILC_STR_UI_CHAR(&src_id_type),
                             SILC_STR_END);
-  if (ret == -1) {
+  if (silc_unlikely(ret == -1)) {
     if (!packet->stream->udp &&
        !silc_socket_stream_is_udp(packet->stream->stream, NULL))
       SILC_LOG_ERROR(("Malformed packet header, packet dropped"));
     return FALSE;
   }
 
-  if (src_id_len > SILC_PACKET_MAX_ID_LEN ||
-      dst_id_len > SILC_PACKET_MAX_ID_LEN) {
+  if (silc_unlikely(src_id_len > SILC_PACKET_MAX_ID_LEN ||
+                   dst_id_len > SILC_PACKET_MAX_ID_LEN)) {
     if (!packet->stream->udp &&
        !silc_socket_stream_is_udp(packet->stream->stream, NULL))
       SILC_LOG_ERROR(("Bad ID lengths in packet (%d and %d)",
@@ -1603,15 +1638,15 @@ static inline SilcBool silc_packet_parse(SilcPacket packet)
                             SILC_STR_DATA(&packet->dst_id, dst_id_len),
                             SILC_STR_OFFSET(padlen),
                             SILC_STR_END);
-  if (ret == -1) {
+  if (silc_unlikely(ret == -1)) {
     if (!packet->stream->udp &&
        !silc_socket_stream_is_udp(packet->stream->stream, NULL))
       SILC_LOG_ERROR(("Malformed packet header, packet dropped"));
     return FALSE;
   }
 
-  if (src_id_type > SILC_ID_CHANNEL ||
-      dst_id_type > SILC_ID_CHANNEL) {
+  if (silc_unlikely(src_id_type > SILC_ID_CHANNEL ||
+                   dst_id_type > SILC_ID_CHANNEL)) {
     if (!packet->stream->udp &&
        !silc_socket_stream_is_udp(packet->stream->stream, NULL))
       SILC_LOG_ERROR(("Bad ID types in packet (%d and %d)",
@@ -1634,9 +1669,10 @@ static inline SilcBool silc_packet_parse(SilcPacket packet)
   return TRUE;
 }
 
-/* Dispatch packet to application.  Called with stream->lock locked. */
+/* Dispatch packet to application.  Called with stream->lock locked.
+   Returns FALSE if the stream was destroyed while dispatching a packet. */
 
-static void silc_packet_dispatch(SilcPacket packet)
+static SilcBool silc_packet_dispatch(SilcPacket packet)
 {
   SilcPacketStream stream = packet->stream;
   SilcPacketProcess p;
@@ -1645,17 +1681,17 @@ static void silc_packet_dispatch(SilcPacket packet)
 
   /* Dispatch packet to all packet processors that want it */
 
-  if (!stream->process) {
+  if (silc_likely(!stream->process)) {
     /* Send to default processor as no others exist */
     SILC_LOG_DEBUG(("Dispatching packet to default callbacks"));
     silc_mutex_unlock(stream->lock);
-    if (!stream->engine->callbacks->
-       packet_receive(stream->engine, stream, packet,
-                      stream->engine->callback_context,
-                      stream->stream_context))
+    if (silc_unlikely(!stream->engine->callbacks->
+                     packet_receive(stream->engine, stream, packet,
+                                    stream->engine->callback_context,
+                                    stream->stream_context)))
       silc_packet_free(packet);
     silc_mutex_lock(stream->lock);
-    return;
+    return stream->destroyed == FALSE;
   }
 
   silc_dlist_start(stream->process);
@@ -1672,7 +1708,7 @@ static void silc_packet_dispatch(SilcPacket packet)
                         stream->engine->callback_context,
                         stream->stream_context)) {
        silc_mutex_lock(stream->lock);
-       return;
+       return stream->destroyed == FALSE;
       }
       silc_mutex_lock(stream->lock);
     }
@@ -1686,7 +1722,7 @@ static void silc_packet_dispatch(SilcPacket packet)
                                       p->callback_context,
                                       stream->stream_context)) {
        silc_mutex_lock(stream->lock);
-       return;
+       return stream->destroyed == FALSE;
       }
       silc_mutex_lock(stream->lock);
     } else {
@@ -1700,7 +1736,7 @@ static void silc_packet_dispatch(SilcPacket packet)
                                         p->callback_context,
                                         stream->stream_context)) {
          silc_mutex_lock(stream->lock);
-         return;
+         return stream->destroyed == FALSE;
        }
        silc_mutex_lock(stream->lock);
        break;
@@ -1717,13 +1753,14 @@ static void silc_packet_dispatch(SilcPacket packet)
                       stream->engine->callback_context,
                       stream->stream_context)) {
       silc_mutex_lock(stream->lock);
-      return;
+      return stream->destroyed == FALSE;
     }
     silc_mutex_lock(stream->lock);
   }
 
   /* If we got here, no one wanted the packet, so drop it */
   silc_packet_free(packet);
+  return stream->destroyed == FALSE;
 }
 
 /* Process incoming data and parse packets.  Called with stream->lock
@@ -1749,20 +1786,20 @@ static void silc_packet_read_process(SilcPacketStream stream)
     hmac = stream->receive_hmac[0];
     normal = FALSE;
 
-    if (silc_buffer_len(&stream->inbuf) <
-       (stream->iv_included ? SILC_PACKET_MIN_HEADER_LEN_IV :
-        SILC_PACKET_MIN_HEADER_LEN)) {
+    if (silc_unlikely(silc_buffer_len(&stream->inbuf) <
+                     (stream->iv_included ? SILC_PACKET_MIN_HEADER_LEN_IV :
+                      SILC_PACKET_MIN_HEADER_LEN))) {
       SILC_LOG_DEBUG(("Partial packet in queue, waiting for the rest"));
       return;
     }
 
-    if (hmac)
+    if (silc_likely(hmac))
       mac_len = silc_hmac_len(hmac);
     else
       mac_len = 0;
 
     /* Decrypt first block of the packet to get the length field out */
-    if (cipher) {
+    if (silc_likely(cipher)) {
       block_len = silc_cipher_get_block_len(cipher);
 
       if (stream->iv_included) {
@@ -1812,7 +1849,7 @@ static void silc_packet_read_process(SilcPacketStream stream)
     SILC_PACKET_LENGTH(header, packetlen, paddedlen);
 
     /* Sanity checks */
-    if (packetlen < SILC_PACKET_MIN_LEN) {
+    if (silc_unlikely(packetlen < SILC_PACKET_MIN_LEN)) {
       if (!stream->udp && !silc_socket_stream_is_udp(stream->stream, NULL))
        SILC_LOG_ERROR(("Received too short packet"));
       silc_mutex_unlock(stream->lock);
@@ -1832,10 +1869,11 @@ static void silc_packet_read_process(SilcPacketStream stream)
     }
 
     /* Check MAC of the packet */
-    if (!silc_packet_check_mac(hmac, stream->inbuf.data,
-                              paddedlen + ivlen,
-                              stream->inbuf.data + ivlen + paddedlen,
-                              packet_seq, stream->receive_psn)) {
+    if (silc_unlikely(!silc_packet_check_mac(hmac, stream->inbuf.data,
+                                            paddedlen + ivlen,
+                                            stream->inbuf.data + ivlen +
+                                            paddedlen, packet_seq,
+                                            stream->receive_psn))) {
       silc_mutex_unlock(stream->lock);
       SILC_PACKET_CALLBACK_ERROR(stream, SILC_PACKET_ERR_MAC_FAILED);
       silc_mutex_lock(stream->lock);
@@ -1846,7 +1884,7 @@ static void silc_packet_read_process(SilcPacketStream stream)
 
     /* Get packet */
     packet = silc_packet_alloc(stream->engine);
-    if (!packet) {
+    if (silc_unlikely(!packet)) {
       silc_mutex_unlock(stream->lock);
       SILC_PACKET_CALLBACK_ERROR(stream, SILC_PACKET_ERR_NO_MEMORY);
       silc_mutex_lock(stream->lock);
@@ -1857,7 +1895,7 @@ static void silc_packet_read_process(SilcPacketStream stream)
     packet->stream = stream;
 
     /* Allocate more space to packet buffer, if needed */
-    if (silc_buffer_truelen(&packet->buffer) < paddedlen) {
+    if (silc_unlikely(silc_buffer_truelen(&packet->buffer) < paddedlen)) {
       if (!silc_buffer_realloc(&packet->buffer,
                               silc_buffer_truelen(&packet->buffer) +
                               (paddedlen -
@@ -1903,11 +1941,11 @@ static void silc_packet_read_process(SilcPacketStream stream)
     silc_buffer_put(&packet->buffer, (stream->inbuf.data + ivlen +
                                      psnlen + (block_len - psnlen)),
                    paddedlen - ivlen - psnlen - (block_len - psnlen));
-    if (cipher) {
+    if (silc_likely(cipher)) {
       silc_cipher_set_iv(cipher, iv);
       ret = silc_packet_decrypt(cipher, hmac, stream->receive_psn,
                                &packet->buffer, normal);
-      if (ret < 0) {
+      if (silc_unlikely(ret < 0)) {
        silc_mutex_unlock(stream->lock);
        SILC_PACKET_CALLBACK_ERROR(stream, SILC_PACKET_ERR_DECRYPTION_FAILED);
        silc_mutex_lock(stream->lock);
@@ -1924,7 +1962,7 @@ static void silc_packet_read_process(SilcPacketStream stream)
     silc_buffer_pull(&stream->inbuf, paddedlen + mac_len);
 
     /* Parse the packet */
-    if (!silc_packet_parse(packet)) {
+    if (silc_unlikely(!silc_packet_parse(packet))) {
       silc_mutex_unlock(stream->lock);
       SILC_PACKET_CALLBACK_ERROR(stream, SILC_PACKET_ERR_MALFORMED);
       silc_mutex_lock(stream->lock);
@@ -1934,7 +1972,8 @@ static void silc_packet_read_process(SilcPacketStream stream)
     }
 
     /* Dispatch the packet to application */
-    silc_packet_dispatch(packet);
+    if (!silc_packet_dispatch(packet))
+      break;
   }
 
   silc_buffer_reset(&stream->inbuf);
@@ -1979,7 +2018,7 @@ silc_packet_wait_packet_receive(SilcPacketEngine engine,
   /* Signal the waiting thread for a new packet */
   silc_mutex_lock(pw->wait_lock);
 
-  if (pw->stopped) {
+  if (silc_unlikely(pw->stopped)) {
     silc_mutex_unlock(pw->wait_lock);
     return FALSE;
   }
@@ -2072,7 +2111,7 @@ int silc_packet_wait(void *waiter, int timeout, SilcPacket *return_packet)
 
   /* Wait here until packet has arrived */
   while (silc_list_count(pw->packet_queue) == 0) {
-    if (pw->stopped) {
+    if (silc_unlikely(pw->stopped)) {
       silc_mutex_unlock(pw->wait_lock);
       return -1;
     }