Fixes to bugs pointed by [BOB]
[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 #define DEBUG_TRACE_CLIENT      0
22
23 // Statistics
24 #define MAX_CONNECTION_QUEUE    5
25 #define INPUT_BUFFER_SIZE       256
26
27 #define HASH_TYPE       SHA1
28 #define HASH_LENGTH     20
29
30 #define MSG_STR_TOO_LONG        "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
31
32 // === TYPES ===
33 typedef struct sClient
34 {
35          int    Socket; // Client socket ID
36          int    ID;     // Client ID
37          
38          int    bIsTrusted;     // Is the connection from a trusted host/port
39         
40         char    *Username;
41         char    Salt[9];
42         
43          int    UID;
44          int    EffectiveUID;
45          int    bIsAuthed;
46 }       tClient;
47
48 // === PROTOTYPES ===
49 void    Server_Start(void);
50 void    Server_Cleanup(void);
51 void    Server_HandleClient(int Socket, int bTrusted);
52 void    Server_ParseClientCommand(tClient *Client, char *CommandString);
53 // --- Commands ---
54 void    Server_Cmd_USER(tClient *Client, char *Args);
55 void    Server_Cmd_PASS(tClient *Client, char *Args);
56 void    Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
57 void    Server_Cmd_SETEUSER(tClient *Client, char *Args);
58 void    Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
59 void    Server_Cmd_ITEMINFO(tClient *Client, char *Args);
60 void    Server_Cmd_DISPENSE(tClient *Client, char *Args);
61 void    Server_Cmd_GIVE(tClient *Client, char *Args);
62 void    Server_Cmd_DONATE(tClient *Client, char *Args);
63 void    Server_Cmd_ADD(tClient *Client, char *Args);
64 void    Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
65 void    Server_Cmd_USERINFO(tClient *Client, char *Args);
66 void    _SendUserInfo(tClient *Client, int UserID);
67 void    Server_Cmd_USERADD(tClient *Client, char *Args);
68 void    Server_Cmd_USERFLAGS(tClient *Client, char *Args);
69 // --- Helpers ---
70  int    Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
71  int    sendf(int Socket, const char *Format, ...);
72
73 // === CONSTANTS ===
74 // - Commands
75 const struct sClientCommand {
76         const char      *Name;
77         void    (*Function)(tClient *Client, char *Arguments);
78 }       gaServer_Commands[] = {
79         {"USER", Server_Cmd_USER},
80         {"PASS", Server_Cmd_PASS},
81         {"AUTOAUTH", Server_Cmd_AUTOAUTH},
82         {"SETEUSER", Server_Cmd_SETEUSER},
83         {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
84         {"ITEM_INFO", Server_Cmd_ITEMINFO},
85         {"DISPENSE", Server_Cmd_DISPENSE},
86         {"GIVE", Server_Cmd_GIVE},
87         {"DONATE", Server_Cmd_DONATE},
88         {"ADD", Server_Cmd_ADD},
89         {"ENUM_USERS", Server_Cmd_ENUMUSERS},
90         {"USER_INFO", Server_Cmd_USERINFO},
91         {"USER_ADD", Server_Cmd_USERADD},
92         {"USER_FLAGS", Server_Cmd_USERFLAGS}
93 };
94 #define NUM_COMMANDS    ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
95
96 // === GLOBALS ===
97  int    giServer_Port = 1020;
98  int    giServer_NextClientID = 1;
99  int    giServer_Socket;
100
101 // === CODE ===
102 /**
103  * \brief Open listenting socket and serve connections
104  */
105 void Server_Start(void)
106 {
107          int    client_socket;
108         struct sockaddr_in      server_addr, client_addr;
109
110         atexit(Server_Cleanup);
111
112         // Create Server
113         giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
114         if( giServer_Socket < 0 ) {
115                 fprintf(stderr, "ERROR: Unable to create server socket\n");
116                 return ;
117         }
118         
119         // Make listen address
120         memset(&server_addr, 0, sizeof(server_addr));
121         server_addr.sin_family = AF_INET;       // Internet Socket
122         server_addr.sin_addr.s_addr = htonl(INADDR_ANY);        // Listen on all interfaces
123         server_addr.sin_port = htons(giServer_Port);    // Port
124
125         // Bind
126         if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
127                 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
128                 perror("Binding");
129                 return ;
130         }
131         
132         // Listen
133         if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
134                 fprintf(stderr, "ERROR: Unable to listen to socket\n");
135                 perror("Listen");
136                 return ;
137         }
138         
139         printf("Listening on 0.0.0.0:%i\n", giServer_Port);
140         
141         for(;;)
142         {
143                 uint    len = sizeof(client_addr);
144                  int    bTrusted = 0;
145                 
146                 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
147                 if(client_socket < 0) {
148                         fprintf(stderr, "ERROR: Unable to accept client connection\n");
149                         return ;
150                 }
151                 
152                 if(giDebugLevel >= 2) {
153                         char    ipstr[INET_ADDRSTRLEN];
154                         inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
155                         printf("Client connection from %s:%i\n",
156                                 ipstr, ntohs(client_addr.sin_port));
157                 }
158                 
159                 // Trusted Connections
160                 if( ntohs(client_addr.sin_port) < 1024 )
161                 {
162                         // TODO: Make this runtime configurable
163                         switch( ntohl( client_addr.sin_addr.s_addr ) )
164                         {
165                         case 0x7F000001:        // 127.0.0.1    localhost
166                         //case 0x825E0D00:      // 130.95.13.0
167                         case 0x825E0D12:        // 130.95.13.18 mussel
168                         case 0x825E0D17:        // 130.95.13.23 martello
169                                 bTrusted = 1;
170                                 break;
171                         default:
172                                 break;
173                         }
174                 }
175                 
176                 // TODO: Multithread this?
177                 Server_HandleClient(client_socket, bTrusted);
178                 
179                 close(client_socket);
180         }
181 }
182
183 void Server_Cleanup(void)
184 {
185         printf("Close(%i)\n", giServer_Socket);
186         close(giServer_Socket);
187 }
188
189 /**
190  * \brief Reads from a client socket and parses the command strings
191  * \param Socket        Client socket number/handle
192  * \param bTrusted      Is the client trusted?
193  */
194 void Server_HandleClient(int Socket, int bTrusted)
195 {
196         char    inbuf[INPUT_BUFFER_SIZE];
197         char    *buf = inbuf;
198          int    remspace = INPUT_BUFFER_SIZE-1;
199          int    bytes = -1;
200         tClient clientInfo;
201         
202         memset(&clientInfo, 0, sizeof(clientInfo));
203         
204         // Initialise Client info
205         clientInfo.Socket = Socket;
206         clientInfo.ID = giServer_NextClientID ++;
207         clientInfo.bIsTrusted = bTrusted;
208         clientInfo.EffectiveUID = -1;
209         
210         // Read from client
211         /*
212          * Notes:
213          * - The `buf` and `remspace` variables allow a line to span several
214          *   calls to recv(), if a line is not completed in one recv() call
215          *   it is saved to the beginning of `inbuf` and `buf` is updated to
216          *   the end of it.
217          */
218         while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
219         {
220                 char    *eol, *start;
221                 buf[bytes] = '\0';      // Allow us to use stdlib string functions on it
222                 
223                 // Split by lines
224                 start = inbuf;
225                 while( (eol = strchr(start, '\n')) )
226                 {
227                         *eol = '\0';
228                         
229                         Server_ParseClientCommand(&clientInfo, start);
230                         
231                         start = eol + 1;
232                 }
233                 
234                 // Check if there was an incomplete line
235                 if( *start != '\0' ) {
236                          int    tailBytes = bytes - (start-buf);
237                         // Roll back in buffer
238                         memcpy(inbuf, start, tailBytes);
239                         remspace -= tailBytes;
240                         if(remspace == 0) {
241                                 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
242                                 buf = inbuf;
243                                 remspace = INPUT_BUFFER_SIZE - 1;
244                         }
245                 }
246                 else {
247                         buf = inbuf;
248                         remspace = INPUT_BUFFER_SIZE - 1;
249                 }
250         }
251         
252         // Check for errors
253         if( bytes < 0 ) {
254                 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
255                 return ;
256         }
257         
258         if(giDebugLevel >= 2) {
259                 printf("Client %i: Disconnected\n", clientInfo.ID);
260         }
261 }
262
263 /**
264  * \brief Parses a client command and calls the required helper function
265  * \param Client        Pointer to client state structure
266  * \param CommandString Command from client (single line of the command)
267  * \return Heap String to return to the client
268  */
269 void Server_ParseClientCommand(tClient *Client, char *CommandString)
270 {
271         char    *space, *args;
272          int    i;
273         #if 0
274         char    **argList;
275          int    numArgs = 0;
276         #endif
277         
278         // Split at first space
279         space = strchr(CommandString, ' ');
280         if(space == NULL) {
281                 args = NULL;
282         }
283         else {
284                 *space = '\0';
285                 args = space + 1;
286                 while( *space == ' ' )  space ++;
287                 
288                 #if 0
289                 // Count arguments
290                 numArgs = 1;
291                 for( i = 0; args[i]; )
292                 {
293                         while( CommandString[i] != ' ' ) {
294                                 if( CommandString[i] == '"' ) {
295                                         while( !(CommandString[i] != '\\' CommandString[i+1] == '"' ) )
296                                                 i ++;
297                                         i ++;
298                                 }
299                                 i ++;
300                         }
301                         numArgs ++;
302                         while( CommandString[i] == ' ' )        i ++;
303                 }
304                 #endif
305         }
306         
307         
308         // Find command
309         for( i = 0; i < NUM_COMMANDS; i++ )
310         {
311                 if(strcmp(CommandString, gaServer_Commands[i].Name) == 0) {
312                         gaServer_Commands[i].Function(Client, args);
313                         return ;
314                 }
315         }
316         
317         sendf(Client->Socket, "400 Unknown Command\n");
318 }
319
320 // ---
321 // Commands
322 // ---
323 /**
324  * \brief Set client username
325  * 
326  * Usage: USER <username>
327  */
328 void Server_Cmd_USER(tClient *Client, char *Args)
329 {
330         char    *space = strchr(Args, ' ');
331         if(space)       *space = '\0';  // Remove characters after the ' '
332         
333         // Debug!
334         if( giDebugLevel )
335                 printf("Client %i authenticating as '%s'\n", Client->ID, Args);
336         
337         // Save username
338         if(Client->Username)
339                 free(Client->Username);
340         Client->Username = strdup(Args);
341         
342         #if USE_SALT
343         // Create a salt (that changes if the username is changed)
344         // Yes, I know, I'm a little paranoid, but who isn't?
345         Client->Salt[0] = 0x21 + (rand()&0x3F);
346         Client->Salt[1] = 0x21 + (rand()&0x3F);
347         Client->Salt[2] = 0x21 + (rand()&0x3F);
348         Client->Salt[3] = 0x21 + (rand()&0x3F);
349         Client->Salt[4] = 0x21 + (rand()&0x3F);
350         Client->Salt[5] = 0x21 + (rand()&0x3F);
351         Client->Salt[6] = 0x21 + (rand()&0x3F);
352         Client->Salt[7] = 0x21 + (rand()&0x3F);
353         
354         // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
355         sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
356         #else
357         sendf(Client->Socket, "100 User Set\n");
358         #endif
359 }
360
361 /**
362  * \brief Authenticate as a user
363  * 
364  * Usage: PASS <hash>
365  */
366 void Server_Cmd_PASS(tClient *Client, char *Args)
367 {
368         char    *space = strchr(Args, ' ');
369         if(space)       *space = '\0';  // Remove characters after the ' '
370         
371         // Pass on to cokebank
372         Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, Args);
373
374         if( Client->UID != -1 ) {
375                 Client->bIsAuthed = 1;
376                 sendf(Client->Socket, "200 Auth OK\n");
377                 return ;
378         }
379         
380         sendf(Client->Socket, "401 Auth Failure\n");
381 }
382
383 /**
384  * \brief Authenticate as a user without a password
385  * 
386  * Usage: AUTOAUTH <user>
387  */
388 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
389 {
390         char    *space = strchr(Args, ' ');
391         if(space)       *space = '\0';  // Remove characters after the ' '
392         
393         // Check if trusted
394         if( !Client->bIsTrusted ) {
395                 if(giDebugLevel)
396                         printf("Client %i: Untrusted client attempting to AUTOAUTH\n", Client->ID);
397                 sendf(Client->Socket, "401 Untrusted\n");
398                 return ;
399         }
400         
401         // Get UID
402         Client->UID = Bank_GetAcctByName( Args );       
403         if( Client->UID < 0 ) {
404                 if(giDebugLevel)
405                         printf("Client %i: Unknown user '%s'\n", Client->ID, Args);
406                 sendf(Client->Socket, "401 Auth Failure\n");
407                 return ;
408         }
409         
410         // You can't be an internal account
411         if( Bank_GetFlags(Client->UID) & USER_FLAG_INTERNAL ) {
412                 Client->UID = -1;
413                 sendf(Client->Socket, "401 Auth Failure\n");
414                 return ;
415         }
416         
417         if(giDebugLevel)
418                 printf("Client %i: Authenticated as '%s' (%i)\n", Client->ID, Args, Client->UID);
419         
420         sendf(Client->Socket, "200 Auth OK\n");
421 }
422
423 /**
424  * \brief Set effective user
425  */
426 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
427 {
428         char    *space;
429         
430         space = strchr(Args, ' ');
431         
432         if(space)       *space = '\0';
433         
434         if( !strlen(Args) ) {
435                 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
436                 return ;
437         }
438
439         // Check user permissions
440         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_COKE) ) {
441                 sendf(Client->Socket, "403 Not in coke\n");
442                 return ;
443         }
444         
445         // Set id
446         Client->EffectiveUID = Bank_GetAcctByName(Args);
447         if( Client->EffectiveUID == -1 ) {
448                 sendf(Client->Socket, "404 User not found\n");
449                 return ;
450         }
451         
452         // You can't be an internal account
453         if( Bank_GetFlags(Client->EffectiveUID) & USER_FLAG_INTERNAL ) {
454                 Client->EffectiveUID = -1;
455                 sendf(Client->Socket, "404 User not found\n");
456                 return ;
457         }
458         
459         sendf(Client->Socket, "200 User set\n");
460 }
461
462 /**
463  * \brief Enumerate the items that the server knows about
464  */
465 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
466 {
467          int    i;
468
469         if( Args != NULL && strlen(Args) ) {
470                 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
471                 return ;
472         }
473
474         sendf(Client->Socket, "201 Items %i\n", giNumItems);
475
476         for( i = 0; i < giNumItems; i ++ ) {
477                 sendf(Client->Socket,
478                         "202 Item %s:%i %i %s\n",
479                          gaItems[i].Handler->Name, gaItems[i].ID, gaItems[i].Price, gaItems[i].Name
480                          );
481         }
482
483         sendf(Client->Socket, "200 List end\n");
484 }
485
486 tItem *_GetItemFromString(char *String)
487 {
488         tHandler        *handler;
489         char    *type = String;
490         char    *colon = strchr(String, ':');
491          int    num, i;
492         
493         if( !colon ) {
494                 return NULL;
495         }
496
497         num = atoi(colon+1);
498         *colon = '\0';
499
500         // Find handler
501         handler = NULL;
502         for( i = 0; i < giNumHandlers; i ++ )
503         {
504                 if( strcmp(gaHandlers[i]->Name, type) == 0) {
505                         handler = gaHandlers[i];
506                         break;
507                 }
508         }
509         if( !handler ) {
510                 return NULL;
511         }
512
513         // Find item
514         for( i = 0; i < giNumItems; i ++ )
515         {
516                 if( gaItems[i].Handler != handler )     continue;
517                 if( gaItems[i].ID != num )      continue;
518                 return &gaItems[i];
519         }
520         return NULL;
521 }
522
523 /**
524  * \brief Fetch information on a specific item
525  */
526 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
527 {
528         tItem   *item = _GetItemFromString(Args);
529         
530         if( !item ) {
531                 sendf(Client->Socket, "406 Bad Item ID\n");
532                 return ;
533         }
534         
535         sendf(Client->Socket,
536                 "202 Item %s:%i %i %s\n",
537                  item->Handler->Name, item->ID, item->Price, item->Name
538                  );
539 }
540
541 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
542 {
543         tItem   *item;
544          int    ret;
545          int    uid;
546          
547         if( !Client->bIsAuthed ) {
548                 sendf(Client->Socket, "401 Not Authenticated\n");
549                 return ;
550         }
551
552         item = _GetItemFromString(Args);
553         if( !item ) {
554                 sendf(Client->Socket, "406 Bad Item ID\n");
555                 return ;
556         }
557         
558         if( Client->EffectiveUID != -1 ) {
559                 uid = Client->EffectiveUID;
560         }
561         else {
562                 uid = Client->UID;
563         }
564
565         switch( ret = DispenseItem( Client->UID, uid, item ) )
566         {
567         case 0: sendf(Client->Socket, "200 Dispense OK\n");     return ;
568         case 1: sendf(Client->Socket, "501 Unable to dispense\n");      return ;
569         case 2: sendf(Client->Socket, "402 Poor You\n");        return ;
570         default:
571                 sendf(Client->Socket, "500 Dispense Error\n");
572                 return ;
573         }
574 }
575
576 void Server_Cmd_GIVE(tClient *Client, char *Args)
577 {
578         char    *recipient, *ammount, *reason;
579          int    uid, iAmmount;
580          int    thisUid;
581         
582         if( !Client->bIsAuthed ) {
583                 sendf(Client->Socket, "401 Not Authenticated\n");
584                 return ;
585         }
586
587         recipient = Args;
588
589         ammount = strchr(Args, ' ');
590         if( !ammount ) {
591                 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
592                 return ;
593         }
594         *ammount = '\0';
595         ammount ++;
596
597         reason = strchr(ammount, ' ');
598         if( !reason ) {
599                 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
600                 return ;
601         }
602         *reason = '\0';
603         reason ++;
604
605         // Get recipient
606         uid = Bank_GetAcctByName(recipient);
607         if( uid == -1 ) {
608                 sendf(Client->Socket, "404 Invalid target user\n");
609                 return ;
610         }
611         
612         // You can't alter an internal account
613         if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
614                 sendf(Client->Socket, "404 Invalid target user\n");
615                 return ;
616         }
617
618         // Parse ammount
619         iAmmount = atoi(ammount);
620         if( iAmmount <= 0 ) {
621                 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
622                 return ;
623         }
624         
625         if( Client->EffectiveUID != -1 ) {
626                 thisUid = Client->EffectiveUID;
627         }
628         else {
629                 thisUid = Client->UID;
630         }
631
632         // Do give
633         switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
634         {
635         case 0:
636                 sendf(Client->Socket, "200 Give OK\n");
637                 return ;
638         case 2:
639                 sendf(Client->Socket, "402 Poor You\n");
640                 return ;
641         default:
642                 sendf(Client->Socket, "500 Unknown error\n");
643                 return ;
644         }
645 }
646
647 void Server_Cmd_DONATE(tClient *Client, char *Args)
648 {
649         char    *ammount, *reason;
650          int    iAmmount;
651          int    thisUid;
652         
653         if( !Client->bIsAuthed ) {
654                 sendf(Client->Socket, "401 Not Authenticated\n");
655                 return ;
656         }
657
658         ammount = Args;
659
660         // Get the start of the reason
661         reason = strchr(Args, ' ');
662         if( !ammount ) {
663                 sendf(Client->Socket, "407 Invalid Argument, expected 2 parameters, 1 encountered\n");
664                 return ;
665         }
666         *reason = '\0';
667         reason ++;
668         
669         // Check the end of the reason
670         if( strchr(reason, ' ') ) {
671                 sendf(Client->Socket, "407 Invalid Argument, expected 2 parameters, more encountered\n");
672                 return ;
673         }
674
675         // Parse ammount
676         iAmmount = atoi(ammount);
677         if( iAmmount <= 0 ) {
678                 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
679                 return ;
680         }
681         
682         // Handle effective users
683         if( Client->EffectiveUID != -1 ) {
684                 thisUid = Client->EffectiveUID;
685         }
686         else {
687                 thisUid = Client->UID;
688         }
689
690         // Do give
691         switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
692         {
693         case 0:
694                 sendf(Client->Socket, "200 Give OK\n");
695                 return ;
696         case 2:
697                 sendf(Client->Socket, "402 Poor You\n");
698                 return ;
699         default:
700                 sendf(Client->Socket, "500 Unknown error\n");
701                 return ;
702         }
703 }
704
705 void Server_Cmd_ADD(tClient *Client, char *Args)
706 {
707         char    *user, *ammount, *reason;
708          int    uid, iAmmount;
709         
710         if( !Client->bIsAuthed ) {
711                 sendf(Client->Socket, "401 Not Authenticated\n");
712                 return ;
713         }
714
715         user = Args;
716
717         ammount = strchr(Args, ' ');
718         if( !ammount ) {
719                 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
720                 return ;
721         }
722         *ammount = '\0';
723         ammount ++;
724
725         reason = strchr(ammount, ' ');
726         if( !reason ) {
727                 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
728                 return ;
729         }
730         *reason = '\0';
731         reason ++;
732
733         // Check user permissions
734         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_COKE)  ) {
735                 sendf(Client->Socket, "403 Not in coke\n");
736                 return ;
737         }
738
739         // Get recipient
740         uid = Bank_GetAcctByName(user);
741         if( uid == -1 ) {
742                 sendf(Client->Socket, "404 Invalid user\n");
743                 return ;
744         }
745         
746         // You can't alter an internal account
747         if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
748                 sendf(Client->Socket, "404 Invalid user\n");
749                 return ;
750         }
751
752         // Parse ammount
753         iAmmount = atoi(ammount);
754         if( iAmmount == 0 && ammount[0] != '0' ) {
755                 sendf(Client->Socket, "407 Invalid Argument\n");
756                 return ;
757         }
758
759         // Do give
760         switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
761         {
762         case 0:
763                 sendf(Client->Socket, "200 Add OK\n");
764                 return ;
765         case 2:
766                 sendf(Client->Socket, "402 Poor Guy\n");
767                 return ;
768         default:
769                 sendf(Client->Socket, "500 Unknown error\n");
770                 return ;
771         }
772 }
773
774 void Server_Cmd_SET(tClient *Client, char *Args)
775 {
776         char    *user, *ammount, *reason;
777          int    uid, iAmmount;
778         
779         if( !Client->bIsAuthed ) {
780                 sendf(Client->Socket, "401 Not Authenticated\n");
781                 return ;
782         }
783
784         user = Args;
785
786         ammount = strchr(Args, ' ');
787         if( !ammount ) {
788                 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
789                 return ;
790         }
791         *ammount = '\0';
792         ammount ++;
793
794         reason = strchr(ammount, ' ');
795         if( !reason ) {
796                 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
797                 return ;
798         }
799         *reason = '\0';
800         reason ++;
801
802         // Check user permissions
803         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN)  ) {
804                 sendf(Client->Socket, "403 Not an admin\n");
805                 return ;
806         }
807
808         // Get recipient
809         uid = Bank_GetAcctByName(user);
810         if( uid == -1 ) {
811                 sendf(Client->Socket, "404 Invalid user\n");
812                 return ;
813         }
814         
815         // You can't alter an internal account
816         if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
817                 sendf(Client->Socket, "404 Invalid user\n");
818                 return ;
819         }
820
821         // Parse ammount
822         iAmmount = atoi(ammount);
823         if( iAmmount == 0 && ammount[0] != '0' ) {
824                 sendf(Client->Socket, "407 Invalid Argument\n");
825                 return ;
826         }
827
828         // Do give
829         switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
830         {
831         case 0:
832                 sendf(Client->Socket, "200 Add OK\n");
833                 return ;
834         case 2:
835                 sendf(Client->Socket, "402 Poor Guy\n");
836                 return ;
837         default:
838                 sendf(Client->Socket, "500 Unknown error\n");
839                 return ;
840         }
841 }
842
843 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
844 {
845          int    i, numRet = 0;
846         tAcctIterator   *it;
847          int    maxBal = INT_MAX, minBal = INT_MIN;
848          int    flagMask = 0, flagVal = 0;
849          int    sort = BANK_ITFLAG_SORT_NAME;
850         time_t  lastSeenAfter=0, lastSeenBefore=0;
851         
852          int    flags;  // Iterator flags
853          int    balValue;       // Balance value for iterator
854         time_t  timeValue;      // Time value for iterator
855         
856         // Parse arguments
857         if( Args && strlen(Args) )
858         {
859                 char    *space = Args, *type, *val;
860                 do
861                 {
862                         type = space;
863                         // Get next space
864                         space = strchr(space, ' ');
865                         if(space)       *space = '\0';
866                         
867                         // Get type
868                         val = strchr(type, ':');
869                         if( val ) {
870                                 *val = '\0';
871                                 val ++;
872                                 
873                                 // Types
874                                 // - Minium Balance
875                                 if( strcmp(type, "min_balance") == 0 ) {
876                                         minBal = atoi(val);
877                                 }
878                                 // - Maximum Balance
879                                 else if( strcmp(type, "max_balance") == 0 ) {
880                                         maxBal = atoi(val);
881                                 }
882                                 // - Flags
883                                 else if( strcmp(type, "flags") == 0 ) {
884                                         if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
885                                                 return ;
886                                 }
887                                 // - Last seen before timestamp
888                                 else if( strcmp(type, "last_seen_before") == 0 ) {
889                                         lastSeenAfter = atoll(val);
890                                 }
891                                 // - Last seen after timestamp
892                                 else if( strcmp(type, "last_seen_after") == 0 ) {
893                                         lastSeenAfter = atoll(val);
894                                 }
895                                 // - Sorting 
896                                 else if( strcmp(type, "sort") == 0 ) {
897                                         char    *dash = strchr(val, '-');
898                                         if( dash ) {
899                                                 *dash = '\0';
900                                                 dash ++;
901                                         }
902                                         if( strcmp(val, "name") == 0 ) {
903                                                 sort = BANK_ITFLAG_SORT_NAME;
904                                         }
905                                         else if( strcmp(val, "balance") == 0 ) {
906                                                 sort = BANK_ITFLAG_SORT_BAL;
907                                         }
908                                         else if( strcmp(val, "lastseen") == 0 ) {
909                                                 sort = BANK_ITFLAG_SORT_LASTSEEN;
910                                         }
911                                         else {
912                                                 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
913                                                 return ;
914                                         }
915                                         // Handle sort direction
916                                         if( dash ) {
917                                                 if( strcmp(dash, "desc") == 0 ) {
918                                                         sort |= BANK_ITFLAG_REVSORT;
919                                                 }
920                                                 else {
921                                                         sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
922                                                         return ;
923                                                 }
924                                                 dash[-1] = '-';
925                                         }
926                                 }
927                                 else {
928                                         sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
929                                         return ;
930                                 }
931                                 
932                                 val[-1] = ':';
933                         }
934                         else {
935                                 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
936                                 return ;
937                         }
938                         
939                         // Eat whitespace
940                         if( space ) {
941                                 *space = ' ';   // Repair (to be nice)
942                                 space ++;
943                                 while(*space == ' ')    space ++;
944                         }
945                 }       while(space);
946         }
947         
948         // Create iterator
949         if( maxBal != INT_MAX ) {
950                 flags = sort|BANK_ITFLAG_MAXBALANCE;
951                 balValue = maxBal;
952         }
953         else if( minBal != INT_MIN ) {
954                 flags = sort|BANK_ITFLAG_MINBALANCE;
955                 balValue = minBal;
956         }
957         else {
958                 flags = sort;
959                 balValue = 0;
960         }
961         if( lastSeenBefore ) {
962                 timeValue = lastSeenBefore;
963                 flags |= BANK_ITFLAG_SEENBEFORE;
964         }
965         else if( lastSeenAfter ) {
966                 timeValue = lastSeenAfter;
967                 flags |= BANK_ITFLAG_SEENAFTER;
968         }
969         else {
970                 timeValue = 0;
971         }
972         it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
973         
974         // Get return number
975         while( (i = Bank_IteratorNext(it)) != -1 )
976         {
977                 int bal = Bank_GetBalance(i);
978                 
979                 if( bal == INT_MIN )    continue;
980                 
981                 if( bal < minBal )      continue;
982                 if( bal > maxBal )      continue;
983                 
984                 numRet ++;
985         }
986         
987         Bank_DelIterator(it);
988         
989         // Send count
990         sendf(Client->Socket, "201 Users %i\n", numRet);
991         
992         
993         // Create iterator
994         it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
995         
996         while( (i = Bank_IteratorNext(it)) != -1 )
997         {
998                 int bal = Bank_GetBalance(i);
999                 
1000                 if( bal == INT_MIN )    continue;
1001                 
1002                 if( bal < minBal )      continue;
1003                 if( bal > maxBal )      continue;
1004                 
1005                 _SendUserInfo(Client, i);
1006         }
1007         
1008         Bank_DelIterator(it);
1009         
1010         sendf(Client->Socket, "200 List End\n");
1011 }
1012
1013 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1014 {
1015          int    uid;
1016         char    *user = Args;
1017         char    *space;
1018         
1019         space = strchr(user, ' ');
1020         if(space)       *space = '\0';
1021         
1022         // Get recipient
1023         uid = Bank_GetAcctByName(user);
1024         if( uid == -1 ) {
1025                 sendf(Client->Socket, "404 Invalid user");
1026                 return ;
1027         }
1028         
1029         _SendUserInfo(Client, uid);
1030 }
1031
1032 void _SendUserInfo(tClient *Client, int UserID)
1033 {
1034         char    *type, *disabled="", *door="";
1035          int    flags = Bank_GetFlags(UserID);
1036         
1037         if( flags & USER_FLAG_INTERNAL ) {
1038                 type = "internal";
1039         }
1040         else if( flags & USER_FLAG_COKE ) {
1041                 if( flags & USER_FLAG_ADMIN )
1042                         type = "coke,admin";
1043                 else
1044                         type = "coke";
1045         }
1046         else if( flags & USER_FLAG_ADMIN ) {
1047                 type = "admin";
1048         }
1049         else {
1050                 type = "user";
1051         }
1052         
1053         if( flags & USER_FLAG_DISABLED )
1054                 disabled = ",disabled";
1055         if( flags & USER_FLAG_DOORGROUP )
1056                 door = ",door";
1057         
1058         // TODO: User flags/type
1059         sendf(
1060                 Client->Socket, "202 User %s %i %s%s\n",
1061                 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1062                 type, disabled
1063                 );
1064 }
1065
1066 void Server_Cmd_USERADD(tClient *Client, char *Args)
1067 {
1068         char    *username, *space;
1069         
1070         // Check permissions
1071         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1072                 sendf(Client->Socket, "403 Not a coke admin\n");
1073                 return ;
1074         }
1075         
1076         // Read arguments
1077         username = Args;
1078         while( *username == ' ' )       username ++;
1079         space = strchr(username, ' ');
1080         if(space)       *space = '\0';
1081         
1082         // Try to create user
1083         if( Bank_CreateAcct(username) == -1 ) {
1084                 sendf(Client->Socket, "404 User exists\n");
1085                 return ;
1086         }
1087         
1088         {
1089                 char    *thisName = Bank_GetAcctName(Client->UID);
1090                 Log_Info("Account '%s' created by '%s'", username, thisName);
1091                 free(thisName);
1092         }
1093         
1094         sendf(Client->Socket, "200 User Added\n");
1095 }
1096
1097 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1098 {
1099         char    *username, *flags;
1100         char    *space;
1101          int    mask=0, value=0;
1102          int    uid;
1103         
1104         // Check permissions
1105         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1106                 sendf(Client->Socket, "403 Not a coke admin\n");
1107                 return ;
1108         }
1109         
1110         // Read arguments
1111         // - Username
1112         username = Args;
1113         while( *username == ' ' )       username ++;
1114         space = strchr(username, ' ');
1115         if(!space) {
1116                 sendf(Client->Socket, "407 USER_FLAGS requires 2 arguments, 1 given\n");
1117                 return ;
1118         }
1119         *space = '\0';
1120         // - Flags
1121         flags = space + 1;
1122         while( *flags == ' ' )  flags ++;
1123         space = strchr(flags, ' ');
1124         if(space)       *space = '\0';
1125         
1126         // Get UID
1127         uid = Bank_GetAcctByName(username);
1128         if( uid == -1 ) {
1129                 sendf(Client->Socket, "404 User '%s' not found\n", username);
1130                 return ;
1131         }
1132         
1133         // Parse flags
1134         if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1135                 return ;
1136         
1137         // Apply flags
1138         Bank_SetFlags(uid, mask, value);
1139         
1140         // Return OK
1141         sendf(Client->Socket, "200 User Updated\n");
1142 }
1143
1144 // --- INTERNAL HELPERS ---
1145 int sendf(int Socket, const char *Format, ...)
1146 {
1147         va_list args;
1148          int    len;
1149         
1150         va_start(args, Format);
1151         len = vsnprintf(NULL, 0, Format, args);
1152         va_end(args);
1153         
1154         {
1155                 char    buf[len+1];
1156                 va_start(args, Format);
1157                 vsnprintf(buf, len+1, Format, args);
1158                 va_end(args);
1159                 
1160                 #if DEBUG_TRACE_CLIENT
1161                 printf("sendf: %s", buf);
1162                 #endif
1163                 
1164                 return send(Socket, buf, len, 0);
1165         }
1166 }
1167
1168 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1169 {
1170         struct {
1171                 const char      *Name;
1172                  int    Mask;
1173                  int    Value;
1174         }       cFLAGS[] = {
1175                  {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1176                 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1177                 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1178                 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1179                 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1180         };
1181         const int       ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1182         
1183         char    *space;
1184         
1185         *Mask = 0;
1186         *Value = 0;
1187         
1188         do {
1189                  int    bRemove = 0;
1190                  int    i;
1191                  int    len;
1192                 
1193                 while( *Str == ' ' )    Str ++; // Eat whitespace
1194                 space = strchr(Str, ',');       // Find the end of the flag
1195                 if(space)
1196                         len = space - Str;
1197                 else
1198                         len = strlen(Str);
1199                 
1200                 // Check for inversion/removal
1201                 if( *Str == '!' || *Str == '-' ) {
1202                         bRemove = 1;
1203                         Str ++;
1204                 }
1205                 else if( *Str == '+' ) {
1206                         Str ++;
1207                 }
1208                 
1209                 // Check flag values
1210                 for( i = 0; i < ciNumFlags; i ++ )
1211                 {
1212                         if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1213                                 *Mask |= cFLAGS[i].Mask;
1214                                 *Value &= ~cFLAGS[i].Mask;
1215                                 if( !bRemove )
1216                                         *Value |= cFLAGS[i].Value;
1217                                 break;
1218                         }
1219                 }
1220                 
1221                 // Error check
1222                 if( i == ciNumFlags ) {
1223                         char    val[len+1];
1224                         strncpy(val, Str, len+1);
1225                         sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);
1226                         return -1;
1227                 }
1228                 
1229                 Str = space + 1;
1230         } while(space);
1231         
1232         return 0;
1233 }

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