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

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