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

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