Networking - Heaps of changes
[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         if( MAC_EQU(to, cMAC_ZERO) ) {
73                 // No route to host
74                 Log_Notice("IPv4", "No route to host %i.%i.%i.%i",
75                         Address.B[0], Address.B[1], Address.B[2], Address.B[3]);
76                 return 0;
77         }
78         
79         // OUTPUT Firewall rule go here
80         ret = IPTables_TestChain("OUTPUT",
81                 4, (tIPv4*)Iface->Address, &Address,
82                 Protocol, 0,
83                 Length, Data);
84         if(ret > 0) {
85                 // Just drop it (with an error)
86                 Log_Notice("IPv4", "Firewall dropped packet");
87                 return 0;
88         }
89         
90         memcpy(&hdr->Options[0], Data, Length);
91         hdr->Version = 4;
92         hdr->HeaderLength = sizeof(tIPv4Header)/4;
93         hdr->DiffServices = 0;  // TODO: Check
94         
95         hdr->Reserved = 0;
96         hdr->DontFragment = 0;
97         hdr->MoreFragments = 0;
98         hdr->FragOffLow = 0;
99         hdr->FragOffHi = 0;
100         
101         hdr->TotalLength = htons( bufSize );
102         hdr->Identifcation = htons( ID );       // TODO: Check
103         hdr->TTL = DEFAULT_TTL;
104         hdr->Protocol = Protocol;
105         hdr->HeaderChecksum = 0;        // Will be set later
106         hdr->Source = *(tIPv4*)Iface->Address;
107         hdr->Destination = Address;
108         hdr->HeaderChecksum = htons(IPv4_Checksum(hdr, sizeof(tIPv4Header)));
109         
110         Log_Log("IPv4", "Sending packet to %i.%i.%i.%i",
111                 Address.B[0], Address.B[1], Address.B[2], Address.B[3]);
112         Link_SendPacket(Iface->Adapter, IPV4_ETHERNET_ID, to, bufSize, buf);
113         return 1;
114 }
115
116 /**
117  * \fn void IPv4_int_GetPacket(tInterface *Adapter, tMacAddr From, int Length, void *Buffer)
118  * \brief Process an IPv4 Packet
119  */
120 void IPv4_int_GetPacket(tAdapter *Adapter, tMacAddr From, int Length, void *Buffer)
121 {
122         tIPv4Header     *hdr = Buffer;
123         tInterface      *iface;
124         Uint8   *data;
125          int    dataLength;
126          int    ret;
127         
128         if(Length < sizeof(tIPv4Header))        return;
129         
130         #if 0
131         //Log_Log("IPv4", "Version = %i", hdr->Version);
132         //Log_Log("IPv4", "HeaderLength = %i", hdr->HeaderLength);
133         //Log_Log("IPv4", "DiffServices = %i", hdr->DiffServices);
134         Log_Debug("IPv4", "TotalLength = %i", ntohs(hdr->TotalLength) );
135         //Log_Log("IPv4", "Identifcation = %i", ntohs(hdr->Identifcation) );
136         //Log_Log("IPv4", "TTL = %i", hdr->TTL );
137         Log_Debug("IPv4", "Protocol = %i", hdr->Protocol );
138         //Log_Log("IPv4", "HeaderChecksum = 0x%x", ntohs(hdr->HeaderChecksum) );
139         Log_Debug("IPv4", "Source = %i.%i.%i.%i",
140                 hdr->Source.B[0], hdr->Source.B[1], hdr->Source.B[2], hdr->Source.B[3] );
141         Log_Debug("IPv4", "Destination = %i.%i.%i.%i",
142                 hdr->Destination.B[0], hdr->Destination.B[1],
143                 hdr->Destination.B[2], hdr->Destination.B[3] );
144         #endif  
145
146         // Check that the version IS IPv4
147         if(hdr->Version != 4) {
148                 Log_Log("IPv4", "hdr->Version(%i) != 4", hdr->Version);
149                 return;
150         }
151         
152         // Check Header checksum
153         {
154                 Uint16  hdrVal, compVal;
155                 hdrVal = ntohs(hdr->HeaderChecksum);
156                 hdr->HeaderChecksum = 0;
157                 compVal = IPv4_Checksum(hdr, hdr->HeaderLength * 4);
158                 if(hdrVal != compVal) {
159                         Log_Log("IPv4", "Header checksum fails (%04x != %04x)", hdrVal, compVal);
160                         return ;
161                 }
162                 hdr->HeaderChecksum = hdrVal;
163         }
164         
165         // Check Packet length
166         if( ntohs(hdr->TotalLength) > Length) {
167                 Log_Log("IPv4", "hdr->TotalLength(%i) > Length(%i)", ntohs(hdr->TotalLength), Length);
168                 return;
169         }
170         
171         // TODO: Handle packet fragmentation
172         
173         
174         // Get Data and Data Length
175         dataLength = ntohs(hdr->TotalLength) - sizeof(tIPv4Header);
176         data = &hdr->Options[0];
177         
178         // Get Interface (allowing broadcasts)
179         iface = IPv4_GetInterface(Adapter, hdr->Destination, 1);
180         
181         // Firewall rules
182         if( iface ) {
183                 // Incoming Packets
184                 ret = IPTables_TestChain("INPUT",
185                         4, &hdr->Source, &hdr->Destination,
186                         hdr->Protocol, 0,
187                         dataLength, data
188                         );
189         }
190         else {
191                 // Routed packets
192                 ret = IPTables_TestChain("FORWARD",
193                         4, &hdr->Source, &hdr->Destination,
194                         hdr->Protocol, 0,
195                         dataLength, data
196                         );
197         }
198         switch(ret)
199         {
200         // 0 - Allow
201         case 0: break;
202         // 1 - Silent Drop
203         case 1:
204                 Log_Debug("IPv4", "Silently dropping packet");
205                 return ;
206         case -1:
207                 // Bad rule
208                 break ;
209         // Unknown, silent drop
210         default:
211                 Log_Warning("IPv4", "Unknown firewall rule");
212                 return ;
213         }
214         
215         // Routing
216         if(!iface)
217         {
218                 tMacAddr        to;
219                 tRoute  *rt;
220                 
221                 Log_Debug("IPv4", "Route the packet");
222                 // Drop the packet if the TTL is zero
223                 if( hdr->TTL == 0 ) {
224                         Log_Warning("IPv4", "TODO: Sent ICMP-Timeout when TTL exceeded");
225                         return ;
226                 }
227                 
228                 hdr->TTL --;
229                 
230                 rt = IPStack_FindRoute(4, NULL, &hdr->Destination);     // Get the route (gets the interface)
231                 to = ARP_Resolve4(rt->Interface, hdr->Destination);     // Resolve address
232                 if( MAC_EQU(to, cMAC_ZERO) )
233                         return ;
234                 
235                 // Send packet
236                 Log_Log("IPv4", "Forwarding packet to %i.%i.%i.%i (via %i.%i.%i.%i)",
237                         hdr->Destination.B[0], hdr->Destination.B[1],
238                         hdr->Destination.B[2], hdr->Destination.B[3],
239                         ((tIPv4*)rt->NextHop)->B[0], ((tIPv4*)rt->NextHop)->B[1],
240                         ((tIPv4*)rt->NextHop)->B[2], ((tIPv4*)rt->NextHop)->B[3]);
241                 Link_SendPacket(rt->Interface->Adapter, IPV4_ETHERNET_ID, to, Length, Buffer);
242                 
243                 
244                 return ;
245         }
246         
247         // Send it on
248         if( !gaIPv4_Callbacks[hdr->Protocol] ) {
249                 Log_Log("IPv4", "Unknown Protocol %i", hdr->Protocol);
250                 return ;
251         }
252         
253         gaIPv4_Callbacks[hdr->Protocol]( iface, &hdr->Source, dataLength, data );
254 }
255
256 /**
257  * \fn tInterface *IPv4_GetInterface(tAdapter *Adapter, tIPv4 Address)
258  * \brief Searches an adapter for a matching address
259  * \param Adapter       Incoming Adapter
260  * \param Address       Destination Address
261  * \param Broadcast     Allow broadcast packets
262  */
263 tInterface *IPv4_GetInterface(tAdapter *Adapter, tIPv4 Address, int Broadcast)
264 {
265         tInterface      *iface = NULL;
266         Uint32  netmask;
267         Uint32  addr, this;
268         
269         addr = ntohl( Address.L );
270         
271         for( iface = gIP_Interfaces; iface; iface = iface->Next)
272         {
273                 if( iface->Adapter != Adapter ) continue;
274                 if( iface->Type != 4 )  continue;
275                 if( IP4_EQU(Address, *(tIPv4*)iface->Address) )
276                         return iface;
277                 
278                 if( !Broadcast )        continue;
279                 
280                 this = ntohl( ((tIPv4*)iface->Address)->L );
281                 
282                 // Check for broadcast
283                 netmask = IPv4_Netmask(iface->SubnetBits);
284                 
285                 if( (addr & netmask) == (this & netmask)
286                  && (addr & ~netmask) == (0xFFFFFFFF & ~netmask) )
287                         return iface;
288         }
289         return NULL;
290 }
291
292 /**
293  * \brief Convert a network prefix to a netmask
294  * \param FixedBits     Netmask size (/n)
295  * 
296  * For example /24 will become 255.255.255.0 (0xFFFFFF00)
297  */
298 Uint32 IPv4_Netmask(int FixedBits)
299 {
300         Uint32  ret = 0xFFFFFFFF;
301         ret >>= (32-FixedBits);
302         ret <<= (32-FixedBits);
303         // Returns a native endian netmask
304         return ret;
305 }
306
307 /**
308  * \brief Calculate the IPv4 Checksum
309  * \param Buf   Input buffer
310  * \param Size  Size of input
311  * 
312  * One's complement sum of all 16-bit words (bitwise inverted)
313  */
314 Uint16 IPv4_Checksum(const void *Buf, int Size)
315 {
316         Uint32  sum = 0;
317         const Uint16    *arr = Buf;
318          int    i;
319         
320         Size = (Size + 1) >> 1; // 16-bit word count
321         for(i = 0; i < Size; i++ )
322         {
323                 Uint16  val = ntohs(arr[i]);
324                 sum += val;
325         }
326         
327         // Apply one's complement
328         while (sum >> 16)
329                 sum = (sum & 0xFFFF) + (sum >> 16);
330         
331         return ~sum;
332 }
333
334 /**
335  * \brief Sends an ICMP Echo and waits for a reply
336  * \param IFace Interface
337  * \param Addr  Destination address
338  */
339 int IPv4_Ping(tInterface *IFace, tIPv4 Addr)
340 {
341         return ICMP_Ping(IFace, Addr);
342 }

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