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

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