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>
22 #define DEBUG_TRACE_CLIENT 0
25 #define MAX_CONNECTION_QUEUE 5
26 #define INPUT_BUFFER_SIZE 256
27 #define CLIENT_TIMEOUT 10 // Seconds
29 #define HASH_TYPE SHA1
30 #define HASH_LENGTH 20
32 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
35 typedef struct sClient
37 int Socket; // Client socket ID
40 int bIsTrusted; // Is the connection from a trusted host/port
51 void Server_Start(void);
52 void Server_Cleanup(void);
53 void Server_HandleClient(int Socket, int bTrusted);
54 void Server_ParseClientCommand(tClient *Client, char *CommandString);
56 void Server_Cmd_USER(tClient *Client, char *Args);
57 void Server_Cmd_PASS(tClient *Client, char *Args);
58 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
59 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
60 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
61 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
62 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
63 void Server_Cmd_REFUND(tClient *Client, char *Args);
64 void Server_Cmd_GIVE(tClient *Client, char *Args);
65 void Server_Cmd_DONATE(tClient *Client, char *Args);
66 void Server_Cmd_ADD(tClient *Client, char *Args);
67 void Server_Cmd_SET(tClient *Client, char *Args);
68 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
69 void Server_Cmd_USERINFO(tClient *Client, char *Args);
70 void _SendUserInfo(tClient *Client, int UserID);
71 void Server_Cmd_USERADD(tClient *Client, char *Args);
72 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
74 void Debug(tClient *Client, const char *Format, ...);
75 int sendf(int Socket, const char *Format, ...);
76 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
77 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
81 const struct sClientCommand {
83 void (*Function)(tClient *Client, char *Arguments);
84 } gaServer_Commands[] = {
85 {"USER", Server_Cmd_USER},
86 {"PASS", Server_Cmd_PASS},
87 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
88 {"SETEUSER", Server_Cmd_SETEUSER},
89 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
90 {"ITEM_INFO", Server_Cmd_ITEMINFO},
91 {"DISPENSE", Server_Cmd_DISPENSE},
92 {"REFUND", Server_Cmd_REFUND},
93 {"GIVE", Server_Cmd_GIVE},
94 {"DONATE", Server_Cmd_DONATE},
95 {"ADD", Server_Cmd_ADD},
96 {"SET", Server_Cmd_SET},
97 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
98 {"USER_INFO", Server_Cmd_USERINFO},
99 {"USER_ADD", Server_Cmd_USERADD},
100 {"USER_FLAGS", Server_Cmd_USERFLAGS}
102 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
106 int giServer_Port = 11020;
107 int gbServer_RunInBackground = 0;
108 char *gsServer_LogFile = "/var/log/dispsrv.log";
109 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
111 int giServer_Socket; // Server socket
112 int giServer_NextClientID = 1; // Debug client ID
117 * \brief Open listenting socket and serve connections
119 void Server_Start(void)
122 struct sockaddr_in server_addr, client_addr;
124 atexit(Server_Cleanup);
125 // Ignore SIGPIPE (stops crashes when the client exits early)
126 signal(SIGPIPE, SIG_IGN);
129 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
130 if( giServer_Socket < 0 ) {
131 fprintf(stderr, "ERROR: Unable to create server socket\n");
135 // Make listen address
136 memset(&server_addr, 0, sizeof(server_addr));
137 server_addr.sin_family = AF_INET; // Internet Socket
138 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
139 server_addr.sin_port = htons(giServer_Port); // Port
142 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
143 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
149 if( gbServer_RunInBackground )
153 fprintf(stderr, "ERROR: Unable to fork\n");
154 perror("fork background");
161 // In child, sort out stdin/stdout
162 reopen(0, "/dev/null", O_READ);
163 reopen(1, gsServer_LogFile, O_CREAT|O_APPEND);
164 reopen(2, gsServer_ErrorLog, O_CREAT|O_APPEND);
169 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
170 fprintf(stderr, "ERROR: Unable to listen to socket\n");
175 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
179 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
180 fprintf(fp, "%i", getpid());
186 uint len = sizeof(client_addr);
189 // Accept a connection
190 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
191 if(client_socket < 0) {
192 fprintf(stderr, "ERROR: Unable to accept client connection\n");
196 // Set a timeout on the user conneciton
199 tv.tv_sec = CLIENT_TIMEOUT;
201 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
203 perror("setsockopt");
208 // Debug: Print the connection string
209 if(giDebugLevel >= 2) {
210 char ipstr[INET_ADDRSTRLEN];
211 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
212 printf("Client connection from %s:%i\n",
213 ipstr, ntohs(client_addr.sin_port));
216 // Doesn't matter what, localhost is trusted
217 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
220 // Trusted Connections
221 if( ntohs(client_addr.sin_port) < 1024 )
223 // TODO: Make this runtime configurable
224 switch( ntohl( client_addr.sin_addr.s_addr ) )
226 case 0x7F000001: // 127.0.0.1 localhost
227 // case 0x825F0D00: // 130.95.13.0
228 case 0x825F0D07: // 130.95.13.7 motsugo
229 case 0x825F0D11: // 130.95.13.17 mermaid
230 case 0x825F0D12: // 130.95.13.18 mussel
231 case 0x825F0D17: // 130.95.13.23 martello
232 case 0x825F0D2A: // 130.95.13.42 meersau
233 case 0x825F0D42: // 130.95.13.66 heathred
241 // TODO: Multithread this?
242 Server_HandleClient(client_socket, bTrusted);
244 close(client_socket);
248 void Server_Cleanup(void)
250 printf("\nClose(%i)\n", giServer_Socket);
251 close(giServer_Socket);
252 unlink("/var/run/dispsrv");
256 * \brief Reads from a client socket and parses the command strings
257 * \param Socket Client socket number/handle
258 * \param bTrusted Is the client trusted?
260 void Server_HandleClient(int Socket, int bTrusted)
262 char inbuf[INPUT_BUFFER_SIZE];
264 int remspace = INPUT_BUFFER_SIZE-1;
268 memset(&clientInfo, 0, sizeof(clientInfo));
270 // Initialise Client info
271 clientInfo.Socket = Socket;
272 clientInfo.ID = giServer_NextClientID ++;
273 clientInfo.bIsTrusted = bTrusted;
274 clientInfo.EffectiveUID = -1;
279 * - The `buf` and `remspace` variables allow a line to span several
280 * calls to recv(), if a line is not completed in one recv() call
281 * it is saved to the beginning of `inbuf` and `buf` is updated to
284 // TODO: Use select() instead (to give a timeout)
285 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
288 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
292 while( (eol = strchr(start, '\n')) )
296 Server_ParseClientCommand(&clientInfo, start);
301 // Check if there was an incomplete line
302 if( *start != '\0' ) {
303 int tailBytes = bytes - (start-buf);
304 // Roll back in buffer
305 memcpy(inbuf, start, tailBytes);
306 remspace -= tailBytes;
308 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
310 remspace = INPUT_BUFFER_SIZE - 1;
315 remspace = INPUT_BUFFER_SIZE - 1;
321 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
325 if(giDebugLevel >= 2) {
326 printf("Client %i: Disconnected\n", clientInfo.ID);
331 * \brief Parses a client command and calls the required helper function
332 * \param Client Pointer to client state structure
333 * \param CommandString Command from client (single line of the command)
334 * \return Heap String to return to the client
336 void Server_ParseClientCommand(tClient *Client, char *CommandString)
338 char *command, *args;
341 if( giDebugLevel >= 2 )
342 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
344 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
346 if( command == NULL ) return ;
347 // printf("command=%s, args=%s\n", command, args);
348 // Is this an error? (just ignore for now)
354 for( i = 0; i < NUM_COMMANDS; i++ )
356 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
357 if( giDebugLevel >= 2 )
358 Debug(Client, "CMD %s - \"%s\"", command, args);
359 gaServer_Commands[i].Function(Client, args);
364 sendf(Client->Socket, "400 Unknown Command\n");
371 * \brief Set client username
373 * Usage: USER <username>
375 void Server_Cmd_USER(tClient *Client, char *Args)
379 if( Server_int_ParseArgs(0, Args, &username, NULL) )
381 sendf(Client->Socket, "407 USER takes 1 argument\n");
387 Debug(Client, "Authenticating as '%s'", username);
391 free(Client->Username);
392 Client->Username = strdup(username);
395 // Create a salt (that changes if the username is changed)
396 // Yes, I know, I'm a little paranoid, but who isn't?
397 Client->Salt[0] = 0x21 + (rand()&0x3F);
398 Client->Salt[1] = 0x21 + (rand()&0x3F);
399 Client->Salt[2] = 0x21 + (rand()&0x3F);
400 Client->Salt[3] = 0x21 + (rand()&0x3F);
401 Client->Salt[4] = 0x21 + (rand()&0x3F);
402 Client->Salt[5] = 0x21 + (rand()&0x3F);
403 Client->Salt[6] = 0x21 + (rand()&0x3F);
404 Client->Salt[7] = 0x21 + (rand()&0x3F);
406 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
407 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
409 sendf(Client->Socket, "100 User Set\n");
414 * \brief Authenticate as a user
418 void Server_Cmd_PASS(tClient *Client, char *Args)
423 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
425 sendf(Client->Socket, "407 PASS takes 1 argument\n");
429 // Pass on to cokebank
430 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
432 if( Client->UID == -1 ) {
433 sendf(Client->Socket, "401 Auth Failure\n");
437 flags = Bank_GetFlags(Client->UID);
438 if( flags & USER_FLAG_DISABLED ) {
440 sendf(Client->Socket, "403 Account Disabled\n");
443 if( flags & USER_FLAG_INTERNAL ) {
445 sendf(Client->Socket, "403 Internal account\n");
449 Client->bIsAuthed = 1;
450 sendf(Client->Socket, "200 Auth OK\n");
454 * \brief Authenticate as a user without a password
456 * Usage: AUTOAUTH <user>
458 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
463 if( Server_int_ParseArgs(0, Args, &username, NULL) )
465 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
470 if( !Client->bIsTrusted ) {
472 Debug(Client, "Untrusted client attempting to AUTOAUTH");
473 sendf(Client->Socket, "401 Untrusted\n");
478 Client->UID = Bank_GetAcctByName( username );
479 if( Client->UID < 0 ) {
481 Debug(Client, "Unknown user '%s'", username);
482 sendf(Client->Socket, "403 Auth Failure\n");
486 userflags = Bank_GetFlags(Client->UID);
487 // You can't be an internal account
488 if( userflags & USER_FLAG_INTERNAL ) {
490 Debug(Client, "Autoauth as '%s', not allowed", username);
492 sendf(Client->Socket, "403 Account is internal\n");
497 if( userflags & USER_FLAG_DISABLED ) {
499 sendf(Client->Socket, "403 Account disabled\n");
503 Client->bIsAuthed = 1;
506 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
508 sendf(Client->Socket, "200 Auth OK\n");
512 * \brief Set effective user
514 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
517 int eUserFlags, userFlags;
519 if( Server_int_ParseArgs(0, Args, &username, NULL) )
521 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
525 if( !strlen(Args) ) {
526 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
530 // Check user permissions
531 userFlags = Bank_GetFlags(Client->UID);
532 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
533 sendf(Client->Socket, "403 Not in coke\n");
538 Client->EffectiveUID = Bank_GetAcctByName(username);
539 if( Client->EffectiveUID == -1 ) {
540 sendf(Client->Socket, "404 User not found\n");
544 // You can't be an internal account
545 if( !(userFlags & USER_FLAG_ADMIN) )
547 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
548 if( eUserFlags & USER_FLAG_INTERNAL ) {
549 Client->EffectiveUID = -1;
550 sendf(Client->Socket, "404 User not found\n");
553 // Disabled only avaliable to admins
554 if( eUserFlags & USER_FLAG_DISABLED ) {
555 Client->EffectiveUID = -1;
556 sendf(Client->Socket, "403 Account disabled\n");
561 sendf(Client->Socket, "200 User set\n");
565 * \brief Send an item status to the client
566 * \param Client Who to?
567 * \param Item Item to send
569 void Server_int_SendItem(tClient *Client, tItem *Item)
571 char *status = "avail";
573 if( Item->Handler->CanDispense )
575 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
577 case 0: status = "avail"; break;
578 case 1: status = "sold"; break;
580 case -1: status = "error"; break;
584 sendf(Client->Socket,
585 "202 Item %s:%i %s %i %s\n",
586 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
591 * \brief Enumerate the items that the server knows about
593 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
597 if( Args != NULL && strlen(Args) ) {
598 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
604 for( i = 0; i < giNumItems; i ++ ) {
605 if( gaItems[i].bHidden ) continue;
609 sendf(Client->Socket, "201 Items %i\n", count);
611 for( i = 0; i < giNumItems; i ++ ) {
612 if( gaItems[i].bHidden ) continue;
613 Server_int_SendItem( Client, &gaItems[i] );
616 sendf(Client->Socket, "200 List end\n");
619 tItem *_GetItemFromString(char *String)
623 char *colon = strchr(String, ':');
635 for( i = 0; i < giNumHandlers; i ++ )
637 if( strcmp(gaHandlers[i]->Name, type) == 0) {
638 handler = gaHandlers[i];
647 for( i = 0; i < giNumItems; i ++ )
649 if( gaItems[i].Handler != handler ) continue;
650 if( gaItems[i].ID != num ) continue;
657 * \brief Fetch information on a specific item
659 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
664 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
665 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
668 item = _GetItemFromString(Args);
671 sendf(Client->Socket, "406 Bad Item ID\n");
675 Server_int_SendItem( Client, item );
678 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
685 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
686 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
690 if( !Client->bIsAuthed ) {
691 sendf(Client->Socket, "401 Not Authenticated\n");
695 item = _GetItemFromString(itemname);
697 sendf(Client->Socket, "406 Bad Item ID\n");
701 if( Client->EffectiveUID != -1 ) {
702 uid = Client->EffectiveUID;
708 switch( ret = DispenseItem( Client->UID, uid, item ) )
710 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
711 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
712 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
714 sendf(Client->Socket, "500 Dispense Error\n");
719 void Server_Cmd_REFUND(tClient *Client, char *Args)
722 int uid, price_override = 0;
723 char *username, *itemname, *price_str;
725 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
726 if( !itemname || price_str ) {
727 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
732 if( !Client->bIsAuthed ) {
733 sendf(Client->Socket, "401 Not Authenticated\n");
737 // Check user permissions
738 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
739 sendf(Client->Socket, "403 Not in coke\n");
743 uid = Bank_GetAcctByName(username);
745 sendf(Client->Socket, "404 Unknown user\n");
749 item = _GetItemFromString(itemname);
751 sendf(Client->Socket, "406 Bad Item ID\n");
756 price_override = atoi(price_str);
758 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
760 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
762 sendf(Client->Socket, "500 Dispense Error\n");
767 void Server_Cmd_GIVE(tClient *Client, char *Args)
769 char *recipient, *ammount, *reason;
774 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
775 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
779 if( !Client->bIsAuthed ) {
780 sendf(Client->Socket, "401 Not Authenticated\n");
785 uid = Bank_GetAcctByName(recipient);
787 sendf(Client->Socket, "404 Invalid target user\n");
791 // You can't alter an internal account
792 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
793 // sendf(Client->Socket, "404 Invalid target user\n");
798 iAmmount = atoi(ammount);
799 if( iAmmount <= 0 ) {
800 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
804 if( Client->EffectiveUID != -1 ) {
805 thisUid = Client->EffectiveUID;
808 thisUid = Client->UID;
812 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
815 sendf(Client->Socket, "200 Give OK\n");
818 sendf(Client->Socket, "402 Poor You\n");
821 sendf(Client->Socket, "500 Unknown error\n");
826 void Server_Cmd_DONATE(tClient *Client, char *Args)
828 char *ammount, *reason;
833 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
834 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
838 if( !Client->bIsAuthed ) {
839 sendf(Client->Socket, "401 Not Authenticated\n");
844 iAmmount = atoi(ammount);
845 if( iAmmount <= 0 ) {
846 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
850 // Handle effective users
851 if( Client->EffectiveUID != -1 ) {
852 thisUid = Client->EffectiveUID;
855 thisUid = Client->UID;
859 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
862 sendf(Client->Socket, "200 Give OK\n");
865 sendf(Client->Socket, "402 Poor You\n");
868 sendf(Client->Socket, "500 Unknown error\n");
873 void Server_Cmd_ADD(tClient *Client, char *Args)
875 char *user, *ammount, *reason;
879 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
880 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
884 if( !Client->bIsAuthed ) {
885 sendf(Client->Socket, "401 Not Authenticated\n");
889 // Check user permissions
890 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
891 sendf(Client->Socket, "403 Not in coke\n");
896 uid = Bank_GetAcctByName(user);
898 sendf(Client->Socket, "404 Invalid user\n");
902 // You can't alter an internal account
903 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
905 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
906 sendf(Client->Socket, "404 Invalid user\n");
909 // TODO: Maybe disallow changes to disabled?
913 iAmmount = atoi(ammount);
914 if( iAmmount == 0 && ammount[0] != '0' ) {
915 sendf(Client->Socket, "407 Invalid Argument\n");
920 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
923 sendf(Client->Socket, "200 Add OK\n");
926 sendf(Client->Socket, "402 Poor Guy\n");
929 sendf(Client->Socket, "500 Unknown error\n");
934 void Server_Cmd_SET(tClient *Client, char *Args)
936 char *user, *ammount, *reason;
940 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
941 sendf(Client->Socket, "407 SET takes 3 arguments\n");
945 if( !Client->bIsAuthed ) {
946 sendf(Client->Socket, "401 Not Authenticated\n");
950 // Check user permissions
951 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
952 sendf(Client->Socket, "403 Not an admin\n");
957 uid = Bank_GetAcctByName(user);
959 sendf(Client->Socket, "404 Invalid user\n");
964 iAmmount = atoi(ammount);
965 if( iAmmount == 0 && ammount[0] != '0' ) {
966 sendf(Client->Socket, "407 Invalid Argument\n");
971 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
974 sendf(Client->Socket, "200 Add OK\n");
977 sendf(Client->Socket, "402 Poor Guy\n");
980 sendf(Client->Socket, "500 Unknown error\n");
985 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
989 int maxBal = INT_MAX, minBal = INT_MIN;
990 int flagMask = 0, flagVal = 0;
991 int sort = BANK_ITFLAG_SORT_NAME;
992 time_t lastSeenAfter=0, lastSeenBefore=0;
994 int flags; // Iterator flags
995 int balValue; // Balance value for iterator
996 time_t timeValue; // Time value for iterator
999 if( Args && strlen(Args) )
1001 char *space = Args, *type, *val;
1005 while(*type == ' ') type ++;
1007 space = strchr(space, ' ');
1008 if(space) *space = '\0';
1011 val = strchr(type, ':');
1018 if( strcmp(type, "min_balance") == 0 ) {
1021 // - Maximum Balance
1022 else if( strcmp(type, "max_balance") == 0 ) {
1026 else if( strcmp(type, "flags") == 0 ) {
1027 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1030 // - Last seen before timestamp
1031 else if( strcmp(type, "last_seen_before") == 0 ) {
1032 lastSeenAfter = atoll(val);
1034 // - Last seen after timestamp
1035 else if( strcmp(type, "last_seen_after") == 0 ) {
1036 lastSeenAfter = atoll(val);
1039 else if( strcmp(type, "sort") == 0 ) {
1040 char *dash = strchr(val, '-');
1045 if( strcmp(val, "name") == 0 ) {
1046 sort = BANK_ITFLAG_SORT_NAME;
1048 else if( strcmp(val, "balance") == 0 ) {
1049 sort = BANK_ITFLAG_SORT_BAL;
1051 else if( strcmp(val, "lastseen") == 0 ) {
1052 sort = BANK_ITFLAG_SORT_LASTSEEN;
1055 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1058 // Handle sort direction
1060 if( strcmp(dash, "desc") == 0 ) {
1061 sort |= BANK_ITFLAG_REVSORT;
1064 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1071 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1078 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1084 *space = ' '; // Repair (to be nice)
1086 while(*space == ' ') space ++;
1092 if( maxBal != INT_MAX ) {
1093 flags = sort|BANK_ITFLAG_MAXBALANCE;
1096 else if( minBal != INT_MIN ) {
1097 flags = sort|BANK_ITFLAG_MINBALANCE;
1104 if( lastSeenBefore ) {
1105 timeValue = lastSeenBefore;
1106 flags |= BANK_ITFLAG_SEENBEFORE;
1108 else if( lastSeenAfter ) {
1109 timeValue = lastSeenAfter;
1110 flags |= BANK_ITFLAG_SEENAFTER;
1115 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1117 // Get return number
1118 while( (i = Bank_IteratorNext(it)) != -1 )
1120 int bal = Bank_GetBalance(i);
1122 if( bal == INT_MIN ) continue;
1124 if( bal < minBal ) continue;
1125 if( bal > maxBal ) continue;
1130 Bank_DelIterator(it);
1133 sendf(Client->Socket, "201 Users %i\n", numRet);
1137 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1139 while( (i = Bank_IteratorNext(it)) != -1 )
1141 int bal = Bank_GetBalance(i);
1143 if( bal == INT_MIN ) continue;
1145 if( bal < minBal ) continue;
1146 if( bal > maxBal ) continue;
1148 _SendUserInfo(Client, i);
1151 Bank_DelIterator(it);
1153 sendf(Client->Socket, "200 List End\n");
1156 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1162 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1163 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1167 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1170 uid = Bank_GetAcctByName(user);
1172 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1174 sendf(Client->Socket, "404 Invalid user\n");
1178 _SendUserInfo(Client, uid);
1181 void _SendUserInfo(tClient *Client, int UserID)
1183 char *type, *disabled="", *door="";
1184 int flags = Bank_GetFlags(UserID);
1186 if( flags & USER_FLAG_INTERNAL ) {
1189 else if( flags & USER_FLAG_COKE ) {
1190 if( flags & USER_FLAG_ADMIN )
1191 type = "coke,admin";
1195 else if( flags & USER_FLAG_ADMIN ) {
1202 if( flags & USER_FLAG_DISABLED )
1203 disabled = ",disabled";
1204 if( flags & USER_FLAG_DOORGROUP )
1207 // TODO: User flags/type
1209 Client->Socket, "202 User %s %i %s%s%s\n",
1210 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1211 type, disabled, door
1215 void Server_Cmd_USERADD(tClient *Client, char *Args)
1220 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1221 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1225 // Check permissions
1226 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1227 sendf(Client->Socket, "403 Not a coke admin\n");
1231 // Try to create user
1232 if( Bank_CreateAcct(username) == -1 ) {
1233 sendf(Client->Socket, "404 User exists\n");
1238 char *thisName = Bank_GetAcctName(Client->UID);
1239 Log_Info("Account '%s' created by '%s'", username, thisName);
1243 sendf(Client->Socket, "200 User Added\n");
1246 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1248 char *username, *flags;
1249 int mask=0, value=0;
1253 if( Server_int_ParseArgs(0, Args, &username, &flags, NULL) ) {
1254 sendf(Client->Socket, "407 USER_FLAGS takes 2 arguments\n");
1258 // Check permissions
1259 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1260 sendf(Client->Socket, "403 Not a coke admin\n");
1265 uid = Bank_GetAcctByName(username);
1267 sendf(Client->Socket, "404 User '%s' not found\n", username);
1272 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1276 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1277 uid, username, mask, value);
1280 Bank_SetFlags(uid, mask, value);
1283 sendf(Client->Socket, "200 User Updated\n");
1286 // --- INTERNAL HELPERS ---
1287 void Debug(tClient *Client, const char *Format, ...)
1290 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1291 printf("[%i] ", Client->ID);
1292 va_start(args, Format);
1293 vprintf(Format, args);
1298 int sendf(int Socket, const char *Format, ...)
1303 va_start(args, Format);
1304 len = vsnprintf(NULL, 0, Format, args);
1309 va_start(args, Format);
1310 vsnprintf(buf, len+1, Format, args);
1313 #if DEBUG_TRACE_CLIENT
1314 printf("sendf: %s", buf);
1317 return send(Socket, buf, len, 0);
1321 // Takes a series of char *'s in
1323 * \brief Parse space-separated entries into
1325 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1330 va_start(args, ArgStr);
1335 while( (dest = va_arg(args, char **)) )
1341 savedChar = *ArgStr;
1343 while( (dest = va_arg(args, char **)) )
1345 // Trim leading spaces
1346 while( *ArgStr == ' ' || *ArgStr == '\t' )
1349 // ... oops, not enough arguments
1350 if( *ArgStr == '\0' )
1352 // NULL unset arguments
1355 } while( (dest = va_arg(args, char **)) );
1360 if( *ArgStr == '"' )
1365 while( *ArgStr && *ArgStr != '"' )
1372 // Read until a space
1373 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1376 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1382 // Oops, extra arguments, and greedy not set
1383 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1390 *ArgStr = savedChar;
1393 return 0; // Success!
1396 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1403 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1404 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1405 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1406 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1407 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1409 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1421 while( *Str == ' ' ) Str ++; // Eat whitespace
1422 space = strchr(Str, ','); // Find the end of the flag
1428 // Check for inversion/removal
1429 if( *Str == '!' || *Str == '-' ) {
1433 else if( *Str == '+' ) {
1437 // Check flag values
1438 for( i = 0; i < ciNumFlags; i ++ )
1440 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1441 *Mask |= cFLAGS[i].Mask;
1442 *Value &= ~cFLAGS[i].Mask;
1444 *Value |= cFLAGS[i].Value;
1450 if( i == ciNumFlags ) {
1452 strncpy(val, Str, len+1);
1453 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);