5b9303b9b302aa14586e36e8de7edda87336cab2
[tpg/acess2.git] / KernelLand / Modules / IPStack / arp.c
1 /*
2  * Acess2 IP Stack
3  * - Address Resolution Protocol
4  * - Part of the IPv4 protocol
5  */
6 #define DEBUG   0
7 #include "ipstack.h"
8 #include "arp.h"
9 #include "link.h"
10 #include "ipv4.h"       // For IPv4_Netmask
11 #include "include/adapters_int.h"       // for MAC addr
12 #include <semaphore.h>
13 #include <timers.h>
14
15 #define ARPv6   0
16 #define ARP_CACHE_SIZE  128
17 #define ARP_MAX_AGE             (60*60*1000)    // 1Hr
18
19 typedef struct sARP_CacheEnt
20 {
21         void    *Layer3Addr;
22         tMacAddr        L2Addr;
23         Sint64  LastUpdate;
24         Sint64  LastUsed;
25 } tARP_CacheEnt;
26 typedef struct sARP_Cache
27 {
28         size_t  AddrSize;
29          int    nCacheEnts;
30         tARP_CacheEnt   Cache[];
31 } tARP_Cache;
32
33 // === IMPORTS ===
34 extern tInterface       *IPv4_GetInterface(tAdapter *Adapter, tIPv4 Address, int Broadcast);
35 #if ARPv6
36 extern tInterface       *IPv6_GetInterface(tAdapter *Adapter, tIPv6 Address, int Broadcast);
37 #endif
38
39 // === PROTOTYPES ===
40  int    ARP_Initialise();
41 tMacAddr        ARP_Resolve4(tInterface *Interface, tIPv4 Address);
42 void    ARP_int_GetPacket(tAdapter *Adapter, tMacAddr From, int Length, void *Buffer);
43
44 // === GLOBALS ===
45  int    giARP_WaitingThreads;
46 struct sARP_Cache4 {
47         tIPv4   IP;
48         tMacAddr        MAC;
49         Sint64  LastUpdate;
50         Sint64  LastUsed;
51 }       *gaARP_Cache4;
52  int    giARP_Cache4Space;
53 tMutex  glARP_Cache4;
54 tSemaphore      gARP_Cache4Semaphore;
55 #if ARPv6
56 struct sARP_Cache6 {
57         tIPv6   IP;
58         tMacAddr        MAC;
59         Sint64  LastUpdate;
60         Sint64  LastUsed;
61 }       *gaARP_Cache6;
62  int    giARP_Cache6Space;
63 tMutex  glARP_Cache6;
64 #endif
65
66 // === CODE ===
67 tARP_Cache *ARP_int_CreateCache(unsigned int NumCacheEntries, size_t AddrSize)
68 {
69         size_t  len = sizeof(tARP_Cache) + NumCacheEntries * (sizeof(tARP_CacheEnt) + AddrSize);
70         tARP_Cache      *ret = calloc(len, 1);
71         
72         ret->nCacheEnts = NumCacheEntries;
73         ret->AddrSize = AddrSize;
74         
75         char    *addr_storage_pos = (void*)&ret->Cache[NumCacheEntries];
76         
77         for( int i = 0; i < NumCacheEntries; i ++ )
78         {
79                 ret->Cache[i].Layer3Addr = addr_storage_pos;
80                 addr_storage_pos += AddrSize;
81         }
82         
83         return ret;
84 }
85 /**
86  * \fn int ARP_Initialise()
87  * \brief Initalise the ARP section
88  */
89 int ARP_Initialise()
90 {
91         gaARP_Cache4 = malloc( ARP_CACHE_SIZE * sizeof(struct sARP_Cache4) );
92         memset( gaARP_Cache4, 0, ARP_CACHE_SIZE * sizeof(struct sARP_Cache4) );
93         giARP_Cache4Space = ARP_CACHE_SIZE;
94         
95         #if ARPv6
96         gaARP_Cache6 = malloc( ARP_CACHE_SIZE * sizeof(struct sARP_Cache6) );
97         memset( gaARP_Cache6, 0, ARP_CACHE_SIZE * sizeof(struct sARP_Cache6) );
98         giARP_Cache6Space = ARP_CACHE_SIZE;
99         #endif
100         
101         Link_RegisterType(0x0806, ARP_int_GetPacket);
102         Semaphore_Init(&gARP_Cache4Semaphore, 0, 0, "ARP4", "Cache Changes");
103         return 1;
104 }
105
106 tMacAddr ARP_Resolve(tInterface *Interface, void *Address)
107 {
108         switch(Interface->Type)
109         {
110         case AF_INET4:
111                 return ARP_Resolve4(Interface, *(tIPv4*)Address);
112 //      case AF_INET6:
113 //              ret = ARP_int_CacheLookup(Interface, 16, Address);
114 //              if(ret == cMAC_ZERO) {
115 //                      // TODO: Send ICMPv6 ND requests
116 //              }
117 //              return ret;
118         }
119         return cMAC_ZERO;
120 }
121
122 /**
123  * \brief Resolves a MAC address from an IPv4 address
124  */
125 tMacAddr ARP_Resolve4(tInterface *Interface, tIPv4 Address)
126 {
127          int    i;
128         struct sArpRequest4     req;
129         
130         ENTER("pInterface xAddress", Interface, Address);
131         
132         // Check for broadcast
133         if( Address.L == -1 )
134         {
135                 LOG("Broadcast");
136                 LEAVE('-');
137                 return cMAC_BROADCAST;
138         }
139
140         // Check routing tables if not on this subnet
141         if( IPStack_CompareAddress(4, &Address, Interface->Address, Interface->SubnetBits) == 0 )
142         {
143                 tRoute  *route = IPStack_FindRoute(4, Interface, &Address);
144                 // If the next hop is defined, use it
145                 // - 0.0.0.0 as the next hop means "no next hop / direct"
146                 if( route && ((tIPv4*)route->NextHop)->L != 0 )
147                 {
148                         // Recursion: see /Recursion/
149                         LOG("Recursing with %s", IPStack_PrintAddress(4, route->NextHop));
150                         LEAVE('-');
151                         return ARP_Resolve4(Interface, *(tIPv4*)route->NextHop);
152                 }
153                 // No route, fall though
154         }
155         else
156         {
157                 Uint32  netmask;
158                 // Check for broadcast
159                 netmask = IPv4_Netmask(Interface->SubnetBits);
160                 if( (Address.L & ~netmask) == (0xFFFFFFFF & ~netmask) )
161                 {
162                         LOG("Local Broadcast");
163                         LEAVE('-');
164                         return cMAC_BROADCAST;
165                 }
166         }
167         
168         // Check ARP Cache
169         Mutex_Acquire( &glARP_Cache4 );
170         for( i = 0; i < giARP_Cache4Space; i++ )
171         {
172                 if(gaARP_Cache4[i].IP.L != Address.L)   continue;
173                 
174                 // Check if the entry needs to be refreshed
175                 if( now() - gaARP_Cache4[i].LastUpdate > ARP_MAX_AGE )  break;
176                 
177                 Mutex_Release( &glARP_Cache4 );
178                 LOG("Return %x:%x:%x:%x:%x:%x",
179                         gaARP_Cache4[i].MAC.B[0], gaARP_Cache4[i].MAC.B[1],
180                         gaARP_Cache4[i].MAC.B[2], gaARP_Cache4[i].MAC.B[3],
181                         gaARP_Cache4[i].MAC.B[4], gaARP_Cache4[i].MAC.B[5]
182                         );
183                 LEAVE('-');
184                 return gaARP_Cache4[i].MAC;
185         }
186         giARP_WaitingThreads ++;
187         Mutex_Release( &glARP_Cache4 );
188         
189         // Create request
190         Log_Log("ARP4", "Asking for address %i.%i.%i.%i",
191                 Address.B[0], Address.B[1], Address.B[2], Address.B[3]
192                 );
193         req.HWType = htons(0x0001);     // Ethernet
194         req.Type   = htons(0x0800);
195         req.HWSize = 6;
196         req.SWSize = 4;
197         req.Request = htons(1);
198         memcpy(&req.SourceMac, Interface->Adapter->HWAddr, 6);  // TODO: Remove hard size
199         req.SourceIP = *(tIPv4*)Interface->Address;
200         req.DestMac = cMAC_BROADCAST;
201         req.DestIP = Address;
202
203         // Assumes only a header and footer at link layer
204         tIPStackBuffer  *buffer = IPStack_Buffer_CreateBuffer(3);
205         IPStack_Buffer_AppendSubBuffer(buffer, sizeof(struct sArpRequest4), 0, &req, NULL, NULL);
206
207         // Send Request
208         Link_SendPacket(Interface->Adapter, 0x0806, req.DestMac, buffer);
209         
210         // Wait for a reply
211         Time_ScheduleTimer(NULL, Interface->TimeoutDelay);
212         for(;;)
213         {
214                 if( Semaphore_Wait(&gARP_Cache4Semaphore, 1) != 1 )
215                 {
216                         giARP_WaitingThreads --;
217                         Log_Log("ARP4", "Timeout");
218                         break;
219                 }
220                 Log_Debug("ARP4", "Cache change");
221                 
222                 Mutex_Acquire( &glARP_Cache4 );
223                 for( i = 0; i < giARP_Cache4Space; i++ )
224                 {
225                         if(gaARP_Cache4[i].IP.L != Address.L)   continue;
226                         
227                         giARP_WaitingThreads --;
228                         Mutex_Release( &glARP_Cache4 );
229                         Log_Debug("ARP4", "Return %02x:%02x:%02x:%02x:%02x:%02x",
230                                 gaARP_Cache4[i].MAC.B[0], gaARP_Cache4[i].MAC.B[1], 
231                                 gaARP_Cache4[i].MAC.B[2], gaARP_Cache4[i].MAC.B[3], 
232                                 gaARP_Cache4[i].MAC.B[4], gaARP_Cache4[i].MAC.B[5]);
233                         return gaARP_Cache4[i].MAC;
234                 }
235                 Mutex_Release( &glARP_Cache4 );
236         }
237         {
238                 tMacAddr        ret = {{0,0,0,0,0,0}};
239                 return ret;
240         }
241 }
242
243 /**
244  * \brief Updates the ARP Cache entry for an IPv4 Address
245  */
246 void ARP_UpdateCache4(tIPv4 SWAddr, tMacAddr HWAddr)
247 {
248          int    i;
249          int    free = -1;
250          int    oldest = 0;
251         
252         // Find an entry for the IP address in the cache
253         Mutex_Acquire(&glARP_Cache4);
254         for( i = giARP_Cache4Space; i--; )
255         {
256                 if(gaARP_Cache4[oldest].LastUpdate > gaARP_Cache4[i].LastUpdate) {
257                         oldest = i;
258                 }
259                 if( gaARP_Cache4[i].IP.L == SWAddr.L )  break;
260                 if( gaARP_Cache4[i].LastUpdate == 0 && free == -1 )     free = i;
261         }
262         // If there was no match, we need to make one
263         if(i == -1) {
264                 if(free != -1)
265                         i = free;
266                 else
267                         i = oldest;
268         }
269
270         if( memcmp(&gaARP_Cache4[i].MAC, &HWAddr, sizeof(HWAddr)) != 0 )
271         {
272                 Log_Log("ARP4", "Caching %i.%i.%i.%i (%02x:%02x:%02x:%02x:%02x:%02x) in %i",
273                         SWAddr.B[0], SWAddr.B[1], SWAddr.B[2], SWAddr.B[3],
274                         HWAddr.B[0], HWAddr.B[1], HWAddr.B[2], HWAddr.B[3], HWAddr.B[4], HWAddr.B[5],
275                         i
276                         );
277                 
278                 gaARP_Cache4[i].IP = SWAddr;
279                 gaARP_Cache4[i].MAC = HWAddr;
280                 gaARP_Cache4[i].LastUpdate = now();
281                 Semaphore_Signal(&gARP_Cache4Semaphore, giARP_WaitingThreads);
282         }
283         Mutex_Release(&glARP_Cache4);
284 }
285
286 #if ARPv6
287 /**
288  * \brief Updates the ARP Cache entry for an IPv6 Address
289  */
290 void ARP_UpdateCache6(tIPv6 SWAddr, tMacAddr HWAddr)
291 {
292          int    i;
293          int    free = -1;
294          int    oldest = 0;
295         
296         // Find an entry for the MAC address in the cache
297         Mutex_Acquire(&glARP_Cache6);
298         for( i = giARP_Cache6Space; i--; )
299         {
300                 if(gaARP_Cache6[oldest].LastUpdate > gaARP_Cache6[i].LastUpdate) {
301                         oldest = i;
302                 }
303                 if( MAC_EQU(gaARP_Cache6[i].MAC, HWAddr) )      break;
304                 if( gaARP_Cache6[i].LastUpdate == 0 && free == -1 )     free = i;
305         }
306         // If there was no match, we need to make one
307         if(i == -1) {
308                 if(free != -1)
309                         i = free;
310                 else
311                         i = oldest;
312                 gaARP_Cache6[i].MAC = HWAddr;
313         }
314         
315         gaARP_Cache6[i].IP = SWAddr;
316         gaARP_Cache6[i].LastUpdate = now();
317         giARP_LastUpdateID ++;
318         Mutex_Release(&glARP_Cache6);
319 }
320 #endif
321
322 /**
323  * \fn void ARP_int_GetPacket(tAdapter *Adapter, tMacAddr From, int Length, void *Buffer)
324  * \brief Called when an ARP packet is recieved
325  */
326 void ARP_int_GetPacket(tAdapter *Adapter, tMacAddr From, int Length, void *Buffer)
327 {
328         tArpRequest4    *req4 = Buffer;
329         #if ARPv6
330         tArpRequest6    *req6 = Buffer;
331         #endif
332         tInterface      *iface;
333         
334         // Sanity Check Packet
335         if( Length < (int)sizeof(tArpRequest4) ) {
336                 Log_Log("ARP", "Recieved undersized packet");
337                 return ;
338         }
339         if( ntohs(req4->Type) != 0x0800 ) {
340                 Log_Log("ARP", "Recieved a packet with a bad type (0x%x)", ntohs(req4->Type));
341                 return ;
342         }
343         if( req4->HWSize != 6 ) {
344                 Log_Log("ARP", "Recieved a packet with HWSize != 6 (%i)", req4->HWSize);
345                 return;
346         }
347         #if ARP_DETECT_SPOOFS
348         if( !MAC_EQU(req4->SourceMac, From) ) {
349                 Log_Log("ARP", "ARP spoofing detected "
350                         "(%02x%02x:%02x%02x:%02x%02x != %02x%02x:%02x%02x:%02x%02x)",
351                         req4->SourceMac.B[0], req4->SourceMac.B[1], req4->SourceMac.B[2],
352                         req4->SourceMac.B[3], req4->SourceMac.B[4], req4->SourceMac.B[5],
353                         From.B[0], From.B[1], From.B[2],
354                         From.B[3], From.B[4], From.B[5]
355                         );
356                 return;
357         }
358         #endif
359         
360         switch( ntohs(req4->Request) )
361         {
362         case 1: // You want my IP?
363                 // Check what type of IP it is
364                 switch( req4->SWSize )
365                 {
366                 case 4:
367                         iface = IPv4_GetInterface(Adapter, req4->DestIP, 0);
368                         if( iface )
369                         {
370                                 Log_Debug("ARP", "ARP Request IPv4 Address %i.%i.%i.%i from %i.%i.%i.%i"
371                                         " (%02x:%02x:%02x:%02x:%02x:%02x)",
372                                         req4->DestIP.B[0], req4->DestIP.B[1], req4->DestIP.B[2],
373                                         req4->DestIP.B[3],
374                                         req4->SourceIP.B[0], req4->SourceIP.B[1],
375                                         req4->SourceIP.B[2], req4->SourceIP.B[3],
376                                         req4->SourceMac.B[0], req4->SourceMac.B[1],
377                                         req4->SourceMac.B[2], req4->SourceMac.B[3],
378                                         req4->SourceMac.B[4], req4->SourceMac.B[5]);
379                                 ARP_UpdateCache4(req4->SourceIP, req4->SourceMac);
380                                 
381                                 req4->DestIP = req4->SourceIP;
382                                 req4->DestMac = req4->SourceMac;
383                                 req4->SourceIP = *(tIPv4*)iface->Address;;
384                                 memcpy(&req4->SourceMac, Adapter->HWAddr, 6);   // TODO: Remove hard size
385                                 req4->Request = htons(2);
386                                 Log_Debug("ARP", "Sending back us (%02x:%02x:%02x:%02x:%02x:%02x)",
387                                         req4->SourceMac.B[0], req4->SourceMac.B[1],
388                                         req4->SourceMac.B[2], req4->SourceMac.B[3],
389                                         req4->SourceMac.B[4], req4->SourceMac.B[5]);
390                                 
391                                 // Assumes only a header and footer at link layer
392                                 tIPStackBuffer  *buffer = IPStack_Buffer_CreateBuffer(3);
393                                 IPStack_Buffer_AppendSubBuffer(buffer,
394                                         sizeof(struct sArpRequest4), 0, req4,
395                                         NULL, NULL);
396                                 Link_SendPacket(Adapter, 0x0806, req4->DestMac, buffer);
397                         }
398                         break;
399                 #if ARPv6
400                 case 6:
401                         if( Length < (int)sizeof(tArpRequest6) ) {
402                                 Log_Log("ARP", "Recieved undersized packet (IPv6)");
403                                 return ;
404                         }
405                         Log_Debug("ARP", "ARP Request IPv6 Address %08x:%08x:%08x:%08x",
406                                 ntohl(req6->DestIP.L[0]), ntohl(req6->DestIP.L[1]),
407                                 ntohl(req6->DestIP.L[2]), ntohl(req6->DestIP.L[3])
408                                 );
409                         iface = IPv6_GetInterface(Adapter, req6->DestIP, 0);
410                         if( iface )
411                         {
412                                 req6->DestIP = req6->SourceIP;
413                                 req6->DestMac = req6->SourceMac;
414                                 req6->SourceIP = *(tIPv6*)iface->Address;
415                                 req6->SourceMac = Adapter->MacAddr;
416                                 req6->Request = htons(2);
417                                 Log_Debug("ARP", "Sending back us (%02x:%02x:%02x:%02x:%02x:%02x)",
418                                         req4->SourceMac.B[0], req4->SourceMac.B[1],
419                                         req4->SourceMac.B[2], req4->SourceMac.B[3],
420                                         req4->SourceMac.B[4], req4->SourceMac.B[5]);
421                                 Link_SendPacket(Adapter, 0x0806, req6->DestMac, sizeof(tArpRequest6), req6);
422                         }
423                         break;
424                 #endif
425                 default:
426                         Log_Debug("ARP", "Unknown Protocol Address size (%i)", req4->SWSize);
427                         return ;
428                 }
429                 
430                 break;
431         
432         case 2: // Ooh! A response!             
433                 // Check what type of IP it is
434                 switch( req4->SWSize )
435                 {
436                 case 4:
437                         ARP_UpdateCache4( req4->SourceIP, From );
438                         break;
439                 #if ARPv6
440                 case 6:
441                         if( Length < (int)sizeof(tArpRequest6) ) {
442                                 Log_Debug("ARP", "Recieved undersized packet (IPv6)");
443                                 return ;
444                         }
445                         ARP_UpdateCache6( req6->SourceIP, From );
446                         break;
447                 #endif
448                 default:
449                         Log_Debug("ARP", "Unknown Protocol Address size (%i)", req4->SWSize);
450                         return ;
451                 }
452                 
453                 break;
454         
455         default:
456                 Log_Warning("ARP", "Unknown Request ID %i", ntohs(req4->Request));
457                 break;
458         }
459 }

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