3 * UCC (University [of WA] Computer Club) Electronic Accounting System
5 * server.c - Client Server Code
7 * This file is licenced under the 3-clause BSD Licence. See the file
8 * COPYING for full details.
13 #include <sys/socket.h>
14 #include <netinet/in.h>
15 #include <arpa/inet.h>
21 #define DEBUG_TRACE_CLIENT 0
24 #define MAX_CONNECTION_QUEUE 5
25 #define INPUT_BUFFER_SIZE 256
26 #define CLIENT_TIMEOUT 10 // Seconds
28 #define HASH_TYPE SHA1
29 #define HASH_LENGTH 20
31 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
34 typedef struct sClient
36 int Socket; // Client socket ID
39 int bIsTrusted; // Is the connection from a trusted host/port
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);
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);
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);
79 const struct sClientCommand {
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}
99 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
103 int giServer_Port = 11020;
104 int gbServer_RunInBackground = 0;
105 char *gsServer_LogFile = "/var/log/dispsrv.log";
106 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
108 int giServer_Socket; // Server socket
109 int giServer_NextClientID = 1; // Debug client ID
114 * \brief Open listenting socket and serve connections
116 void Server_Start(void)
119 struct sockaddr_in server_addr, client_addr;
121 atexit(Server_Cleanup);
124 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
125 if( giServer_Socket < 0 ) {
126 fprintf(stderr, "ERROR: Unable to create server socket\n");
130 // Make listen address
131 memset(&server_addr, 0, sizeof(server_addr));
132 server_addr.sin_family = AF_INET; // Internet Socket
133 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
134 server_addr.sin_port = htons(giServer_Port); // Port
137 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
138 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
144 if( gbServer_RunInBackground )
148 fprintf(stderr, "ERROR: Unable to fork\n");
149 perror("fork background");
156 // In child, sort out stdin/stdout
157 reopen(0, "/dev/null", O_READ);
158 reopen(1, gsServer_LogFile, O_CREAT|O_APPEND);
159 reopen(2, gsServer_ErrorLog, O_CREAT|O_APPEND);
164 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
165 fprintf(stderr, "ERROR: Unable to listen to socket\n");
170 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
174 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
175 fprintf(fp, "%i", getpid());
181 uint len = sizeof(client_addr);
184 // Accept a connection
185 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
186 if(client_socket < 0) {
187 fprintf(stderr, "ERROR: Unable to accept client connection\n");
191 // Set a timeout on the user conneciton
194 tv.tv_sec = CLIENT_TIMEOUT;
196 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
198 perror("setsockopt");
203 // Debug: Print the connection string
204 if(giDebugLevel >= 2) {
205 char ipstr[INET_ADDRSTRLEN];
206 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
207 printf("Client connection from %s:%i\n",
208 ipstr, ntohs(client_addr.sin_port));
211 // Doesn't matter what, localhost is trusted
212 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
215 // Trusted Connections
216 if( ntohs(client_addr.sin_port) < 1024 )
218 // TODO: Make this runtime configurable
219 switch( ntohl( client_addr.sin_addr.s_addr ) )
221 case 0x7F000001: // 127.0.0.1 localhost
222 // case 0x825F0D00: // 130.95.13.0
223 case 0x825F0D07: // 130.95.13.7 motsugo
224 case 0x825F0D11: // 130.95.13.17 mermaid
225 case 0x825F0D12: // 130.95.13.18 mussel
226 case 0x825F0D17: // 130.95.13.23 martello
227 case 0x825F0D42: // 130.95.13.66 heathred
235 // TODO: Multithread this?
236 Server_HandleClient(client_socket, bTrusted);
238 close(client_socket);
242 void Server_Cleanup(void)
244 printf("\nClose(%i)\n", giServer_Socket);
245 close(giServer_Socket);
246 unlink("/var/run/dispsrv");
250 * \brief Reads from a client socket and parses the command strings
251 * \param Socket Client socket number/handle
252 * \param bTrusted Is the client trusted?
254 void Server_HandleClient(int Socket, int bTrusted)
256 char inbuf[INPUT_BUFFER_SIZE];
258 int remspace = INPUT_BUFFER_SIZE-1;
262 memset(&clientInfo, 0, sizeof(clientInfo));
264 // Initialise Client info
265 clientInfo.Socket = Socket;
266 clientInfo.ID = giServer_NextClientID ++;
267 clientInfo.bIsTrusted = bTrusted;
268 clientInfo.EffectiveUID = -1;
273 * - The `buf` and `remspace` variables allow a line to span several
274 * calls to recv(), if a line is not completed in one recv() call
275 * it is saved to the beginning of `inbuf` and `buf` is updated to
278 // TODO: Use select() instead (to give a timeout)
279 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
282 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
286 while( (eol = strchr(start, '\n')) )
290 Server_ParseClientCommand(&clientInfo, start);
295 // Check if there was an incomplete line
296 if( *start != '\0' ) {
297 int tailBytes = bytes - (start-buf);
298 // Roll back in buffer
299 memcpy(inbuf, start, tailBytes);
300 remspace -= tailBytes;
302 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
304 remspace = INPUT_BUFFER_SIZE - 1;
309 remspace = INPUT_BUFFER_SIZE - 1;
315 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
319 if(giDebugLevel >= 2) {
320 printf("Client %i: Disconnected\n", clientInfo.ID);
325 * \brief Parses a client command and calls the required helper function
326 * \param Client Pointer to client state structure
327 * \param CommandString Command from client (single line of the command)
328 * \return Heap String to return to the client
330 void Server_ParseClientCommand(tClient *Client, char *CommandString)
332 char *command, *args;
335 if( giDebugLevel >= 2 )
336 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
338 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
340 if( command == NULL ) return ;
341 // printf("command=%s, args=%s\n", command, args);
342 // Is this an error? (just ignore for now)
348 for( i = 0; i < NUM_COMMANDS; i++ )
350 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
351 if( giDebugLevel >= 2 )
352 Debug(Client, "CMD %s - \"%s\"", command, args);
353 gaServer_Commands[i].Function(Client, args);
358 sendf(Client->Socket, "400 Unknown Command\n");
365 * \brief Set client username
367 * Usage: USER <username>
369 void Server_Cmd_USER(tClient *Client, char *Args)
373 if( Server_int_ParseArgs(0, Args, &username, NULL) )
375 sendf(Client->Socket, "407 USER takes 1 argument\n");
381 Debug(Client, "Authenticating as '%s'", username);
385 free(Client->Username);
386 Client->Username = strdup(username);
389 // Create a salt (that changes if the username is changed)
390 // Yes, I know, I'm a little paranoid, but who isn't?
391 Client->Salt[0] = 0x21 + (rand()&0x3F);
392 Client->Salt[1] = 0x21 + (rand()&0x3F);
393 Client->Salt[2] = 0x21 + (rand()&0x3F);
394 Client->Salt[3] = 0x21 + (rand()&0x3F);
395 Client->Salt[4] = 0x21 + (rand()&0x3F);
396 Client->Salt[5] = 0x21 + (rand()&0x3F);
397 Client->Salt[6] = 0x21 + (rand()&0x3F);
398 Client->Salt[7] = 0x21 + (rand()&0x3F);
400 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
401 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
403 sendf(Client->Socket, "100 User Set\n");
408 * \brief Authenticate as a user
412 void Server_Cmd_PASS(tClient *Client, char *Args)
417 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
419 sendf(Client->Socket, "407 PASS takes 1 argument\n");
423 // Pass on to cokebank
424 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
426 if( Client->UID == -1 ) {
427 sendf(Client->Socket, "401 Auth Failure\n");
431 flags = Bank_GetFlags(Client->UID);
432 if( flags & USER_FLAG_DISABLED ) {
434 sendf(Client->Socket, "403 Account Disabled\n");
437 if( flags & USER_FLAG_INTERNAL ) {
439 sendf(Client->Socket, "403 Internal account\n");
443 Client->bIsAuthed = 1;
444 sendf(Client->Socket, "200 Auth OK\n");
448 * \brief Authenticate as a user without a password
450 * Usage: AUTOAUTH <user>
452 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
457 if( Server_int_ParseArgs(0, Args, &username, NULL) )
459 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
464 if( !Client->bIsTrusted ) {
466 Debug(Client, "Untrusted client attempting to AUTOAUTH");
467 sendf(Client->Socket, "401 Untrusted\n");
472 Client->UID = Bank_GetAcctByName( username );
473 if( Client->UID < 0 ) {
475 Debug(Client, "Unknown user '%s'", username);
476 sendf(Client->Socket, "403 Auth Failure\n");
480 userflags = Bank_GetFlags(Client->UID);
481 // You can't be an internal account
482 if( userflags & USER_FLAG_INTERNAL ) {
484 Debug(Client, "Autoauth as '%s', not allowed", username);
486 sendf(Client->Socket, "403 Account is internal\n");
491 if( userflags & USER_FLAG_DISABLED ) {
493 sendf(Client->Socket, "403 Account disabled\n");
497 Client->bIsAuthed = 1;
500 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
502 sendf(Client->Socket, "200 Auth OK\n");
506 * \brief Set effective user
508 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
511 int eUserFlags, userFlags;
513 if( Server_int_ParseArgs(0, Args, &username, NULL) )
515 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
519 if( !strlen(Args) ) {
520 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
524 // Check user permissions
525 userFlags = Bank_GetFlags(Client->UID);
526 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
527 sendf(Client->Socket, "403 Not in coke\n");
532 Client->EffectiveUID = Bank_GetAcctByName(username);
533 if( Client->EffectiveUID == -1 ) {
534 sendf(Client->Socket, "404 User not found\n");
538 // You can't be an internal account
539 if( !(userFlags & USER_FLAG_ADMIN) )
541 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
542 if( eUserFlags & USER_FLAG_INTERNAL ) {
543 Client->EffectiveUID = -1;
544 sendf(Client->Socket, "404 User not found\n");
547 // Disabled only avaliable to admins
548 if( eUserFlags & USER_FLAG_DISABLED ) {
549 Client->EffectiveUID = -1;
550 sendf(Client->Socket, "403 Account disabled\n");
555 sendf(Client->Socket, "200 User set\n");
559 * \brief Send an item status to the client
560 * \param Client Who to?
561 * \param Item Item to send
563 void Server_int_SendItem(tClient *Client, tItem *Item)
565 char *status = "avail";
567 if( Item->Handler->CanDispense )
569 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
571 case 0: status = "avail"; break;
572 case 1: status = "sold"; break;
574 case -1: status = "error"; break;
578 sendf(Client->Socket,
579 "202 Item %s:%i %s %i %s\n",
580 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
585 * \brief Enumerate the items that the server knows about
587 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
591 if( Args != NULL && strlen(Args) ) {
592 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
598 for( i = 0; i < giNumItems; i ++ ) {
599 if( gaItems[i].bHidden ) continue;
603 sendf(Client->Socket, "201 Items %i\n", count);
605 for( i = 0; i < giNumItems; i ++ ) {
606 if( gaItems[i].bHidden ) continue;
607 Server_int_SendItem( Client, &gaItems[i] );
610 sendf(Client->Socket, "200 List end\n");
613 tItem *_GetItemFromString(char *String)
617 char *colon = strchr(String, ':');
629 for( i = 0; i < giNumHandlers; i ++ )
631 if( strcmp(gaHandlers[i]->Name, type) == 0) {
632 handler = gaHandlers[i];
641 for( i = 0; i < giNumItems; i ++ )
643 if( gaItems[i].Handler != handler ) continue;
644 if( gaItems[i].ID != num ) continue;
651 * \brief Fetch information on a specific item
653 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
658 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
659 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
662 item = _GetItemFromString(Args);
665 sendf(Client->Socket, "406 Bad Item ID\n");
669 Server_int_SendItem( Client, item );
672 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
679 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
680 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
684 if( !Client->bIsAuthed ) {
685 sendf(Client->Socket, "401 Not Authenticated\n");
689 item = _GetItemFromString(itemname);
691 sendf(Client->Socket, "406 Bad Item ID\n");
695 if( Client->EffectiveUID != -1 ) {
696 uid = Client->EffectiveUID;
702 switch( ret = DispenseItem( Client->UID, uid, item ) )
704 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
705 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
706 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
708 sendf(Client->Socket, "500 Dispense Error\n");
713 void Server_Cmd_GIVE(tClient *Client, char *Args)
715 char *recipient, *ammount, *reason;
720 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
721 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
725 if( !Client->bIsAuthed ) {
726 sendf(Client->Socket, "401 Not Authenticated\n");
731 uid = Bank_GetAcctByName(recipient);
733 sendf(Client->Socket, "404 Invalid target user\n");
737 // You can't alter an internal account
738 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
739 // sendf(Client->Socket, "404 Invalid target user\n");
744 iAmmount = atoi(ammount);
745 if( iAmmount <= 0 ) {
746 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
750 if( Client->EffectiveUID != -1 ) {
751 thisUid = Client->EffectiveUID;
754 thisUid = Client->UID;
758 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
761 sendf(Client->Socket, "200 Give OK\n");
764 sendf(Client->Socket, "402 Poor You\n");
767 sendf(Client->Socket, "500 Unknown error\n");
772 void Server_Cmd_DONATE(tClient *Client, char *Args)
774 char *ammount, *reason;
779 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
780 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
784 if( !Client->bIsAuthed ) {
785 sendf(Client->Socket, "401 Not Authenticated\n");
790 iAmmount = atoi(ammount);
791 if( iAmmount <= 0 ) {
792 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
796 // Handle effective users
797 if( Client->EffectiveUID != -1 ) {
798 thisUid = Client->EffectiveUID;
801 thisUid = Client->UID;
805 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
808 sendf(Client->Socket, "200 Give OK\n");
811 sendf(Client->Socket, "402 Poor You\n");
814 sendf(Client->Socket, "500 Unknown error\n");
819 void Server_Cmd_ADD(tClient *Client, char *Args)
821 char *user, *ammount, *reason;
825 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
826 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
830 if( !Client->bIsAuthed ) {
831 sendf(Client->Socket, "401 Not Authenticated\n");
835 // Check user permissions
836 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
837 sendf(Client->Socket, "403 Not in coke\n");
842 uid = Bank_GetAcctByName(user);
844 sendf(Client->Socket, "404 Invalid user\n");
848 // You can't alter an internal account
849 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
851 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
852 sendf(Client->Socket, "404 Invalid user\n");
855 // TODO: Maybe disallow changes to disabled?
859 iAmmount = atoi(ammount);
860 if( iAmmount == 0 && ammount[0] != '0' ) {
861 sendf(Client->Socket, "407 Invalid Argument\n");
866 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
869 sendf(Client->Socket, "200 Add OK\n");
872 sendf(Client->Socket, "402 Poor Guy\n");
875 sendf(Client->Socket, "500 Unknown error\n");
880 void Server_Cmd_SET(tClient *Client, char *Args)
882 char *user, *ammount, *reason;
886 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
887 sendf(Client->Socket, "407 SET takes 3 arguments\n");
891 if( !Client->bIsAuthed ) {
892 sendf(Client->Socket, "401 Not Authenticated\n");
896 // Check user permissions
897 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
898 sendf(Client->Socket, "403 Not an admin\n");
903 uid = Bank_GetAcctByName(user);
905 sendf(Client->Socket, "404 Invalid user\n");
910 iAmmount = atoi(ammount);
911 if( iAmmount == 0 && ammount[0] != '0' ) {
912 sendf(Client->Socket, "407 Invalid Argument\n");
917 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
920 sendf(Client->Socket, "200 Add OK\n");
923 sendf(Client->Socket, "402 Poor Guy\n");
926 sendf(Client->Socket, "500 Unknown error\n");
931 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
935 int maxBal = INT_MAX, minBal = INT_MIN;
936 int flagMask = 0, flagVal = 0;
937 int sort = BANK_ITFLAG_SORT_NAME;
938 time_t lastSeenAfter=0, lastSeenBefore=0;
940 int flags; // Iterator flags
941 int balValue; // Balance value for iterator
942 time_t timeValue; // Time value for iterator
945 if( Args && strlen(Args) )
947 char *space = Args, *type, *val;
951 while(*type == ' ') type ++;
953 space = strchr(space, ' ');
954 if(space) *space = '\0';
957 val = strchr(type, ':');
964 if( strcmp(type, "min_balance") == 0 ) {
968 else if( strcmp(type, "max_balance") == 0 ) {
972 else if( strcmp(type, "flags") == 0 ) {
973 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
976 // - Last seen before timestamp
977 else if( strcmp(type, "last_seen_before") == 0 ) {
978 lastSeenAfter = atoll(val);
980 // - Last seen after timestamp
981 else if( strcmp(type, "last_seen_after") == 0 ) {
982 lastSeenAfter = atoll(val);
985 else if( strcmp(type, "sort") == 0 ) {
986 char *dash = strchr(val, '-');
991 if( strcmp(val, "name") == 0 ) {
992 sort = BANK_ITFLAG_SORT_NAME;
994 else if( strcmp(val, "balance") == 0 ) {
995 sort = BANK_ITFLAG_SORT_BAL;
997 else if( strcmp(val, "lastseen") == 0 ) {
998 sort = BANK_ITFLAG_SORT_LASTSEEN;
1001 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1004 // Handle sort direction
1006 if( strcmp(dash, "desc") == 0 ) {
1007 sort |= BANK_ITFLAG_REVSORT;
1010 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1017 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1024 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1030 *space = ' '; // Repair (to be nice)
1032 while(*space == ' ') space ++;
1038 if( maxBal != INT_MAX ) {
1039 flags = sort|BANK_ITFLAG_MAXBALANCE;
1042 else if( minBal != INT_MIN ) {
1043 flags = sort|BANK_ITFLAG_MINBALANCE;
1050 if( lastSeenBefore ) {
1051 timeValue = lastSeenBefore;
1052 flags |= BANK_ITFLAG_SEENBEFORE;
1054 else if( lastSeenAfter ) {
1055 timeValue = lastSeenAfter;
1056 flags |= BANK_ITFLAG_SEENAFTER;
1061 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1063 // Get return number
1064 while( (i = Bank_IteratorNext(it)) != -1 )
1066 int bal = Bank_GetBalance(i);
1068 if( bal == INT_MIN ) continue;
1070 if( bal < minBal ) continue;
1071 if( bal > maxBal ) continue;
1076 Bank_DelIterator(it);
1079 sendf(Client->Socket, "201 Users %i\n", numRet);
1083 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1085 while( (i = Bank_IteratorNext(it)) != -1 )
1087 int bal = Bank_GetBalance(i);
1089 if( bal == INT_MIN ) continue;
1091 if( bal < minBal ) continue;
1092 if( bal > maxBal ) continue;
1094 _SendUserInfo(Client, i);
1097 Bank_DelIterator(it);
1099 sendf(Client->Socket, "200 List End\n");
1102 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1108 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1109 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1113 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1116 uid = Bank_GetAcctByName(user);
1118 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1120 sendf(Client->Socket, "404 Invalid user\n");
1124 _SendUserInfo(Client, uid);
1127 void _SendUserInfo(tClient *Client, int UserID)
1129 char *type, *disabled="", *door="";
1130 int flags = Bank_GetFlags(UserID);
1132 if( flags & USER_FLAG_INTERNAL ) {
1135 else if( flags & USER_FLAG_COKE ) {
1136 if( flags & USER_FLAG_ADMIN )
1137 type = "coke,admin";
1141 else if( flags & USER_FLAG_ADMIN ) {
1148 if( flags & USER_FLAG_DISABLED )
1149 disabled = ",disabled";
1150 if( flags & USER_FLAG_DOORGROUP )
1153 // TODO: User flags/type
1155 Client->Socket, "202 User %s %i %s%s%s\n",
1156 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1157 type, disabled, door
1161 void Server_Cmd_USERADD(tClient *Client, char *Args)
1166 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1167 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1171 // Check permissions
1172 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1173 sendf(Client->Socket, "403 Not a coke admin\n");
1177 // Try to create user
1178 if( Bank_CreateAcct(username) == -1 ) {
1179 sendf(Client->Socket, "404 User exists\n");
1184 char *thisName = Bank_GetAcctName(Client->UID);
1185 Log_Info("Account '%s' created by '%s'", username, thisName);
1189 sendf(Client->Socket, "200 User Added\n");
1192 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1194 char *username, *flags;
1195 int mask=0, value=0;
1199 if( Server_int_ParseArgs(0, Args, &username, &flags, NULL) ) {
1200 sendf(Client->Socket, "407 USER_FLAGS takes 2 arguments\n");
1204 // Check permissions
1205 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1206 sendf(Client->Socket, "403 Not a coke admin\n");
1211 uid = Bank_GetAcctByName(username);
1213 sendf(Client->Socket, "404 User '%s' not found\n", username);
1218 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1222 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1223 uid, username, mask, value);
1226 Bank_SetFlags(uid, mask, value);
1229 sendf(Client->Socket, "200 User Updated\n");
1232 // --- INTERNAL HELPERS ---
1233 void Debug(tClient *Client, const char *Format, ...)
1236 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1237 printf("[%i] ", Client->ID);
1238 va_start(args, Format);
1239 vprintf(Format, args);
1244 int sendf(int Socket, const char *Format, ...)
1249 va_start(args, Format);
1250 len = vsnprintf(NULL, 0, Format, args);
1255 va_start(args, Format);
1256 vsnprintf(buf, len+1, Format, args);
1259 #if DEBUG_TRACE_CLIENT
1260 printf("sendf: %s", buf);
1263 return send(Socket, buf, len, 0);
1267 // Takes a series of char *'s in
1269 * \brief Parse space-separated entries into
1271 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1276 va_start(args, ArgStr);
1281 while( (dest = va_arg(args, char **)) )
1287 savedChar = *ArgStr;
1289 while( (dest = va_arg(args, char **)) )
1291 // Trim leading spaces
1292 while( *ArgStr == ' ' || *ArgStr == '\t' )
1295 // ... oops, not enough arguments
1296 if( *ArgStr == '\0' )
1298 // NULL unset arguments
1301 } while( (dest = va_arg(args, char **)) );
1306 if( *ArgStr == '"' )
1311 while( *ArgStr && *ArgStr != '"' )
1318 // Read until a space
1319 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1322 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1328 // Oops, extra arguments, and greedy not set
1329 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1336 *ArgStr = savedChar;
1339 return 0; // Success!
1342 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1349 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1350 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1351 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1352 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1353 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1355 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1367 while( *Str == ' ' ) Str ++; // Eat whitespace
1368 space = strchr(Str, ','); // Find the end of the flag
1374 // Check for inversion/removal
1375 if( *Str == '!' || *Str == '-' ) {
1379 else if( *Str == '+' ) {
1383 // Check flag values
1384 for( i = 0; i < ciNumFlags; i ++ )
1386 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1387 *Mask |= cFLAGS[i].Mask;
1388 *Value &= ~cFLAGS[i].Mask;
1390 *Value |= cFLAGS[i].Value;
1396 if( i == ciNumFlags ) {
1398 strncpy(val, Str, len+1);
1399 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);