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

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