SQLite database works, time for more thorough stress testing
[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_ENUMUSERS(tClient *Client, char *Args)
775 {
776          int    i, numRet = 0;
777         tAcctIterator   *it;
778          int    maxBal = INT_MAX, minBal = INT_MIN;
779          int    flagMask = 0, flagVal = 0;
780          int    sort = BANK_ITFLAG_SORT_NAME;
781         time_t  lastSeenAfter=0, lastSeenBefore=0;
782         
783          int    flags;  // Iterator flags
784          int    balValue;       // Balance value for iterator
785         time_t  timeValue;      // Time value for iterator
786         
787         // Parse arguments
788         if( Args && strlen(Args) )
789         {
790                 char    *space = Args, *type, *val;
791                 do
792                 {
793                         type = space;
794                         // Get next space
795                         space = strchr(space, ' ');
796                         if(space)       *space = '\0';
797                         
798                         // Get type
799                         val = strchr(type, ':');
800                         if( val ) {
801                                 *val = '\0';
802                                 val ++;
803                                 
804                                 // Types
805                                 // - Minium Balance
806                                 if( strcmp(type, "min_balance") == 0 ) {
807                                         minBal = atoi(val);
808                                 }
809                                 // - Maximum Balance
810                                 else if( strcmp(type, "max_balance") == 0 ) {
811                                         maxBal = atoi(val);
812                                 }
813                                 // - Flags
814                                 else if( strcmp(type, "flags") == 0 ) {
815                                         if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
816                                                 return ;
817                                 }
818                                 // - Last seen before timestamp
819                                 else if( strcmp(type, "last_seen_before") == 0 ) {
820                                         lastSeenAfter = atoll(val);
821                                 }
822                                 // - Last seen after timestamp
823                                 else if( strcmp(type, "last_seen_after") == 0 ) {
824                                         lastSeenAfter = atoll(val);
825                                 }
826                                 // - Sorting 
827                                 else if( strcmp(type, "sort") == 0 ) {
828                                         char    *dash = strchr(val, '-');
829                                         if( dash ) {
830                                                 *dash = '\0';
831                                                 dash ++;
832                                         }
833                                         if( strcmp(val, "name") == 0 ) {
834                                                 sort = BANK_ITFLAG_SORT_NAME;
835                                         }
836                                         else if( strcmp(val, "balance") == 0 ) {
837                                                 sort = BANK_ITFLAG_SORT_BAL;
838                                         }
839                                         else if( strcmp(val, "lastseen") == 0 ) {
840                                                 sort = BANK_ITFLAG_SORT_LASTSEEN;
841                                         }
842                                         else {
843                                                 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
844                                                 return ;
845                                         }
846                                         // Handle sort direction
847                                         if( dash ) {
848                                                 if( strcmp(dash, "desc") == 0 ) {
849                                                         sort |= BANK_ITFLAG_REVSORT;
850                                                 }
851                                                 else {
852                                                         sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
853                                                         return ;
854                                                 }
855                                                 dash[-1] = '-';
856                                         }
857                                 }
858                                 else {
859                                         sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
860                                         return ;
861                                 }
862                                 
863                                 val[-1] = ':';
864                         }
865                         else {
866                                 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
867                                 return ;
868                         }
869                         
870                         // Eat whitespace
871                         if( space ) {
872                                 *space = ' ';   // Repair (to be nice)
873                                 space ++;
874                                 while(*space == ' ')    space ++;
875                         }
876                 }       while(space);
877         }
878         
879         // Create iterator
880         if( maxBal != INT_MAX ) {
881                 flags = sort|BANK_ITFLAG_MAXBALANCE;
882                 balValue = maxBal;
883         }
884         else if( minBal != INT_MIN ) {
885                 flags = sort|BANK_ITFLAG_MINBALANCE;
886                 balValue = minBal;
887         }
888         else {
889                 flags = sort;
890                 balValue = 0;
891         }
892         if( lastSeenBefore ) {
893                 timeValue = lastSeenBefore;
894                 flags |= BANK_ITFLAG_SEENBEFORE;
895         }
896         else if( lastSeenAfter ) {
897                 timeValue = lastSeenAfter;
898                 flags |= BANK_ITFLAG_SEENAFTER;
899         }
900         else {
901                 timeValue = 0;
902         }
903         it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
904         
905         // Get return number
906         while( (i = Bank_IteratorNext(it)) != -1 )
907         {
908                 int bal = Bank_GetBalance(i);
909                 
910                 if( bal == INT_MIN )    continue;
911                 
912                 if( bal < minBal )      continue;
913                 if( bal > maxBal )      continue;
914                 
915                 numRet ++;
916         }
917         
918         Bank_DelIterator(it);
919         
920         // Send count
921         sendf(Client->Socket, "201 Users %i\n", numRet);
922         
923         
924         // Create iterator
925         it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
926         
927         while( (i = Bank_IteratorNext(it)) != -1 )
928         {
929                 int bal = Bank_GetBalance(i);
930                 
931                 if( bal == INT_MIN )    continue;
932                 
933                 if( bal < minBal )      continue;
934                 if( bal > maxBal )      continue;
935                 
936                 _SendUserInfo(Client, i);
937         }
938         
939         Bank_DelIterator(it);
940         
941         sendf(Client->Socket, "200 List End\n");
942 }
943
944 void Server_Cmd_USERINFO(tClient *Client, char *Args)
945 {
946          int    uid;
947         char    *user = Args;
948         char    *space;
949         
950         space = strchr(user, ' ');
951         if(space)       *space = '\0';
952         
953         // Get recipient
954         uid = Bank_GetAcctByName(user);
955         if( uid == -1 ) {
956                 sendf(Client->Socket, "404 Invalid user");
957                 return ;
958         }
959         
960         _SendUserInfo(Client, uid);
961 }
962
963 void _SendUserInfo(tClient *Client, int UserID)
964 {
965         char    *type, *disabled="", *door="";
966          int    flags = Bank_GetFlags(UserID);
967         
968         if( flags & USER_FLAG_INTERNAL ) {
969                 type = "internal";
970         }
971         else if( flags & USER_FLAG_COKE ) {
972                 if( flags & USER_FLAG_ADMIN )
973                         type = "coke,admin";
974                 else
975                         type = "coke";
976         }
977         else if( flags & USER_FLAG_ADMIN ) {
978                 type = "admin";
979         }
980         else {
981                 type = "user";
982         }
983         
984         if( flags & USER_FLAG_DISABLED )
985                 disabled = ",disabled";
986         if( flags & USER_FLAG_DOORGROUP )
987                 door = ",door";
988         
989         // TODO: User flags/type
990         sendf(
991                 Client->Socket, "202 User %s %i %s%s\n",
992                 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
993                 type, disabled
994                 );
995 }
996
997 void Server_Cmd_USERADD(tClient *Client, char *Args)
998 {
999         char    *username, *space;
1000         
1001         // Check permissions
1002         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1003                 sendf(Client->Socket, "403 Not a coke admin\n");
1004                 return ;
1005         }
1006         
1007         // Read arguments
1008         username = Args;
1009         while( *username == ' ' )       username ++;
1010         space = strchr(username, ' ');
1011         if(space)       *space = '\0';
1012         
1013         // Try to create user
1014         if( Bank_CreateAcct(username) == -1 ) {
1015                 sendf(Client->Socket, "404 User exists\n");
1016                 return ;
1017         }
1018         
1019         {
1020                 char    *thisName = Bank_GetAcctName(Client->UID);
1021                 Log_Info("Account '%s' created by '%s'", username, thisName);
1022                 free(thisName);
1023         }
1024         
1025         sendf(Client->Socket, "200 User Added\n");
1026 }
1027
1028 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1029 {
1030         char    *username, *flags;
1031         char    *space;
1032          int    mask=0, value=0;
1033          int    uid;
1034         
1035         // Check permissions
1036         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1037                 sendf(Client->Socket, "403 Not a coke admin\n");
1038                 return ;
1039         }
1040         
1041         // Read arguments
1042         // - Username
1043         username = Args;
1044         while( *username == ' ' )       username ++;
1045         space = strchr(username, ' ');
1046         if(!space) {
1047                 sendf(Client->Socket, "407 USER_FLAGS requires 2 arguments, 1 given\n");
1048                 return ;
1049         }
1050         *space = '\0';
1051         // - Flags
1052         flags = space + 1;
1053         while( *flags == ' ' )  flags ++;
1054         space = strchr(flags, ' ');
1055         if(space)       *space = '\0';
1056         
1057         // Get UID
1058         uid = Bank_GetAcctByName(username);
1059         if( uid == -1 ) {
1060                 sendf(Client->Socket, "404 User '%s' not found\n", username);
1061                 return ;
1062         }
1063         
1064         // Parse flags
1065         if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1066                 return ;
1067         
1068         // Apply flags
1069         Bank_SetFlags(uid, mask, value);
1070         
1071         // Return OK
1072         sendf(Client->Socket, "200 User Updated\n");
1073 }
1074
1075 // --- INTERNAL HELPERS ---
1076 int sendf(int Socket, const char *Format, ...)
1077 {
1078         va_list args;
1079          int    len;
1080         
1081         va_start(args, Format);
1082         len = vsnprintf(NULL, 0, Format, args);
1083         va_end(args);
1084         
1085         {
1086                 char    buf[len+1];
1087                 va_start(args, Format);
1088                 vsnprintf(buf, len+1, Format, args);
1089                 va_end(args);
1090                 
1091                 #if DEBUG_TRACE_CLIENT
1092                 printf("sendf: %s", buf);
1093                 #endif
1094                 
1095                 return send(Socket, buf, len, 0);
1096         }
1097 }
1098
1099 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1100 {
1101         struct {
1102                 const char      *Name;
1103                  int    Mask;
1104                  int    Value;
1105         }       cFLAGS[] = {
1106                  {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1107                 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1108                 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1109                 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1110                 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1111         };
1112         const int       ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1113         
1114         char    *space;
1115         
1116         *Mask = 0;
1117         *Value = 0;
1118         
1119         do {
1120                  int    bRemove = 0;
1121                  int    i;
1122                  int    len;
1123                 
1124                 while( *Str == ' ' )    Str ++; // Eat whitespace
1125                 space = strchr(Str, ',');       // Find the end of the flag
1126                 if(space)
1127                         len = space - Str;
1128                 else
1129                         len = strlen(Str);
1130                 
1131                 // Check for inversion/removal
1132                 if( *Str == '!' || *Str == '-' ) {
1133                         bRemove = 1;
1134                         Str ++;
1135                 }
1136                 else if( *Str == '+' ) {
1137                         Str ++;
1138                 }
1139                 
1140                 // Check flag values
1141                 for( i = 0; i < ciNumFlags; i ++ )
1142                 {
1143                         if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1144                                 *Mask |= cFLAGS[i].Mask;
1145                                 *Value &= ~cFLAGS[i].Mask;
1146                                 if( !bRemove )
1147                                         *Value |= cFLAGS[i].Value;
1148                                 break;
1149                         }
1150                 }
1151                 
1152                 // Error check
1153                 if( i == ciNumFlags ) {
1154                         char    val[len+1];
1155                         strncpy(val, Str, len+1);
1156                         sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);
1157                         return -1;
1158                 }
1159                 
1160                 Str = space + 1;
1161         } while(space);
1162         
1163         return 0;
1164 }

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