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

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