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

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