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

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