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

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