Client - Fixed funny colours
[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 <fcntl.h>      // O_*
18 #include <string.h>
19 #include <limits.h>
20 #include <stdarg.h>
21 #include <signal.h>     // Signal handling
22 #include <ident.h>      // AUTHIDENT
23 #include <time.h>       // time(2)
24 #include <ctype.h>
25
26 #define DEBUG_TRACE_CLIENT      0
27 #define HACK_NO_REFUNDS 1
28
29 #define PIDFILE "/var/run/dispsrv.pid"
30
31 // Statistics
32 #define MAX_CONNECTION_QUEUE    5
33 #define INPUT_BUFFER_SIZE       256
34 #define CLIENT_TIMEOUT  10      // Seconds
35
36 #define HASH_TYPE       SHA1
37 #define HASH_LENGTH     20
38
39 #define MSG_STR_TOO_LONG        "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
40
41 #define IDENT_TRUSTED_NETWORK 0x825F0D00
42 #define IDENT_TRUSTED_NETMASK 0xFFFFFFC0
43
44 // === TYPES ===
45 typedef struct sClient
46 {
47          int    Socket; // Client socket ID
48          int    ID;     // Client ID
49          
50          int    bTrustedHost;
51          int    bCanAutoAuth;   // Is the connection from a trusted host/port
52         
53         char    *Username;
54         char    Salt[9];
55         
56          int    UID;
57          int    EffectiveUID;
58          int    bIsAuthed;
59 }       tClient;
60
61 // === PROTOTYPES ===
62 void    Server_Start(void);
63 void    Server_Cleanup(void);
64 void    Server_HandleClient(int Socket, int bTrustedHost, int bRootPort);
65 void    Server_ParseClientCommand(tClient *Client, char *CommandString);
66 // --- Commands ---
67 void    Server_Cmd_USER(tClient *Client, char *Args);
68 void    Server_Cmd_PASS(tClient *Client, char *Args);
69 void    Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
70 void    Server_Cmd_AUTHIDENT(tClient *Client, char *Args);
71 void    Server_Cmd_SETEUSER(tClient *Client, char *Args);
72 void    Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
73 void    Server_Cmd_ITEMINFO(tClient *Client, char *Args);
74 void    Server_Cmd_DISPENSE(tClient *Client, char *Args);
75 void    Server_Cmd_REFUND(tClient *Client, char *Args);
76 void    Server_Cmd_GIVE(tClient *Client, char *Args);
77 void    Server_Cmd_DONATE(tClient *Client, char *Args);
78 void    Server_Cmd_ADD(tClient *Client, char *Args);
79 void    Server_Cmd_SET(tClient *Client, char *Args);
80 void    Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
81 void    Server_Cmd_USERINFO(tClient *Client, char *Args);
82 void    _SendUserInfo(tClient *Client, int UserID);
83 void    Server_Cmd_USERADD(tClient *Client, char *Args);
84 void    Server_Cmd_USERFLAGS(tClient *Client, char *Args);
85 void    Server_Cmd_UPDATEITEM(tClient *Client, char *Args);
86 void    Server_Cmd_PINCHECK(tClient *Client, char *Args);
87 void    Server_Cmd_PINSET(tClient *Client, char *Args);
88 // --- Helpers ---
89 void    Debug(tClient *Client, const char *Format, ...);
90  int    sendf(int Socket, const char *Format, ...);
91  int    Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
92  int    Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
93
94 // === CONSTANTS ===
95 // - Commands
96 const struct sClientCommand {
97         const char      *Name;
98         void    (*Function)(tClient *Client, char *Arguments);
99 }       gaServer_Commands[] = {
100         {"USER", Server_Cmd_USER},
101         {"PASS", Server_Cmd_PASS},
102         {"AUTOAUTH", Server_Cmd_AUTOAUTH},
103         {"AUTHIDENT", Server_Cmd_AUTHIDENT},
104         {"SETEUSER", Server_Cmd_SETEUSER},
105         {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
106         {"ITEM_INFO", Server_Cmd_ITEMINFO},
107         {"DISPENSE", Server_Cmd_DISPENSE},
108         {"REFUND", Server_Cmd_REFUND},
109         {"GIVE", Server_Cmd_GIVE},
110         {"DONATE", Server_Cmd_DONATE},
111         {"ADD", Server_Cmd_ADD},
112         {"SET", Server_Cmd_SET},
113         {"ENUM_USERS", Server_Cmd_ENUMUSERS},
114         {"USER_INFO", Server_Cmd_USERINFO},
115         {"USER_ADD", Server_Cmd_USERADD},
116         {"USER_FLAGS", Server_Cmd_USERFLAGS},
117         {"UPDATE_ITEM", Server_Cmd_UPDATEITEM},
118         {"PIN_CHECK", Server_Cmd_PINCHECK},
119         {"PIN_SET", Server_Cmd_PINSET}
120 };
121 #define NUM_COMMANDS    ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
122
123 // === GLOBALS ===
124 // - Configuration
125  int    giServer_Port = 11020;
126  int    gbServer_RunInBackground = 0;
127 char    *gsServer_LogFile = "/var/log/dispsrv.log";
128 char    *gsServer_ErrorLog = "/var/log/dispsrv.err";
129  int    giServer_NumTrustedHosts;
130 struct in_addr  *gaServer_TrustedHosts;
131 // - State variables
132  int    giServer_Socket;        // Server socket
133  int    giServer_NextClientID = 1;      // Debug client ID
134  
135
136 // === CODE ===
137 /**
138  * \brief Open listenting socket and serve connections
139  */
140 void Server_Start(void)
141 {
142          int    client_socket;
143         struct sockaddr_in      server_addr, client_addr;
144
145         // Parse trusted hosts list
146         giServer_NumTrustedHosts = Config_GetValueCount("trusted_host");
147         gaServer_TrustedHosts = malloc(giServer_NumTrustedHosts * sizeof(*gaServer_TrustedHosts));
148         for( int i = 0; i < giServer_NumTrustedHosts; i ++ )
149         {
150                 const char      *addr = Config_GetValue("trusted_host", i);
151                 
152                 if( inet_aton(addr, &gaServer_TrustedHosts[i]) == 0 ) {
153                         fprintf(stderr, "Invalid IP address '%s'\n", addr);
154                         continue ;
155                 }
156         }
157
158         atexit(Server_Cleanup);
159         // Ignore SIGPIPE (stops crashes when the client exits early)
160         signal(SIGPIPE, SIG_IGN);
161
162         // Create Server
163         giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
164         if( giServer_Socket < 0 ) {
165                 fprintf(stderr, "ERROR: Unable to create server socket\n");
166                 return ;
167         }
168         
169         // Make listen address
170         memset(&server_addr, 0, sizeof(server_addr));
171         server_addr.sin_family = AF_INET;       // Internet Socket
172         server_addr.sin_addr.s_addr = htonl(INADDR_ANY);        // Listen on all interfaces
173         server_addr.sin_port = htons(giServer_Port);    // Port
174
175         // Bind
176         if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
177                 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
178                 perror("Binding");
179                 return ;
180         }
181
182         // Fork into background
183         if( gbServer_RunInBackground )
184         {
185                 int pid = fork();
186                 if( pid == -1 ) {
187                         fprintf(stderr, "ERROR: Unable to fork\n");
188                         perror("fork background");
189                         exit(-1);
190                 }
191                 if( pid != 0 ) {
192                         // Parent, quit
193                         printf("Forked child %i\n", pid);
194                         exit(0);
195                 }
196                 // In child
197                 // - Sort out stdin/stdout
198                 #if 0
199                 dup2( open("/dev/null", O_RDONLY, 0644), STDIN_FILENO );
200                 dup2( open(gsServer_LogFile, O_CREAT|O_APPEND, 0644), STDOUT_FILENO );
201                 dup2( open(gsServer_ErrorLog, O_CREAT|O_APPEND, 0644), STDERR_FILENO );
202                 #else
203                 freopen("/dev/null", "r", stdin);
204                 freopen(gsServer_LogFile, "a", stdout);
205                 freopen(gsServer_ErrorLog, "a", stderr);
206                 fprintf(stdout, "OpenDispense 2 Server Started at %lld\n", (long long)time(NULL));
207                 fprintf(stderr, "OpenDispense 2 Server Started at %lld\n", (long long)time(NULL));
208                 #endif
209         }
210
211         // Start the helper thread
212         StartPeriodicThread();
213         
214         // Listen
215         if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
216                 fprintf(stderr, "ERROR: Unable to listen to socket\n");
217                 perror("Listen");
218                 return ;
219         }
220         
221         printf("Listening on 0.0.0.0:%i\n", giServer_Port);
222         
223         // write pidfile
224         {
225                 FILE *fp = fopen(PIDFILE, "w");
226                 if( fp ) {
227                         fprintf(fp, "%i", getpid());
228                         fclose(fp);
229                 }
230         }
231
232         for(;;)
233         {
234                 uint    len = sizeof(client_addr);
235                  int    bTrusted = 0;
236                  int    bRootPort = 0;
237                 
238                 // Accept a connection
239                 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
240                 if(client_socket < 0) {
241                         fprintf(stderr, "ERROR: Unable to accept client connection\n");
242                         return ;
243                 }
244                 
245                 // Set a timeout on the user conneciton
246                 {
247                         struct timeval tv;
248                         tv.tv_sec = CLIENT_TIMEOUT;
249                         tv.tv_usec = 0;
250                         if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
251                         {
252                                 perror("setsockopt");
253                                 return ;
254                         }
255                 }
256                 
257                 // Debug: Print the connection string
258                 if(giDebugLevel >= 2) {
259                         char    ipstr[INET_ADDRSTRLEN];
260                         inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
261                         printf("Client connection from %s:%i\n",
262                                 ipstr, ntohs(client_addr.sin_port));
263                 }
264                 
265                 // Doesn't matter what, localhost is trusted
266                 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
267                         bTrusted = 1;
268         
269                 // Check if the host is on the trusted list     
270                 for( int i = 0; i < giServer_NumTrustedHosts; i ++ )
271                 {
272                         if( memcmp(&client_addr.sin_addr, &gaServer_TrustedHosts[i], sizeof(struct in_addr)) == 0 )
273                         {
274                                 bTrusted = 1;
275                                 break;
276                         }
277                 }
278
279                 // Root port (can AUTOAUTH if also a trusted machine
280                 if( ntohs(client_addr.sin_port) < 1024 )
281                         bRootPort = 1;
282                 
283                 #if 0
284                 {
285                         // TODO: Make this runtime configurable
286                         switch( ntohl( client_addr.sin_addr.s_addr ) )
287                         {
288                         case 0x7F000001:        // 127.0.0.1    localhost
289                 //      case 0x825F0D00:        // 130.95.13.0
290                         case 0x825F0D04:        // 130.95.13.4  merlo
291                 //      case 0x825F0D05:        // 130.95.13.5  heathred (MR)
292                         case 0x825F0D07:        // 130.95.13.7  motsugo
293                         case 0x825F0D11:        // 130.95.13.17 mermaid
294                         case 0x825F0D12:        // 130.95.13.18 mussel
295                         case 0x825F0D17:        // 130.95.13.23 martello
296                         case 0x825F0D2A:        // 130.95.13.42 meersau
297                 //      case 0x825F0D42:        // 130.95.13.66 heathred (Clubroom)
298                                 bTrusted = 1;
299                                 break;
300                         default:
301                                 break;
302                         }
303                 }
304                 #endif
305                 
306                 // TODO: Multithread this?
307                 Server_HandleClient(client_socket, bTrusted, bRootPort);
308                 
309                 close(client_socket);
310         }
311 }
312
313 void Server_Cleanup(void)
314 {
315         printf("\nClose(%i)\n", giServer_Socket);
316         close(giServer_Socket);
317         unlink(PIDFILE);
318 }
319
320 /**
321  * \brief Reads from a client socket and parses the command strings
322  * \param Socket        Client socket number/handle
323  * \param bTrusted      Is the client trusted?
324  */
325 void Server_HandleClient(int Socket, int bTrusted, int bRootPort)
326 {
327         char    inbuf[INPUT_BUFFER_SIZE];
328         char    *buf = inbuf;
329          int    remspace = INPUT_BUFFER_SIZE-1;
330          int    bytes = -1;
331         tClient clientInfo;
332         
333         memset(&clientInfo, 0, sizeof(clientInfo));
334         
335         // Initialise Client info
336         clientInfo.Socket = Socket;
337         clientInfo.ID = giServer_NextClientID ++;
338         clientInfo.bTrustedHost = bTrusted;
339         clientInfo.bCanAutoAuth = bTrusted && bRootPort;
340         clientInfo.EffectiveUID = -1;
341         
342         // Read from client
343         /*
344          * Notes:
345          * - The `buf` and `remspace` variables allow a line to span several
346          *   calls to recv(), if a line is not completed in one recv() call
347          *   it is saved to the beginning of `inbuf` and `buf` is updated to
348          *   the end of it.
349          */
350         // TODO: Use select() instead (to give a timeout)
351         while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
352         {
353                 char    *eol, *start;
354                 buf[bytes] = '\0';      // Allow us to use stdlib string functions on it
355                 
356                 // Split by lines
357                 start = inbuf;
358                 while( (eol = strchr(start, '\n')) )
359                 {
360                         *eol = '\0';
361                         
362                         Server_ParseClientCommand(&clientInfo, start);
363                         
364                         start = eol + 1;
365                 }
366                 
367                 // Check if there was an incomplete line
368                 if( *start != '\0' ) {
369                          int    tailBytes = bytes - (start-buf);
370                         // Roll back in buffer
371                         memcpy(inbuf, start, tailBytes);
372                         remspace -= tailBytes;
373                         if(remspace == 0) {
374                                 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
375                                 buf = inbuf;
376                                 remspace = INPUT_BUFFER_SIZE - 1;
377                         }
378                 }
379                 else {
380                         buf = inbuf;
381                         remspace = INPUT_BUFFER_SIZE - 1;
382                 }
383         }
384         
385         // Check for errors
386         if( bytes < 0 ) {
387                 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
388                 return ;
389         }
390         
391         if(giDebugLevel >= 2) {
392                 printf("Client %i: Disconnected\n", clientInfo.ID);
393         }
394 }
395
396 /**
397  * \brief Parses a client command and calls the required helper function
398  * \param Client        Pointer to client state structure
399  * \param CommandString Command from client (single line of the command)
400  * \return Heap String to return to the client
401  */
402 void Server_ParseClientCommand(tClient *Client, char *CommandString)
403 {
404         char    *command, *args;
405          int    i;
406         
407         if( giDebugLevel >= 2 )
408                 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
409         
410         if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
411         {
412                 if( command == NULL )   return ;
413                 // Is this an error? (just ignore for now)
414         }
415         
416         
417         // Find command
418         for( i = 0; i < NUM_COMMANDS; i++ )
419         {
420                 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
421                         if( giDebugLevel >= 2 )
422                                 Debug(Client, "CMD %s - \"%s\"", command, args);
423                         gaServer_Commands[i].Function(Client, args);
424                         return ;
425                 }
426         }
427         
428         sendf(Client->Socket, "400 Unknown Command\n");
429 }
430
431 // ---
432 // Commands
433 // ---
434 /**
435  * \brief Set client username
436  * 
437  * Usage: USER <username>
438  */
439 void Server_Cmd_USER(tClient *Client, char *Args)
440 {
441         char    *username;
442         
443         if( Server_int_ParseArgs(0, Args, &username, NULL) )
444         {
445                 sendf(Client->Socket, "407 USER takes 1 argument\n");
446                 return ;
447         }
448         
449         // Debug!
450         if( giDebugLevel )
451                 Debug(Client, "Authenticating as '%s'", username);
452         
453         // Save username
454         if(Client->Username)
455                 free(Client->Username);
456         Client->Username = strdup(username);
457         
458         #if USE_SALT
459         // Create a salt (that changes if the username is changed)
460         // Yes, I know, I'm a little paranoid, but who isn't?
461         Client->Salt[0] = 0x21 + (rand()&0x3F);
462         Client->Salt[1] = 0x21 + (rand()&0x3F);
463         Client->Salt[2] = 0x21 + (rand()&0x3F);
464         Client->Salt[3] = 0x21 + (rand()&0x3F);
465         Client->Salt[4] = 0x21 + (rand()&0x3F);
466         Client->Salt[5] = 0x21 + (rand()&0x3F);
467         Client->Salt[6] = 0x21 + (rand()&0x3F);
468         Client->Salt[7] = 0x21 + (rand()&0x3F);
469         
470         // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
471         sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
472         #else
473         sendf(Client->Socket, "100 User Set\n");
474         #endif
475 }
476
477 /**
478  * \brief Authenticate as a user
479  * 
480  * Usage: PASS <hash>
481  */
482 void Server_Cmd_PASS(tClient *Client, char *Args)
483 {
484         char    *passhash;
485          int    flags;
486
487         if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
488         {
489                 sendf(Client->Socket, "407 PASS takes 1 argument\n");
490                 return ;
491         }
492         
493         // Pass on to cokebank
494         Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
495
496         if( Client->UID == -1 ) {
497                 sendf(Client->Socket, "401 Auth Failure\n");
498                 return ;
499         }
500
501         flags = Bank_GetFlags(Client->UID);
502         if( flags & USER_FLAG_DISABLED ) {
503                 Client->UID = -1;
504                 sendf(Client->Socket, "403 Account Disabled\n");
505                 return ;
506         }
507         if( flags & USER_FLAG_INTERNAL ) {
508                 Client->UID = -1;
509                 sendf(Client->Socket, "403 Internal account\n");
510                 return ;
511         }
512         
513         Client->bIsAuthed = 1;
514         sendf(Client->Socket, "200 Auth OK\n");
515 }
516
517 /**
518  * \brief Authenticate as a user without a password
519  * 
520  * Usage: AUTOAUTH <user>
521  */
522 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
523 {
524         char    *username;
525          int    userflags;
526         
527         if( Server_int_ParseArgs(0, Args, &username, NULL) )
528         {
529                 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
530                 return ;
531         }
532         
533         // Check if trusted
534         if( !Client->bCanAutoAuth ) {
535                 if(giDebugLevel)
536                         Debug(Client, "Untrusted client attempting to AUTOAUTH");
537                 sendf(Client->Socket, "401 Untrusted\n");
538                 return ;
539         }
540         
541         // Get UID
542         Client->UID = Bank_GetAcctByName( username, 0 );        
543         if( Client->UID < 0 ) {
544                 if(giDebugLevel)
545                         Debug(Client, "Unknown user '%s'", username);
546                 sendf(Client->Socket, "403 Auth Failure\n");
547                 return ;
548         }
549         
550         userflags = Bank_GetFlags(Client->UID);
551         // You can't be an internal account
552         if( userflags & USER_FLAG_INTERNAL ) {
553                 if(giDebugLevel)
554                         Debug(Client, "Autoauth as '%s', not allowed", username);
555                 Client->UID = -1;
556                 sendf(Client->Socket, "403 Account is internal\n");
557                 return ;
558         }
559
560         // Disabled accounts
561         if( userflags & USER_FLAG_DISABLED ) {
562                 Client->UID = -1;
563                 sendf(Client->Socket, "403 Account disabled\n");
564                 return ;
565         }
566
567         // Save username
568         if(Client->Username)
569                 free(Client->Username);
570         Client->Username = strdup(username);
571
572         Client->bIsAuthed = 1;
573         
574         if(giDebugLevel)
575                 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
576         
577         sendf(Client->Socket, "200 Auth OK\n");
578 }
579
580 /**
581  * \brief Authenticate as a user using the IDENT protocol
582  *
583  * Usage: AUTHIDENT
584  */
585 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args)
586 {
587         char    *username;
588          int    userflags;
589         const int ident_timeout = 5;
590
591         if( Args != NULL && strlen(Args) ) {
592                 sendf(Client->Socket, "407 AUTHIDENT takes no arguments\n");
593                 return ;
594         }
595
596         // Check if trusted
597         if( !Client->bTrustedHost ) {
598                 if(giDebugLevel)
599                         Debug(Client, "Untrusted client attempting to AUTHIDENT");
600                 sendf(Client->Socket, "401 Untrusted\n");
601                 return ;
602         }
603
604         // Get username via IDENT
605         username = ident_id(Client->Socket, ident_timeout);
606         if( !username ) {
607                 perror("AUTHIDENT - IDENT timed out");
608                 sendf(Client->Socket, "403 Authentication failure: IDENT auth timed out\n");
609                 return ;
610         }
611
612         // Get UID
613         Client->UID = Bank_GetAcctByName( username, 0 );
614         if( Client->UID < 0 ) {
615                 if(giDebugLevel)
616                         Debug(Client, "Unknown user '%s'", username);
617                 sendf(Client->Socket, "403 Authentication failure: unknown account\n");
618                 free(username);
619                 return ;
620         }
621
622         userflags = Bank_GetFlags(Client->UID);
623         // You can't be an internal account
624         if( userflags & USER_FLAG_INTERNAL ) {
625                 if(giDebugLevel)
626                         Debug(Client, "IDENT auth as '%s', not allowed", username);
627                 Client->UID = -1;
628                 sendf(Client->Socket, "403 Authentication failure: that account is internal\n");
629                 free(username);
630                 return ;
631         }
632
633         // Disabled accounts
634         if( userflags & USER_FLAG_DISABLED ) {
635                 Client->UID = -1;
636                 sendf(Client->Socket, "403 Authentication failure: account disabled\n");
637                 free(username);
638                 return ;
639         }
640
641         // Save username
642         if(Client->Username)
643                 free(Client->Username);
644         Client->Username = strdup(username);
645
646         Client->bIsAuthed = 1;
647
648         if(giDebugLevel)
649                 Debug(Client, "IDENT authenticated as '%s' (%i)", username, Client->UID);
650         free(username);
651
652         sendf(Client->Socket, "200 Auth OK\n");
653 }
654
655 /**
656  * \brief Set effective user
657  */
658 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
659 {
660         char    *username;
661          int    eUserFlags, userFlags;
662         
663         if( Server_int_ParseArgs(0, Args, &username, NULL) )
664         {
665                 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
666                 return ;
667         }
668         
669         if( !strlen(Args) ) {
670                 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
671                 return ;
672         }
673         
674         // Check authentication
675         if( !Client->bIsAuthed ) {
676                 sendf(Client->Socket, "401 Not Authenticated\n");
677                 return ;
678         }
679
680         // Check user permissions
681         userFlags = Bank_GetFlags(Client->UID);
682         if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
683                 sendf(Client->Socket, "403 Not in coke\n");
684                 return ;
685         }
686         
687         // Set id
688         Client->EffectiveUID = Bank_GetAcctByName(username, 0);
689         if( Client->EffectiveUID == -1 ) {
690                 sendf(Client->Socket, "404 User not found\n");
691                 return ;
692         }
693         // You can't be an internal account (unless you're an admin)
694         if( !(userFlags & USER_FLAG_ADMIN) )
695         {
696                 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
697                 if( eUserFlags & USER_FLAG_INTERNAL ) {
698                         Client->EffectiveUID = -1;
699                         sendf(Client->Socket, "404 User not found\n");
700                         return ;
701                 }
702                 // Disabled only avaliable to admins
703                 if( eUserFlags & USER_FLAG_DISABLED ) {
704                         Client->EffectiveUID = -1;
705                         sendf(Client->Socket, "403 Account disabled\n");
706                         return ;
707                 }
708         }
709
710         // Disabled accounts
711         if( userFlags & USER_FLAG_DISABLED ) {
712                 Client->EffectiveUID = -1;
713                 sendf(Client->Socket, "403 Account disabled\n");
714                 return ;
715         }
716         
717         sendf(Client->Socket, "200 User set\n");
718 }
719
720 /**
721  * \brief Send an item status to the client
722  * \param Client        Who to?
723  * \param Item  Item to send
724  */
725 void Server_int_SendItem(tClient *Client, tItem *Item)
726 {
727         char    *status = "avail";
728         
729         if( Item->Handler->CanDispense )
730         {
731                 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
732                 {
733                 case  0:        status = "avail";       break;
734                 case  1:        status = "sold";        break;
735                 default:
736                 case -1:        status = "error";       break;
737                 }
738         }
739         
740         if( !gbNoCostMode && Item->Price == 0 )
741                 status = "error";
742         // KNOWN HACK: Naming a slot 'dead' disables it
743         if( strcmp(Item->Name, "dead") == 0 )
744                 status = "sold";        // Another status?
745         
746         sendf(Client->Socket,
747                 "202 Item %s:%i %s %i %s\n",
748                 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
749                 );
750 }
751
752 /**
753  * \brief Enumerate the items that the server knows about
754  */
755 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
756 {
757          int    i, count;
758
759         if( Args != NULL && strlen(Args) ) {
760                 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
761                 return ;
762         }
763         
764         // Count shown items
765         count = 0;
766         for( i = 0; i < giNumItems; i ++ ) {
767                 if( gaItems[i].bHidden )        continue;
768                 count ++;
769         }
770
771         sendf(Client->Socket, "201 Items %i\n", count);
772
773         for( i = 0; i < giNumItems; i ++ ) {
774                 if( gaItems[i].bHidden )        continue;
775                 Server_int_SendItem( Client, &gaItems[i] );
776         }
777
778         sendf(Client->Socket, "200 List end\n");
779 }
780
781 tItem *_GetItemFromString(char *String)
782 {
783         tHandler        *handler;
784         char    *type = String;
785         char    *colon = strchr(String, ':');
786          int    num, i;
787         
788         if( !colon ) {
789                 return NULL;
790         }
791
792         num = atoi(colon+1);
793         *colon = '\0';
794
795         // Find handler
796         handler = NULL;
797         for( i = 0; i < giNumHandlers; i ++ )
798         {
799                 if( strcmp(gaHandlers[i]->Name, type) == 0) {
800                         handler = gaHandlers[i];
801                         break;
802                 }
803         }
804         if( !handler ) {
805                 return NULL;
806         }
807
808         // Find item
809         for( i = 0; i < giNumItems; i ++ )
810         {
811                 if( gaItems[i].Handler != handler )     continue;
812                 if( gaItems[i].ID != num )      continue;
813                 return &gaItems[i];
814         }
815         return NULL;
816 }
817
818 /**
819  * \brief Fetch information on a specific item
820  *
821  * Usage: ITEMINFO <item ID>
822  */
823 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
824 {
825         tItem   *item;
826         char    *itemname;
827         
828         if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
829                 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
830                 return ;
831         }
832         item = _GetItemFromString(Args);
833         
834         if( !item ) {
835                 sendf(Client->Socket, "406 Bad Item ID\n");
836                 return ;
837         }
838         
839         Server_int_SendItem( Client, item );
840 }
841
842 /**
843  * \brief Dispense an item
844  *
845  * Usage: DISPENSE <Item ID>
846  */
847 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
848 {
849         tItem   *item;
850          int    ret;
851          int    uid;
852         char    *itemname;
853         
854         if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
855                 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
856                 return ;
857         }
858          
859         if( !Client->bIsAuthed ) {
860                 sendf(Client->Socket, "401 Not Authenticated\n");
861                 return ;
862         }
863
864         item = _GetItemFromString(itemname);
865         if( !item ) {
866                 sendf(Client->Socket, "406 Bad Item ID\n");
867                 return ;
868         }
869         
870         if( Client->EffectiveUID != -1 ) {
871                 uid = Client->EffectiveUID;
872         }
873         else {
874                 uid = Client->UID;
875         }
876
877         switch( ret = DispenseItem( Client->UID, uid, item ) )
878         {
879         case 0: sendf(Client->Socket, "200 Dispense OK\n");     return ;
880         case 1: sendf(Client->Socket, "501 Unable to dispense\n");      return ;
881         case 2: sendf(Client->Socket, "402 Poor You\n");        return ;
882         default:
883                 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
884                 return ;
885         }
886 }
887
888 /**
889  * \brief Refund an item to a user
890  *
891  * Usage: REFUND <user> <item id> [<price>]
892  */
893 void Server_Cmd_REFUND(tClient *Client, char *Args)
894 {
895         tItem   *item;
896          int    uid, price_override = 0;
897         char    *username, *itemname, *price_str;
898
899         if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
900                 if( !itemname || price_str ) {
901                         sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
902                         return ;
903                 }
904         }
905
906         if( !Client->bIsAuthed ) {
907                 sendf(Client->Socket, "401 Not Authenticated\n");
908                 return ;
909         }
910
911         // Check user permissions
912         if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN))  ) {
913                 sendf(Client->Socket, "403 Not in coke\n");
914                 return ;
915         }
916
917         uid = Bank_GetAcctByName(username, 0);
918         if( uid == -1 ) {
919                 sendf(Client->Socket, "404 Unknown user\n");
920                 return ;
921         }
922         
923         item = _GetItemFromString(itemname);
924         if( !item ) {
925                 sendf(Client->Socket, "406 Bad Item ID\n");
926                 return ;
927         }
928
929         if( price_str )
930                 price_override = atoi(price_str);
931
932         switch( DispenseRefund( Client->UID, uid, item, price_override ) )
933         {
934         case 0: sendf(Client->Socket, "200 Item Refunded\n");   return ;
935         default:
936                 sendf(Client->Socket, "500 Dispense Error\n");
937                 return;
938         }
939 }
940
941 /**
942  * \brief Transfer money to another account
943  *
944  * Usage: GIVE <dest> <ammount> <reason...>
945  */
946 void Server_Cmd_GIVE(tClient *Client, char *Args)
947 {
948         char    *recipient, *ammount, *reason;
949          int    uid, iAmmount;
950          int    thisUid;
951         
952         // Parse arguments
953         if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
954                 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
955                 return ;
956         }
957         
958         // Check for authed
959         if( !Client->bIsAuthed ) {
960                 sendf(Client->Socket, "401 Not Authenticated\n");
961                 return ;
962         }
963
964         // Get recipient
965         uid = Bank_GetAcctByName(recipient, 0);
966         if( uid == -1 ) {
967                 sendf(Client->Socket, "404 Invalid target user\n");
968                 return ;
969         }
970         
971         // You can't alter an internal account
972 //      if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
973 //              sendf(Client->Socket, "404 Invalid target user\n");
974 //              return ;
975 //      }
976
977         // Parse ammount
978         iAmmount = atoi(ammount);
979         if( iAmmount <= 0 ) {
980                 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
981                 return ;
982         }
983         
984         if( Client->EffectiveUID != -1 ) {
985                 thisUid = Client->EffectiveUID;
986         }
987         else {
988                 thisUid = Client->UID;
989         }
990
991         // Do give
992         switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
993         {
994         case 0:
995                 sendf(Client->Socket, "200 Give OK\n");
996                 return ;
997         case 2:
998                 sendf(Client->Socket, "402 Poor You\n");
999                 return ;
1000         default:
1001                 sendf(Client->Socket, "500 Unknown error\n");
1002                 return ;
1003         }
1004 }
1005
1006 void Server_Cmd_DONATE(tClient *Client, char *Args)
1007 {
1008         char    *ammount, *reason;
1009          int    iAmmount;
1010          int    thisUid;
1011         
1012         // Parse arguments
1013         if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
1014                 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
1015                 return ;
1016         }
1017         
1018         if( !Client->bIsAuthed ) {
1019                 sendf(Client->Socket, "401 Not Authenticated\n");
1020                 return ;
1021         }
1022
1023         // Parse ammount
1024         iAmmount = atoi(ammount);
1025         if( iAmmount <= 0 ) {
1026                 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
1027                 return ;
1028         }
1029         
1030         // Handle effective users
1031         if( Client->EffectiveUID != -1 ) {
1032                 thisUid = Client->EffectiveUID;
1033         }
1034         else {
1035                 thisUid = Client->UID;
1036         }
1037
1038         // Do give
1039         switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
1040         {
1041         case 0:
1042                 sendf(Client->Socket, "200 Give OK\n");
1043                 return ;
1044         case 2:
1045                 sendf(Client->Socket, "402 Poor You\n");
1046                 return ;
1047         default:
1048                 sendf(Client->Socket, "500 Unknown error\n");
1049                 return ;
1050         }
1051 }
1052
1053 void Server_Cmd_ADD(tClient *Client, char *Args)
1054 {
1055         char    *user, *ammount, *reason;
1056          int    uid, iAmmount;
1057         
1058         // Parse arguments
1059         if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1060                 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
1061                 return ;
1062         }
1063         
1064         if( !Client->bIsAuthed ) {
1065                 sendf(Client->Socket, "401 Not Authenticated\n");
1066                 return ;
1067         }
1068
1069         // Check user permissions
1070         if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN))  ) {
1071                 sendf(Client->Socket, "403 Not in coke\n");
1072                 return ;
1073         }
1074
1075         #if !ROOT_CAN_ADD
1076         if( strcmp( Client->Username, "root" ) == 0 ) {
1077                 // Allow adding for new users
1078                 if( strcmp(reason, "treasurer: new user") != 0 ) {
1079                         sendf(Client->Socket, "403 Root may not add\n");
1080                         return ;
1081                 }
1082         }
1083         #endif
1084
1085         #if HACK_NO_REFUNDS
1086         if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
1087         {
1088                 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
1089                 return ;
1090         }
1091         #endif
1092
1093         // Get recipient
1094         uid = Bank_GetAcctByName(user, 0);
1095         if( uid == -1 ) {
1096                 sendf(Client->Socket, "404 Invalid user\n");
1097                 return ;
1098         }
1099         
1100         // You can't alter an internal account
1101         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
1102         {
1103                 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
1104                         sendf(Client->Socket, "404 Invalid user\n");
1105                         return ;
1106                 }
1107                 // TODO: Maybe disallow changes to disabled?
1108         }
1109
1110         // Parse ammount
1111         iAmmount = atoi(ammount);
1112         if( iAmmount == 0 && ammount[0] != '0' ) {
1113                 sendf(Client->Socket, "407 Invalid Argument\n");
1114                 return ;
1115         }
1116
1117         // Do give
1118         switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
1119         {
1120         case 0:
1121                 sendf(Client->Socket, "200 Add OK\n");
1122                 return ;
1123         case 2:
1124                 sendf(Client->Socket, "402 Poor Guy\n");
1125                 return ;
1126         default:
1127                 sendf(Client->Socket, "500 Unknown error\n");
1128                 return ;
1129         }
1130 }
1131
1132 void Server_Cmd_SET(tClient *Client, char *Args)
1133 {
1134         char    *user, *ammount, *reason;
1135          int    uid, iAmmount;
1136         
1137         // Parse arguments
1138         if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1139                 sendf(Client->Socket, "407 SET takes 3 arguments\n");
1140                 return ;
1141         }
1142         
1143         if( !Client->bIsAuthed ) {
1144                 sendf(Client->Socket, "401 Not Authenticated\n");
1145                 return ;
1146         }
1147
1148         // Check user permissions
1149         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN)  ) {
1150                 sendf(Client->Socket, "403 Not an admin\n");
1151                 return ;
1152         }
1153
1154         // Get recipient
1155         uid = Bank_GetAcctByName(user, 0);
1156         if( uid == -1 ) {
1157                 sendf(Client->Socket, "404 Invalid user\n");
1158                 return ;
1159         }
1160
1161         // Parse ammount
1162         iAmmount = atoi(ammount);
1163         if( iAmmount == 0 && ammount[0] != '0' ) {
1164                 sendf(Client->Socket, "407 Invalid Argument\n");
1165                 return ;
1166         }
1167
1168         // Do give
1169         switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
1170         {
1171         case 0:
1172                 sendf(Client->Socket, "200 Add OK\n");
1173                 return ;
1174         case 2:
1175                 sendf(Client->Socket, "402 Poor Guy\n");
1176                 return ;
1177         default:
1178                 sendf(Client->Socket, "500 Unknown error\n");
1179                 return ;
1180         }
1181 }
1182
1183 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1184 {
1185          int    i, numRet = 0;
1186         tAcctIterator   *it;
1187          int    maxBal = INT_MAX, minBal = INT_MIN;
1188          int    flagMask = 0, flagVal = 0;
1189          int    sort = BANK_ITFLAG_SORT_NAME;
1190         time_t  lastSeenAfter=0, lastSeenBefore=0;
1191         
1192          int    flags;  // Iterator flags
1193          int    balValue;       // Balance value for iterator
1194         time_t  timeValue;      // Time value for iterator
1195         
1196         // Parse arguments
1197         if( Args && strlen(Args) )
1198         {
1199                 char    *space = Args, *type, *val;
1200                 do
1201                 {
1202                         type = space;
1203                         while(*type == ' ')     type ++;
1204                         // Get next space
1205                         space = strchr(space, ' ');
1206                         if(space)       *space = '\0';
1207                         
1208                         // Get type
1209                         val = strchr(type, ':');
1210                         if( val ) {
1211                                 *val = '\0';
1212                                 val ++;
1213                                 
1214                                 // Types
1215                                 // - Minium Balance
1216                                 if( strcmp(type, "min_balance") == 0 ) {
1217                                         minBal = atoi(val);
1218                                 }
1219                                 // - Maximum Balance
1220                                 else if( strcmp(type, "max_balance") == 0 ) {
1221                                         maxBal = atoi(val);
1222                                 }
1223                                 // - Flags
1224                                 else if( strcmp(type, "flags") == 0 ) {
1225                                         if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1226                                                 return ;
1227                                 }
1228                                 // - Last seen before timestamp
1229                                 else if( strcmp(type, "last_seen_before") == 0 ) {
1230                                         lastSeenAfter = atoll(val);
1231                                 }
1232                                 // - Last seen after timestamp
1233                                 else if( strcmp(type, "last_seen_after") == 0 ) {
1234                                         lastSeenAfter = atoll(val);
1235                                 }
1236                                 // - Sorting 
1237                                 else if( strcmp(type, "sort") == 0 ) {
1238                                         char    *dash = strchr(val, '-');
1239                                         if( dash ) {
1240                                                 *dash = '\0';
1241                                                 dash ++;
1242                                         }
1243                                         if( strcmp(val, "name") == 0 ) {
1244                                                 sort = BANK_ITFLAG_SORT_NAME;
1245                                         }
1246                                         else if( strcmp(val, "balance") == 0 ) {
1247                                                 sort = BANK_ITFLAG_SORT_BAL;
1248                                         }
1249                                         else if( strcmp(val, "lastseen") == 0 ) {
1250                                                 sort = BANK_ITFLAG_SORT_LASTSEEN;
1251                                         }
1252                                         else {
1253                                                 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1254                                                 return ;
1255                                         }
1256                                         // Handle sort direction
1257                                         if( dash ) {
1258                                                 if( strcmp(dash, "desc") == 0 ) {
1259                                                         sort |= BANK_ITFLAG_REVSORT;
1260                                                 }
1261                                                 else {
1262                                                         sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1263                                                         return ;
1264                                                 }
1265                                                 dash[-1] = '-';
1266                                         }
1267                                 }
1268                                 else {
1269                                         sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1270                                         return ;
1271                                 }
1272                                 
1273                                 val[-1] = ':';
1274                         }
1275                         else {
1276                                 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1277                                 return ;
1278                         }
1279                         
1280                         // Eat whitespace
1281                         if( space ) {
1282                                 *space = ' ';   // Repair (to be nice)
1283                                 space ++;
1284                                 while(*space == ' ')    space ++;
1285                         }
1286                 }       while(space);
1287         }
1288         
1289         // Create iterator
1290         if( maxBal != INT_MAX ) {
1291                 flags = sort|BANK_ITFLAG_MAXBALANCE;
1292                 balValue = maxBal;
1293         }
1294         else if( minBal != INT_MIN ) {
1295                 flags = sort|BANK_ITFLAG_MINBALANCE;
1296                 balValue = minBal;
1297         }
1298         else {
1299                 flags = sort;
1300                 balValue = 0;
1301         }
1302         if( lastSeenBefore ) {
1303                 timeValue = lastSeenBefore;
1304                 flags |= BANK_ITFLAG_SEENBEFORE;
1305         }
1306         else if( lastSeenAfter ) {
1307                 timeValue = lastSeenAfter;
1308                 flags |= BANK_ITFLAG_SEENAFTER;
1309         }
1310         else {
1311                 timeValue = 0;
1312         }
1313         it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1314         
1315         // Get return number
1316         while( (i = Bank_IteratorNext(it)) != -1 )
1317         {
1318                 int bal = Bank_GetBalance(i);
1319                 
1320                 if( bal == INT_MIN )    continue;
1321                 
1322                 if( bal < minBal )      continue;
1323                 if( bal > maxBal )      continue;
1324                 
1325                 numRet ++;
1326         }
1327         
1328         Bank_DelIterator(it);
1329         
1330         // Send count
1331         sendf(Client->Socket, "201 Users %i\n", numRet);
1332         
1333         
1334         // Create iterator
1335         it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1336         
1337         while( (i = Bank_IteratorNext(it)) != -1 )
1338         {
1339                 int bal = Bank_GetBalance(i);
1340                 
1341                 if( bal == INT_MIN )    continue;
1342                 
1343                 if( bal < minBal )      continue;
1344                 if( bal > maxBal )      continue;
1345                 
1346                 _SendUserInfo(Client, i);
1347         }
1348         
1349         Bank_DelIterator(it);
1350         
1351         sendf(Client->Socket, "200 List End\n");
1352 }
1353
1354 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1355 {
1356          int    uid;
1357         char    *user;
1358         
1359         // Parse arguments
1360         if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1361                 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1362                 return ;
1363         }
1364         
1365         if( giDebugLevel )      Debug(Client, "User Info '%s'", user);
1366         
1367         // Get recipient
1368         uid = Bank_GetAcctByName(user, 0);
1369         
1370         if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1371         if( uid == -1 ) {
1372                 sendf(Client->Socket, "404 Invalid user\n");
1373                 return ;
1374         }
1375         
1376         _SendUserInfo(Client, uid);
1377 }
1378
1379 void _SendUserInfo(tClient *Client, int UserID)
1380 {
1381         char    *type, *disabled="", *door="";
1382          int    flags = Bank_GetFlags(UserID);
1383         
1384         if( flags & USER_FLAG_INTERNAL ) {
1385                 type = "internal";
1386         }
1387         else if( flags & USER_FLAG_COKE ) {
1388                 if( flags & USER_FLAG_ADMIN )
1389                         type = "coke,admin";
1390                 else
1391                         type = "coke";
1392         }
1393         else if( flags & USER_FLAG_ADMIN ) {
1394                 type = "admin";
1395         }
1396         else {
1397                 type = "user";
1398         }
1399         
1400         if( flags & USER_FLAG_DISABLED )
1401                 disabled = ",disabled";
1402         if( flags & USER_FLAG_DOORGROUP )
1403                 door = ",door";
1404         
1405         // TODO: User flags/type
1406         sendf(
1407                 Client->Socket, "202 User %s %i %s%s%s\n",
1408                 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1409                 type, disabled, door
1410                 );
1411 }
1412
1413 void Server_Cmd_USERADD(tClient *Client, char *Args)
1414 {
1415         char    *username;
1416         
1417         // Parse arguments
1418         if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1419                 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1420                 return ;
1421         }
1422         
1423         // Check authentication
1424         if( !Client->bIsAuthed ) {
1425                 sendf(Client->Socket, "401 Not Authenticated\n");
1426                 return ;
1427         }
1428         
1429         // Check permissions
1430         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1431                 sendf(Client->Socket, "403 Not a coke admin\n");
1432                 return ;
1433         }
1434         
1435         // Try to create user
1436         if( Bank_CreateAcct(username) == -1 ) {
1437                 sendf(Client->Socket, "404 User exists\n");
1438                 return ;
1439         }
1440         
1441         {
1442                 char    *thisName = Bank_GetAcctName(Client->UID);
1443                 Log_Info("Account '%s' created by '%s'", username, thisName);
1444                 free(thisName);
1445         }
1446         
1447         sendf(Client->Socket, "200 User Added\n");
1448 }
1449
1450 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1451 {
1452         char    *username, *flags, *reason=NULL;
1453          int    mask=0, value=0;
1454          int    uid;
1455         
1456         // Parse arguments
1457         if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1458                 if( !flags ) {
1459                         sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1460                         return ;
1461                 }
1462                 reason = "";
1463         }
1464         
1465         // Check authentication
1466         if( !Client->bIsAuthed ) {
1467                 sendf(Client->Socket, "401 Not Authenticated\n");
1468                 return ;
1469         }
1470         
1471         // Check permissions
1472         if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1473                 sendf(Client->Socket, "403 Not a coke admin\n");
1474                 return ;
1475         }
1476         
1477         // Get UID
1478         uid = Bank_GetAcctByName(username, 0);
1479         if( uid == -1 ) {
1480                 sendf(Client->Socket, "404 User '%s' not found\n", username);
1481                 return ;
1482         }
1483         
1484         // Parse flags
1485         if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1486                 return ;
1487         
1488         if( giDebugLevel )
1489                 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1490                         uid, username, mask, value);
1491         
1492         // Apply flags
1493         Bank_SetFlags(uid, mask, value);
1494
1495         // Log the change
1496         Log_Info("Updated '%s' with flag set '%s' by '%s' - Reason: %s",
1497                 username, flags, Client->Username, reason);
1498         
1499         // Return OK
1500         sendf(Client->Socket, "200 User Updated\n");
1501 }
1502
1503 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1504 {
1505         char    *itemname, *price_str, *description;
1506          int    price;
1507         tItem   *item;
1508         
1509         if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1510                 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1511                 return ;
1512         }
1513         
1514         if( !Client->bIsAuthed ) {
1515                 sendf(Client->Socket, "401 Not Authenticated\n");
1516                 return ;
1517         }
1518
1519         // Check user permissions
1520         if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN))  ) {
1521                 sendf(Client->Socket, "403 Not in coke\n");
1522                 return ;
1523         }
1524         
1525         item = _GetItemFromString(itemname);
1526         if( !item ) {
1527                 // TODO: Create item?
1528                 sendf(Client->Socket, "406 Bad Item ID\n");
1529                 return ;
1530         }
1531         
1532         price = atoi(price_str);
1533         if( price <= 0 && price_str[0] != '0' ) {
1534                 sendf(Client->Socket, "407 Invalid price set\n");
1535         }
1536         
1537         switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1538         {
1539         case 0:
1540                 // Return OK
1541                 sendf(Client->Socket, "200 Item updated\n");
1542                 break;
1543         default:
1544                 break;
1545         }
1546 }
1547
1548 void Server_Cmd_PINCHECK(tClient *Client, char *Args)
1549 {
1550         char    *username, *pinstr;
1551          int    pin;
1552
1553         if( Server_int_ParseArgs(0, Args, &username, &pinstr, NULL) ) {
1554                 sendf(Client->Socket, "407 PIN_CHECK takes 2 arguments\n");
1555                 return ;
1556         }
1557         
1558         if( !isdigit(pinstr[0]) || !isdigit(pinstr[1]) || !isdigit(pinstr[2]) || !isdigit(pinstr[3]) || pinstr[4] != '\0' ) {
1559                 sendf(Client->Socket, "407 PIN should be four digits\n");
1560                 return ;
1561         }
1562         pin = atoi(pinstr);
1563
1564         // Not strictly needed, but ensures that randoms don't do brute forcing
1565         if( !Client->bIsAuthed ) {
1566                 sendf(Client->Socket, "401 Not Authenticated\n");
1567                 return ;
1568         }
1569         
1570         // Check user permissions
1571         if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN))  ) {
1572                 sendf(Client->Socket, "403 Not in coke\n");
1573                 return ;
1574         }
1575         
1576         // Get user
1577         int uid = Bank_GetAcctByName(username, 0);
1578         if( uid == -1 ) {
1579                 sendf(Client->Socket, "404 User '%s' not found\n", username);
1580                 return ;
1581         }
1582         
1583         // Get the pin
1584         static time_t   last_wrong_pin_time;
1585         static int      backoff = 1;
1586         if( time(NULL) - last_wrong_pin_time < backoff ) {
1587                 sendf(Client->Socket, "407 Rate limited (%i seconds remaining)\n",
1588                         backoff - (time(NULL) - last_wrong_pin_time));
1589                 return ;
1590         }       
1591         last_wrong_pin_time = time(NULL);
1592         if( !Bank_IsPinValid(uid, pin) )
1593         {
1594                 sendf(Client->Socket, "403 Pin incorrect\n");
1595                 if( backoff < 5)
1596                         backoff ++;
1597                 return ;
1598         }
1599
1600         last_wrong_pin_time = 0;
1601         backoff = 1;
1602         sendf(Client->Socket, "200 Pin correct\n");
1603         return ;
1604 }
1605 void Server_Cmd_PINSET(tClient *Client, char *Args)
1606 {
1607         char    *pinstr;
1608          int    pin;
1609         
1610
1611         if( Server_int_ParseArgs(0, Args, &pinstr, NULL) ) {
1612                 sendf(Client->Socket, "407 PIN_SET takes 2 arguments\n");
1613                 return ;
1614         }
1615         
1616         if( !isdigit(pinstr[0]) || !isdigit(pinstr[1]) || !isdigit(pinstr[2]) || !isdigit(pinstr[3]) || pinstr[4] != '\0' ) {
1617                 sendf(Client->Socket, "407 PIN should be four digits\n");
1618                 return ;
1619         }
1620         pin = atoi(pinstr);
1621
1622         // Not strictly needed, but ensures that randoms don't do brute forcing
1623         if( !Client->bIsAuthed ) {
1624                 sendf(Client->Socket, "401 Not Authenticated\n");
1625                 return ;
1626         }
1627         
1628         int uid = Client->EffectiveUID;
1629         if(uid == -1)
1630                 uid = Client->UID;
1631         // Can only pinset yourself (well, the effective user)
1632         Bank_SetPin(uid, pin);
1633         sendf(Client->Socket, "200 Pin updated\n");
1634         return ;
1635 }
1636
1637 // --- INTERNAL HELPERS ---
1638 void Debug(tClient *Client, const char *Format, ...)
1639 {
1640         va_list args;
1641         //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1642         printf("[%i] ", Client->ID);
1643         va_start(args, Format);
1644         vprintf(Format, args);
1645         va_end(args);
1646         printf("\n");
1647 }
1648
1649 int sendf(int Socket, const char *Format, ...)
1650 {
1651         va_list args;
1652          int    len;
1653         
1654         va_start(args, Format);
1655         len = vsnprintf(NULL, 0, Format, args);
1656         va_end(args);
1657         
1658         {
1659                 char    buf[len+1];
1660                 va_start(args, Format);
1661                 vsnprintf(buf, len+1, Format, args);
1662                 va_end(args);
1663                 
1664                 #if DEBUG_TRACE_CLIENT
1665                 printf("sendf: %s", buf);
1666                 #endif
1667                 
1668                 return send(Socket, buf, len, 0);
1669         }
1670 }
1671
1672 // Takes a series of char *'s in
1673 /**
1674  * \brief Parse space-separated entries into 
1675  */
1676 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1677 {
1678         va_list args;
1679         char    savedChar;
1680         char    **dest;
1681         va_start(args, ArgStr);
1682
1683         // Check for null
1684         if( !ArgStr )
1685         {
1686                 while( (dest = va_arg(args, char **)) )
1687                         *dest = NULL;
1688                 va_end(args);
1689                 return 1;
1690         }
1691
1692         savedChar = *ArgStr;
1693         
1694         while( (dest = va_arg(args, char **)) )
1695         {
1696                 // Trim leading spaces
1697                 while( *ArgStr == ' ' || *ArgStr == '\t' )
1698                         ArgStr ++;
1699                 
1700                 // ... oops, not enough arguments
1701                 if( *ArgStr == '\0' )
1702                 {
1703                         // NULL unset arguments
1704                         do {
1705                                 *dest = NULL;
1706                         }       while( (dest = va_arg(args, char **)) );
1707                 va_end(args);
1708                         return -1;
1709                 }
1710                 
1711                 if( *ArgStr == '"' )
1712                 {
1713                         ArgStr ++;
1714                         *dest = ArgStr;
1715                         // Read until quote
1716                         while( *ArgStr && *ArgStr != '"' )
1717                                 ArgStr ++;
1718                 }
1719                 else
1720                 {
1721                         // Set destination
1722                         *dest = ArgStr;
1723                         // Read until a space
1724                         while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1725                                 ArgStr ++;
1726                 }
1727                 savedChar = *ArgStr;    // savedChar is used to un-mangle the last string
1728                 *ArgStr = '\0';
1729                 ArgStr ++;
1730         }
1731         va_end(args);
1732         
1733         // Oops, extra arguments, and greedy not set
1734         if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1735                 return -1;
1736         }
1737         
1738         // Un-mangle last
1739         if(bUseLongLast) {
1740                 ArgStr --;
1741                 *ArgStr = savedChar;
1742         }
1743         
1744         return 0;       // Success!
1745 }
1746
1747 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1748 {
1749         struct {
1750                 const char      *Name;
1751                  int    Mask;
1752                  int    Value;
1753         }       cFLAGS[] = {
1754                  {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1755                 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1756                 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1757                 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1758                 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1759         };
1760         const int       ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1761         
1762         char    *space;
1763         
1764         *Mask = 0;
1765         *Value = 0;
1766         
1767         do {
1768                  int    bRemove = 0;
1769                  int    i;
1770                  int    len;
1771                 
1772                 while( *Str == ' ' )    Str ++; // Eat whitespace
1773                 space = strchr(Str, ',');       // Find the end of the flag
1774                 if(space)
1775                         len = space - Str;
1776                 else
1777                         len = strlen(Str);
1778                 
1779                 // Check for inversion/removal
1780                 if( *Str == '!' || *Str == '-' ) {
1781                         bRemove = 1;
1782                         Str ++;
1783                 }
1784                 else if( *Str == '+' ) {
1785                         Str ++;
1786                 }
1787                 
1788                 // Check flag values
1789                 for( i = 0; i < ciNumFlags; i ++ )
1790                 {
1791                         if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1792                                 *Mask |= cFLAGS[i].Mask;
1793                                 *Value &= ~cFLAGS[i].Mask;
1794                                 if( !bRemove )
1795                                         *Value |= cFLAGS[i].Value;
1796                                 break;
1797                         }
1798                 }
1799                 
1800                 // Error check
1801                 if( i == ciNumFlags ) {
1802                         char    val[len+1];
1803                         strncpy(val, Str, len+1);
1804                         sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);
1805                         return -1;
1806                 }
1807                 
1808                 Str = space + 1;
1809         } while(space);
1810         
1811         return 0;
1812 }
1813

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