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

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