User enumeration implemented
[tpg/opendispense2.git] / src / server / server.c
1 /*
2  * OpenDispense 2 
3  * UCC (University [of WA] Computer Club) Electronic Accounting System
4  *
5  * server.c - Client Server Code
6  *
7  * This file is licenced under the 3-clause BSD Licence. See the file
8  * COPYING for full details.
9  */
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include "common.h"
13 #include <sys/socket.h>
14 #include <netinet/in.h>
15 #include <arpa/inet.h>
16 #include <unistd.h>
17 #include <string.h>
18 #include <limits.h>
19 #include <stdarg.h>
20
21 // HACKS
22 #define HACK_TPG_NOAUTH 1
23 #define HACK_ROOT_NOAUTH        1
24
25 #define DEBUG_TRACE_CLIENT      1
26
27 // Statistics
28 #define MAX_CONNECTION_QUEUE    5
29 #define INPUT_BUFFER_SIZE       256
30
31 #define HASH_TYPE       SHA1
32 #define HASH_LENGTH     20
33
34 #define MSG_STR_TOO_LONG        "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
35
36 // === TYPES ===
37 typedef struct sClient
38 {
39          int    Socket; // Client socket ID
40          int    ID;     // Client ID
41          
42          int    bIsTrusted;     // Is the connection from a trusted host/port
43         
44         char    *Username;
45         char    Salt[9];
46         
47          int    UID;
48          int    bIsAuthed;
49 }       tClient;
50
51 // === PROTOTYPES ===
52 void    Server_Start(void);
53 void    Server_Cleanup(void);
54 void    Server_HandleClient(int Socket, int bTrusted);
55 char    *Server_ParseClientCommand(tClient *Client, char *CommandString);
56 // --- Commands ---
57 char    *Server_Cmd_USER(tClient *Client, char *Args);
58 char    *Server_Cmd_PASS(tClient *Client, char *Args);
59 char    *Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
60 char    *Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
61 char    *Server_Cmd_ITEMINFO(tClient *Client, char *Args);
62 char    *Server_Cmd_DISPENSE(tClient *Client, char *Args);
63 char    *Server_Cmd_GIVE(tClient *Client, char *Args);
64 char    *Server_Cmd_ADD(tClient *Client, char *Args);
65 char    *Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
66 char    *Server_Cmd_USERINFO(tClient *Client, char *Args);
67 // --- Helpers ---
68  int    sendf(int Socket, const char *Format, ...);
69  int    GetUserAuth(const char *Salt, const char *Username, const uint8_t *Hash);
70 void    HexBin(uint8_t *Dest, char *Src, int BufSize);
71
72 // === GLOBALS ===
73  int    giServer_Port = 1020;
74  int    giServer_NextClientID = 1;
75 // - Commands
76 struct sClientCommand {
77         char    *Name;
78         char    *(*Function)(tClient *Client, char *Arguments);
79 }       gaServer_Commands[] = {
80         {"USER", Server_Cmd_USER},
81         {"PASS", Server_Cmd_PASS},
82         {"AUTOAUTH", Server_Cmd_AUTOAUTH},
83         {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
84         {"ITEM_INFO", Server_Cmd_ITEMINFO},
85         {"DISPENSE", Server_Cmd_DISPENSE},
86         {"GIVE", Server_Cmd_GIVE},
87         {"ADD", Server_Cmd_ADD},
88         {"ENUM_USERS", Server_Cmd_ENUMUSERS},
89         {"USER_INFO", Server_Cmd_USERINFO}
90 };
91 #define NUM_COMMANDS    (sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0]))
92  int    giServer_Socket;
93
94 // === CODE ===
95 /**
96  * \brief Open listenting socket and serve connections
97  */
98 void Server_Start(void)
99 {
100          int    client_socket;
101         struct sockaddr_in      server_addr, client_addr;
102
103         atexit(Server_Cleanup);
104
105         // Create Server
106         giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
107         if( giServer_Socket < 0 ) {
108                 fprintf(stderr, "ERROR: Unable to create server socket\n");
109                 return ;
110         }
111         
112         // Make listen address
113         memset(&server_addr, 0, sizeof(server_addr));
114         server_addr.sin_family = AF_INET;       // Internet Socket
115         server_addr.sin_addr.s_addr = htonl(INADDR_ANY);        // Listen on all interfaces
116         server_addr.sin_port = htons(giServer_Port);    // Port
117
118         // Bind
119         if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
120                 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
121                 perror("Binding");
122                 return ;
123         }
124         
125         // Listen
126         if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
127                 fprintf(stderr, "ERROR: Unable to listen to socket\n");
128                 perror("Listen");
129                 return ;
130         }
131         
132         printf("Listening on 0.0.0.0:%i\n", giServer_Port);
133         
134         for(;;)
135         {
136                 uint    len = sizeof(client_addr);
137                  int    bTrusted = 0;
138                 
139                 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
140                 if(client_socket < 0) {
141                         fprintf(stderr, "ERROR: Unable to accept client connection\n");
142                         return ;
143                 }
144                 
145                 if(giDebugLevel >= 2) {
146                         char    ipstr[INET_ADDRSTRLEN];
147                         inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
148                         printf("Client connection from %s:%i\n",
149                                 ipstr, ntohs(client_addr.sin_port));
150                 }
151                 
152                 // Trusted Connections
153                 if( ntohs(client_addr.sin_port) < 1024 )
154                 {
155                         // TODO: Make this runtime configurable
156                         switch( ntohl( client_addr.sin_addr.s_addr ) )
157                         {
158                         case 0x7F000001:        // 127.0.0.1    localhost
159                         //case 0x825E0D00:      // 130.95.13.0
160                         case 0x825E0D12:        // 130.95.13.18 mussel
161                         case 0x825E0D17:        // 130.95.13.23 martello
162                                 bTrusted = 1;
163                                 break;
164                         default:
165                                 break;
166                         }
167                 }
168                 
169                 // TODO: Multithread this?
170                 Server_HandleClient(client_socket, bTrusted);
171                 
172                 close(client_socket);
173         }
174 }
175
176 void Server_Cleanup(void)
177 {
178         printf("Close(%i)\n", giServer_Socket);
179         close(giServer_Socket);
180 }
181
182 /**
183  * \brief Reads from a client socket and parses the command strings
184  * \param Socket        Client socket number/handle
185  * \param bTrusted      Is the client trusted?
186  */
187 void Server_HandleClient(int Socket, int bTrusted)
188 {
189         char    inbuf[INPUT_BUFFER_SIZE];
190         char    *buf = inbuf;
191          int    remspace = INPUT_BUFFER_SIZE-1;
192          int    bytes = -1;
193         tClient clientInfo = {0};
194         
195         // Initialise Client info
196         clientInfo.Socket = Socket;
197         clientInfo.ID = giServer_NextClientID ++;
198         clientInfo.bIsTrusted = bTrusted;
199         
200         // Read from client
201         /*
202          * Notes:
203          * - The `buf` and `remspace` variables allow a line to span several
204          *   calls to recv(), if a line is not completed in one recv() call
205          *   it is saved to the beginning of `inbuf` and `buf` is updated to
206          *   the end of it.
207          */
208         while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
209         {
210                 char    *eol, *start;
211                 buf[bytes] = '\0';      // Allow us to use stdlib string functions on it
212                 
213                 // Split by lines
214                 start = inbuf;
215                 while( (eol = strchr(start, '\n')) )
216                 {
217                         char    *ret;
218                         *eol = '\0';
219                         ret = Server_ParseClientCommand(&clientInfo, start);
220                         
221                         #if DEBUG_TRACE_CLIENT
222                         printf("send : %s", ret);
223                         #endif
224                         
225                         // `ret` is a string on the heap
226                         send(Socket, ret, strlen(ret), 0);
227                         free(ret);
228                         start = eol + 1;
229                 }
230                 
231                 // Check if there was an incomplete line
232                 if( *start != '\0' ) {
233                          int    tailBytes = bytes - (start-buf);
234                         // Roll back in buffer
235                         memcpy(inbuf, start, tailBytes);
236                         remspace -= tailBytes;
237                         if(remspace == 0) {
238                                 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
239                                 buf = inbuf;
240                                 remspace = INPUT_BUFFER_SIZE - 1;
241                         }
242                 }
243                 else {
244                         buf = inbuf;
245                         remspace = INPUT_BUFFER_SIZE - 1;
246                 }
247         }
248         
249         // Check for errors
250         if( bytes < 0 ) {
251                 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
252                 return ;
253         }
254         
255         if(giDebugLevel >= 2) {
256                 printf("Client %i: Disconnected\n", clientInfo.ID);
257         }
258 }
259
260 /**
261  * \brief Parses a client command and calls the required helper function
262  * \param Client        Pointer to client state structure
263  * \param CommandString Command from client (single line of the command)
264  * \return Heap String to return to the client
265  */
266 char *Server_ParseClientCommand(tClient *Client, char *CommandString)
267 {
268         char    *space, *args;
269          int    i;
270         
271         // Split at first space
272         space = strchr(CommandString, ' ');
273         if(space == NULL) {
274                 args = NULL;
275         }
276         else {
277                 *space = '\0';
278                 args = space + 1;
279         }
280         
281         // Find command
282         for( i = 0; i < NUM_COMMANDS; i++ )
283         {
284                 if(strcmp(CommandString, gaServer_Commands[i].Name) == 0)
285                         return gaServer_Commands[i].Function(Client, args);
286         }
287         
288         return strdup("400 Unknown Command\n");
289 }
290
291 // ---
292 // Commands
293 // ---
294 /**
295  * \brief Set client username
296  * 
297  * Usage: USER <username>
298  */
299 char *Server_Cmd_USER(tClient *Client, char *Args)
300 {
301         char    *ret;
302         
303         // Debug!
304         if( giDebugLevel )
305                 printf("Client %i authenticating as '%s'\n", Client->ID, Args);
306         
307         // Save username
308         if(Client->Username)
309                 free(Client->Username);
310         Client->Username = strdup(Args);
311         
312         #if USE_SALT
313         // Create a salt (that changes if the username is changed)
314         // Yes, I know, I'm a little paranoid, but who isn't?
315         Client->Salt[0] = 0x21 + (rand()&0x3F);
316         Client->Salt[1] = 0x21 + (rand()&0x3F);
317         Client->Salt[2] = 0x21 + (rand()&0x3F);
318         Client->Salt[3] = 0x21 + (rand()&0x3F);
319         Client->Salt[4] = 0x21 + (rand()&0x3F);
320         Client->Salt[5] = 0x21 + (rand()&0x3F);
321         Client->Salt[6] = 0x21 + (rand()&0x3F);
322         Client->Salt[7] = 0x21 + (rand()&0x3F);
323         
324         // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
325         ret = mkstr("100 SALT %s\n", Client->Salt);
326         #else
327         ret = strdup("100 User Set\n");
328         #endif
329         return ret;
330 }
331
332 /**
333  * \brief Authenticate as a user
334  * 
335  * Usage: PASS <hash>
336  */
337 char *Server_Cmd_PASS(tClient *Client, char *Args)
338 {
339         uint8_t clienthash[HASH_LENGTH] = {0};
340         
341         // Read user's hash
342         HexBin(clienthash, Args, HASH_LENGTH);
343         
344         // TODO: Decrypt password passed
345         
346         Client->UID = GetUserAuth(Client->Salt, Client->Username, clienthash);
347
348         if( Client->UID != -1 ) {
349                 Client->bIsAuthed = 1;
350                 return strdup("200 Auth OK\n");
351         }
352
353         if( giDebugLevel ) {
354                  int    i;
355                 printf("Client %i: Password hash ", Client->ID);
356                 for(i=0;i<HASH_LENGTH;i++)
357                         printf("%02x", clienthash[i]&0xFF);
358                 printf("\n");
359         }
360         
361         return strdup("401 Auth Failure\n");
362 }
363
364 /**
365  * \brief Authenticate as a user without a password
366  * 
367  * Usage: AUTOAUTH <user>
368  */
369 char *Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
370 {
371         char    *spos = strchr(Args, ' ');
372         if(spos)        *spos = '\0';   // Remove characters after the ' '
373         
374         // Check if trusted
375         if( !Client->bIsTrusted ) {
376                 if(giDebugLevel)
377                         printf("Client %i: Untrusted client attempting to AUTOAUTH\n", Client->ID);
378                 return strdup("401 Untrusted\n");
379         }
380         
381         // Get UID
382         Client->UID = GetUserID( Args );
383         if( Client->UID < 0 ) {
384                 if(giDebugLevel)
385                         printf("Client %i: Unknown user '%s'\n", Client->ID, Args);
386                 return strdup("401 Auth Failure\n");
387         }
388         
389         if(giDebugLevel)
390                 printf("Client %i: Authenticated as '%s' (%i)\n", Client->ID, Args, Client->UID);
391         
392         return strdup("200 Auth OK\n");
393 }
394
395 /**
396  * \brief Enumerate the items that the server knows about
397  */
398 char *Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
399 {
400          int    retLen;
401          int    i;
402         char    *ret;
403
404         retLen = snprintf(NULL, 0, "201 Items %i", giNumItems);
405
406         for( i = 0; i < giNumItems; i ++ )
407         {
408                 retLen += snprintf(NULL, 0, " %s:%i", gaItems[i].Handler->Name, gaItems[i].ID);
409         }
410
411         ret = malloc(retLen+1);
412         retLen = 0;
413         retLen += sprintf(ret+retLen, "201 Items %i", giNumItems);
414
415         for( i = 0; i < giNumItems; i ++ ) {
416                 retLen += sprintf(ret+retLen, " %s:%i", gaItems[i].Handler->Name, gaItems[i].ID);
417         }
418
419         strcat(ret, "\n");
420
421         return ret;
422 }
423
424 tItem *_GetItemFromString(char *String)
425 {
426         tHandler        *handler;
427         char    *type = String;
428         char    *colon = strchr(String, ':');
429          int    num, i;
430         
431         if( !colon ) {
432                 return NULL;
433         }
434
435         num = atoi(colon+1);
436         *colon = '\0';
437
438         // Find handler
439         handler = NULL;
440         for( i = 0; i < giNumHandlers; i ++ )
441         {
442                 if( strcmp(gaHandlers[i]->Name, type) == 0) {
443                         handler = gaHandlers[i];
444                         break;
445                 }
446         }
447         if( !handler ) {
448                 return NULL;
449         }
450
451         // Find item
452         for( i = 0; i < giNumItems; i ++ )
453         {
454                 if( gaItems[i].Handler != handler )     continue;
455                 if( gaItems[i].ID != num )      continue;
456                 return &gaItems[i];
457         }
458         return NULL;
459 }
460
461 /**
462  * \brief Fetch information on a specific item
463  */
464 char *Server_Cmd_ITEMINFO(tClient *Client, char *Args)
465 {
466          int    retLen = 0;
467         char    *ret;
468         tItem   *item = _GetItemFromString(Args);
469         
470         if( !item ) {
471                 return strdup("406 Bad Item ID\n");
472         }
473
474         // Create return
475         retLen = snprintf(NULL, 0, "202 Item %s:%i %i %s\n",
476                 item->Handler->Name, item->ID, item->Price, item->Name);
477         ret = malloc(retLen+1);
478         sprintf(ret, "202 Item %s:%i %i %s\n",
479                 item->Handler->Name, item->ID, item->Price, item->Name);
480
481         return ret;
482 }
483
484 char *Server_Cmd_DISPENSE(tClient *Client, char *Args)
485 {
486         tItem   *item;
487          int    ret;
488         if( !Client->bIsAuthed )        return strdup("401 Not Authenticated\n");
489
490         item = _GetItemFromString(Args);
491         if( !item ) {
492                 return strdup("406 Bad Item ID\n");
493         }
494
495         switch( ret = DispenseItem( Client->UID, item ) )
496         {
497         case 0: return strdup("200 Dispense OK\n");
498         case 1: return strdup("501 Unable to dispense\n");
499         case 2: return strdup("402 Poor You\n");
500         default:
501                 return strdup("500 Dispense Error\n");
502         }
503 }
504
505 char *Server_Cmd_GIVE(tClient *Client, char *Args)
506 {
507         char    *recipient, *ammount, *reason;
508          int    uid, iAmmount;
509         
510         if( !Client->bIsAuthed )        return strdup("401 Not Authenticated\n");
511
512         recipient = Args;
513
514         ammount = strchr(Args, ' ');
515         if( !ammount )  return strdup("407 Invalid Argument, expected 3 parameters, 1 encountered\n");
516         *ammount = '\0';
517         ammount ++;
518
519         reason = strchr(ammount, ' ');
520         if( !reason )   return strdup("407 Invalid Argument, expected 3 parameters, 2 encountered\n");
521         *reason = '\0';
522         reason ++;
523
524         // Get recipient
525         uid = GetUserID(recipient);
526         if( uid == -1 ) return strdup("404 Invalid target user");
527
528         // Parse ammount
529         iAmmount = atoi(ammount);
530         if( iAmmount <= 0 )     return strdup("407 Invalid Argument, ammount must be > zero\n");
531
532         // Do give
533         switch( DispenseGive(Client->UID, uid, iAmmount, reason) )
534         {
535         case 0:
536                 return strdup("200 Give OK\n");
537         case 2:
538                 return strdup("402 Poor You\n");
539         default:
540                 return strdup("500 Unknown error\n");
541         }
542 }
543
544 char *Server_Cmd_ADD(tClient *Client, char *Args)
545 {
546         char    *user, *ammount, *reason;
547          int    uid, iAmmount;
548         
549         if( !Client->bIsAuthed )        return strdup("401 Not Authenticated\n");
550
551         user = Args;
552
553         ammount = strchr(Args, ' ');
554         if( !ammount )  return strdup("407 Invalid Argument, expected 3 parameters, 1 encountered\n");
555         *ammount = '\0';
556         ammount ++;
557
558         reason = strchr(ammount, ' ');
559         if( !reason )   return strdup("407 Invalid Argument, expected 3 parameters, 2 encountered\n");
560         *reason = '\0';
561         reason ++;
562
563         // TODO: Check if the current user is in coke/higher
564
565         // Get recipient
566         uid = GetUserID(user);
567         if( uid == -1 ) return strdup("404 Invalid user");
568
569         // Parse ammount
570         iAmmount = atoi(ammount);
571         if( iAmmount == 0 && ammount[0] != '0' )
572                 return strdup("407 Invalid Argument\n");
573
574         // Do give
575         switch( DispenseAdd(uid, Client->UID, iAmmount, reason) )
576         {
577         case 0:
578                 return strdup("200 Add OK\n");
579         case 2:
580                 return strdup("402 Poor Guy\n");
581         default:
582                 return strdup("500 Unknown error\n");
583         }
584 }
585
586 char *Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
587 {
588          int    i, numRet = 0;
589          int    maxBal = INT_MAX, minBal = INT_MIN;
590          int    numUsr = GetMaxID();
591         
592         // Parse arguments
593         //minBal = atoi(Args);
594         
595         // Get return number
596         for( i = 0; i < numUsr; i ++ )
597         {
598                 int bal = GetBalance(i);
599                 
600                 if( bal == INT_MIN )    continue;
601                 
602                 if( bal < minBal )      continue;
603                 if( bal > maxBal )      continue;
604                 
605                 numRet ++;
606         }
607         
608         // Send count
609         sendf(Client->Socket, "201 Users %i\n", numRet);
610         
611         for( i = 0; i < numUsr; i ++ )
612         {
613                 int bal = GetBalance(i);
614                 
615                 if( bal == INT_MIN )    continue;
616                 
617                 if( bal < minBal )      continue;
618                 if( bal > maxBal )      continue;
619                 
620                 // TODO: User flags
621                 sendf(Client->Socket, "202 User %s %i user\n", GetUserName(i), GetBalance(i));
622         }
623         
624         return strdup("200 List End\n");
625 }
626
627 char *Server_Cmd_USERINFO(tClient *Client, char *Args)
628 {
629          int    uid;
630         char    *user = Args;
631         char    *space;
632         
633         space = strchr(user, ' ');
634         if(space)       *space = '\0';
635         
636         // Get recipient
637         uid = GetUserID(user);
638         if( uid == -1 ) return strdup("404 Invalid user");
639
640         // TODO: User flags/type
641         return mkstr("202 User %s %i user\n", user, GetBalance(uid));
642 }
643
644 /**
645  * \brief Authenticate a user
646  * \return User ID, or -1 if authentication failed
647  */
648 int GetUserAuth(const char *Salt, const char *Username, const uint8_t *ProvidedHash)
649 {
650         #if 0
651         uint8_t h[20];
652          int    ofs = strlen(Username) + strlen(Salt);
653         char    input[ ofs + 40 + 1];
654         char    tmp[4 + strlen(Username) + 1];  // uid=%s
655         #endif
656         
657         #if HACK_TPG_NOAUTH
658         if( strcmp(Username, "tpg") == 0 )
659                 return GetUserID("tpg");
660         #endif
661         #if HACK_ROOT_NOAUTH
662         if( strcmp(Username, "root") == 0 )
663                 return GetUserID("root");
664         #endif
665         
666         #if 0
667         //
668         strcpy(input, Username);
669         strcpy(input, Salt);
670         // TODO: Get user's SHA-1 hash
671         sprintf(tmp, "uid=%s", Username);
672         ldap_search_s(ld, "", LDAP_SCOPE_BASE, tmp, "userPassword", 0, res);
673         
674         sprintf(input+ofs, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
675                 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
676                 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
677                 );
678         // Then create the hash from the provided salt
679         // Compare that with the provided hash
680         #endif
681         
682         return -1;
683 }
684
685 // --- INTERNAL HELPERS ---
686 int sendf(int Socket, const char *Format, ...)
687 {
688         va_list args;
689          int    len;
690         
691         va_start(args, Format);
692         len = vsnprintf(NULL, 0, Format, args);
693         va_end(args);
694         
695         {
696                 char    buf[len+1];
697                 va_start(args, Format);
698                 vsnprintf(buf, len+1, Format, args);
699                 va_end(args);
700                 
701                 #if DEBUG_TRACE_CLIENT
702                 printf("sendf: %s", buf);
703                 #endif
704                 
705                 return send(Socket, buf, len, 0);
706         }
707 }
708
709 // TODO: Move to another file
710 void HexBin(uint8_t *Dest, char *Src, int BufSize)
711 {
712          int    i;
713         for( i = 0; i < BufSize; i ++ )
714         {
715                 uint8_t val = 0;
716                 
717                 if('0' <= *Src && *Src <= '9')
718                         val |= (*Src-'0') << 4;
719                 else if('A' <= *Src && *Src <= 'F')
720                         val |= (*Src-'A'+10) << 4;
721                 else if('a' <= *Src && *Src <= 'f')
722                         val |= (*Src-'a'+10) << 4;
723                 else
724                         break;
725                 Src ++;
726                 
727                 if('0' <= *Src && *Src <= '9')
728                         val |= (*Src-'0');
729                 else if('A' <= *Src && *Src <= 'F')
730                         val |= (*Src-'A'+10);
731                 else if('a' <= *Src && *Src <= 'f')
732                         val |= (*Src-'a'+10);
733                 else
734                         break;
735                 Src ++;
736                 
737                 Dest[i] = val;
738         }
739         for( ; i < BufSize; i++ )
740                 Dest[i] = 0;
741 }
742
743 /**
744  * \brief Decode a Base64 value
745  */
746 int UnBase64(uint8_t *Dest, char *Src, int BufSize)
747 {
748         uint32_t        val;
749          int    i, j;
750         char    *start_src = Src;
751         
752         for( i = 0; i+2 < BufSize; i += 3 )
753         {
754                 val = 0;
755                 for( j = 0; j < 4; j++, Src ++ ) {
756                         if('A' <= *Src && *Src <= 'Z')
757                                 val |= (*Src - 'A') << ((3-j)*6);
758                         else if('a' <= *Src && *Src <= 'z')
759                                 val |= (*Src - 'a' + 26) << ((3-j)*6);
760                         else if('0' <= *Src && *Src <= '9')
761                                 val |= (*Src - '0' + 52) << ((3-j)*6);
762                         else if(*Src == '+')
763                                 val |= 62 << ((3-j)*6);
764                         else if(*Src == '/')
765                                 val |= 63 << ((3-j)*6);
766                         else if(!*Src)
767                                 break;
768                         else if(*Src != '=')
769                                 j --;   // Ignore invalid characters
770                 }
771                 Dest[i  ] = (val >> 16) & 0xFF;
772                 Dest[i+1] = (val >> 8) & 0xFF;
773                 Dest[i+2] = val & 0xFF;
774                 if(j != 4)      break;
775         }
776         
777         // Finish things off
778         if(i   < BufSize)
779                 Dest[i] = (val >> 16) & 0xFF;
780         if(i+1 < BufSize)
781                 Dest[i+1] = (val >> 8) & 0xFF;
782         
783         return Src - start_src;
784 }

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