Modules/IPStack - TCP minor bugfixes, arp semaphore name
[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         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         Semaphore_Signal(&gARP_Cache4Semaphore, giARP_WaitingThreads);
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