chiark / gitweb /
sd-dhcp: avoid checksum calculation if possible
[elogind.git] / src / libsystemd-network / dhcp-packet.c
index bed942f..4f90c28 100644 (file)
@@ -130,6 +130,11 @@ int dhcp_packet_verify_headers(DHCPPacket *packet, size_t len, bool checksum) {
                 return -EINVAL;
         }
 
+        if (packet->ip.version != IPVERSION) {
+                log_dhcp_client(client, "ignoring packet: not IPv4");
+                return -EINVAL;
+        }
+
         if (packet->ip.ihl < 5) {
                 log_dhcp_client(client, "ignoring packet: IPv4 IHL (%u words) invalid",
                                 packet->ip.ihl);
@@ -150,13 +155,13 @@ int dhcp_packet_verify_headers(DHCPPacket *packet, size_t len, bool checksum) {
                 return -EINVAL;
         }
 
-        if (dhcp_packet_checksum(&packet->ip, hdrlen)) {
-                log_dhcp_client(client, "ignoring packet: invalid IP checksum");
+        /* UDP */
+
+        if (packet->ip.protocol != IPPROTO_UDP) {
+                log_dhcp_client(client, "ignoring packet: not UDP");
                 return -EINVAL;
         }
 
-        /* UDP */
-
         if (len < DHCP_IP_UDP_SIZE) {
                 log_dhcp_client(client, "ignoring packet: packet (%zu bytes) "
                                 " smaller than IP+UDP header (%u bytes)", len,
@@ -171,6 +176,22 @@ int dhcp_packet_verify_headers(DHCPPacket *packet, size_t len, bool checksum) {
                 return -EINVAL;
         }
 
+        if (be16toh(packet->udp.dest) != DHCP_PORT_CLIENT) {
+                log_dhcp_client(client, "ignoring packet: to port %u, which "
+                                "is not the DHCP client port (%u)",
+                                be16toh(packet->udp.dest), DHCP_PORT_CLIENT);
+                return -EINVAL;
+        }
+
+        /* checksums - computing these is relatively expensive, so only do it
+           if all the other checks have passed
+         */
+
+        if (dhcp_packet_checksum(&packet->ip, hdrlen)) {
+                log_dhcp_client(client, "ignoring packet: invalid IP checksum");
+                return -EINVAL;
+        }
+
         if (checksum && packet->udp.check) {
                 packet->ip.check = packet->udp.len;
                 packet->ip.ttl = 0;
@@ -182,12 +203,5 @@ int dhcp_packet_verify_headers(DHCPPacket *packet, size_t len, bool checksum) {
                 }
         }
 
-        if (be16toh(packet->udp.dest) != DHCP_PORT_CLIENT) {
-                log_dhcp_client(client, "ignoring packet: to port %u, which "
-                                "is not the DHCP client port (%u)",
-                                be16toh(packet->udp.dest), DHCP_PORT_CLIENT);
-                return -EINVAL;
-        }
-
         return 0;
 }