17e8549a391b11d35201c07e2b98c429fc364862
[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 )
1035                 Debug(Client, "User Info '%s'", user);
1036         
1037         // Get recipient
1038         uid = Bank_GetAcctByName(user);
1039         if( uid == -1 ) {
1040                 sendf(Client->Socket, "404 Invalid user");
1041                 return ;
1042         }
1043         
1044         _SendUserInfo(Client, uid);
1045 }
1046
1047 void _SendUserInfo(tClient *Client, int UserID)
1048 {
1049         char    *type, *disabled="", *door="";
1050          int    flags = Bank_GetFlags(UserID);
1051         
1052         if( flags & USER_FLAG_INTERNAL ) {
1053                 type = "internal";
1054         }
1055         else if( flags & USER_FLAG_COKE ) {
1056                 if( flags & USER_FLAG_ADMIN )
1057                         type = "coke,admin";
1058                 else
1059                         type = "coke";
1060         }
1061         else if( flags & USER_FLAG_ADMIN ) {
1062                 type = "admin";
1063         }
1064         else {
1065                 type = "user";
1066         }
1067         
1068         if( flags & USER_FLAG_DISABLED )
1069                 disabled = ",disabled";
1070         if( flags & USER_FLAG_DOORGROUP )
1071                 door = ",door";
1072         
1073         // TODO: User flags/type
1074         sendf(
1075                 Client->Socket, "202 User %s %i %s%s\n",
1076                 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1077                 type, disabled
1078                 );
1079 }
1080
1081 void Server_Cmd_USERADD(tClient *Client, char *Args)
1082 {
1083         char    *username, *space;
1084         
1085         // Check permissions
1086         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1087                 sendf(Client->Socket, "403 Not a coke admin\n");
1088                 return ;
1089         }
1090         
1091         // Read arguments
1092         username = Args;
1093         while( *username == ' ' )       username ++;
1094         space = strchr(username, ' ');
1095         if(space)       *space = '\0';
1096         
1097         // Try to create user
1098         if( Bank_CreateAcct(username) == -1 ) {
1099                 sendf(Client->Socket, "404 User exists\n");
1100                 return ;
1101         }
1102         
1103         {
1104                 char    *thisName = Bank_GetAcctName(Client->UID);
1105                 Log_Info("Account '%s' created by '%s'", username, thisName);
1106                 free(thisName);
1107         }
1108         
1109         sendf(Client->Socket, "200 User Added\n");
1110 }
1111
1112 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1113 {
1114         char    *username, *flags;
1115         char    *space;
1116          int    mask=0, value=0;
1117          int    uid;
1118         
1119         // Check permissions
1120         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1121                 sendf(Client->Socket, "403 Not a coke admin\n");
1122                 return ;
1123         }
1124         
1125         // Read arguments
1126         // - Username
1127         username = Args;
1128         while( *username == ' ' )       username ++;
1129         space = strchr(username, ' ');
1130         if(!space) {
1131                 sendf(Client->Socket, "407 USER_FLAGS requires 2 arguments, 1 given\n");
1132                 return ;
1133         }
1134         *space = '\0';
1135         // - Flags
1136         flags = space + 1;
1137         while( *flags == ' ' )  flags ++;
1138         space = strchr(flags, ' ');
1139         if(space)       *space = '\0';
1140         
1141         // Get UID
1142         uid = Bank_GetAcctByName(username);
1143         if( uid == -1 ) {
1144                 sendf(Client->Socket, "404 User '%s' not found\n", username);
1145                 return ;
1146         }
1147         
1148         // Parse flags
1149         if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1150                 return ;
1151         
1152         // Apply flags
1153         Bank_SetFlags(uid, mask, value);
1154         
1155         // Return OK
1156         sendf(Client->Socket, "200 User Updated\n");
1157 }
1158
1159 // --- INTERNAL HELPERS ---
1160 void Debug(tClient *Client, const char *Format, ...)
1161 {
1162         va_list args;
1163         //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1164         printf("[%i] ", Client->ID);
1165         va_start(args, Format);
1166         vprintf(Format, args);
1167         va_end(args);
1168         printf("\n");
1169 }
1170
1171 int sendf(int Socket, const char *Format, ...)
1172 {
1173         va_list args;
1174          int    len;
1175         
1176         va_start(args, Format);
1177         len = vsnprintf(NULL, 0, Format, args);
1178         va_end(args);
1179         
1180         {
1181                 char    buf[len+1];
1182                 va_start(args, Format);
1183                 vsnprintf(buf, len+1, Format, args);
1184                 va_end(args);
1185                 
1186                 #if DEBUG_TRACE_CLIENT
1187                 printf("sendf: %s", buf);
1188                 #endif
1189                 
1190                 return send(Socket, buf, len, 0);
1191         }
1192 }
1193
1194 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1195 {
1196         struct {
1197                 const char      *Name;
1198                  int    Mask;
1199                  int    Value;
1200         }       cFLAGS[] = {
1201                  {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1202                 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1203                 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1204                 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1205                 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1206         };
1207         const int       ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1208         
1209         char    *space;
1210         
1211         *Mask = 0;
1212         *Value = 0;
1213         
1214         do {
1215                  int    bRemove = 0;
1216                  int    i;
1217                  int    len;
1218                 
1219                 while( *Str == ' ' )    Str ++; // Eat whitespace
1220                 space = strchr(Str, ',');       // Find the end of the flag
1221                 if(space)
1222                         len = space - Str;
1223                 else
1224                         len = strlen(Str);
1225                 
1226                 // Check for inversion/removal
1227                 if( *Str == '!' || *Str == '-' ) {
1228                         bRemove = 1;
1229                         Str ++;
1230                 }
1231                 else if( *Str == '+' ) {
1232                         Str ++;
1233                 }
1234                 
1235                 // Check flag values
1236                 for( i = 0; i < ciNumFlags; i ++ )
1237                 {
1238                         if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1239                                 *Mask |= cFLAGS[i].Mask;
1240                                 *Value &= ~cFLAGS[i].Mask;
1241                                 if( !bRemove )
1242                                         *Value |= cFLAGS[i].Value;
1243                                 break;
1244                         }
1245                 }
1246                 
1247                 // Error check
1248                 if( i == ciNumFlags ) {
1249                         char    val[len+1];
1250                         strncpy(val, Str, len+1);
1251                         sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);
1252                         return -1;
1253                 }
1254                 
1255                 Str = space + 1;
1256         } while(space);
1257         
1258         return 0;
1259 }

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