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

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