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

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