From bbac2ece529eb51593a12a208411473a27563254 Mon Sep 17 00:00:00 2001
From: James R T <jamestiotio@gmail.com>
Date: Sun, 17 Mar 2024 23:18:02 +0800
Subject: [PATCH] Replace remaining `rfind_pdu` calls to `find_pdu` in `src`
 directory (#527)

This commit replaces the remaining `rfind_pdu` calls to `find_pdu` in
the `src` directory. Any existing `rfind_pdu` calls in the `examples`
and `tests` directories are unmodified.

The main motivation is that conditional statements are generally more
performant than exception handling. Since `rfind_pdu` calls `find_pdu`
internally anyway, this eliminates some overhead as well.

Signed-off-by: James Raphael Tiovalen <jamestiotio@gmail.com>
---
 src/crypto.cpp        | 7 +++++--
 src/tcp_ip/stream.cpp | 8 +++++---
 2 files changed, 10 insertions(+), 5 deletions(-)

diff --git a/src/crypto.cpp b/src/crypto.cpp
index cf335303..a908f079 100644
--- a/src/crypto.cpp
+++ b/src/crypto.cpp
@@ -705,8 +705,11 @@ WPA2Decrypter::bssids_map::const_iterator WPA2Decrypter::find_ap(const Dot11Data
 
 bool WPA2Decrypter::decrypt(PDU& pdu) {
     if (capturer_.process_packet(pdu)) {
-        try_add_keys(pdu.rfind_pdu<Dot11Data>(), capturer_.handshakes().front());
-        capturer_.clear_handshakes();
+        Dot11Data* data = pdu.find_pdu<Dot11Data>();
+        if (data) {
+            try_add_keys(*data, capturer_.handshakes().front());
+            capturer_.clear_handshakes();
+        }
     }
     else if (const Dot11Beacon* beacon = pdu.find_pdu<Dot11Beacon>()) {
         if (aps_.count(beacon->addr3()) == 0) {
diff --git a/src/tcp_ip/stream.cpp b/src/tcp_ip/stream.cpp
index 1274b803..f788d878 100644
--- a/src/tcp_ip/stream.cpp
+++ b/src/tcp_ip/stream.cpp
@@ -59,9 +59,11 @@ Stream::Stream(PDU& packet, const timestamp_type& ts)
         client_hw_addr_ = eth->src_addr();
         server_hw_addr_ = eth->dst_addr();
     }
-    const TCP& tcp = packet.rfind_pdu<TCP>();
-    // If this is not the first packet of a stream (SYN), then it's a partial stream
-    is_partial_stream_ = !tcp.has_flags(TCP::SYN);
+    const TCP* tcp = packet.find_pdu<TCP>();
+    if (tcp) {
+        // If this is not the first packet of a stream (SYN), then it's a partial stream
+        is_partial_stream_ = !tcp->has_flags(TCP::SYN);
+    }
 }
 
 void Stream::process_packet(PDU& packet, const timestamp_type& ts) {