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

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