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

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