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

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