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 uint len = sizeof(client_addr);
151 // Accept a connection
152 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
153 if(client_socket < 0) {
154 fprintf(stderr, "ERROR: Unable to accept client connection\n");
158 // Set a timeout on the user conneciton
161 tv.tv_sec = CLIENT_TIMEOUT;
163 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
165 perror("setsockopt");
170 // Debug: Print the connection string
171 if(giDebugLevel >= 2) {
172 char ipstr[INET_ADDRSTRLEN];
173 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
174 printf("Client connection from %s:%i\n",
175 ipstr, ntohs(client_addr.sin_port));
178 // Doesn't matter what, localhost is trusted
179 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
182 // Trusted Connections
183 if( ntohs(client_addr.sin_port) < 1024 )
185 // TODO: Make this runtime configurable
186 switch( ntohl( client_addr.sin_addr.s_addr ) )
188 case 0x7F000001: // 127.0.0.1 localhost
189 // case 0x825F0D00: // 130.95.13.0
190 case 0x825F0D07: // 130.95.13.7 motsugo
191 case 0x825F0D11: // 130.95.13.17 mermaid
192 case 0x825F0D12: // 130.95.13.18 mussel
193 case 0x825F0D17: // 130.95.13.23 martello
194 case 0x825F0D42: // 130.95.13.66 heathred
202 // TODO: Multithread this?
203 Server_HandleClient(client_socket, bTrusted);
205 close(client_socket);
209 void Server_Cleanup(void)
211 printf("Close(%i)\n", giServer_Socket);
212 close(giServer_Socket);
216 * \brief Reads from a client socket and parses the command strings
217 * \param Socket Client socket number/handle
218 * \param bTrusted Is the client trusted?
220 void Server_HandleClient(int Socket, int bTrusted)
222 char inbuf[INPUT_BUFFER_SIZE];
224 int remspace = INPUT_BUFFER_SIZE-1;
228 memset(&clientInfo, 0, sizeof(clientInfo));
230 // Initialise Client info
231 clientInfo.Socket = Socket;
232 clientInfo.ID = giServer_NextClientID ++;
233 clientInfo.bIsTrusted = bTrusted;
234 clientInfo.EffectiveUID = -1;
239 * - The `buf` and `remspace` variables allow a line to span several
240 * calls to recv(), if a line is not completed in one recv() call
241 * it is saved to the beginning of `inbuf` and `buf` is updated to
244 // TODO: Use select() instead (to give a timeout)
245 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
248 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
252 while( (eol = strchr(start, '\n')) )
256 Server_ParseClientCommand(&clientInfo, start);
261 // Check if there was an incomplete line
262 if( *start != '\0' ) {
263 int tailBytes = bytes - (start-buf);
264 // Roll back in buffer
265 memcpy(inbuf, start, tailBytes);
266 remspace -= tailBytes;
268 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
270 remspace = INPUT_BUFFER_SIZE - 1;
275 remspace = INPUT_BUFFER_SIZE - 1;
281 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
285 if(giDebugLevel >= 2) {
286 printf("Client %i: Disconnected\n", clientInfo.ID);
291 * \brief Parses a client command and calls the required helper function
292 * \param Client Pointer to client state structure
293 * \param CommandString Command from client (single line of the command)
294 * \return Heap String to return to the client
296 void Server_ParseClientCommand(tClient *Client, char *CommandString)
298 char *command, *args;
301 if( giDebugLevel >= 2 )
302 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
304 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
306 // printf("command=%s, args=%s\n", command, args);
307 // Is this an error? (just ignore for now)
313 for( i = 0; i < NUM_COMMANDS; i++ )
315 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
316 if( giDebugLevel >= 2 )
317 Debug(Client, "CMD %s - \"%s\"", command, args);
318 gaServer_Commands[i].Function(Client, args);
323 sendf(Client->Socket, "400 Unknown Command\n");
330 * \brief Set client username
332 * Usage: USER <username>
334 void Server_Cmd_USER(tClient *Client, char *Args)
338 if( Server_int_ParseArgs(0, Args, &username, NULL) )
340 sendf(Client->Socket, "407 USER takes 1 argument\n");
346 Debug(Client, "Authenticating as '%s'", username);
350 free(Client->Username);
351 Client->Username = strdup(username);
354 // Create a salt (that changes if the username is changed)
355 // Yes, I know, I'm a little paranoid, but who isn't?
356 Client->Salt[0] = 0x21 + (rand()&0x3F);
357 Client->Salt[1] = 0x21 + (rand()&0x3F);
358 Client->Salt[2] = 0x21 + (rand()&0x3F);
359 Client->Salt[3] = 0x21 + (rand()&0x3F);
360 Client->Salt[4] = 0x21 + (rand()&0x3F);
361 Client->Salt[5] = 0x21 + (rand()&0x3F);
362 Client->Salt[6] = 0x21 + (rand()&0x3F);
363 Client->Salt[7] = 0x21 + (rand()&0x3F);
365 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
366 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
368 sendf(Client->Socket, "100 User Set\n");
373 * \brief Authenticate as a user
377 void Server_Cmd_PASS(tClient *Client, char *Args)
382 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
384 sendf(Client->Socket, "407 PASS takes 1 argument\n");
388 // Pass on to cokebank
389 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
391 if( Client->UID == -1 ) {
392 sendf(Client->Socket, "401 Auth Failure\n");
396 flags = Bank_GetFlags(Client->UID);
397 if( flags & USER_FLAG_DISABLED ) {
399 sendf(Client->Socket, "403 Account Disabled\n");
402 if( flags & USER_FLAG_INTERNAL ) {
404 sendf(Client->Socket, "403 Internal account\n");
408 Client->bIsAuthed = 1;
409 sendf(Client->Socket, "200 Auth OK\n");
413 * \brief Authenticate as a user without a password
415 * Usage: AUTOAUTH <user>
417 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
422 if( Server_int_ParseArgs(0, Args, &username, NULL) )
424 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
429 if( !Client->bIsTrusted ) {
431 Debug(Client, "Untrusted client attempting to AUTOAUTH");
432 sendf(Client->Socket, "401 Untrusted\n");
437 Client->UID = Bank_GetAcctByName( username );
438 if( Client->UID < 0 ) {
440 Debug(Client, "Unknown user '%s'", username);
441 sendf(Client->Socket, "401 Auth Failure\n");
445 userflags = Bank_GetFlags(Client->UID);
446 // You can't be an internal account
447 if( userflags & USER_FLAG_INTERNAL ) {
449 Debug(Client, "Autoauth as '%s', not allowed", username);
451 sendf(Client->Socket, "403 Account is internal\n");
456 if( userflags & USER_FLAG_DISABLED ) {
458 sendf(Client->Socket, "403 Account disabled\n");
462 Client->bIsAuthed = 1;
465 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
467 sendf(Client->Socket, "200 Auth OK\n");
471 * \brief Set effective user
473 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
476 int eUserFlags, userFlags;
478 if( Server_int_ParseArgs(0, Args, &username, NULL) )
480 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
484 if( !strlen(Args) ) {
485 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
489 // Check user permissions
490 userFlags = Bank_GetFlags(Client->UID);
491 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
492 sendf(Client->Socket, "403 Not in coke\n");
497 Client->EffectiveUID = Bank_GetAcctByName(username);
498 if( Client->EffectiveUID == -1 ) {
499 sendf(Client->Socket, "404 User not found\n");
503 // You can't be an internal account
504 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
505 if( eUserFlags & USER_FLAG_INTERNAL ) {
506 Client->EffectiveUID = -1;
507 sendf(Client->Socket, "404 User not found\n");
510 // Disabled only avaliable to admins
511 if( (eUserFlags & USER_FLAG_DISABLED) && !(userFlags & USER_FLAG_ADMIN) ) {
512 Client->EffectiveUID = -1;
513 sendf(Client->Socket, "403 Account disabled\n");
517 sendf(Client->Socket, "200 User set\n");
521 * \brief Send an item status to the client
522 * \param Client Who to?
523 * \param Item Item to send
525 void Server_int_SendItem(tClient *Client, tItem *Item)
527 char *status = "avail";
529 if( Item->Handler->CanDispense )
531 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
533 case 0: status = "avail"; break;
534 case 1: status = "sold"; break;
536 case -1: status = "error"; break;
540 sendf(Client->Socket,
541 "202 Item %s:%i %s %i %s\n",
542 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
547 * \brief Enumerate the items that the server knows about
549 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
553 if( Args != NULL && strlen(Args) ) {
554 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
560 for( i = 0; i < giNumItems; i ++ ) {
561 if( gaItems[i].bHidden ) continue;
565 sendf(Client->Socket, "201 Items %i\n", count);
567 for( i = 0; i < giNumItems; i ++ ) {
568 if( gaItems[i].bHidden ) continue;
569 Server_int_SendItem( Client, &gaItems[i] );
572 sendf(Client->Socket, "200 List end\n");
575 tItem *_GetItemFromString(char *String)
579 char *colon = strchr(String, ':');
591 for( i = 0; i < giNumHandlers; i ++ )
593 if( strcmp(gaHandlers[i]->Name, type) == 0) {
594 handler = gaHandlers[i];
603 for( i = 0; i < giNumItems; i ++ )
605 if( gaItems[i].Handler != handler ) continue;
606 if( gaItems[i].ID != num ) continue;
613 * \brief Fetch information on a specific item
615 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
620 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
621 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
624 item = _GetItemFromString(Args);
627 sendf(Client->Socket, "406 Bad Item ID\n");
631 Server_int_SendItem( Client, item );
634 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
641 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
642 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
646 if( !Client->bIsAuthed ) {
647 sendf(Client->Socket, "401 Not Authenticated\n");
651 item = _GetItemFromString(itemname);
653 sendf(Client->Socket, "406 Bad Item ID\n");
657 if( Client->EffectiveUID != -1 ) {
658 uid = Client->EffectiveUID;
664 switch( ret = DispenseItem( Client->UID, uid, item ) )
666 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
667 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
668 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
670 sendf(Client->Socket, "500 Dispense Error\n");
675 void Server_Cmd_GIVE(tClient *Client, char *Args)
677 char *recipient, *ammount, *reason;
682 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
683 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
687 if( !Client->bIsAuthed ) {
688 sendf(Client->Socket, "401 Not Authenticated\n");
693 uid = Bank_GetAcctByName(recipient);
695 sendf(Client->Socket, "404 Invalid target user\n");
699 // You can't alter an internal account
700 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
701 // sendf(Client->Socket, "404 Invalid target user\n");
706 iAmmount = atoi(ammount);
707 if( iAmmount <= 0 ) {
708 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
712 if( Client->EffectiveUID != -1 ) {
713 thisUid = Client->EffectiveUID;
716 thisUid = Client->UID;
720 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
723 sendf(Client->Socket, "200 Give OK\n");
726 sendf(Client->Socket, "402 Poor You\n");
729 sendf(Client->Socket, "500 Unknown error\n");
734 void Server_Cmd_DONATE(tClient *Client, char *Args)
736 char *ammount, *reason;
741 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
742 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
746 if( !Client->bIsAuthed ) {
747 sendf(Client->Socket, "401 Not Authenticated\n");
752 iAmmount = atoi(ammount);
753 if( iAmmount <= 0 ) {
754 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
758 // Handle effective users
759 if( Client->EffectiveUID != -1 ) {
760 thisUid = Client->EffectiveUID;
763 thisUid = Client->UID;
767 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
770 sendf(Client->Socket, "200 Give OK\n");
773 sendf(Client->Socket, "402 Poor You\n");
776 sendf(Client->Socket, "500 Unknown error\n");
781 void Server_Cmd_ADD(tClient *Client, char *Args)
783 char *user, *ammount, *reason;
787 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
788 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
792 if( !Client->bIsAuthed ) {
793 sendf(Client->Socket, "401 Not Authenticated\n");
797 // Check user permissions
798 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
799 sendf(Client->Socket, "403 Not in coke\n");
804 uid = Bank_GetAcctByName(user);
806 sendf(Client->Socket, "404 Invalid user\n");
810 // You can't alter an internal account
811 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
812 sendf(Client->Socket, "404 Invalid user\n");
817 iAmmount = atoi(ammount);
818 if( iAmmount == 0 && ammount[0] != '0' ) {
819 sendf(Client->Socket, "407 Invalid Argument\n");
824 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
827 sendf(Client->Socket, "200 Add OK\n");
830 sendf(Client->Socket, "402 Poor Guy\n");
833 sendf(Client->Socket, "500 Unknown error\n");
838 void Server_Cmd_SET(tClient *Client, char *Args)
840 char *user, *ammount, *reason;
844 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
845 sendf(Client->Socket, "407 SET takes 3 arguments\n");
849 if( !Client->bIsAuthed ) {
850 sendf(Client->Socket, "401 Not Authenticated\n");
854 // Check user permissions
855 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
856 sendf(Client->Socket, "403 Not an admin\n");
861 uid = Bank_GetAcctByName(user);
863 sendf(Client->Socket, "404 Invalid user\n");
867 // You can't alter an internal account
868 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
869 sendf(Client->Socket, "404 Invalid user\n");
874 iAmmount = atoi(ammount);
875 if( iAmmount == 0 && ammount[0] != '0' ) {
876 sendf(Client->Socket, "407 Invalid Argument\n");
881 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
884 sendf(Client->Socket, "200 Add OK\n");
887 sendf(Client->Socket, "402 Poor Guy\n");
890 sendf(Client->Socket, "500 Unknown error\n");
895 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
899 int maxBal = INT_MAX, minBal = INT_MIN;
900 int flagMask = 0, flagVal = 0;
901 int sort = BANK_ITFLAG_SORT_NAME;
902 time_t lastSeenAfter=0, lastSeenBefore=0;
904 int flags; // Iterator flags
905 int balValue; // Balance value for iterator
906 time_t timeValue; // Time value for iterator
909 if( Args && strlen(Args) )
911 char *space = Args, *type, *val;
915 while(*type == ' ') type ++;
917 space = strchr(space, ' ');
918 if(space) *space = '\0';
921 val = strchr(type, ':');
928 if( strcmp(type, "min_balance") == 0 ) {
932 else if( strcmp(type, "max_balance") == 0 ) {
936 else if( strcmp(type, "flags") == 0 ) {
937 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
940 // - Last seen before timestamp
941 else if( strcmp(type, "last_seen_before") == 0 ) {
942 lastSeenAfter = atoll(val);
944 // - Last seen after timestamp
945 else if( strcmp(type, "last_seen_after") == 0 ) {
946 lastSeenAfter = atoll(val);
949 else if( strcmp(type, "sort") == 0 ) {
950 char *dash = strchr(val, '-');
955 if( strcmp(val, "name") == 0 ) {
956 sort = BANK_ITFLAG_SORT_NAME;
958 else if( strcmp(val, "balance") == 0 ) {
959 sort = BANK_ITFLAG_SORT_BAL;
961 else if( strcmp(val, "lastseen") == 0 ) {
962 sort = BANK_ITFLAG_SORT_LASTSEEN;
965 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
968 // Handle sort direction
970 if( strcmp(dash, "desc") == 0 ) {
971 sort |= BANK_ITFLAG_REVSORT;
974 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
981 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
988 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
994 *space = ' '; // Repair (to be nice)
996 while(*space == ' ') space ++;
1002 if( maxBal != INT_MAX ) {
1003 flags = sort|BANK_ITFLAG_MAXBALANCE;
1006 else if( minBal != INT_MIN ) {
1007 flags = sort|BANK_ITFLAG_MINBALANCE;
1014 if( lastSeenBefore ) {
1015 timeValue = lastSeenBefore;
1016 flags |= BANK_ITFLAG_SEENBEFORE;
1018 else if( lastSeenAfter ) {
1019 timeValue = lastSeenAfter;
1020 flags |= BANK_ITFLAG_SEENAFTER;
1025 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1027 // Get return number
1028 while( (i = Bank_IteratorNext(it)) != -1 )
1030 int bal = Bank_GetBalance(i);
1032 if( bal == INT_MIN ) continue;
1034 if( bal < minBal ) continue;
1035 if( bal > maxBal ) continue;
1040 Bank_DelIterator(it);
1043 sendf(Client->Socket, "201 Users %i\n", numRet);
1047 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1049 while( (i = Bank_IteratorNext(it)) != -1 )
1051 int bal = Bank_GetBalance(i);
1053 if( bal == INT_MIN ) continue;
1055 if( bal < minBal ) continue;
1056 if( bal > maxBal ) continue;
1058 _SendUserInfo(Client, i);
1061 Bank_DelIterator(it);
1063 sendf(Client->Socket, "200 List End\n");
1066 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1072 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1073 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1077 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1080 uid = Bank_GetAcctByName(user);
1082 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1084 sendf(Client->Socket, "404 Invalid user\n");
1088 _SendUserInfo(Client, uid);
1091 void _SendUserInfo(tClient *Client, int UserID)
1093 char *type, *disabled="", *door="";
1094 int flags = Bank_GetFlags(UserID);
1096 if( flags & USER_FLAG_INTERNAL ) {
1099 else if( flags & USER_FLAG_COKE ) {
1100 if( flags & USER_FLAG_ADMIN )
1101 type = "coke,admin";
1105 else if( flags & USER_FLAG_ADMIN ) {
1112 if( flags & USER_FLAG_DISABLED )
1113 disabled = ",disabled";
1114 if( flags & USER_FLAG_DOORGROUP )
1117 // TODO: User flags/type
1119 Client->Socket, "202 User %s %i %s%s%s\n",
1120 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1121 type, disabled, door
1125 void Server_Cmd_USERADD(tClient *Client, char *Args)
1130 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1131 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1135 // Check permissions
1136 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1137 sendf(Client->Socket, "403 Not a coke admin\n");
1141 // Try to create user
1142 if( Bank_CreateAcct(username) == -1 ) {
1143 sendf(Client->Socket, "404 User exists\n");
1148 char *thisName = Bank_GetAcctName(Client->UID);
1149 Log_Info("Account '%s' created by '%s'", username, thisName);
1153 sendf(Client->Socket, "200 User Added\n");
1156 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1158 char *username, *flags;
1159 int mask=0, value=0;
1163 if( Server_int_ParseArgs(0, Args, &username, &flags, NULL) ) {
1164 sendf(Client->Socket, "407 USER_FLAGS takes 2 arguments\n");
1168 // Check permissions
1169 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1170 sendf(Client->Socket, "403 Not a coke admin\n");
1175 uid = Bank_GetAcctByName(username);
1177 sendf(Client->Socket, "404 User '%s' not found\n", username);
1182 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1186 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1187 uid, username, mask, value);
1190 Bank_SetFlags(uid, mask, value);
1193 sendf(Client->Socket, "200 User Updated\n");
1196 // --- INTERNAL HELPERS ---
1197 void Debug(tClient *Client, const char *Format, ...)
1200 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1201 printf("[%i] ", Client->ID);
1202 va_start(args, Format);
1203 vprintf(Format, args);
1208 int sendf(int Socket, const char *Format, ...)
1213 va_start(args, Format);
1214 len = vsnprintf(NULL, 0, Format, args);
1219 va_start(args, Format);
1220 vsnprintf(buf, len+1, Format, args);
1223 #if DEBUG_TRACE_CLIENT
1224 printf("sendf: %s", buf);
1227 return send(Socket, buf, len, 0);
1231 // Takes a series of char *'s in
1233 * \brief Parse space-separated entries into
1235 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1240 va_start(args, ArgStr);
1245 while( (dest = va_arg(args, char **)) )
1251 savedChar = *ArgStr;
1253 while( (dest = va_arg(args, char **)) )
1255 // Trim leading spaces
1256 while( *ArgStr == ' ' || *ArgStr == '\t' )
1259 // ... oops, not enough arguments
1260 if( *ArgStr == '\0' )
1262 // NULL unset arguments
1265 } while( (dest = va_arg(args, char **)) );
1270 if( *ArgStr == '"' )
1275 while( *ArgStr && *ArgStr != '"' )
1282 // Read until a space
1283 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1286 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1292 // Oops, extra arguments, and greedy not set
1293 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1300 *ArgStr = savedChar;
1303 return 0; // Success!
1306 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1313 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1314 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1315 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1316 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1317 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1319 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1331 while( *Str == ' ' ) Str ++; // Eat whitespace
1332 space = strchr(Str, ','); // Find the end of the flag
1338 // Check for inversion/removal
1339 if( *Str == '!' || *Str == '-' ) {
1343 else if( *Str == '+' ) {
1347 // Check flag values
1348 for( i = 0; i < ciNumFlags; i ++ )
1350 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1351 *Mask |= cFLAGS[i].Mask;
1352 *Value &= ~cFLAGS[i].Mask;
1354 *Value |= cFLAGS[i].Value;
1360 if( i == ciNumFlags ) {
1362 strncpy(val, Str, len+1);
1363 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);