5b122d8d0369853fa018b6e2e2496ad8f2dbaa85
[tpg/acess2.git] / Usermode / Applications / dhcpclient_src / main.c
1 /*
2  * 
3  * http://www.ietf.org/rfc/rfc2131.txt
4  */
5 #include <unistd.h>
6 #include <stdint.h>
7 #include <stdio.h>
8 #include <string.h>
9 #include <stdlib.h>
10 #include <net.h>
11 #include <acess/sys.h>
12
13 #define FILENAME_MAX    255
14 // --- Translation functions ---
15 static inline uint32_t htonl(uint32_t v)
16 {
17         return    (((v >> 24) & 0xFF) <<  0)
18                 | (((v >> 16) & 0xFF) <<  8)
19                 | (((v >>  8) & 0xFF) << 16)
20                 | (((v >>  0) & 0xFF) << 24);
21 }
22 static inline uint16_t htons(uint16_t v)
23 {
24         return    (((v >> 8) & 0xFF) <<  0)
25                 | (((v >> 0) & 0xFF) <<  8);
26 }
27 #define htonb(v)        v
28 #define ntohl(v)        htonl(v)
29 #define ntohs(v)        htons(v)
30
31 // === CONSTANTS ===
32 enum eStates
33 {
34         STATE_PREINIT,
35         STATE_DISCOVER_SENT,
36         STATE_REQUEST_SENT,
37         STATE_COMPLETE
38 };
39
40 // === STRUCTURES ===
41 #define DHCP_MAGIC      0x63825363
42 struct sDHCP_Message
43 {
44         uint8_t op;
45         uint8_t htype;  // 1 = Ethernet
46         uint8_t hlen;   // 6 bytes for MAC
47         uint8_t hops;   // Hop counting
48         uint32_t        xid;
49         uint16_t        secs;
50         uint16_t        flags;
51         uint32_t        ciaddr;
52         uint32_t        yiaddr;
53         uint32_t        siaddr;
54         uint32_t        giaddr;
55         uint8_t chaddr[16];
56         uint8_t sname[64];
57         uint8_t file[128];
58         uint32_t        dhcp_magic;     // 0x63 0x82 0x53 0x63
59         uint8_t options[];
60 };
61
62 typedef struct sInterface
63 {
64         struct sInterface       *Next;
65         char    *Adapter;
66          int    State;
67          int    Num;
68          int    SocketFD;
69          int    IfaceFD;
70
71         uint32_t        TransactionID;
72         char    HWAddr[6];
73         
74         int64_t Timeout;
75 } tInterface;
76
77 // === PROTOTYPES ===
78 int     main(int argc, char *argv[]);
79 void    Scan_Dir(tInterface **IfaceList, const char *Directory);
80 int     Start_Interface(tInterface *Iface);
81 void    Send_DHCPDISCOVER(tInterface *Iface);
82 void    Send_DHCPREQUEST(tInterface *Iface, void *OfferBuffer, int TypeOffset);
83 int     Handle_Packet(tInterface *Iface);
84 void    Handle_Timeout(tInterface *Iface);
85 void    Update_State(tInterface *Iface, int newState);
86 void    SetAddress(tInterface *Iface, void *Addr, void *Mask, void *Router);
87
88 // === CODE ===
89 int main(int argc, char *argv[])
90 {
91         tInterface      *ifaces = NULL, *i;
92
93         // TODO: Scan /Devices and search for network adapters
94         if( argc > 2 ) {
95                 fprintf(stderr, "Usage: %s <interface>\n", argv[0]);
96                 return -1;
97         }
98         
99         if( argc == 2 ) {
100                 ifaces = malloc(sizeof(tInterface));
101                 ifaces->Next = NULL;
102                 ifaces->Adapter = argv[1];
103         }
104         else {
105                 Scan_Dir( &ifaces, "/Devices/ip/adapters" );
106         }
107
108         for( i = ifaces; i; i = i->Next )
109         {
110                 if( Start_Interface(i) < 0 ) {
111                         return -1;
112                 }
113                 i->State = STATE_PREINIT;
114                 
115                 // Send request
116                 Send_DHCPDISCOVER(i);
117         }
118
119         while( ifaces ) 
120         {
121                  int    maxfd;
122                 fd_set  fds;
123                 tInterface      *p;
124                 int64_t timeout = 1000;
125         
126                 maxfd = 0;
127                 FD_ZERO(&fds);
128                 for( i = ifaces; i; i = i->Next )
129                 {
130                         FD_SET(i->SocketFD, &fds);
131                         if(maxfd < i->SocketFD) maxfd = i->SocketFD;
132                 }
133                 
134                 if( select(maxfd+1, &fds, NULL, NULL, &timeout) < 0 )
135                 {
136                         // TODO: Check error result
137                         return -1;
138                 }
139
140                 _SysDebug("select() returned");
141
142                 // Check for changes (with magic to allow inline deletion)
143                 for( p = (void*)&ifaces, i = ifaces; i; p=i,i = i->Next )
144                 {
145                         if( FD_ISSET(i->SocketFD, &fds) )
146                         {
147                                 if( Handle_Packet( i ) )
148                                 {
149                                         _SysClose(i->SocketFD);
150                                         _SysClose(i->IfaceFD);
151                                         p->Next = i->Next;
152                                         free(i);
153                                         i = p;
154                                 }
155                         }
156                         
157                         if( _SysTimestamp() > i->Timeout )
158                         {
159                                 Handle_Timeout(i);
160                         }
161                 }
162         }
163         return 0;
164 }
165
166 void Scan_Dir(tInterface **IfaceList, const char *Directory)
167 {
168         int dp = _SysOpen(Directory, OPENFLAG_READ);
169         char filename[FILENAME_MAX];
170
171         if( dp == -1 ) {
172                 fprintf(stderr, "Unable to open directory '%s'\n", Directory);
173                 return ;
174         }
175
176         while( _SysReadDir(dp, filename) )
177         {
178                 if( filename[0] == '.' )        continue ;              
179                 if( strcmp(filename, "lo") == 0 )       continue ;
180
181                 tInterface *new = malloc(sizeof(tInterface) + strlen(filename)+1);
182                 new->Adapter = (void*)(new + 1);
183                 strcpy(new->Adapter, filename);
184                 new->Next = *IfaceList;
185                 *IfaceList = new;
186         }
187         _SysClose(dp);
188 }
189
190 // RETURN: Client FD
191 int Start_Interface(tInterface *Iface)
192 {
193          int    fd, tmp;
194         char    path[] = "/Devices/ip/XXXXX/udpc";
195         char    addr[4] = {0,0,0,0};
196         
197         // TODO: Check that the adapter is not in use
198         
199         // Request MAC address from network adapter
200         {
201                 char    path[] = "/Devices/ip/adapters/ethXXXX";
202                 sprintf(path, "/Devices/ip/adapters/%s", Iface->Adapter);
203                 fd = _SysOpen(path, 0);
204                 if(fd == -1) {
205                         _SysDebug("Unable to open adapter %s", path);
206                         return -1;
207                 }
208                 _SysIOCtl(fd, 4, Iface->HWAddr);
209                 // TODO: Check if ioctl() failed
210                 _SysClose(fd);
211         }
212         
213         // Initialise an interface, with a dummy IP address (zero)
214         fd = _SysOpen("/Devices/ip", 0);
215         if( fd == -1 ) {
216                 fprintf(stderr, "ERROR: Unable to open '/Devices/ip'\n"); 
217                 return -1;
218         }
219         Iface->Num = _SysIOCtl(fd, 4, (void*)Iface->Adapter);   // Create interface
220         if( Iface->Num == -1 ) {
221                 fprintf(stderr, "ERROR: Unable to create new interface\n");
222                 return -1;
223         }
224         _SysClose(fd);
225         
226         // Open new interface
227         snprintf(path, sizeof(path), "/Devices/ip/%i", Iface->Num);
228         Iface->IfaceFD = fd = _SysOpen(path, 0);
229         if( fd == -1 ) {
230                 fprintf(stderr, "ERROR: Unable to open '%s'\n", path); 
231                 return -1;
232         }
233         tmp = 4; _SysIOCtl(fd, 4, &tmp);        // Set to IPv4
234         _SysIOCtl(fd, 6, addr); // Set address to 0.0.0.0
235         tmp = 0; _SysIOCtl(fd, 7, &tmp);        // Set subnet mask to 0
236
237         // Open UDP Client
238         snprintf(path, sizeof(path), "/Devices/ip/%i/udp", Iface->Num);
239         Iface->SocketFD = fd = _SysOpen(path, O_RDWR);
240         if( fd == -1 ) {
241                 fprintf(stderr, "ERROR: Unable to open '%s'\n", path); 
242                 return -1;
243         }
244         tmp = 68; _SysIOCtl(fd, 4, &tmp);       // Local port
245         tmp = 67; _SysIOCtl(fd, 5, &tmp);       // Remote port
246         tmp = 0;        _SysIOCtl(fd, 7, &tmp); // Remote addr mask bits - we don't care where the reply comes from
247         addr[0] = addr[1] = addr[2] = addr[3] = 255;    // 255.255.255.255
248         _SysIOCtl(fd, 8, addr); // Remote address
249         
250         return 0;
251 }
252
253 void Send_DHCPRELEASE(tInterface *Iface)
254 {
255 }
256
257 void Send_DHCPDISCOVER(tInterface *Iface)
258 {
259         uint32_t        transaction_id;
260         struct sDHCP_Message    *msg;
261         char    data[8 + sizeof(struct sDHCP_Message) + 3 + 1];
262         msg = (void*)data + 8;
263         
264         _SysDebug("DHCPDISCOVER to %s", Iface->Adapter);
265
266         transaction_id = rand();
267         Iface->TransactionID = transaction_id;
268
269         msg->op    = htonb(1);  // BOOTREQUEST
270         msg->htype = htonb(1);  // 10mb Ethernet
271         msg->hlen  = htonb(6);  // 6 byte MAC
272         msg->hops  = htonb(0);  // Hop count so far
273         msg->xid   = htonl(transaction_id);     // Transaction ID
274         msg->secs  = htons(0);  // secs - No time has elapsed
275         msg->flags = htons(0x0000);     // flags - Broadcast is unset
276         msg->ciaddr = htonl(0); // ciaddr - Zero, as we don't have one yet
277         msg->yiaddr = htonl(0); // yiaddr - Zero?
278         msg->siaddr = htonl(0); // siaddr - Zero? maybe -1
279         msg->giaddr = htonl(0); // giaddr - Zero?
280         memcpy(msg->chaddr, Iface->HWAddr, 6);
281
282         memset(msg->sname, 0, sizeof(msg->sname));      // Nuke the rest
283         memset(msg->file, 0, sizeof(msg->file));        // Nuke the rest
284         msg->dhcp_magic = htonl(DHCP_MAGIC);
285
286         int i = 0;
287         msg->options[i++] =  53;        // DHCP Message Type
288         msg->options[i++] =   1;
289         msg->options[i++] =   1;        // - DHCPDISCOVER
290         msg->options[i++] = 255;        // End of list
291         
292
293         data[0] = 67;   data[1] = 0;    // Port
294         data[2] = 4;    data[3] = 0;    // AddrType
295         data[4] = 255;  data[5] = 255;  data[6] = 255;  data[7] = 255;
296
297         _SysWrite(Iface->SocketFD, data, sizeof(data));
298         Update_State(Iface, STATE_DISCOVER_SENT);
299 }
300
301 void Send_DHCPREQUEST(tInterface *Iface, void *OfferPacket, int TypeOffset)
302 {
303         struct sDHCP_Message    *msg;
304          int    i;
305         msg = (void*) ((char*)OfferPacket) + 8;
306
307         // Reuses old data :)
308         msg->op    = 1;
309         msg->htype = 1;
310         msg->hlen  = 6;
311         msg->hops  = 0;
312         msg->xid   = msg->xid;
313         msg->secs  = htons(0);  // TODO: Maintain times
314         msg->flags = htons(0);
315         memcpy(msg->chaddr, Iface->HWAddr, 6);
316         memset(msg->sname, 0, sizeof(msg->sname));      // Nuke the rest
317         memset(msg->file, 0, sizeof(msg->file));        // Nuke the rest
318
319         i = 0;
320         msg->options[i++] = 53; // Message type = DHCPREQUEST
321         msg->options[i++] = 1;
322         msg->options[i++] = 3;
323         msg->options[i++] = 50; // Requested Address
324         msg->options[i++] = 4;
325         memcpy(msg->options + i, &msg->yiaddr, 4);      i += 4;
326 //      msg->options[i++] = 54; // Server identifier
327 //      msg->options[i++] = 4;
328 //      memcpy(msg->options + i, (char*)OfferPacket + 4, 4);    i += 4;
329         msg->options[i++] = 255;
330         
331         // Clear last because yiaddr is needed in option setup
332         msg->ciaddr = htonl(0);
333         msg->yiaddr = htonl(0);
334         msg->siaddr = htonl(0);
335         msg->giaddr = htonl(0);
336
337         // HACK
338         ((uint8_t*)OfferPacket)[4] = 255;
339         ((uint8_t*)OfferPacket)[5] = 255;
340         ((uint8_t*)OfferPacket)[6] = 255;
341         ((uint8_t*)OfferPacket)[7] = 255;
342         
343         _SysWrite(Iface->SocketFD, OfferPacket, 8 + sizeof(*msg) + i);
344         Update_State(Iface, STATE_REQUEST_SENT);
345 }
346
347 int Handle_Packet(tInterface *Iface)
348 {
349         char    data[8+576];
350         struct sDHCP_Message    *msg = (void*)(data + 8);
351          int    len, i;
352         
353          int    dhcp_msg_type = 0, dhcp_msg_type_ofs;
354         void    *router = NULL;
355         void    *subnet_mask = NULL;
356         
357         _SysDebug("Doing read on %i", Iface->SocketFD);
358         len = _SysRead(Iface->SocketFD, data, sizeof(data));
359         _SysDebug("len = %i", len);
360
361         _SysDebug("*msg = {");
362         _SysDebug("  .op = %i", msg->op);
363         _SysDebug("  .htype = %i", msg->htype);
364         _SysDebug("  .ciaddr = 0x%x", ntohl(msg->ciaddr));
365         _SysDebug("  .yiaddr = 0x%x", ntohl(msg->yiaddr));
366         _SysDebug("}");
367         if( msg->op != 2 ) {
368                 // Not a response
369                 _SysDebug("Not a response message");
370                 return 0;
371         }
372
373         if( htonl(msg->dhcp_magic) != DHCP_MAGIC ) {
374                 _SysDebug("DHCP magic doesn't match (got 0x%x, expected 0x%x)",
375                         htonl(msg->dhcp_magic), DHCP_MAGIC);
376                 return 0;
377         }       
378
379
380         // Check if the packet is related to our requests
381         if( ntohl(msg->xid) != Iface->TransactionID ) {
382                 _SysDebug("Transaction ID mis-match, ignoring (0x%x != 0x%x)",
383                         ntohl(msg->xid), Iface->TransactionID);
384                 return 0;
385         }
386         if( memcmp(msg->chaddr, Iface->HWAddr, 6) != 0 ) {
387                 _SysDebug("Hardware address mis-match, ignoring");
388                 return 0;
389         }
390
391         // Parse options
392         i = 0;
393         while( i < len - sizeof(*msg) - 8 && msg->options[i] != 255 )
394         {
395                 if( msg->options[i] == 0 ) {
396                         i ++;
397                         continue ;
398                 }
399                 _SysDebug("Option %i, %i bytes long", msg->options[i], msg->options[i+1]);
400                 switch(msg->options[i])
401                 {
402                 case 1:
403                         subnet_mask = &msg->options[i+2];
404                         break;
405                 case 3:
406                         router = &msg->options[i+2];
407                         break;
408                 case 53:
409                         dhcp_msg_type_ofs = i;
410                         dhcp_msg_type = msg->options[i+2];
411                         break;
412                 }
413                 i += msg->options[i+1]+2;
414         }
415         
416         _SysDebug("dhcp_msg_type = %i", dhcp_msg_type);
417
418         switch( dhcp_msg_type )
419         {
420         case 1: // DHCPDISCOVER - wut?
421                 break;
422         case 2: // DHCPOFFER
423                 // Send out request for this address
424                 if( Iface->State != STATE_DISCOVER_SENT ) {
425                         _SysDebug("Ignoring DHCPOFFER when not in STATE_DISCOVER_SENT");
426                         return 0;
427                 }
428                 Send_DHCPREQUEST(Iface, data, dhcp_msg_type_ofs);
429                 break;
430         case 3: // DHCPREQUEST - wut?
431                 break;
432         case 4: // DHCPDECLINE - ?
433                 break;
434         case 5: // DHCPACK
435                 SetAddress(Iface, &msg->yiaddr, subnet_mask, router);
436                 // Return 1 to remove from list
437                 return 1;
438         }
439         return 0;
440 }
441
442 void Handle_Timeout(tInterface *Iface)
443 {
444         switch(Iface->State)
445         {
446         case STATE_DISCOVER_SENT:
447                 Send_DHCPDISCOVER(Iface);
448                 break;
449         default:
450                 _SysDebug("Timeout with state = %i", Iface->State);
451                 break;
452         }
453 }
454
455 void Update_State(tInterface *Iface, int newState)
456 {
457         if( Iface->State != newState )
458         {
459                 Iface->Timeout = _SysTimestamp() + 500;
460                 Iface->State = newState;
461         }
462         else
463         {
464                 // TODO: Exponential backoff
465                 Iface->Timeout = _SysTimestamp() + 3000;
466                 _SysDebug("State %i repeated, timeout is 3000ms now", newState);
467         }
468 }
469
470 void SetAddress(tInterface *Iface, void *Addr, void *Mask, void *Router)
471 {
472          int    mask_bits = 0;  
473
474         // Translate the mask
475         if( Mask )
476         {
477                 uint8_t *mask = Mask;
478                  int    i;
479                 _SysDebug("Mask %i.%i.%i.%i", mask[0], mask[1], mask[2], mask[3]);
480                 for( i = 0; i < 4 && mask[i] == 0xFF; i ++ ) ;
481                 mask_bits = i*8;
482                 if( i == 4 )
483                 {
484                         // Wut? /32?
485                 }
486                 else
487                 {
488                         switch(mask[i])
489                         {
490                         case 0x00:      mask_bits += 0; break;
491                         case 0x80:      mask_bits += 1; break;
492                         case 0xC0:      mask_bits += 2; break;
493                         case 0xE0:      mask_bits += 3; break;
494                         case 0xF0:      mask_bits += 4; break;
495                         case 0xF8:      mask_bits += 5; break;
496                         case 0xFC:      mask_bits += 6; break;
497                         case 0xFE:      mask_bits += 7; break;
498                         default:
499                                 // Bad mask!
500                                 break;
501                         }
502                 }
503         }
504         
505         {
506                 uint8_t *addr = Addr;
507                 _SysDebug("Addr %i.%i.%i.%i/%i", addr[0], addr[1], addr[2], addr[3], mask_bits);
508
509                 printf("Assigned %i.%i.%i.%i/%i to IF#%i (%s)\n",
510                         addr[0], addr[1], addr[2], addr[3], mask_bits,
511                         Iface->Num, Iface->Adapter
512                         );
513         }
514
515         _SysIOCtl(Iface->IfaceFD, 6, Addr);
516         _SysIOCtl(Iface->IfaceFD, 7, &mask_bits);
517
518         if( Router );
519         {
520                 uint8_t *addr = Router;
521                 _SysDebug("Router %i.%i.%i.%i", addr[0], addr[1], addr[2], addr[3]);
522                 
523                 // Set default route
524                  int    fd;
525                 fd = _SysOpen("/Devices/ip/routes/4:00000000:0:0", OPENFLAG_CREATE);
526                 if(fd == -1) {
527                         fprintf(stderr, "ERROR: Unable to open default route\n");
528                 }
529                 else {
530                         char ifname[snprintf(NULL,0,"%i",Iface->Num)+1];
531                         sprintf(ifname, "%i", Iface->Num);
532                         _SysIOCtl(fd, _SysIOCtl(fd, 3, "set_nexthop"), Router);
533                         _SysIOCtl(fd, _SysIOCtl(fd, 3, "set_interface"), ifname);
534                         _SysClose(fd);
535                 }
536         }
537 }
538

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