Modules/USB - Cleanup mostly
[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 <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 //! 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         for( iface = gIP_Interfaces; iface; iface = iface->Next )
148         {
149                 if( strcmp(iface->Name, Name) == 0 )
150                 {
151                         LEAVE('p', &iface->Node);
152                         return &iface->Node;
153                 }
154         }
155         
156         LEAVE('p', NULL);
157         return NULL;
158 }
159
160 static const char *casIOCtls_Root[] = { DRV_IOCTLNAMES, "add_interface", NULL };
161 /**
162  * \brief Handles IOCtls for the IPStack root
163  */
164 int IPStack_Root_IOCtl(tVFS_Node *Node, int ID, void *Data)
165 {
166          int    tmp;
167         ENTER("pNode iID pData", Node, ID, Data);
168         
169         switch(ID)
170         {
171         // --- Standard IOCtls (0-3) ---
172         BASE_IOCTLS(DRV_TYPE_MISC, "IPStack", VERSION, casIOCtls_Root)
173                 
174         /*
175          * add_interface
176          * - Adds a new IP interface and binds it to a device
177          */
178         case 4:
179                 if( Threads_GetUID() != 0 )     LEAVE_RET('i', -1);
180                 if( !CheckString( Data ) )      LEAVE_RET('i', -1);
181                 {
182                         char    name[4] = "";
183                         tInterface      *iface = IPStack_AddInterface(Data, name);
184                         if(iface == NULL)       LEAVE_RET('i', -1);
185                         tmp = iface->Node.ImplInt;
186                 }
187                 LEAVE_RET('i', tmp);
188         }
189         LEAVE('i', 0);
190         return 0;
191 }
192
193 /**
194  * \fn tInterface *IPStack_AddInterface(char *Device)
195  * \brief Adds an interface to the list
196  */
197 tInterface *IPStack_AddInterface(const char *Device, const char *Name)
198 {
199         tInterface      *iface;
200         tAdapter        *card;
201          int    nameLen;
202         
203         ENTER("sDevice", Device);
204         
205         card = IPStack_GetAdapter(Device);
206         if( !card ) {
207                 Log_Debug("IPStack", "Unable to open card '%s'", Device);
208                 LEAVE('n');
209                 return NULL;    // ERR_YOURBAD
210         }
211         
212         nameLen = sprintf(NULL, "%i", giIP_NextIfaceId);
213         
214         iface = malloc(
215                 sizeof(tInterface)
216                 + nameLen + 1
217                 + IPStack_GetAddressSize(-1)*3  // Address, Route->Network, Route->NextHop
218                 );
219         if(!iface) {
220                 Log_Warning("IPStack", "AddInterface - malloc() failed");
221                 LEAVE('n');
222                 return NULL;    // Return ERR_MYBAD
223         }
224         
225         iface->Next = NULL;
226         iface->Type = 0;        // Unset type
227         iface->Address = iface->Name + nameLen + 1;     // Address
228         iface->Route.Network = iface->Address + IPStack_GetAddressSize(-1);
229         iface->Route.NextHop = iface->Route.Network + IPStack_GetAddressSize(-1);
230         
231         // Create Node
232         iface->Node.ImplPtr = iface;
233         iface->Node.Flags = VFS_FFLAG_DIRECTORY;
234         iface->Node.Size = -1;
235         iface->Node.NumACLs = 1;
236         iface->Node.ACLs = &gVFS_ACL_EveryoneRX;
237         iface->Node.ReadDir = IPStack_Iface_ReadDir;
238         iface->Node.FindDir = IPStack_Iface_FindDir;
239         iface->Node.IOCtl = IPStack_Iface_IOCtl;
240         iface->Node.MkNod = NULL;
241         iface->Node.Link = NULL;
242         iface->Node.Relink = NULL;
243         iface->Node.Close = NULL;
244         
245         // Set Defaults
246         iface->TimeoutDelay = DEFAULT_TIMEOUT;
247         
248         // Get adapter handle
249         iface->Adapter = card;
250         
251         // Delay setting ImplInt until after the adapter is opened
252         // Keeps things simple
253         iface->Node.ImplInt = giIP_NextIfaceId++;
254         sprintf(iface->Name, "%i", (int)iface->Node.ImplInt);
255         
256         // Append to list
257         SHORTLOCK( &glIP_Interfaces );
258         if( gIP_Interfaces ) {
259                 gIP_Interfaces_Last->Next = iface;
260                 gIP_Interfaces_Last = iface;
261         }
262         else {
263                 gIP_Interfaces = iface;
264                 gIP_Interfaces_Last = iface;
265         }
266         SHORTREL( &glIP_Interfaces );
267
268 //      gIP_DriverInfo.RootNode.Size ++;
269         
270         // Success!
271         LEAVE('p', iface);
272         return iface;
273 }
274
275 /**
276  * \brief Adds a file to the socket list
277  */
278 int IPStack_AddFile(tSocketFile *File)
279 {
280         Log_Log("IPStack", "Added file '%s'", File->Name);
281         File->Next = gIP_FileTemplates;
282         gIP_FileTemplates = File;
283         return 0;
284 }
285
286 // ---
287 // VFS Functions
288 // ---
289 /**
290  * \brief Read from an interface's directory
291  */
292 char *IPStack_Iface_ReadDir(tVFS_Node *Node, int Pos)
293 {
294         tSocketFile     *file = gIP_FileTemplates;
295         while(Pos-- && file) {
296                 file = file->Next;
297         }
298         
299         if(!file)       return NULL;
300         
301         return strdup(file->Name);
302 }
303
304 /**
305  * \brief Gets a named node from an interface directory
306  */
307 tVFS_Node *IPStack_Iface_FindDir(tVFS_Node *Node, const char *Name)
308 {
309         tSocketFile     *file = gIP_FileTemplates;
310         
311         // Get file definition
312         for(;file;file = file->Next)
313         {
314                 if( strcmp(file->Name, Name) == 0 )     break;
315         }
316         if(!file)       return NULL;
317         
318         // Pass the buck!
319         return file->Init(Node->ImplPtr);
320 }
321
322 /**
323  * \brief Names for interface IOCtl Calls
324  */
325 static const char *casIOCtls_Iface[] = {
326         DRV_IOCTLNAMES,
327         "getset_type",
328         "get_address", "set_address",
329         "getset_subnet",
330         "get_device",
331         "ping",
332         NULL
333         };
334 /**
335  * \brief Handles IOCtls for the IPStack interfaces
336  */
337 int IPStack_Iface_IOCtl(tVFS_Node *Node, int ID, void *Data)
338 {
339          int    tmp, size;
340         tInterface      *iface = (tInterface*)Node->ImplPtr;
341         ENTER("pNode iID pData", Node, ID, Data);
342         
343         switch(ID)
344         {
345         // --- Standard IOCtls (0-3) ---
346         BASE_IOCTLS(DRV_TYPE_MISC, "IPStack", VERSION, casIOCtls_Iface)
347         
348         /*
349          * getset_type
350          * - Get/Set the interface type
351          */
352         case 4:
353                 // Set Type?
354                 if( Data )
355                 {
356                         // Ok, it's set type
357                         if( Threads_GetUID() != 0 ) {
358                                 LOG("Attempt by non-root to alter an interface (%i)", Threads_GetUID());
359                                 LEAVE('i', -1);
360                                 return -1;
361                         }
362                         if( !CheckMem( Data, sizeof(int) ) ) {
363                                 LOG("Invalid pointer %p", Data);
364                                 LEAVE('i', -1);
365                                 return -1;
366                         }
367                         
368                         // Set type
369                         iface->Type = *(int*)Data;
370                         size = IPStack_GetAddressSize(iface->Type);
371                         // Check it's actually valid
372                         if( iface->Type != 0 && size == 0 ) {
373                                 iface->Type = 0;
374                                 LEAVE('i', -1);
375                                 return -1;
376                         }
377                         
378                         // Clear address
379                         memset(iface->Address, 0, size);
380                 }
381                 LEAVE('i', iface->Type);
382                 return iface->Type;
383         
384         /*
385          * get_address
386          * - Get the interface's address
387          */
388         case 5:
389                 size = IPStack_GetAddressSize(iface->Type);
390                 if( !CheckMem( Data, size ) )   LEAVE_RET('i', -1);
391                 memcpy( Data, iface->Address, size );
392                 LEAVE('i', 1);
393                 return 1;
394         
395         /*
396          * set_address
397          * - Set the interface's address
398          */
399         case 6:
400                 if( Threads_GetUID() != 0 )     LEAVE_RET('i', -1);
401                 
402                 size = IPStack_GetAddressSize(iface->Type);
403                 if( !CheckMem( Data, size ) )   LEAVE_RET('i', -1);
404                 // TODO: Protect against trashing
405                 memcpy( iface->Address, Data, size );
406                 LEAVE('i', 1);
407                 return 1;
408         
409         /*
410          * getset_subnet
411          * - Get/Set the bits in the address subnet
412          */
413         case 7:
414                 // Do we want to set the value?
415                 if( Data )
416                 {
417                         // Are we root? (TODO: Check Owner/Group)
418                         if( Threads_GetUID() != 0 )     LEAVE_RET('i', -1);
419                         // Is the memory valid
420                         if( !CheckMem(Data, sizeof(int)) )      LEAVE_RET('i', -1);
421                         
422                         // Is the mask sane?
423                         if( *(int*)Data < 0 || *(int*)Data > IPStack_GetAddressSize(iface->Type)*8-1 )
424                                 LEAVE_RET('i', -1);
425                         
426                         // Ok, set it
427                         iface->SubnetBits = *(int*)Data;
428                 }
429                 LEAVE('i', iface->SubnetBits);
430                 return iface->SubnetBits;
431         
432         /*
433          * get_device
434          * - Gets the name of the attached device
435          */
436         case 8:
437                 if( iface->Adapter == NULL )
438                         LEAVE_RET('i', 0);
439                 if( Data == NULL )
440                         LEAVE_RET('i', iface->Adapter->DeviceLen);
441                 if( !CheckMem( Data, iface->Adapter->DeviceLen+1 ) )
442                         LEAVE_RET('i', -1);
443                 strcpy( Data, iface->Adapter->Device );
444                 return iface->Adapter->DeviceLen;
445         
446         /*
447          * ping
448          * - Send an ICMP Echo
449          */
450         case 9:
451                 switch(iface->Type)
452                 {
453                 case 0:
454                         LEAVE_RET('i', 1);
455                 
456                 case 4:
457                         if( !CheckMem( Data, sizeof(tIPv4) ) )  LEAVE_RET('i', -1);
458                         tmp = IPv4_Ping(iface, *(tIPv4*)Data);
459                         LEAVE('i', tmp);
460                         return tmp;
461                         
462                 case 6:
463                         LEAVE_RET('i', 1);
464                 }
465                 break;
466         
467         }
468         
469         LEAVE('i', 0);
470         return 0;
471 }
472
473 // --- Internal ---
474 /**
475  * \fn tAdapter *IPStack_GetAdapter(const char *Path)
476  * \brief Gets/opens an adapter given the path
477  */
478 tAdapter *IPStack_GetAdapter(const char *Path)
479 {
480         tAdapter        *dev;
481          int    tmp;
482         
483         ENTER("sPath", Path);
484         
485         // Check for loopback
486         if( strcmp(Path, "LOOPBACK") == 0 )
487         {
488                 // Initialise if required
489                 if( gIP_LoopAdapter.DeviceFD == 0 )
490                 {
491                         dev = &gIP_LoopAdapter;
492                         
493                         dev->NRef = 1;
494                         dev->DeviceLen = 8;
495                         
496                         dev->DeviceFD = VFS_Open( "/Devices/fifo/anon", VFS_OPENFLAG_READ|VFS_OPENFLAG_WRITE );
497                         if( dev->DeviceFD == -1 ) {
498                                 Log_Warning("IPStack", "Unable to open FIFO '/Devices/fifo/anon' for loopback");
499                                 return NULL;
500                         }
501                         
502                         dev->MacAddr.B[0] = 'A';
503                         dev->MacAddr.B[1] = 'c';
504                         dev->MacAddr.B[2] = 'e';
505                         dev->MacAddr.B[3] = 's';
506                         dev->MacAddr.B[4] = 's';
507                         dev->MacAddr.B[5] = '2';
508                         
509                         // Start watcher
510                         Link_WatchDevice( dev );
511                 }
512                 LEAVE('p', &gIP_LoopAdapter);
513                 return &gIP_LoopAdapter;
514         }
515         
516         Mutex_Acquire( &glIP_Adapters );
517         
518         // Check if this adapter is already open
519         for( dev = gIP_Adapters; dev; dev = dev->Next )
520         {
521                 if( strcmp(dev->Device, Path) == 0 ) {
522                         dev->NRef ++;
523                         Mutex_Release( &glIP_Adapters );
524                         LEAVE('p', dev);
525                         return dev;
526                 }
527         }
528         
529         // Ok, so let's open it
530         dev = malloc( sizeof(tAdapter) + strlen(Path) + 1 );
531         if(!dev) {
532                 Log_Warning("IPStack", "GetAdapter - malloc() failed");
533                 Mutex_Release( &glIP_Adapters );
534                 LEAVE('n');
535                 return NULL;
536         }
537         
538         // Fill Structure
539         strcpy( dev->Device, Path );
540         dev->NRef = 1;
541         dev->DeviceLen = strlen(Path);
542         
543         // Open Device
544         dev->DeviceFD = VFS_Open( dev->Device, VFS_OPENFLAG_READ|VFS_OPENFLAG_WRITE );
545         if( dev->DeviceFD == -1 ) {
546                 free( dev );
547                 Mutex_Release( &glIP_Adapters );
548                 LEAVE('n');
549                 return NULL;
550         }
551         
552         // Check that it is a network interface
553         tmp = VFS_IOCtl(dev->DeviceFD, 0, NULL);
554         LOG("Device type = %i", tmp);
555         if( tmp != DRV_TYPE_NETWORK ) {
556                 Log_Warning("IPStack", "IPStack_GetAdapter: '%s' is not a network interface", dev->Device);
557                 VFS_Close( dev->DeviceFD );
558                 free( dev );
559                 Mutex_Release( &glIP_Adapters );
560                 LEAVE('n');
561                 return NULL;
562         }
563         
564         // Get MAC Address
565         VFS_IOCtl(dev->DeviceFD, NET_IOCTL_GETMAC, &dev->MacAddr);
566         
567         // Add to list
568         dev->Next = gIP_Adapters;
569         gIP_Adapters = dev;
570         
571         Mutex_Release( &glIP_Adapters );
572         
573         // Start watcher
574         Link_WatchDevice( dev );
575         
576         LEAVE('p', dev);
577         return dev;
578 }

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