Modules/IPStack - Fix page fault in TCP, quietened some things
[tpg/acess2.git] / KernelLand / Modules / IPStack / ipv4.c
1 /*
2  * Acess2 IP Stack
3  * - IPv4 Protcol Handling
4  */
5 #define DEBUG   0
6 #include "ipstack.h"
7 #include "link.h"
8 #include "ipv4.h"
9 #include "firewall.h"
10
11 // === CONSTANTS ===
12 #define DEFAULT_TTL     32
13 #define IPV4_TRACE      1       // set to 1 to enable packet tracing
14
15 // === IMPORTS ===
16 extern tInterface       *gIP_Interfaces;
17 extern void     ICMP_Initialise();
18 extern  int     ICMP_Ping(tInterface *Interface, tIPv4 Addr);
19 extern tMacAddr ARP_Resolve4(tInterface *Interface, tIPv4 Address);
20 extern void     ARP_UpdateCache4(tIPv4 SWAddr, tMacAddr HWAddr);
21
22 // === PROTOTYPES ===
23  int    IPv4_Initialise();
24  int    IPv4_RegisterCallback(int ID, tIPCallback Callback);
25 void    IPv4_int_GetPacket(tAdapter *Interface, tMacAddr From, int Length, void *Buffer);
26 tInterface      *IPv4_GetInterface(tAdapter *Adapter, tIPv4 Address, int Broadcast);
27 Uint32  IPv4_Netmask(int FixedBits);
28 Uint16  IPv4_Checksum(const void *Buf, size_t Length);
29  int    IPv4_Ping(tInterface *Iface, tIPv4 Addr);
30
31 // === GLOBALS ===
32 tIPCallback     gaIPv4_Callbacks[256];
33
34 // === CODE ===
35 /**
36  * \brief Initialise the IPv4 Code
37  */
38 int IPv4_Initialise()
39 {
40         ICMP_Initialise();
41         Link_RegisterType(IPV4_ETHERNET_ID, IPv4_int_GetPacket);
42         return 1;
43 }
44
45 /**
46  * \brief Registers a callback
47  * \param ID    8-bit packet type ID
48  * \param Callback      Callback function
49  */
50 int IPv4_RegisterCallback(int ID, tIPCallback Callback)
51 {
52         if( ID < 0 || ID > 255 )        return 0;
53         if( gaIPv4_Callbacks[ID] )      return 0;
54         gaIPv4_Callbacks[ID] = Callback;
55         return 1;
56 }
57
58 /**
59  * \brief Creates and sends an IPv4 Packet
60  * \param Iface Interface
61  * \param Address       Destination IP
62  * \param Protocol      Protocol ID
63  * \param ID    Some random ID number
64  * \param Length        Data Length
65  * \param Data  Packet Data
66  * \return Boolean Success
67  */
68 int IPv4_SendPacket(tInterface *Iface, tIPv4 Address, int Protocol, int ID, tIPStackBuffer *Buffer)
69 {
70         tMacAddr        to;
71         tIPv4Header     hdr;
72          int    length;
73
74         length = IPStack_Buffer_GetLength(Buffer);
75         
76         // --- Resolve destination MAC address
77         to = ARP_Resolve4(Iface, Address);
78         if( MAC_EQU(to, cMAC_ZERO) ) {
79                 // No route to host
80                 Log_Notice("IPv4", "No route to host %i.%i.%i.%i",
81                         Address.B[0], Address.B[1], Address.B[2], Address.B[3]);
82                 return 0;
83         }
84         
85         // --- Handle OUTPUT firewall rules
86         // TODO: Update firewall rules for tIPStackBuffer
87         #if 0
88         int ret = IPTables_TestChain("OUTPUT",
89                 4, (tIPv4*)Iface->Address, &Address,
90                 Protocol, 0,
91                 length, Data);
92         if(ret > 0) {
93                 // Just drop it (with an error)
94                 Log_Notice("IPv4", "Firewall dropped packet");
95                 return 0;
96         }
97         #endif
98
99         // --- Initialise header        
100         hdr.Version = 4;
101         hdr.HeaderLength = sizeof(tIPv4Header)/4;
102         hdr.DiffServices = 0;   // TODO: Check
103         
104         hdr.Reserved = 0;
105         hdr.DontFragment = 0;
106         hdr.MoreFragments = 0;
107         hdr.FragOffLow = 0;
108         hdr.FragOffHi = 0;
109         
110         hdr.TotalLength = htons( sizeof(tIPv4Header) + length );
111         hdr.Identifcation = htons( ID );        // TODO: Check
112         hdr.TTL = DEFAULT_TTL;
113         hdr.Protocol = Protocol;
114         hdr.HeaderChecksum = 0; // Will be set later
115         hdr.Source = *(tIPv4*)Iface->Address;
116         hdr.Destination = Address;
117
118         // Actually set checksum (zeroed above)
119         hdr.HeaderChecksum = htons( IPv4_Checksum(&hdr, sizeof(tIPv4Header)) );
120
121         IPStack_Buffer_AppendSubBuffer(Buffer, sizeof(tIPv4Header), 0, &hdr, NULL, NULL);
122
123         #if IPV4_TRACE
124         Log_Log("IPv4", "Sending packet to %i.%i.%i.%i",
125                 Address.B[0], Address.B[1], Address.B[2], Address.B[3]);
126         #endif
127         Link_SendPacket(Iface->Adapter, IPV4_ETHERNET_ID, to, Buffer);
128         return 1;
129 }
130
131 /**
132  * \fn void IPv4_int_GetPacket(tInterface *Adapter, tMacAddr From, int Length, void *Buffer)
133  * \brief Process an IPv4 Packet
134  */
135 void IPv4_int_GetPacket(tAdapter *Adapter, tMacAddr From, int Length, void *Buffer)
136 {
137         tIPv4Header     *hdr = Buffer;
138         tInterface      *iface;
139         Uint8   *data;
140          int    dataLength;
141          int    ret;
142         
143         if(Length < sizeof(tIPv4Header))        return;
144         
145         #if 0
146         //Log_Log("IPv4", "Version = %i", hdr->Version);
147         //Log_Log("IPv4", "HeaderLength = %i", hdr->HeaderLength);
148         //Log_Log("IPv4", "DiffServices = %i", hdr->DiffServices);
149         Log_Debug("IPv4", "TotalLength = %i", ntohs(hdr->TotalLength) );
150         //Log_Log("IPv4", "Identifcation = %i", ntohs(hdr->Identifcation) );
151         //Log_Log("IPv4", "TTL = %i", hdr->TTL );
152         Log_Debug("IPv4", "Protocol = %i", hdr->Protocol );
153         //Log_Log("IPv4", "HeaderChecksum = 0x%x", ntohs(hdr->HeaderChecksum) );
154         Log_Debug("IPv4", "Source = %i.%i.%i.%i",
155                 hdr->Source.B[0], hdr->Source.B[1], hdr->Source.B[2], hdr->Source.B[3] );
156         Log_Debug("IPv4", "Destination = %i.%i.%i.%i",
157                 hdr->Destination.B[0], hdr->Destination.B[1],
158                 hdr->Destination.B[2], hdr->Destination.B[3] );
159         #endif  
160
161         // Check that the version IS IPv4
162         if(hdr->Version != 4) {
163                 Log_Log("IPv4", "hdr->Version(%i) != 4", hdr->Version);
164                 return;
165         }
166         
167         // Check Header checksum
168         {
169                 Uint16  hdrVal, compVal;
170                 hdrVal = ntohs(hdr->HeaderChecksum);
171                 hdr->HeaderChecksum = 0;
172                 compVal = IPv4_Checksum(hdr, hdr->HeaderLength * 4);
173                 if(hdrVal != compVal) {
174                         Log_Log("IPv4", "Header checksum fails (%04x != %04x)", hdrVal, compVal);
175                         return ;
176                 }
177                 hdr->HeaderChecksum = hdrVal;
178         }
179         
180         // Check Packet length
181         if( ntohs(hdr->TotalLength) > Length) {
182                 Log_Log("IPv4", "hdr->TotalLength(%i) > Length(%i)", ntohs(hdr->TotalLength), Length);
183                 return;
184         }
185         
186         // TODO: Handle packet fragmentation
187         
188         #if IPV4_TRACE
189         Log_Debug("IPv4", "Proto 0x%x From %i.%i.%i.%i to %i.%i.%i.%i",
190                 hdr->Protocol,
191                 hdr->Source.B[0], hdr->Source.B[1], hdr->Source.B[2], hdr->Source.B[3],
192                 hdr->Destination.B[0], hdr->Destination.B[1], hdr->Destination.B[2], hdr->Destination.B[3]
193                 );
194         #endif
195         
196         // Get Data and Data Length
197         dataLength = ntohs(hdr->TotalLength) - sizeof(tIPv4Header);
198         data = &hdr->Options[0];
199
200         // Populate ARP cache from sniffing.
201         // - Downside: Poisoning, polluting from routed packets
202         //ARP_UpdateCache4(hdr->Source, From);
203         
204         // Get Interface (allowing broadcasts)
205         iface = IPv4_GetInterface(Adapter, hdr->Destination, 1);
206         
207         // Firewall rules
208         if( iface ) {
209                 // Incoming Packets
210                 ret = IPTables_TestChain("INPUT",
211                         4, &hdr->Source, &hdr->Destination,
212                         hdr->Protocol, 0,
213                         dataLength, data
214                         );
215         }
216         else {
217                 // Routed packets
218                 ret = IPTables_TestChain("FORWARD",
219                         4, &hdr->Source, &hdr->Destination,
220                         hdr->Protocol, 0,
221                         dataLength, data
222                         );
223         }
224         switch(ret)
225         {
226         // 0 - Allow
227         case 0: break;
228         // 1 - Silent Drop
229         case 1:
230                 Log_Debug("IPv4", "Silently dropping packet");
231                 return ;
232         case -1:
233                 // Bad rule
234                 break ;
235         // Unknown, silent drop
236         default:
237                 Log_Warning("IPv4", "Unknown firewall rule");
238                 return ;
239         }
240         
241         // Routing
242         if(!iface)
243         {
244                 #if 0
245                 tMacAddr        to;
246                 tRoute  *rt;
247         
248
249                 // TODO: Put this in another thread to avoid delays in the RX thread    
250                 Log_Debug("IPv4", "Route the packet");
251                 // Drop the packet if the TTL is zero
252                 if( hdr->TTL == 0 ) {
253                         Log_Warning("IPv4", "TODO: Send ICMP-Timeout when TTL exceeded");
254                         return ;
255                 }
256                 
257                 hdr->TTL --;
258                 
259                 rt = IPStack_FindRoute(4, NULL, &hdr->Destination);     // Get the route (gets the interface)
260                 if( !rt || !rt->Interface )
261                         return ;
262                 to = ARP_Resolve4(rt->Interface, hdr->Destination);     // Resolve address
263                 if( MAC_EQU(to, cMAC_ZERO) )
264                         return ;
265                 
266                 // Send packet
267                 Log_Log("IPv4", "Forwarding packet to %i.%i.%i.%i (via %i.%i.%i.%i)",
268                         hdr->Destination.B[0], hdr->Destination.B[1],
269                         hdr->Destination.B[2], hdr->Destination.B[3],
270                         ((tIPv4*)rt->NextHop)->B[0], ((tIPv4*)rt->NextHop)->B[1],
271                         ((tIPv4*)rt->NextHop)->B[2], ((tIPv4*)rt->NextHop)->B[3]);
272                 Log_Warning("IPv4", "TODO: Implement forwarding with tIPStackBuffer");
273 //              Link_SendPacket(rt->Interface->Adapter, IPV4_ETHERNET_ID, to, Length, Buffer);
274                 #endif
275                 
276                 return ;
277         }
278
279         // Populate ARP cache from recieved packets
280         // - Should be safe
281         ARP_UpdateCache4(hdr->Source, From);
282         
283         // Send it on
284         if( !gaIPv4_Callbacks[hdr->Protocol] ) {
285                 Log_Log("IPv4", "Unknown Protocol %i", hdr->Protocol);
286                 return ;
287         }
288         
289         gaIPv4_Callbacks[hdr->Protocol]( iface, &hdr->Source, dataLength, data );
290 }
291
292 /**
293  * \fn tInterface *IPv4_GetInterface(tAdapter *Adapter, tIPv4 Address)
294  * \brief Searches an adapter for a matching address
295  * \param Adapter       Incoming Adapter
296  * \param Address       Destination Address
297  * \param Broadcast     Allow broadcast packets
298  */
299 tInterface *IPv4_GetInterface(tAdapter *Adapter, tIPv4 Address, int Broadcast)
300 {
301         tInterface      *iface = NULL, *zero_iface = NULL;
302         Uint32  netmask;
303         Uint32  addr, this;
304
305         ENTER("pAdapter xAddress bBroadcast", Adapter, Address, Broadcast);     
306
307         addr = ntohl( Address.L );
308         LOG("addr = 0x%x", addr);
309         
310         for( iface = gIP_Interfaces; iface; iface = iface->Next)
311         {
312                 if( iface->Adapter != Adapter ) continue;
313                 if( iface->Type != 4 )  continue;
314                 if( IP4_EQU(Address, *(tIPv4*)iface->Address) ) {
315                         LOG("Exact match");
316                         LEAVE('p', iface);
317                         return iface;
318                 }
319
320                 LOG("iface->Address = 0x%x", *(Uint32*)iface->Address);
321
322                 if( *(Uint32*)iface->Address == 0 ) {
323                         if( zero_iface ) {
324                                 Log_Notice("IPv4", "Multiple 0.0.0.0 interfaces on the same adapter, ignoring");
325                         }
326                         else {
327                                 zero_iface = iface;
328                                 LOG("Zero IF %p", iface);
329                         }
330                         continue ;
331                 }               
332
333                 if( !Broadcast )        continue;
334                 
335                 // Check for broadcast
336                 this = ntohl( ((tIPv4*)iface->Address)->L );
337                 netmask = IPv4_Netmask(iface->SubnetBits);
338                 LOG("iface addr = 0x%x, netmask = 0x%x (bits = %i)", this, netmask, iface->SubnetBits);
339
340                 if( (addr & netmask) == (this & netmask) && (addr & ~netmask) == (0xFFFFFFFF & ~netmask) )
341                 {
342                         LOG("Broadcast match");
343                         LEAVE('p', iface);
344                         return iface;
345                 }
346         }
347
348         // Special case for intefaces that are being DHCP configured
349         // - If the interface address is 0.0.0.0, then if there is no match for the
350         //   destination the packet is treated as if it was addressed to 0.0.0.0
351         if( zero_iface && Broadcast )
352         {
353                 LOG("Using 0.0.0.0 interface with magic!");
354                 LEAVE('p', zero_iface);
355                 return zero_iface;
356         }
357
358         LEAVE('n');
359         return NULL;
360 }
361
362 /**
363  * \brief Convert a network prefix to a netmask
364  * \param FixedBits     Netmask size (/n)
365  * 
366  * For example /24 will become 255.255.255.0 (0xFFFFFF00)
367  */
368 Uint32 IPv4_Netmask(int FixedBits)
369 {
370         Uint32  ret = 0xFFFFFFFF;
371         if( FixedBits == 0 )
372                 return 0;
373         if( FixedBits < 32 )
374         {
375                 ret >>= (32-FixedBits);
376                 ret <<= (32-FixedBits);
377         }
378         // Returns a native endian netmask
379         return ret;
380 }
381
382 /**
383  * \brief Calculate the IPv4 Checksum
384  * \param Buf   Input buffer
385  * \param Size  Size of input
386  * 
387  * One's complement sum of all 16-bit words (bitwise inverted)
388  */
389 Uint16 IPv4_Checksum(const void *Buf, size_t Length)
390 {
391         const Uint16    *words = Buf;
392         Uint32  sum = 0;
393          int    i;
394         
395         // Sum all whole words
396         for(i = 0; i < Length/2; i++ )
397         {
398                 sum += ntohs(words[i]);
399         }
400         if( Length & 1 )
401                 sum += ntohs( words[i] & 0xFF );
402         
403         // Apply one's complement
404         while (sum >> 16)
405                 sum = (sum & 0xFFFF) + (sum >> 16);
406         
407         return ~sum;
408 }
409
410 /**
411  * \brief Sends an ICMP Echo and waits for a reply
412  * \param IFace Interface
413  * \param Addr  Destination address
414  */
415 int IPv4_Ping(tInterface *IFace, tIPv4 Addr)
416 {
417         return ICMP_Ping(IFace, Addr);
418 }

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