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

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