Sorting source tree a bit
[tpg/acess2.git] / KernelLand / Modules / IPStack / interface.c
1 /*
2  * Acess2 IP Stack
3  * - Interface Control
4  */
5 #define DEBUG   0
6 #define VERSION VER2(0,10)
7 #include "ipstack.h"
8 #include "link.h"
9 #include <api_drv_common.h>
10 #include <api_drv_network.h>
11
12 // === CONSTANTS ===
13 //! Default timeout value, 30 seconds
14 #define DEFAULT_TIMEOUT (30*1000)
15
16 // === IMPORTS ===
17 extern int      IPv4_Ping(tInterface *Iface, tIPv4 Addr);
18 //extern int    IPv6_Ping(tInterface *Iface, tIPv6 Addr);
19 extern tVFS_Node        gIP_RouteNode;
20
21 // === PROTOTYPES ===
22 char    *IPStack_Root_ReadDir(tVFS_Node *Node, int Pos);
23 tVFS_Node       *IPStack_Root_FindDir(tVFS_Node *Node, const char *Name);
24  int    IPStack_Root_IOCtl(tVFS_Node *Node, int ID, void *Data);
25
26  int    IPStack_AddFile(tSocketFile *File);
27 tInterface      *IPStack_AddInterface(const char *Device, const char *Name);
28 tAdapter        *IPStack_GetAdapter(const char *Path);
29
30 char    *IPStack_Iface_ReadDir(tVFS_Node *Node, int Pos);
31 tVFS_Node       *IPStack_Iface_FindDir(tVFS_Node *Node, const char *Name);
32  int    IPStack_Iface_IOCtl(tVFS_Node *Node, int ID, void *Data);
33
34 // === GLOBALS ===
35 tVFS_NodeType   gIP_InterfaceNodeType = {
36                 .ReadDir = IPStack_Iface_ReadDir,
37                 .FindDir = IPStack_Iface_FindDir,
38                 .IOCtl = IPStack_Iface_IOCtl
39 };
40 //! Loopback (127.0.0.0/8, ::1) Pseudo-Interface
41 tInterface      gIP_LoopInterface = {
42         .Node = {
43                 .ImplPtr = &gIP_LoopInterface,
44                 .Flags = VFS_FFLAG_DIRECTORY,
45                 .Size = -1,
46                 .NumACLs = 1,
47                 .ACLs = &gVFS_ACL_EveryoneRX,
48                 .Type = &gIP_InterfaceNodeType
49         },
50         .Adapter = NULL,
51         .Type = 0
52 };
53 tShortSpinlock  glIP_Interfaces;
54 tInterface      *gIP_Interfaces = NULL;
55 tInterface      *gIP_Interfaces_Last = NULL;
56
57 tSocketFile     *gIP_FileTemplates;
58
59 tAdapter        gIP_LoopAdapter = {
60         .DeviceLen = 8,
61         .Device = "LOOPBACK"
62         };
63 tMutex  glIP_Adapters;
64 tAdapter        *gIP_Adapters = NULL;
65  int    giIP_NextIfaceId = 1;
66
67 // === CODE ===
68
69 /**
70  * \brief Read from the IP Stack's Device Directory
71  */
72 char *IPStack_Root_ReadDir(tVFS_Node *Node, int Pos)
73 {
74         tInterface      *iface;
75         char    *name;
76         ENTER("pNode iPos", Node, Pos);
77         
78
79         // Routing Subdir
80         if( Pos == 0 ) {
81                 LEAVE('s', "routes");
82                 return strdup("routes");
83         }
84         // Pseudo Interfaces
85         if( Pos == 1 ) {
86                 LEAVE('s', "lo");
87                 return strdup("lo");
88         }
89         Pos -= 2;
90         
91         // Traverse the list
92         for( iface = gIP_Interfaces; iface && Pos--; iface = iface->Next ) ;
93         
94         // Did we run off the end?
95         if(!iface) {
96                 LEAVE('n');
97                 return NULL;
98         }
99         
100         name = malloc(4);
101         if(!name) {
102                 Log_Warning("IPStack", "IPStack_Root_ReadDir - malloc error");
103                 LEAVE('n');
104                 return NULL;
105         }
106         
107         // Create the name
108         Pos = iface->Node.ImplInt;
109         if(Pos < 10) {
110                 name[0] = '0' + Pos;
111                 name[1] = '\0';
112         }
113         else if(Pos < 100) {
114                 name[0] = '0' + Pos/10;
115                 name[1] = '0' + Pos%10;
116                 name[2] = '\0';
117         }
118         else {
119                 name[0] = '0' + Pos/100;
120                 name[1] = '0' + (Pos/10)%10;
121                 name[2] = '0' + Pos%10;
122                 name[3] = '\0';
123         }
124         
125         LEAVE('s', name);
126         // Return the pre-generated name
127         return name;
128 }
129
130 /**
131  * \brief Get the node of an interface
132  */
133 tVFS_Node *IPStack_Root_FindDir(tVFS_Node *Node, const char *Name)
134 {
135         #if 0
136          int    i, num;
137         #endif
138         tInterface      *iface;
139         
140         ENTER("pNode sName", Node, Name);
141         
142         // Routing subdir
143         if( strcmp(Name, "routes") == 0 ) {
144                 LEAVE('p', &gIP_RouteNode);
145                 return &gIP_RouteNode;
146         }
147         
148         // Loopback
149         if( strcmp(Name, "lo") == 0 ) {
150                 LEAVE('p', &gIP_LoopInterface.Node);
151                 return &gIP_LoopInterface.Node;
152         }
153         
154         for( iface = gIP_Interfaces; iface; iface = iface->Next )
155         {
156                 if( strcmp(iface->Name, Name) == 0 )
157                 {
158                         LEAVE('p', &iface->Node);
159                         return &iface->Node;
160                 }
161         }
162         
163         LEAVE('p', NULL);
164         return NULL;
165 }
166
167 static const char *casIOCtls_Root[] = { DRV_IOCTLNAMES, "add_interface", NULL };
168 /**
169  * \brief Handles IOCtls for the IPStack root
170  */
171 int IPStack_Root_IOCtl(tVFS_Node *Node, int ID, void *Data)
172 {
173          int    tmp;
174         ENTER("pNode iID pData", Node, ID, Data);
175         
176         switch(ID)
177         {
178         // --- Standard IOCtls (0-3) ---
179         BASE_IOCTLS(DRV_TYPE_MISC, "IPStack", VERSION, casIOCtls_Root)
180                 
181         /*
182          * add_interface
183          * - Adds a new IP interface and binds it to a device
184          */
185         case 4:
186                 if( Threads_GetUID() != 0 )     LEAVE_RET('i', -1);
187                 if( !CheckString( Data ) )      LEAVE_RET('i', -1);
188                 LOG("New interface for '%s'", Data);
189                 {
190                         char    name[4] = "";
191                         tInterface      *iface = IPStack_AddInterface(Data, name);
192                         if(iface == NULL)       LEAVE_RET('i', -1);
193                         tmp = iface->Node.ImplInt;
194                 }
195                 LEAVE_RET('i', tmp);
196         }
197         LEAVE('i', 0);
198         return 0;
199 }
200
201 /**
202  * \fn tInterface *IPStack_AddInterface(char *Device)
203  * \brief Adds an interface to the list
204  */
205 tInterface *IPStack_AddInterface(const char *Device, const char *Name)
206 {
207         tInterface      *iface;
208         tAdapter        *card;
209          int    nameLen;
210         
211         ENTER("sDevice", Device);
212         
213         card = IPStack_GetAdapter(Device);
214         if( !card ) {
215                 Log_Debug("IPStack", "Unable to open card '%s'", Device);
216                 LEAVE('n');
217                 return NULL;    // ERR_YOURBAD
218         }
219         
220         nameLen = sprintf(NULL, "%i", giIP_NextIfaceId);
221         
222         iface = malloc(
223                 sizeof(tInterface)
224                 + nameLen + 1
225                 + IPStack_GetAddressSize(-1)*3  // Address, Route->Network, Route->NextHop
226                 );
227         if(!iface) {
228                 Log_Warning("IPStack", "AddInterface - malloc() failed");
229                 LEAVE('n');
230                 return NULL;    // Return ERR_MYBAD
231         }
232         
233         iface->Next = NULL;
234         iface->Type = 0;        // Unset type
235         iface->Address = iface->Name + nameLen + 1;     // Address
236         iface->Route.Network = iface->Address + IPStack_GetAddressSize(-1);
237         iface->Route.NextHop = iface->Route.Network + IPStack_GetAddressSize(-1);
238         
239         // Create Node
240         iface->Node.ImplPtr = iface;
241         iface->Node.Flags = VFS_FFLAG_DIRECTORY;
242         iface->Node.Size = -1;
243         iface->Node.NumACLs = 1;
244         iface->Node.ACLs = &gVFS_ACL_EveryoneRX;
245         iface->Node.Type = &gIP_InterfaceNodeType;
246         
247         // Set Defaults
248         iface->TimeoutDelay = DEFAULT_TIMEOUT;
249         
250         // Get adapter handle
251         iface->Adapter = card;
252         
253         // Delay setting ImplInt until after the adapter is opened
254         // Keeps things simple
255         iface->Node.ImplInt = giIP_NextIfaceId++;
256         sprintf(iface->Name, "%i", (int)iface->Node.ImplInt);
257         
258         // Append to list
259         SHORTLOCK( &glIP_Interfaces );
260         if( gIP_Interfaces ) {
261                 gIP_Interfaces_Last->Next = iface;
262                 gIP_Interfaces_Last = iface;
263         }
264         else {
265                 gIP_Interfaces = iface;
266                 gIP_Interfaces_Last = iface;
267         }
268         SHORTREL( &glIP_Interfaces );
269
270 //      gIP_DriverInfo.RootNode.Size ++;
271         
272         // Success!
273         LEAVE('p', iface);
274         return iface;
275 }
276
277 /**
278  * \brief Adds a file to the socket list
279  */
280 int IPStack_AddFile(tSocketFile *File)
281 {
282         Log_Log("IPStack", "Added file '%s'", File->Name);
283         File->Next = gIP_FileTemplates;
284         gIP_FileTemplates = File;
285         return 0;
286 }
287
288 // ---
289 // VFS Functions
290 // ---
291 /**
292  * \brief Read from an interface's directory
293  */
294 char *IPStack_Iface_ReadDir(tVFS_Node *Node, int Pos)
295 {
296         tSocketFile     *file = gIP_FileTemplates;
297         while(Pos-- && file) {
298                 file = file->Next;
299         }
300         
301         if(!file)       return NULL;
302         
303         return strdup(file->Name);
304 }
305
306 /**
307  * \brief Gets a named node from an interface directory
308  */
309 tVFS_Node *IPStack_Iface_FindDir(tVFS_Node *Node, const char *Name)
310 {
311         tSocketFile     *file = gIP_FileTemplates;
312         
313         // Get file definition
314         for(;file;file = file->Next)
315         {
316                 if( strcmp(file->Name, Name) == 0 )     break;
317         }
318         if(!file)       return NULL;
319         
320         // Pass the buck!
321         return file->Init(Node->ImplPtr);
322 }
323
324 /**
325  * \brief Names for interface IOCtl Calls
326  */
327 static const char *casIOCtls_Iface[] = {
328         DRV_IOCTLNAMES,
329         "getset_type",
330         "get_address", "set_address",
331         "getset_subnet",
332         "get_device",
333         "ping",
334         NULL
335         };
336 /**
337  * \brief Handles IOCtls for the IPStack interfaces
338  */
339 int IPStack_Iface_IOCtl(tVFS_Node *Node, int ID, void *Data)
340 {
341          int    tmp, size;
342         tInterface      *iface = (tInterface*)Node->ImplPtr;
343         ENTER("pNode iID pData", Node, ID, Data);
344         
345         switch(ID)
346         {
347         // --- Standard IOCtls (0-3) ---
348         BASE_IOCTLS(DRV_TYPE_MISC, "IPStack", VERSION, casIOCtls_Iface)
349         
350         /*
351          * getset_type
352          * - Get/Set the interface type
353          */
354         case 4:
355                 // Set Type?
356                 if( Data )
357                 {
358                         // Ok, it's set type
359                         if( Threads_GetUID() != 0 ) {
360                                 LOG("Attempt by non-root to alter an interface (%i)", Threads_GetUID());
361                                 LEAVE('i', -1);
362                                 return -1;
363                         }
364                         if( !CheckMem( Data, sizeof(int) ) ) {
365                                 LOG("Invalid pointer %p", Data);
366                                 LEAVE('i', -1);
367                                 return -1;
368                         }
369                         
370                         // Set type
371                         iface->Type = *(int*)Data;
372                         LOG("Interface type set to %i", iface->Type);
373                         size = IPStack_GetAddressSize(iface->Type);
374                         // Check it's actually valid
375                         if( iface->Type != 0 && size == 0 ) {
376                                 iface->Type = 0;
377                                 LEAVE('i', -1);
378                                 return -1;
379                         }
380                         
381                         // Clear address
382                         memset(iface->Address, 0, size);
383                 }
384                 LEAVE('i', iface->Type);
385                 return iface->Type;
386         
387         /*
388          * get_address
389          * - Get the interface's address
390          */
391         case 5:
392                 size = IPStack_GetAddressSize(iface->Type);
393                 if( !CheckMem( Data, size ) )   LEAVE_RET('i', -1);
394                 memcpy( Data, iface->Address, size );
395                 LEAVE('i', 1);
396                 return 1;
397         
398         /*
399          * set_address
400          * - Set the interface's address
401          */
402         case 6:
403                 if( Threads_GetUID() != 0 )     LEAVE_RET('i', -1);
404                 
405                 size = IPStack_GetAddressSize(iface->Type);
406                 if( !CheckMem( Data, size ) )   LEAVE_RET('i', -1);
407                 // TODO: Protect against trashing
408                 LOG("Interface address set to '%s'", IPStack_PrintAddress(iface->Type, Data));
409                 memcpy( iface->Address, Data, size );
410                 LEAVE_RET('i', 1);
411         
412         /*
413          * getset_subnet
414          * - Get/Set the bits in the address subnet
415          */
416         case 7:
417                 // Do we want to set the value?
418                 if( Data )
419                 {
420                         // Are we root? (TODO: Check Owner/Group)
421                         if( Threads_GetUID() != 0 )     LEAVE_RET('i', -1);
422                         // Is the memory valid
423                         if( !CheckMem(Data, sizeof(int)) )      LEAVE_RET('i', -1);
424                         
425                         // Is the mask sane?
426                         if( *(int*)Data < 0 || *(int*)Data > IPStack_GetAddressSize(iface->Type)*8-1 )
427                                 LEAVE_RET('i', -1);
428                         LOG("Set subnet bits to %i", *(int*)Data);
429                         // Ok, set it
430                         iface->SubnetBits = *(int*)Data;
431                 }
432                 LEAVE_RET('i', iface->SubnetBits);
433         
434         /*
435          * get_device
436          * - Gets the name of the attached device
437          */
438         case 8:
439                 if( iface->Adapter == NULL )
440                         LEAVE_RET('i', 0);
441                 if( Data == NULL )
442                         LEAVE_RET('i', iface->Adapter->DeviceLen);
443                 if( !CheckMem( Data, iface->Adapter->DeviceLen+1 ) )
444                         LEAVE_RET('i', -1);
445                 strcpy( Data, iface->Adapter->Device );
446                 LEAVE_RET('i', iface->Adapter->DeviceLen);
447         
448         /*
449          * ping
450          * - Send an ICMP Echo
451          */
452         case 9:
453                 switch(iface->Type)
454                 {
455                 case 0:
456                         LEAVE_RET('i', 1);
457                 
458                 case 4:
459                         if( !CheckMem( Data, sizeof(tIPv4) ) )  LEAVE_RET('i', -1);
460                         tmp = IPv4_Ping(iface, *(tIPv4*)Data);
461                         LEAVE_RET('i', tmp);
462                         
463                 case 6:
464                         LEAVE_RET('i', 1);
465                 }
466                 break;
467         
468         }
469         
470         LEAVE('i', 0);
471         return 0;
472 }
473
474 // --- Internal ---
475 /**
476  * \fn tAdapter *IPStack_GetAdapter(const char *Path)
477  * \brief Gets/opens an adapter given the path
478  */
479 tAdapter *IPStack_GetAdapter(const char *Path)
480 {
481         tAdapter        *dev;
482          int    tmp;
483         
484         ENTER("sPath", Path);
485         
486         // Check for loopback
487         if( strcmp(Path, "LOOPBACK") == 0 )
488         {
489                 // Initialise if required
490                 if( gIP_LoopAdapter.DeviceFD == 0 )
491                 {
492                         dev = &gIP_LoopAdapter;
493                         
494                         dev->NRef = 1;
495                         dev->DeviceLen = 8;
496                         
497                         dev->DeviceFD = VFS_Open( "/Devices/fifo/anon", VFS_OPENFLAG_READ|VFS_OPENFLAG_WRITE );
498                         if( dev->DeviceFD == -1 ) {
499                                 Log_Warning("IPStack", "Unable to open FIFO '/Devices/fifo/anon' for loopback");
500                                 return NULL;
501                         }
502                         
503                         dev->MacAddr.B[0] = 'A';
504                         dev->MacAddr.B[1] = 'c';
505                         dev->MacAddr.B[2] = 'e';
506                         dev->MacAddr.B[3] = 's';
507                         dev->MacAddr.B[4] = 's';
508                         dev->MacAddr.B[5] = '2';
509                         
510                         // Start watcher
511                         Link_WatchDevice( dev );
512                 }
513                 LEAVE('p', &gIP_LoopAdapter);
514                 return &gIP_LoopAdapter;
515         }
516         
517         Mutex_Acquire( &glIP_Adapters );
518         
519         // Check if this adapter is already open
520         for( dev = gIP_Adapters; dev; dev = dev->Next )
521         {
522                 if( strcmp(dev->Device, Path) == 0 ) {
523                         dev->NRef ++;
524                         Mutex_Release( &glIP_Adapters );
525                         LEAVE('p', dev);
526                         return dev;
527                 }
528         }
529         
530         // Ok, so let's open it
531         dev = malloc( sizeof(tAdapter) + strlen(Path) + 1 );
532         if(!dev) {
533                 Log_Warning("IPStack", "GetAdapter - malloc() failed");
534                 Mutex_Release( &glIP_Adapters );
535                 LEAVE('n');
536                 return NULL;
537         }
538         
539         // Fill Structure
540         strcpy( dev->Device, Path );
541         dev->NRef = 1;
542         dev->DeviceLen = strlen(Path);
543         
544         // Open Device
545         dev->DeviceFD = VFS_Open( dev->Device, VFS_OPENFLAG_READ|VFS_OPENFLAG_WRITE );
546         if( dev->DeviceFD == -1 ) {
547                 free( dev );
548                 Mutex_Release( &glIP_Adapters );
549                 LEAVE('n');
550                 return NULL;
551         }
552         
553         // Check that it is a network interface
554         tmp = VFS_IOCtl(dev->DeviceFD, 0, NULL);
555         LOG("Device type = %i", tmp);
556         if( tmp != DRV_TYPE_NETWORK ) {
557                 Log_Warning("IPStack", "IPStack_GetAdapter: '%s' is not a network interface", dev->Device);
558                 VFS_Close( dev->DeviceFD );
559                 free( dev );
560                 Mutex_Release( &glIP_Adapters );
561                 LEAVE('n');
562                 return NULL;
563         }
564         
565         // Get MAC Address
566         VFS_IOCtl(dev->DeviceFD, NET_IOCTL_GETMAC, &dev->MacAddr);
567         
568         // Add to list
569         dev->Next = gIP_Adapters;
570         gIP_Adapters = dev;
571         
572         Mutex_Release( &glIP_Adapters );
573         
574         // Start watcher
575         Link_WatchDevice( dev );
576         
577         LEAVE('p', dev);
578         return dev;
579 }

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