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

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