d1d50cdaf07aa90a2f2e8524a6da7835addc5e4e
[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         // Clean up
211         IPStack_Buffer_DestroyBuffer(buffer);
212         
213         // Wait for a reply
214         Time_ScheduleTimer(NULL, Interface->TimeoutDelay);
215         for(;;)
216         {
217                 if( Semaphore_Wait(&gARP_Cache4Semaphore, 1) != 1 )
218                 {
219                         giARP_WaitingThreads --;
220                         Log_Log("ARP4", "Timeout");
221                         break;
222                 }
223                 Log_Debug("ARP4", "Cache change");
224                 
225                 Mutex_Acquire( &glARP_Cache4 );
226                 for( i = 0; i < giARP_Cache4Space; i++ )
227                 {
228                         if(gaARP_Cache4[i].IP.L != Address.L)   continue;
229                         
230                         giARP_WaitingThreads --;
231                         Mutex_Release( &glARP_Cache4 );
232                         Log_Debug("ARP4", "Return %02x:%02x:%02x:%02x:%02x:%02x",
233                                 gaARP_Cache4[i].MAC.B[0], gaARP_Cache4[i].MAC.B[1], 
234                                 gaARP_Cache4[i].MAC.B[2], gaARP_Cache4[i].MAC.B[3], 
235                                 gaARP_Cache4[i].MAC.B[4], gaARP_Cache4[i].MAC.B[5]);
236                         return gaARP_Cache4[i].MAC;
237                 }
238                 Mutex_Release( &glARP_Cache4 );
239         }
240         {
241                 tMacAddr        ret = {{0,0,0,0,0,0}};
242                 return ret;
243         }
244 }
245
246 /**
247  * \brief Updates the ARP Cache entry for an IPv4 Address
248  */
249 void ARP_UpdateCache4(tIPv4 SWAddr, tMacAddr HWAddr)
250 {
251          int    i;
252          int    free = -1;
253          int    oldest = 0;
254         
255         // Find an entry for the IP address in the cache
256         Mutex_Acquire(&glARP_Cache4);
257         for( i = giARP_Cache4Space; i--; )
258         {
259                 if(gaARP_Cache4[oldest].LastUpdate > gaARP_Cache4[i].LastUpdate) {
260                         oldest = i;
261                 }
262                 if( gaARP_Cache4[i].IP.L == SWAddr.L )  break;
263                 if( gaARP_Cache4[i].LastUpdate == 0 && free == -1 )     free = i;
264         }
265         // If there was no match, we need to make one
266         if(i == -1) {
267                 if(free != -1)
268                         i = free;
269                 else
270                         i = oldest;
271         }
272
273         if( memcmp(&gaARP_Cache4[i].MAC, &HWAddr, sizeof(HWAddr)) != 0 )
274         {
275                 Log_Log("ARP4", "Caching %i.%i.%i.%i (%02x:%02x:%02x:%02x:%02x:%02x) in %i",
276                         SWAddr.B[0], SWAddr.B[1], SWAddr.B[2], SWAddr.B[3],
277                         HWAddr.B[0], HWAddr.B[1], HWAddr.B[2], HWAddr.B[3], HWAddr.B[4], HWAddr.B[5],
278                         i
279                         );
280                 
281                 gaARP_Cache4[i].IP = SWAddr;
282                 gaARP_Cache4[i].MAC = HWAddr;
283                 gaARP_Cache4[i].LastUpdate = now();
284                 Semaphore_Signal(&gARP_Cache4Semaphore, giARP_WaitingThreads);
285         }
286         Mutex_Release(&glARP_Cache4);
287 }
288
289 #if ARPv6
290 /**
291  * \brief Updates the ARP Cache entry for an IPv6 Address
292  */
293 void ARP_UpdateCache6(tIPv6 SWAddr, tMacAddr HWAddr)
294 {
295          int    i;
296          int    free = -1;
297          int    oldest = 0;
298         
299         // Find an entry for the MAC address in the cache
300         Mutex_Acquire(&glARP_Cache6);
301         for( i = giARP_Cache6Space; i--; )
302         {
303                 if(gaARP_Cache6[oldest].LastUpdate > gaARP_Cache6[i].LastUpdate) {
304                         oldest = i;
305                 }
306                 if( MAC_EQU(gaARP_Cache6[i].MAC, HWAddr) )      break;
307                 if( gaARP_Cache6[i].LastUpdate == 0 && free == -1 )     free = i;
308         }
309         // If there was no match, we need to make one
310         if(i == -1) {
311                 if(free != -1)
312                         i = free;
313                 else
314                         i = oldest;
315                 gaARP_Cache6[i].MAC = HWAddr;
316         }
317         
318         gaARP_Cache6[i].IP = SWAddr;
319         gaARP_Cache6[i].LastUpdate = now();
320         giARP_LastUpdateID ++;
321         Mutex_Release(&glARP_Cache6);
322 }
323 #endif
324
325 /**
326  * \fn void ARP_int_GetPacket(tAdapter *Adapter, tMacAddr From, int Length, void *Buffer)
327  * \brief Called when an ARP packet is recieved
328  */
329 void ARP_int_GetPacket(tAdapter *Adapter, tMacAddr From, int Length, void *Buffer)
330 {
331         tArpRequest4    *req4 = Buffer;
332         #if ARPv6
333         tArpRequest6    *req6 = Buffer;
334         #endif
335         tInterface      *iface;
336         
337         // Sanity Check Packet
338         if( Length < (int)sizeof(tArpRequest4) ) {
339                 Log_Log("ARP", "Recieved undersized packet");
340                 return ;
341         }
342         if( ntohs(req4->Type) != 0x0800 ) {
343                 Log_Log("ARP", "Recieved a packet with a bad type (0x%x)", ntohs(req4->Type));
344                 return ;
345         }
346         if( req4->HWSize != 6 ) {
347                 Log_Log("ARP", "Recieved a packet with HWSize != 6 (%i)", req4->HWSize);
348                 return;
349         }
350         #if ARP_DETECT_SPOOFS
351         if( !MAC_EQU(req4->SourceMac, From) ) {
352                 Log_Log("ARP", "ARP spoofing detected "
353                         "(%02x%02x:%02x%02x:%02x%02x != %02x%02x:%02x%02x:%02x%02x)",
354                         req4->SourceMac.B[0], req4->SourceMac.B[1], req4->SourceMac.B[2],
355                         req4->SourceMac.B[3], req4->SourceMac.B[4], req4->SourceMac.B[5],
356                         From.B[0], From.B[1], From.B[2],
357                         From.B[3], From.B[4], From.B[5]
358                         );
359                 return;
360         }
361         #endif
362         
363         switch( ntohs(req4->Request) )
364         {
365         case 1: // You want my IP?
366                 // Check what type of IP it is
367                 switch( req4->SWSize )
368                 {
369                 case 4:
370                         Log_Debug("ARP", "ARP Request IPv4 Address %i.%i.%i.%i from %i.%i.%i.%i",
371                                 req4->DestIP.B[0], req4->DestIP.B[1], req4->DestIP.B[2],
372                                 req4->DestIP.B[3],
373                                 req4->SourceIP.B[0], req4->SourceIP.B[1],
374                                 req4->SourceIP.B[2], req4->SourceIP.B[3]);
375                         Log_Debug("ARP", " from MAC %02x:%02x:%02x:%02x:%02x:%02x",
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                         iface = IPv4_GetInterface(Adapter, req4->DestIP, 0);
380                         if( iface )
381                         {
382                                 ARP_UpdateCache4(req4->SourceIP, req4->SourceMac);
383                                 
384                                 req4->DestIP = req4->SourceIP;
385                                 req4->DestMac = req4->SourceMac;
386                                 req4->SourceIP = *(tIPv4*)iface->Address;;
387                                 memcpy(&req4->SourceMac, Adapter->HWAddr, 6);   // TODO: Remove hard size
388                                 req4->Request = htons(2);
389                                 Log_Debug("ARP", "Sending back us (%02x:%02x:%02x:%02x:%02x:%02x)",
390                                         req4->SourceMac.B[0], req4->SourceMac.B[1],
391                                         req4->SourceMac.B[2], req4->SourceMac.B[3],
392                                         req4->SourceMac.B[4], req4->SourceMac.B[5]);
393                                 
394                                 // Assumes only a header and footer at link layer
395                                 tIPStackBuffer  *buffer = IPStack_Buffer_CreateBuffer(3);
396                                 IPStack_Buffer_AppendSubBuffer(buffer, sizeof(struct sArpRequest4), 0, req4, NULL, NULL);
397                                 Link_SendPacket(Adapter, 0x0806, req4->DestMac, buffer);
398                                 IPStack_Buffer_DestroyBuffer(buffer);
399                         }
400                         break;
401                 #if ARPv6
402                 case 6:
403                         if( Length < (int)sizeof(tArpRequest6) ) {
404                                 Log_Log("ARP", "Recieved undersized packet (IPv6)");
405                                 return ;
406                         }
407                         Log_Debug("ARP", "ARP Request IPv6 Address %08x:%08x:%08x:%08x",
408                                 ntohl(req6->DestIP.L[0]), ntohl(req6->DestIP.L[1]),
409                                 ntohl(req6->DestIP.L[2]), ntohl(req6->DestIP.L[3])
410                                 );
411                         iface = IPv6_GetInterface(Adapter, req6->DestIP, 0);
412                         if( iface )
413                         {
414                                 req6->DestIP = req6->SourceIP;
415                                 req6->DestMac = req6->SourceMac;
416                                 req6->SourceIP = *(tIPv6*)iface->Address;
417                                 req6->SourceMac = Adapter->MacAddr;
418                                 req6->Request = htons(2);
419                                 Log_Debug("ARP", "Sending back us (%02x:%02x:%02x:%02x:%02x:%02x)",
420                                         req4->SourceMac.B[0], req4->SourceMac.B[1],
421                                         req4->SourceMac.B[2], req4->SourceMac.B[3],
422                                         req4->SourceMac.B[4], req4->SourceMac.B[5]);
423                                 Link_SendPacket(Adapter, 0x0806, req6->DestMac, sizeof(tArpRequest6), req6);
424                         }
425                         break;
426                 #endif
427                 default:
428                         Log_Debug("ARP", "Unknown Protocol Address size (%i)", req4->SWSize);
429                         return ;
430                 }
431                 
432                 break;
433         
434         case 2: // Ooh! A response!             
435                 // Check what type of IP it is
436                 switch( req4->SWSize )
437                 {
438                 case 4:
439                         ARP_UpdateCache4( req4->SourceIP, From );
440                         break;
441                 #if ARPv6
442                 case 6:
443                         if( Length < (int)sizeof(tArpRequest6) ) {
444                                 Log_Debug("ARP", "Recieved undersized packet (IPv6)");
445                                 return ;
446                         }
447                         ARP_UpdateCache6( req6->SourceIP, From );
448                         break;
449                 #endif
450                 default:
451                         Log_Debug("ARP", "Unknown Protocol Address size (%i)", req4->SWSize);
452                         return ;
453                 }
454                 
455                 break;
456         
457         default:
458                 Log_Warning("ARP", "Unknown Request ID %i", ntohs(req4->Request));
459                 break;
460         }
461 }

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