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 = 1020;
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)
381 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
383 sendf(Client->Socket, "407 PASS takes 1 argument\n");
387 // Pass on to cokebank
388 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
390 if( Client->UID != -1 ) {
391 Client->bIsAuthed = 1;
392 sendf(Client->Socket, "200 Auth OK\n");
396 sendf(Client->Socket, "401 Auth Failure\n");
400 * \brief Authenticate as a user without a password
402 * Usage: AUTOAUTH <user>
404 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
408 if( Server_int_ParseArgs(0, Args, &username, NULL) )
410 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
415 if( !Client->bIsTrusted ) {
417 Debug(Client, "Untrusted client attempting to AUTOAUTH");
418 sendf(Client->Socket, "401 Untrusted\n");
423 Client->UID = Bank_GetAcctByName( username );
424 if( Client->UID < 0 ) {
426 Debug(Client, "Unknown user '%s'", username);
427 sendf(Client->Socket, "401 Auth Failure\n");
431 // You can't be an internal account
432 if( Bank_GetFlags(Client->UID) & USER_FLAG_INTERNAL ) {
434 Debug(Client, "Autoauth as '%s', not allowed", username);
436 sendf(Client->Socket, "401 Auth Failure\n");
440 Client->bIsAuthed = 1;
443 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
445 sendf(Client->Socket, "200 Auth OK\n");
449 * \brief Set effective user
451 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
455 if( Server_int_ParseArgs(0, Args, &username, NULL) )
457 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
461 if( !strlen(Args) ) {
462 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
466 // Check user permissions
467 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
468 sendf(Client->Socket, "403 Not in coke\n");
473 Client->EffectiveUID = Bank_GetAcctByName(username);
474 if( Client->EffectiveUID == -1 ) {
475 sendf(Client->Socket, "404 User not found\n");
479 // You can't be an internal account
480 if( Bank_GetFlags(Client->EffectiveUID) & USER_FLAG_INTERNAL ) {
481 Client->EffectiveUID = -1;
482 sendf(Client->Socket, "404 User not found\n");
486 sendf(Client->Socket, "200 User set\n");
490 * \brief Send an item status to the client
491 * \param Client Who to?
492 * \param Item Item to send
494 void Server_int_SendItem(tClient *Client, tItem *Item)
496 char *status = "avail";
498 if( Item->Handler->CanDispense )
500 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
502 case 0: status = "avail"; break;
503 case 1: status = "sold"; break;
505 case -1: status = "error"; break;
509 sendf(Client->Socket,
510 "202 Item %s:%i %s %i %s\n",
511 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
516 * \brief Enumerate the items that the server knows about
518 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
522 if( Args != NULL && strlen(Args) ) {
523 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
529 for( i = 0; i < giNumItems; i ++ ) {
530 if( gaItems[i].bHidden ) continue;
534 sendf(Client->Socket, "201 Items %i\n", count);
536 for( i = 0; i < giNumItems; i ++ ) {
537 if( gaItems[i].bHidden ) continue;
538 Server_int_SendItem( Client, &gaItems[i] );
541 sendf(Client->Socket, "200 List end\n");
544 tItem *_GetItemFromString(char *String)
548 char *colon = strchr(String, ':');
560 for( i = 0; i < giNumHandlers; i ++ )
562 if( strcmp(gaHandlers[i]->Name, type) == 0) {
563 handler = gaHandlers[i];
572 for( i = 0; i < giNumItems; i ++ )
574 if( gaItems[i].Handler != handler ) continue;
575 if( gaItems[i].ID != num ) continue;
582 * \brief Fetch information on a specific item
584 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
589 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
590 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
593 item = _GetItemFromString(Args);
596 sendf(Client->Socket, "406 Bad Item ID\n");
600 Server_int_SendItem( Client, item );
603 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
610 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
611 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
615 if( !Client->bIsAuthed ) {
616 sendf(Client->Socket, "401 Not Authenticated\n");
620 item = _GetItemFromString(itemname);
622 sendf(Client->Socket, "406 Bad Item ID\n");
626 if( Client->EffectiveUID != -1 ) {
627 uid = Client->EffectiveUID;
633 switch( ret = DispenseItem( Client->UID, uid, item ) )
635 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
636 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
637 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
639 sendf(Client->Socket, "500 Dispense Error\n");
644 void Server_Cmd_GIVE(tClient *Client, char *Args)
646 char *recipient, *ammount, *reason;
651 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
652 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
656 if( !Client->bIsAuthed ) {
657 sendf(Client->Socket, "401 Not Authenticated\n");
662 uid = Bank_GetAcctByName(recipient);
664 sendf(Client->Socket, "404 Invalid target user\n");
668 // You can't alter an internal account
669 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
670 sendf(Client->Socket, "404 Invalid target user\n");
675 iAmmount = atoi(ammount);
676 if( iAmmount <= 0 ) {
677 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
681 if( Client->EffectiveUID != -1 ) {
682 thisUid = Client->EffectiveUID;
685 thisUid = Client->UID;
689 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
692 sendf(Client->Socket, "200 Give OK\n");
695 sendf(Client->Socket, "402 Poor You\n");
698 sendf(Client->Socket, "500 Unknown error\n");
703 void Server_Cmd_DONATE(tClient *Client, char *Args)
705 char *ammount, *reason;
710 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
711 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
715 if( !Client->bIsAuthed ) {
716 sendf(Client->Socket, "401 Not Authenticated\n");
721 iAmmount = atoi(ammount);
722 if( iAmmount <= 0 ) {
723 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
727 // Handle effective users
728 if( Client->EffectiveUID != -1 ) {
729 thisUid = Client->EffectiveUID;
732 thisUid = Client->UID;
736 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
739 sendf(Client->Socket, "200 Give OK\n");
742 sendf(Client->Socket, "402 Poor You\n");
745 sendf(Client->Socket, "500 Unknown error\n");
750 void Server_Cmd_ADD(tClient *Client, char *Args)
752 char *user, *ammount, *reason;
756 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
757 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
761 if( !Client->bIsAuthed ) {
762 sendf(Client->Socket, "401 Not Authenticated\n");
766 // Check user permissions
767 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
768 sendf(Client->Socket, "403 Not in coke\n");
773 uid = Bank_GetAcctByName(user);
775 sendf(Client->Socket, "404 Invalid user\n");
779 // You can't alter an internal account
780 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
781 sendf(Client->Socket, "404 Invalid user\n");
786 iAmmount = atoi(ammount);
787 if( iAmmount == 0 && ammount[0] != '0' ) {
788 sendf(Client->Socket, "407 Invalid Argument\n");
793 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
796 sendf(Client->Socket, "200 Add OK\n");
799 sendf(Client->Socket, "402 Poor Guy\n");
802 sendf(Client->Socket, "500 Unknown error\n");
807 void Server_Cmd_SET(tClient *Client, char *Args)
809 char *user, *ammount, *reason;
813 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
814 sendf(Client->Socket, "407 SET takes 3 arguments\n");
818 if( !Client->bIsAuthed ) {
819 sendf(Client->Socket, "401 Not Authenticated\n");
823 // Check user permissions
824 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
825 sendf(Client->Socket, "403 Not an admin\n");
830 uid = Bank_GetAcctByName(user);
832 sendf(Client->Socket, "404 Invalid user\n");
836 // You can't alter an internal account
837 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
838 sendf(Client->Socket, "404 Invalid user\n");
843 iAmmount = atoi(ammount);
844 if( iAmmount == 0 && ammount[0] != '0' ) {
845 sendf(Client->Socket, "407 Invalid Argument\n");
850 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
853 sendf(Client->Socket, "200 Add OK\n");
856 sendf(Client->Socket, "402 Poor Guy\n");
859 sendf(Client->Socket, "500 Unknown error\n");
864 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
868 int maxBal = INT_MAX, minBal = INT_MIN;
869 int flagMask = 0, flagVal = 0;
870 int sort = BANK_ITFLAG_SORT_NAME;
871 time_t lastSeenAfter=0, lastSeenBefore=0;
873 int flags; // Iterator flags
874 int balValue; // Balance value for iterator
875 time_t timeValue; // Time value for iterator
878 if( Args && strlen(Args) )
880 char *space = Args, *type, *val;
884 while(*type == ' ') type ++;
886 space = strchr(space, ' ');
887 if(space) *space = '\0';
890 val = strchr(type, ':');
897 if( strcmp(type, "min_balance") == 0 ) {
901 else if( strcmp(type, "max_balance") == 0 ) {
905 else if( strcmp(type, "flags") == 0 ) {
906 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
909 // - Last seen before timestamp
910 else if( strcmp(type, "last_seen_before") == 0 ) {
911 lastSeenAfter = atoll(val);
913 // - Last seen after timestamp
914 else if( strcmp(type, "last_seen_after") == 0 ) {
915 lastSeenAfter = atoll(val);
918 else if( strcmp(type, "sort") == 0 ) {
919 char *dash = strchr(val, '-');
924 if( strcmp(val, "name") == 0 ) {
925 sort = BANK_ITFLAG_SORT_NAME;
927 else if( strcmp(val, "balance") == 0 ) {
928 sort = BANK_ITFLAG_SORT_BAL;
930 else if( strcmp(val, "lastseen") == 0 ) {
931 sort = BANK_ITFLAG_SORT_LASTSEEN;
934 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
937 // Handle sort direction
939 if( strcmp(dash, "desc") == 0 ) {
940 sort |= BANK_ITFLAG_REVSORT;
943 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
950 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
957 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
963 *space = ' '; // Repair (to be nice)
965 while(*space == ' ') space ++;
971 if( maxBal != INT_MAX ) {
972 flags = sort|BANK_ITFLAG_MAXBALANCE;
975 else if( minBal != INT_MIN ) {
976 flags = sort|BANK_ITFLAG_MINBALANCE;
983 if( lastSeenBefore ) {
984 timeValue = lastSeenBefore;
985 flags |= BANK_ITFLAG_SEENBEFORE;
987 else if( lastSeenAfter ) {
988 timeValue = lastSeenAfter;
989 flags |= BANK_ITFLAG_SEENAFTER;
994 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
997 while( (i = Bank_IteratorNext(it)) != -1 )
999 int bal = Bank_GetBalance(i);
1001 if( bal == INT_MIN ) continue;
1003 if( bal < minBal ) continue;
1004 if( bal > maxBal ) continue;
1009 Bank_DelIterator(it);
1012 sendf(Client->Socket, "201 Users %i\n", numRet);
1016 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1018 while( (i = Bank_IteratorNext(it)) != -1 )
1020 int bal = Bank_GetBalance(i);
1022 if( bal == INT_MIN ) continue;
1024 if( bal < minBal ) continue;
1025 if( bal > maxBal ) continue;
1027 _SendUserInfo(Client, i);
1030 Bank_DelIterator(it);
1032 sendf(Client->Socket, "200 List End\n");
1035 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1041 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1042 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1046 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1049 uid = Bank_GetAcctByName(user);
1051 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1053 sendf(Client->Socket, "404 Invalid user\n");
1057 _SendUserInfo(Client, uid);
1060 void _SendUserInfo(tClient *Client, int UserID)
1062 char *type, *disabled="", *door="";
1063 int flags = Bank_GetFlags(UserID);
1065 if( flags & USER_FLAG_INTERNAL ) {
1068 else if( flags & USER_FLAG_COKE ) {
1069 if( flags & USER_FLAG_ADMIN )
1070 type = "coke,admin";
1074 else if( flags & USER_FLAG_ADMIN ) {
1081 if( flags & USER_FLAG_DISABLED )
1082 disabled = ",disabled";
1083 if( flags & USER_FLAG_DOORGROUP )
1086 // TODO: User flags/type
1088 Client->Socket, "202 User %s %i %s%s%s\n",
1089 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1090 type, disabled, door
1094 void Server_Cmd_USERADD(tClient *Client, char *Args)
1099 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1100 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1104 // Check permissions
1105 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1106 sendf(Client->Socket, "403 Not a coke admin\n");
1110 // Try to create user
1111 if( Bank_CreateAcct(username) == -1 ) {
1112 sendf(Client->Socket, "404 User exists\n");
1117 char *thisName = Bank_GetAcctName(Client->UID);
1118 Log_Info("Account '%s' created by '%s'", username, thisName);
1122 sendf(Client->Socket, "200 User Added\n");
1125 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1127 char *username, *flags;
1128 int mask=0, value=0;
1132 if( Server_int_ParseArgs(0, Args, &username, &flags, NULL) ) {
1133 sendf(Client->Socket, "407 USER_FLAGS takes 2 arguments\n");
1137 // Check permissions
1138 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1139 sendf(Client->Socket, "403 Not a coke admin\n");
1144 uid = Bank_GetAcctByName(username);
1146 sendf(Client->Socket, "404 User '%s' not found\n", username);
1151 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1155 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1156 uid, username, mask, value);
1159 Bank_SetFlags(uid, mask, value);
1162 sendf(Client->Socket, "200 User Updated\n");
1165 // --- INTERNAL HELPERS ---
1166 void Debug(tClient *Client, const char *Format, ...)
1169 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1170 printf("[%i] ", Client->ID);
1171 va_start(args, Format);
1172 vprintf(Format, args);
1177 int sendf(int Socket, const char *Format, ...)
1182 va_start(args, Format);
1183 len = vsnprintf(NULL, 0, Format, args);
1188 va_start(args, Format);
1189 vsnprintf(buf, len+1, Format, args);
1192 #if DEBUG_TRACE_CLIENT
1193 printf("sendf: %s", buf);
1196 return send(Socket, buf, len, 0);
1200 // Takes a series of char *'s in
1202 * \brief Parse space-separated entries into
1204 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1209 va_start(args, ArgStr);
1214 while( (dest = va_arg(args, char **)) )
1220 savedChar = *ArgStr;
1222 while( (dest = va_arg(args, char **)) )
1224 // Trim leading spaces
1225 while( *ArgStr == ' ' || *ArgStr == '\t' )
1228 // ... oops, not enough arguments
1229 if( *ArgStr == '\0' )
1231 // NULL unset arguments
1234 } while( (dest = va_arg(args, char **)) );
1239 if( *ArgStr == '"' )
1244 while( *ArgStr && *ArgStr != '"' )
1251 // Read until a space
1252 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1255 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1261 // Oops, extra arguments, and greedy not set
1262 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1269 *ArgStr = savedChar;
1272 return 0; // Success!
1275 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1282 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1283 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1284 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1285 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1286 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1288 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1300 while( *Str == ' ' ) Str ++; // Eat whitespace
1301 space = strchr(Str, ','); // Find the end of the flag
1307 // Check for inversion/removal
1308 if( *Str == '!' || *Str == '-' ) {
1312 else if( *Str == '+' ) {
1316 // Check flag values
1317 for( i = 0; i < ciNumFlags; i ++ )
1319 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1320 *Mask |= cFLAGS[i].Mask;
1321 *Value &= ~cFLAGS[i].Mask;
1323 *Value |= cFLAGS[i].Value;
1329 if( i == ciNumFlags ) {
1331 strncpy(val, Str, len+1);
1332 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);