Fixed IPv4 checksum (network byte order, dimwit)
[tpg/acess2.git] / Modules / IPStack / ipv4.c
1 /*
2  * Acess2 IP Stack
3  * - IPv4 Protcol Handling
4  */
5 #include "ipstack.h"
6 #include "link.h"
7 #include "ipv4.h"
8 #include "firewall.h"
9
10 #define DEFAULT_TTL     32
11
12 // === IMPORTS ===
13 extern tInterface       *gIP_Interfaces;
14 extern void     ICMP_Initialise();
15 extern  int     ICMP_Ping(tInterface *Interface, tIPv4 Addr);
16 extern tMacAddr ARP_Resolve4(tInterface *Interface, tIPv4 Address);
17
18 // === PROTOTYPES ===
19  int    IPv4_Initialise();
20  int    IPv4_RegisterCallback(int ID, tIPCallback Callback);
21 void    IPv4_int_GetPacket(tAdapter *Interface, tMacAddr From, int Length, void *Buffer);
22 tInterface      *IPv4_GetInterface(tAdapter *Adapter, tIPv4 Address, int Broadcast);
23 Uint32  IPv4_Netmask(int FixedBits);
24 Uint16  IPv4_Checksum(const void *Buf, int Size);
25  int    IPv4_Ping(tInterface *Iface, tIPv4 Addr);
26
27 // === GLOBALS ===
28 tIPCallback     gaIPv4_Callbacks[256];
29
30 // === CODE ===
31 /**
32  * \brief Initialise the IPv4 Code
33  */
34 int IPv4_Initialise()
35 {
36         ICMP_Initialise();
37         Link_RegisterType(IPV4_ETHERNET_ID, IPv4_int_GetPacket);
38         return 1;
39 }
40
41 /**
42  * \brief Registers a callback
43  * \param ID    8-bit packet type ID
44  * \param Callback      Callback function
45  */
46 int IPv4_RegisterCallback(int ID, tIPCallback Callback)
47 {
48         if( ID < 0 || ID > 255 )        return 0;
49         if( gaIPv4_Callbacks[ID] )      return 0;
50         gaIPv4_Callbacks[ID] = Callback;
51         return 1;
52 }
53
54 /**
55  * \brief Creates and sends an IPv4 Packet
56  * \param Iface Interface
57  * \param Address       Destination IP
58  * \param Protocol      Protocol ID
59  * \param ID    Some random ID number
60  * \param Length        Data Length
61  * \param Data  Packet Data
62  * \return Boolean Success
63  */
64 int IPv4_SendPacket(tInterface *Iface, tIPv4 Address, int Protocol, int ID, int Length, const void *Data)
65 {
66         tMacAddr        to = ARP_Resolve4(Iface, Address);
67          int    bufSize = sizeof(tIPv4Header) + Length;
68         char    buf[bufSize];
69         tIPv4Header     *hdr = (void*)buf;
70          int    ret;
71         
72         // OUTPUT Firewall rule go here
73         ret = IPTablesV4_TestChain("OUTPUT",
74                 (tIPv4*)Iface->Address, &Address,
75                 Protocol, 0,
76                 Length, Data);
77         if(ret != 0) {
78                 // Just drop it (with an error)
79                 return 0;
80         }
81         
82         memcpy(&hdr->Options[0], Data, Length);
83         hdr->Version = 4;
84         hdr->HeaderLength = sizeof(tIPv4Header)/4;
85         hdr->DiffServices = 0;  // TODO: Check
86         
87         hdr->Reserved = 0;
88         hdr->DontFragment = 0;
89         hdr->MoreFragments = 0;
90         hdr->FragOffLow = 0;
91         hdr->FragOffHi = 0;
92         
93         hdr->TotalLength = htons( bufSize );
94         hdr->Identifcation = htons( ID );       // TODO: Check
95         hdr->TTL = DEFAULT_TTL;
96         hdr->Protocol = Protocol;
97         hdr->HeaderChecksum = 0;        // Will be set later
98         hdr->Source = *(tIPv4*)Iface->Address;
99         hdr->Destination = Address;
100         hdr->HeaderChecksum = IPv4_Checksum(hdr, sizeof(tIPv4Header));
101         
102         Log_Log("IPv4", "Sending packet to %i.%i.%i.%i",
103                 Address.B[0], Address.B[1], Address.B[2], Address.B[3]);
104         Link_SendPacket(Iface->Adapter, IPV4_ETHERNET_ID, to, bufSize, buf);
105         return 1;
106 }
107
108 /**
109  * \fn void IPv4_int_GetPacket(tInterface *Adapter, tMacAddr From, int Length, void *Buffer)
110  * \brief Process an IPv4 Packet
111  */
112 void IPv4_int_GetPacket(tAdapter *Adapter, tMacAddr From, int Length, void *Buffer)
113 {
114         tIPv4Header     *hdr = Buffer;
115         tInterface      *iface;
116         Uint8   *data;
117          int    dataLength;
118          int    ret;
119          
120         if(Length < sizeof(tIPv4Header))        return;
121         
122         #if 0
123         //Log_Log("IPv4", "Version = %i", hdr->Version);
124         //Log_Log("IPv4", "HeaderLength = %i", hdr->HeaderLength);
125         //Log_Log("IPv4", "DiffServices = %i", hdr->DiffServices);
126         Log_Debug("IPv4", "TotalLength = %i", ntohs(hdr->TotalLength) );
127         //Log_Log("IPv4", "Identifcation = %i", ntohs(hdr->Identifcation) );
128         //Log_Log("IPv4", "TTL = %i", hdr->TTL );
129         Log_Debug("IPv4", "Protocol = %i", hdr->Protocol );
130         //Log_Log("IPv4", "HeaderChecksum = 0x%x", ntohs(hdr->HeaderChecksum) );
131         Log_Debug("IPv4", "Source = %i.%i.%i.%i",
132                 hdr->Source.B[0], hdr->Source.B[1], hdr->Source.B[2], hdr->Source.B[3] );
133         Log_Debug("IPv4", "Destination = %i.%i.%i.%i",
134                 hdr->Destination.B[0], hdr->Destination.B[1],
135                 hdr->Destination.B[2], hdr->Destination.B[3] );
136         #endif  
137
138         // Check that the version IS IPv4
139         if(hdr->Version != 4) {
140                 Log_Log("IPv4", "hdr->Version(%i) != 4", hdr->Version);
141                 return;
142         }
143         
144         // Check Header checksum
145         {
146                 Uint16  hdrVal, compVal;
147                 hdrVal = hdr->HeaderChecksum;
148                 hdr->HeaderChecksum = 0;
149                 compVal = IPv4_Checksum(hdr, hdr->HeaderLength);
150                 if(hdrVal != compVal) {
151                         Log_Log("IPv4", "Header checksum fails (%04x != %04x)", hdrVal, compVal);
152                         return ;
153                 }
154                 hdr->HeaderChecksum = hdrVal;
155         }
156         
157         // Check Packet length
158         if( ntohs(hdr->TotalLength) > Length) {
159                 Log_Log("IPv4", "hdr->TotalLength(%i) > Length(%i)", ntohs(hdr->TotalLength), Length);
160                 return;
161         }
162         
163         // TODO: Handle packet fragmentation
164         
165         
166         // Get Data and Data Length
167         dataLength = ntohs(hdr->TotalLength) - sizeof(tIPv4Header);
168         data = &hdr->Options[0];
169         
170         // Get Interface (allowing broadcasts)
171         iface = IPv4_GetInterface(Adapter, hdr->Destination, 1);
172         
173         // Firewall rules
174         if( iface ) {
175                 // Incoming Packets
176                 ret = IPTablesV4_TestChain("INPUT",
177                         &hdr->Source, &hdr->Destination,
178                         hdr->Protocol, 0,
179                         dataLength, data
180                         );
181         }
182         else {
183                 // Routed packets
184                 ret = IPTablesV4_TestChain("FORWARD",
185                         &hdr->Source, &hdr->Destination,
186                         hdr->Protocol, 0,
187                         dataLength, data
188                         );
189         }
190         switch(ret)
191         {
192         // 0 - Allow
193         case 0: break;
194         // 1 - Silent Drop
195         case 1:
196                 Log_Debug("IPv4", "Silently dropping packet");
197                 return ;
198         // Unknown, silent drop
199         default:
200                 return ;
201         }
202         
203         // Routing
204         if(!iface)
205         {
206                 Log_Debug("IPv4", "Route the packet");
207                 
208                 // TODO: Parse Routing tables and determine where to send it
209                 
210                 return ;
211         }
212         
213         // Send it on
214         if( gaIPv4_Callbacks[hdr->Protocol] )
215                 gaIPv4_Callbacks[hdr->Protocol]( iface, &hdr->Source, dataLength, data );
216         else
217                 Log_Log("IPv4", "Unknown Protocol %i", hdr->Protocol);
218 }
219
220 /**
221  * \fn tInterface *IPv4_GetInterface(tAdapter *Adapter, tIPv4 Address)
222  * \brief Searches an adapter for a matching address
223  * \param Adapter       Incoming Adapter
224  * \param Address       Destination Address
225  * \param Broadcast     Allow broadcast packets
226  */
227 tInterface *IPv4_GetInterface(tAdapter *Adapter, tIPv4 Address, int Broadcast)
228 {
229         tInterface      *iface = NULL;
230         Uint32  netmask;
231         Uint32  addr, this;
232         
233         addr = ntohl( Address.L );
234         
235         for( iface = gIP_Interfaces; iface; iface = iface->Next)
236         {
237                 if( iface->Adapter != Adapter ) continue;
238                 if( iface->Type != 4 )  continue;
239                 if( IP4_EQU(Address, *(tIPv4*)iface->Address) )
240                         return iface;
241                 
242                 if( !Broadcast )        continue;
243                 
244                 this = ntohl( ((tIPv4*)iface->Address)->L );
245                 
246                 // Check for broadcast
247                 netmask = IPv4_Netmask(iface->SubnetBits);
248                 
249                 if( (addr & netmask) == (this & netmask)
250                  && (addr & ~netmask) == (0xFFFFFFFF & ~netmask) )
251                         return iface;
252         }
253         return NULL;
254 }
255
256 /**
257  * \brief Convert a network prefix to a netmask
258  * \param FixedBits     Netmask size (/n)
259  * 
260  * For example /24 will become 255.255.255.0
261  */
262 Uint32 IPv4_Netmask(int FixedBits)
263 {
264         Uint32  ret = 0xFFFFFFFF;
265         ret >>= (32-FixedBits);
266         ret <<= (32-FixedBits);
267         // Returns a native endian netmask
268         return ret;
269 }
270
271 /**
272  * \brief Calculate the IPv4 Checksum
273  * \param Buf   Input buffer
274  * \param Size  Size of input
275  * 
276  * One's complement sum of all 16-bit words (bitwise inverted)
277  */
278 Uint16 IPv4_Checksum(const void *Buf, int Size)
279 {
280         Uint16  sum = 0;
281         const Uint16    *arr = Buf;
282          int    i;
283         
284         Size = (Size + 1) >> 1; // 16-bit word count
285         for(i = 0; i < Size; i++ )
286         {
287                 Uint16  val = ntohs(arr[i]);
288                 if((int)sum + val > 0xFFFF)
289                         sum ++; // Simulate 1's complement
290                 sum += val;
291         }
292         return ~sum ;
293 }
294
295 /**
296  * \brief Sends an ICMP Echo and waits for a reply
297  * \param IFace Interface
298  * \param Addr  Destination address
299  */
300 int IPv4_Ping(tInterface *IFace, tIPv4 Addr)
301 {
302         return ICMP_Ping(IFace, Addr);
303 }

UCC git Repository :: git.ucc.asn.au