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

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