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

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