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

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