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])))
102 int giServer_Port = 11020;
103 int giServer_NextClientID = 1;
108 * \brief Open listenting socket and serve connections
110 void Server_Start(void)
113 struct sockaddr_in server_addr, client_addr;
115 atexit(Server_Cleanup);
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");
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
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);
138 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
139 fprintf(stderr, "ERROR: Unable to listen to socket\n");
144 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
148 // FILE *fp = fopen("/var/run/dispsrv.pid", "w");
149 // fprintf(fp, "%i", getpid());
155 uint len = sizeof(client_addr);
158 // Accept a connection
159 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
160 if(client_socket < 0) {
161 fprintf(stderr, "ERROR: Unable to accept client connection\n");
165 // Set a timeout on the user conneciton
168 tv.tv_sec = CLIENT_TIMEOUT;
170 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
172 perror("setsockopt");
177 // Debug: Print the connection string
178 if(giDebugLevel >= 2) {
179 char ipstr[INET_ADDRSTRLEN];
180 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
181 printf("Client connection from %s:%i\n",
182 ipstr, ntohs(client_addr.sin_port));
185 // Doesn't matter what, localhost is trusted
186 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
189 // Trusted Connections
190 if( ntohs(client_addr.sin_port) < 1024 )
192 // TODO: Make this runtime configurable
193 switch( ntohl( client_addr.sin_addr.s_addr ) )
195 case 0x7F000001: // 127.0.0.1 localhost
196 // case 0x825F0D00: // 130.95.13.0
197 case 0x825F0D07: // 130.95.13.7 motsugo
198 case 0x825F0D11: // 130.95.13.17 mermaid
199 case 0x825F0D12: // 130.95.13.18 mussel
200 case 0x825F0D17: // 130.95.13.23 martello
201 case 0x825F0D42: // 130.95.13.66 heathred
209 // TODO: Multithread this?
210 Server_HandleClient(client_socket, bTrusted);
212 close(client_socket);
216 void Server_Cleanup(void)
218 printf("Close(%i)\n", giServer_Socket);
219 close(giServer_Socket);
223 * \brief Reads from a client socket and parses the command strings
224 * \param Socket Client socket number/handle
225 * \param bTrusted Is the client trusted?
227 void Server_HandleClient(int Socket, int bTrusted)
229 char inbuf[INPUT_BUFFER_SIZE];
231 int remspace = INPUT_BUFFER_SIZE-1;
235 memset(&clientInfo, 0, sizeof(clientInfo));
237 // Initialise Client info
238 clientInfo.Socket = Socket;
239 clientInfo.ID = giServer_NextClientID ++;
240 clientInfo.bIsTrusted = bTrusted;
241 clientInfo.EffectiveUID = -1;
246 * - The `buf` and `remspace` variables allow a line to span several
247 * calls to recv(), if a line is not completed in one recv() call
248 * it is saved to the beginning of `inbuf` and `buf` is updated to
251 // TODO: Use select() instead (to give a timeout)
252 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
255 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
259 while( (eol = strchr(start, '\n')) )
263 Server_ParseClientCommand(&clientInfo, start);
268 // Check if there was an incomplete line
269 if( *start != '\0' ) {
270 int tailBytes = bytes - (start-buf);
271 // Roll back in buffer
272 memcpy(inbuf, start, tailBytes);
273 remspace -= tailBytes;
275 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
277 remspace = INPUT_BUFFER_SIZE - 1;
282 remspace = INPUT_BUFFER_SIZE - 1;
288 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
292 if(giDebugLevel >= 2) {
293 printf("Client %i: Disconnected\n", clientInfo.ID);
298 * \brief Parses a client command and calls the required helper function
299 * \param Client Pointer to client state structure
300 * \param CommandString Command from client (single line of the command)
301 * \return Heap String to return to the client
303 void Server_ParseClientCommand(tClient *Client, char *CommandString)
305 char *command, *args;
308 if( giDebugLevel >= 2 )
309 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
311 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
313 // printf("command=%s, args=%s\n", command, args);
314 // Is this an error? (just ignore for now)
320 for( i = 0; i < NUM_COMMANDS; i++ )
322 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
323 if( giDebugLevel >= 2 )
324 Debug(Client, "CMD %s - \"%s\"", command, args);
325 gaServer_Commands[i].Function(Client, args);
330 sendf(Client->Socket, "400 Unknown Command\n");
337 * \brief Set client username
339 * Usage: USER <username>
341 void Server_Cmd_USER(tClient *Client, char *Args)
345 if( Server_int_ParseArgs(0, Args, &username, NULL) )
347 sendf(Client->Socket, "407 USER takes 1 argument\n");
353 Debug(Client, "Authenticating as '%s'", username);
357 free(Client->Username);
358 Client->Username = strdup(username);
361 // Create a salt (that changes if the username is changed)
362 // Yes, I know, I'm a little paranoid, but who isn't?
363 Client->Salt[0] = 0x21 + (rand()&0x3F);
364 Client->Salt[1] = 0x21 + (rand()&0x3F);
365 Client->Salt[2] = 0x21 + (rand()&0x3F);
366 Client->Salt[3] = 0x21 + (rand()&0x3F);
367 Client->Salt[4] = 0x21 + (rand()&0x3F);
368 Client->Salt[5] = 0x21 + (rand()&0x3F);
369 Client->Salt[6] = 0x21 + (rand()&0x3F);
370 Client->Salt[7] = 0x21 + (rand()&0x3F);
372 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
373 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
375 sendf(Client->Socket, "100 User Set\n");
380 * \brief Authenticate as a user
384 void Server_Cmd_PASS(tClient *Client, char *Args)
389 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
391 sendf(Client->Socket, "407 PASS takes 1 argument\n");
395 // Pass on to cokebank
396 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
398 if( Client->UID == -1 ) {
399 sendf(Client->Socket, "401 Auth Failure\n");
403 flags = Bank_GetFlags(Client->UID);
404 if( flags & USER_FLAG_DISABLED ) {
406 sendf(Client->Socket, "403 Account Disabled\n");
409 if( flags & USER_FLAG_INTERNAL ) {
411 sendf(Client->Socket, "403 Internal account\n");
415 Client->bIsAuthed = 1;
416 sendf(Client->Socket, "200 Auth OK\n");
420 * \brief Authenticate as a user without a password
422 * Usage: AUTOAUTH <user>
424 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
429 if( Server_int_ParseArgs(0, Args, &username, NULL) )
431 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
436 if( !Client->bIsTrusted ) {
438 Debug(Client, "Untrusted client attempting to AUTOAUTH");
439 sendf(Client->Socket, "401 Untrusted\n");
444 Client->UID = Bank_GetAcctByName( username );
445 if( Client->UID < 0 ) {
447 Debug(Client, "Unknown user '%s'", username);
448 sendf(Client->Socket, "403 Auth Failure\n");
452 userflags = Bank_GetFlags(Client->UID);
453 // You can't be an internal account
454 if( userflags & USER_FLAG_INTERNAL ) {
456 Debug(Client, "Autoauth as '%s', not allowed", username);
458 sendf(Client->Socket, "403 Account is internal\n");
463 if( userflags & USER_FLAG_DISABLED ) {
465 sendf(Client->Socket, "403 Account disabled\n");
469 Client->bIsAuthed = 1;
472 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
474 sendf(Client->Socket, "200 Auth OK\n");
478 * \brief Set effective user
480 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
483 int eUserFlags, userFlags;
485 if( Server_int_ParseArgs(0, Args, &username, NULL) )
487 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
491 if( !strlen(Args) ) {
492 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
496 // Check user permissions
497 userFlags = Bank_GetFlags(Client->UID);
498 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
499 sendf(Client->Socket, "403 Not in coke\n");
504 Client->EffectiveUID = Bank_GetAcctByName(username);
505 if( Client->EffectiveUID == -1 ) {
506 sendf(Client->Socket, "404 User not found\n");
510 // You can't be an internal account
511 if( !(userFlags & USER_FLAG_ADMIN) )
513 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
514 if( eUserFlags & USER_FLAG_INTERNAL ) {
515 Client->EffectiveUID = -1;
516 sendf(Client->Socket, "404 User not found\n");
519 // Disabled only avaliable to admins
520 if( eUserFlags & USER_FLAG_DISABLED ) {
521 Client->EffectiveUID = -1;
522 sendf(Client->Socket, "403 Account disabled\n");
527 sendf(Client->Socket, "200 User set\n");
531 * \brief Send an item status to the client
532 * \param Client Who to?
533 * \param Item Item to send
535 void Server_int_SendItem(tClient *Client, tItem *Item)
537 char *status = "avail";
539 if( Item->Handler->CanDispense )
541 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
543 case 0: status = "avail"; break;
544 case 1: status = "sold"; break;
546 case -1: status = "error"; break;
550 sendf(Client->Socket,
551 "202 Item %s:%i %s %i %s\n",
552 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
557 * \brief Enumerate the items that the server knows about
559 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
563 if( Args != NULL && strlen(Args) ) {
564 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
570 for( i = 0; i < giNumItems; i ++ ) {
571 if( gaItems[i].bHidden ) continue;
575 sendf(Client->Socket, "201 Items %i\n", count);
577 for( i = 0; i < giNumItems; i ++ ) {
578 if( gaItems[i].bHidden ) continue;
579 Server_int_SendItem( Client, &gaItems[i] );
582 sendf(Client->Socket, "200 List end\n");
585 tItem *_GetItemFromString(char *String)
589 char *colon = strchr(String, ':');
601 for( i = 0; i < giNumHandlers; i ++ )
603 if( strcmp(gaHandlers[i]->Name, type) == 0) {
604 handler = gaHandlers[i];
613 for( i = 0; i < giNumItems; i ++ )
615 if( gaItems[i].Handler != handler ) continue;
616 if( gaItems[i].ID != num ) continue;
623 * \brief Fetch information on a specific item
625 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
630 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
631 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
634 item = _GetItemFromString(Args);
637 sendf(Client->Socket, "406 Bad Item ID\n");
641 Server_int_SendItem( Client, item );
644 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
651 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
652 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
656 if( !Client->bIsAuthed ) {
657 sendf(Client->Socket, "401 Not Authenticated\n");
661 item = _GetItemFromString(itemname);
663 sendf(Client->Socket, "406 Bad Item ID\n");
667 if( Client->EffectiveUID != -1 ) {
668 uid = Client->EffectiveUID;
674 switch( ret = DispenseItem( Client->UID, uid, item ) )
676 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
677 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
678 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
680 sendf(Client->Socket, "500 Dispense Error\n");
685 void Server_Cmd_GIVE(tClient *Client, char *Args)
687 char *recipient, *ammount, *reason;
692 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
693 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
697 if( !Client->bIsAuthed ) {
698 sendf(Client->Socket, "401 Not Authenticated\n");
703 uid = Bank_GetAcctByName(recipient);
705 sendf(Client->Socket, "404 Invalid target user\n");
709 // You can't alter an internal account
710 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
711 // sendf(Client->Socket, "404 Invalid target user\n");
716 iAmmount = atoi(ammount);
717 if( iAmmount <= 0 ) {
718 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
722 if( Client->EffectiveUID != -1 ) {
723 thisUid = Client->EffectiveUID;
726 thisUid = Client->UID;
730 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
733 sendf(Client->Socket, "200 Give OK\n");
736 sendf(Client->Socket, "402 Poor You\n");
739 sendf(Client->Socket, "500 Unknown error\n");
744 void Server_Cmd_DONATE(tClient *Client, char *Args)
746 char *ammount, *reason;
751 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
752 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
756 if( !Client->bIsAuthed ) {
757 sendf(Client->Socket, "401 Not Authenticated\n");
762 iAmmount = atoi(ammount);
763 if( iAmmount <= 0 ) {
764 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
768 // Handle effective users
769 if( Client->EffectiveUID != -1 ) {
770 thisUid = Client->EffectiveUID;
773 thisUid = Client->UID;
777 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
780 sendf(Client->Socket, "200 Give OK\n");
783 sendf(Client->Socket, "402 Poor You\n");
786 sendf(Client->Socket, "500 Unknown error\n");
791 void Server_Cmd_ADD(tClient *Client, char *Args)
793 char *user, *ammount, *reason;
797 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
798 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
802 if( !Client->bIsAuthed ) {
803 sendf(Client->Socket, "401 Not Authenticated\n");
807 // Check user permissions
808 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
809 sendf(Client->Socket, "403 Not in coke\n");
814 uid = Bank_GetAcctByName(user);
816 sendf(Client->Socket, "404 Invalid user\n");
820 // You can't alter an internal account
821 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
823 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
824 sendf(Client->Socket, "404 Invalid user\n");
827 // TODO: Maybe disallow changes to disabled?
831 iAmmount = atoi(ammount);
832 if( iAmmount == 0 && ammount[0] != '0' ) {
833 sendf(Client->Socket, "407 Invalid Argument\n");
838 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
841 sendf(Client->Socket, "200 Add OK\n");
844 sendf(Client->Socket, "402 Poor Guy\n");
847 sendf(Client->Socket, "500 Unknown error\n");
852 void Server_Cmd_SET(tClient *Client, char *Args)
854 char *user, *ammount, *reason;
858 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
859 sendf(Client->Socket, "407 SET takes 3 arguments\n");
863 if( !Client->bIsAuthed ) {
864 sendf(Client->Socket, "401 Not Authenticated\n");
868 // Check user permissions
869 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
870 sendf(Client->Socket, "403 Not an admin\n");
875 uid = Bank_GetAcctByName(user);
877 sendf(Client->Socket, "404 Invalid user\n");
882 iAmmount = atoi(ammount);
883 if( iAmmount == 0 && ammount[0] != '0' ) {
884 sendf(Client->Socket, "407 Invalid Argument\n");
889 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
892 sendf(Client->Socket, "200 Add OK\n");
895 sendf(Client->Socket, "402 Poor Guy\n");
898 sendf(Client->Socket, "500 Unknown error\n");
903 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
907 int maxBal = INT_MAX, minBal = INT_MIN;
908 int flagMask = 0, flagVal = 0;
909 int sort = BANK_ITFLAG_SORT_NAME;
910 time_t lastSeenAfter=0, lastSeenBefore=0;
912 int flags; // Iterator flags
913 int balValue; // Balance value for iterator
914 time_t timeValue; // Time value for iterator
917 if( Args && strlen(Args) )
919 char *space = Args, *type, *val;
923 while(*type == ' ') type ++;
925 space = strchr(space, ' ');
926 if(space) *space = '\0';
929 val = strchr(type, ':');
936 if( strcmp(type, "min_balance") == 0 ) {
940 else if( strcmp(type, "max_balance") == 0 ) {
944 else if( strcmp(type, "flags") == 0 ) {
945 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
948 // - Last seen before timestamp
949 else if( strcmp(type, "last_seen_before") == 0 ) {
950 lastSeenAfter = atoll(val);
952 // - Last seen after timestamp
953 else if( strcmp(type, "last_seen_after") == 0 ) {
954 lastSeenAfter = atoll(val);
957 else if( strcmp(type, "sort") == 0 ) {
958 char *dash = strchr(val, '-');
963 if( strcmp(val, "name") == 0 ) {
964 sort = BANK_ITFLAG_SORT_NAME;
966 else if( strcmp(val, "balance") == 0 ) {
967 sort = BANK_ITFLAG_SORT_BAL;
969 else if( strcmp(val, "lastseen") == 0 ) {
970 sort = BANK_ITFLAG_SORT_LASTSEEN;
973 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
976 // Handle sort direction
978 if( strcmp(dash, "desc") == 0 ) {
979 sort |= BANK_ITFLAG_REVSORT;
982 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
989 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
996 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1002 *space = ' '; // Repair (to be nice)
1004 while(*space == ' ') space ++;
1010 if( maxBal != INT_MAX ) {
1011 flags = sort|BANK_ITFLAG_MAXBALANCE;
1014 else if( minBal != INT_MIN ) {
1015 flags = sort|BANK_ITFLAG_MINBALANCE;
1022 if( lastSeenBefore ) {
1023 timeValue = lastSeenBefore;
1024 flags |= BANK_ITFLAG_SEENBEFORE;
1026 else if( lastSeenAfter ) {
1027 timeValue = lastSeenAfter;
1028 flags |= BANK_ITFLAG_SEENAFTER;
1033 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1035 // Get return number
1036 while( (i = Bank_IteratorNext(it)) != -1 )
1038 int bal = Bank_GetBalance(i);
1040 if( bal == INT_MIN ) continue;
1042 if( bal < minBal ) continue;
1043 if( bal > maxBal ) continue;
1048 Bank_DelIterator(it);
1051 sendf(Client->Socket, "201 Users %i\n", numRet);
1055 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1057 while( (i = Bank_IteratorNext(it)) != -1 )
1059 int bal = Bank_GetBalance(i);
1061 if( bal == INT_MIN ) continue;
1063 if( bal < minBal ) continue;
1064 if( bal > maxBal ) continue;
1066 _SendUserInfo(Client, i);
1069 Bank_DelIterator(it);
1071 sendf(Client->Socket, "200 List End\n");
1074 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1080 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1081 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1085 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1088 uid = Bank_GetAcctByName(user);
1090 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1092 sendf(Client->Socket, "404 Invalid user\n");
1096 _SendUserInfo(Client, uid);
1099 void _SendUserInfo(tClient *Client, int UserID)
1101 char *type, *disabled="", *door="";
1102 int flags = Bank_GetFlags(UserID);
1104 if( flags & USER_FLAG_INTERNAL ) {
1107 else if( flags & USER_FLAG_COKE ) {
1108 if( flags & USER_FLAG_ADMIN )
1109 type = "coke,admin";
1113 else if( flags & USER_FLAG_ADMIN ) {
1120 if( flags & USER_FLAG_DISABLED )
1121 disabled = ",disabled";
1122 if( flags & USER_FLAG_DOORGROUP )
1125 // TODO: User flags/type
1127 Client->Socket, "202 User %s %i %s%s%s\n",
1128 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1129 type, disabled, door
1133 void Server_Cmd_USERADD(tClient *Client, char *Args)
1138 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1139 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1143 // Check permissions
1144 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1145 sendf(Client->Socket, "403 Not a coke admin\n");
1149 // Try to create user
1150 if( Bank_CreateAcct(username) == -1 ) {
1151 sendf(Client->Socket, "404 User exists\n");
1156 char *thisName = Bank_GetAcctName(Client->UID);
1157 Log_Info("Account '%s' created by '%s'", username, thisName);
1161 sendf(Client->Socket, "200 User Added\n");
1164 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1166 char *username, *flags;
1167 int mask=0, value=0;
1171 if( Server_int_ParseArgs(0, Args, &username, &flags, NULL) ) {
1172 sendf(Client->Socket, "407 USER_FLAGS takes 2 arguments\n");
1176 // Check permissions
1177 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1178 sendf(Client->Socket, "403 Not a coke admin\n");
1183 uid = Bank_GetAcctByName(username);
1185 sendf(Client->Socket, "404 User '%s' not found\n", username);
1190 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1194 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1195 uid, username, mask, value);
1198 Bank_SetFlags(uid, mask, value);
1201 sendf(Client->Socket, "200 User Updated\n");
1204 // --- INTERNAL HELPERS ---
1205 void Debug(tClient *Client, const char *Format, ...)
1208 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1209 printf("[%i] ", Client->ID);
1210 va_start(args, Format);
1211 vprintf(Format, args);
1216 int sendf(int Socket, const char *Format, ...)
1221 va_start(args, Format);
1222 len = vsnprintf(NULL, 0, Format, args);
1227 va_start(args, Format);
1228 vsnprintf(buf, len+1, Format, args);
1231 #if DEBUG_TRACE_CLIENT
1232 printf("sendf: %s", buf);
1235 return send(Socket, buf, len, 0);
1239 // Takes a series of char *'s in
1241 * \brief Parse space-separated entries into
1243 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1248 va_start(args, ArgStr);
1253 while( (dest = va_arg(args, char **)) )
1259 savedChar = *ArgStr;
1261 while( (dest = va_arg(args, char **)) )
1263 // Trim leading spaces
1264 while( *ArgStr == ' ' || *ArgStr == '\t' )
1267 // ... oops, not enough arguments
1268 if( *ArgStr == '\0' )
1270 // NULL unset arguments
1273 } while( (dest = va_arg(args, char **)) );
1278 if( *ArgStr == '"' )
1283 while( *ArgStr && *ArgStr != '"' )
1290 // Read until a space
1291 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1294 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1300 // Oops, extra arguments, and greedy not set
1301 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1308 *ArgStr = savedChar;
1311 return 0; // Success!
1314 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1321 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1322 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1323 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1324 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1325 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1327 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1339 while( *Str == ' ' ) Str ++; // Eat whitespace
1340 space = strchr(Str, ','); // Find the end of the flag
1346 // Check for inversion/removal
1347 if( *Str == '!' || *Str == '-' ) {
1351 else if( *Str == '+' ) {
1355 // Check flag values
1356 for( i = 0; i < ciNumFlags; i ++ )
1358 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1359 *Mask |= cFLAGS[i].Mask;
1360 *Value &= ~cFLAGS[i].Mask;
1362 *Value |= cFLAGS[i].Value;
1368 if( i == ciNumFlags ) {
1370 strncpy(val, Str, len+1);
1371 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);