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

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