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");
181 fprintf(fp, "%i", getpid());
188 uint len = sizeof(client_addr);
191 // Accept a connection
192 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
193 if(client_socket < 0) {
194 fprintf(stderr, "ERROR: Unable to accept client connection\n");
198 // Set a timeout on the user conneciton
201 tv.tv_sec = CLIENT_TIMEOUT;
203 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
205 perror("setsockopt");
210 // Debug: Print the connection string
211 if(giDebugLevel >= 2) {
212 char ipstr[INET_ADDRSTRLEN];
213 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
214 printf("Client connection from %s:%i\n",
215 ipstr, ntohs(client_addr.sin_port));
218 // Doesn't matter what, localhost is trusted
219 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
222 // Trusted Connections
223 if( ntohs(client_addr.sin_port) < 1024 )
225 // TODO: Make this runtime configurable
226 switch( ntohl( client_addr.sin_addr.s_addr ) )
228 case 0x7F000001: // 127.0.0.1 localhost
229 // case 0x825F0D00: // 130.95.13.0
230 case 0x825F0D07: // 130.95.13.7 motsugo
231 case 0x825F0D11: // 130.95.13.17 mermaid
232 case 0x825F0D12: // 130.95.13.18 mussel
233 case 0x825F0D17: // 130.95.13.23 martello
234 case 0x825F0D2A: // 130.95.13.42 meersau
235 case 0x825F0D42: // 130.95.13.66 heathred
243 // TODO: Multithread this?
244 Server_HandleClient(client_socket, bTrusted);
246 close(client_socket);
250 void Server_Cleanup(void)
252 printf("\nClose(%i)\n", giServer_Socket);
253 close(giServer_Socket);
254 unlink("/var/run/dispsrv.pid");
258 * \brief Reads from a client socket and parses the command strings
259 * \param Socket Client socket number/handle
260 * \param bTrusted Is the client trusted?
262 void Server_HandleClient(int Socket, int bTrusted)
264 char inbuf[INPUT_BUFFER_SIZE];
266 int remspace = INPUT_BUFFER_SIZE-1;
270 memset(&clientInfo, 0, sizeof(clientInfo));
272 // Initialise Client info
273 clientInfo.Socket = Socket;
274 clientInfo.ID = giServer_NextClientID ++;
275 clientInfo.bIsTrusted = bTrusted;
276 clientInfo.EffectiveUID = -1;
281 * - The `buf` and `remspace` variables allow a line to span several
282 * calls to recv(), if a line is not completed in one recv() call
283 * it is saved to the beginning of `inbuf` and `buf` is updated to
286 // TODO: Use select() instead (to give a timeout)
287 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
290 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
294 while( (eol = strchr(start, '\n')) )
298 Server_ParseClientCommand(&clientInfo, start);
303 // Check if there was an incomplete line
304 if( *start != '\0' ) {
305 int tailBytes = bytes - (start-buf);
306 // Roll back in buffer
307 memcpy(inbuf, start, tailBytes);
308 remspace -= tailBytes;
310 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
312 remspace = INPUT_BUFFER_SIZE - 1;
317 remspace = INPUT_BUFFER_SIZE - 1;
323 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
327 if(giDebugLevel >= 2) {
328 printf("Client %i: Disconnected\n", clientInfo.ID);
333 * \brief Parses a client command and calls the required helper function
334 * \param Client Pointer to client state structure
335 * \param CommandString Command from client (single line of the command)
336 * \return Heap String to return to the client
338 void Server_ParseClientCommand(tClient *Client, char *CommandString)
340 char *command, *args;
343 if( giDebugLevel >= 2 )
344 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
346 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
348 if( command == NULL ) return ;
349 // printf("command=%s, args=%s\n", command, args);
350 // Is this an error? (just ignore for now)
356 for( i = 0; i < NUM_COMMANDS; i++ )
358 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
359 if( giDebugLevel >= 2 )
360 Debug(Client, "CMD %s - \"%s\"", command, args);
361 gaServer_Commands[i].Function(Client, args);
366 sendf(Client->Socket, "400 Unknown Command\n");
373 * \brief Set client username
375 * Usage: USER <username>
377 void Server_Cmd_USER(tClient *Client, char *Args)
381 if( Server_int_ParseArgs(0, Args, &username, NULL) )
383 sendf(Client->Socket, "407 USER takes 1 argument\n");
389 Debug(Client, "Authenticating as '%s'", username);
393 free(Client->Username);
394 Client->Username = strdup(username);
397 // Create a salt (that changes if the username is changed)
398 // Yes, I know, I'm a little paranoid, but who isn't?
399 Client->Salt[0] = 0x21 + (rand()&0x3F);
400 Client->Salt[1] = 0x21 + (rand()&0x3F);
401 Client->Salt[2] = 0x21 + (rand()&0x3F);
402 Client->Salt[3] = 0x21 + (rand()&0x3F);
403 Client->Salt[4] = 0x21 + (rand()&0x3F);
404 Client->Salt[5] = 0x21 + (rand()&0x3F);
405 Client->Salt[6] = 0x21 + (rand()&0x3F);
406 Client->Salt[7] = 0x21 + (rand()&0x3F);
408 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
409 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
411 sendf(Client->Socket, "100 User Set\n");
416 * \brief Authenticate as a user
420 void Server_Cmd_PASS(tClient *Client, char *Args)
425 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
427 sendf(Client->Socket, "407 PASS takes 1 argument\n");
431 // Pass on to cokebank
432 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
434 if( Client->UID == -1 ) {
435 sendf(Client->Socket, "401 Auth Failure\n");
439 flags = Bank_GetFlags(Client->UID);
440 if( flags & USER_FLAG_DISABLED ) {
442 sendf(Client->Socket, "403 Account Disabled\n");
445 if( flags & USER_FLAG_INTERNAL ) {
447 sendf(Client->Socket, "403 Internal account\n");
451 Client->bIsAuthed = 1;
452 sendf(Client->Socket, "200 Auth OK\n");
456 * \brief Authenticate as a user without a password
458 * Usage: AUTOAUTH <user>
460 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
465 if( Server_int_ParseArgs(0, Args, &username, NULL) )
467 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
472 if( !Client->bIsTrusted ) {
474 Debug(Client, "Untrusted client attempting to AUTOAUTH");
475 sendf(Client->Socket, "401 Untrusted\n");
480 Client->UID = Bank_GetAcctByName( username );
481 if( Client->UID < 0 ) {
483 Debug(Client, "Unknown user '%s'", username);
484 sendf(Client->Socket, "403 Auth Failure\n");
488 userflags = Bank_GetFlags(Client->UID);
489 // You can't be an internal account
490 if( userflags & USER_FLAG_INTERNAL ) {
492 Debug(Client, "Autoauth as '%s', not allowed", username);
494 sendf(Client->Socket, "403 Account is internal\n");
499 if( userflags & USER_FLAG_DISABLED ) {
501 sendf(Client->Socket, "403 Account disabled\n");
505 Client->bIsAuthed = 1;
508 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
510 sendf(Client->Socket, "200 Auth OK\n");
514 * \brief Set effective user
516 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
519 int eUserFlags, userFlags;
521 if( Server_int_ParseArgs(0, Args, &username, NULL) )
523 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
527 if( !strlen(Args) ) {
528 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
532 // Check user permissions
533 userFlags = Bank_GetFlags(Client->UID);
534 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
535 sendf(Client->Socket, "403 Not in coke\n");
540 Client->EffectiveUID = Bank_GetAcctByName(username);
541 if( Client->EffectiveUID == -1 ) {
542 sendf(Client->Socket, "404 User not found\n");
546 // You can't be an internal account
547 if( !(userFlags & USER_FLAG_ADMIN) )
549 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
550 if( eUserFlags & USER_FLAG_INTERNAL ) {
551 Client->EffectiveUID = -1;
552 sendf(Client->Socket, "404 User not found\n");
555 // Disabled only avaliable to admins
556 if( eUserFlags & USER_FLAG_DISABLED ) {
557 Client->EffectiveUID = -1;
558 sendf(Client->Socket, "403 Account disabled\n");
563 sendf(Client->Socket, "200 User set\n");
567 * \brief Send an item status to the client
568 * \param Client Who to?
569 * \param Item Item to send
571 void Server_int_SendItem(tClient *Client, tItem *Item)
573 char *status = "avail";
575 if( Item->Handler->CanDispense )
577 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
579 case 0: status = "avail"; break;
580 case 1: status = "sold"; break;
582 case -1: status = "error"; break;
586 sendf(Client->Socket,
587 "202 Item %s:%i %s %i %s\n",
588 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
593 * \brief Enumerate the items that the server knows about
595 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
599 if( Args != NULL && strlen(Args) ) {
600 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
606 for( i = 0; i < giNumItems; i ++ ) {
607 if( gaItems[i].bHidden ) continue;
611 sendf(Client->Socket, "201 Items %i\n", count);
613 for( i = 0; i < giNumItems; i ++ ) {
614 if( gaItems[i].bHidden ) continue;
615 Server_int_SendItem( Client, &gaItems[i] );
618 sendf(Client->Socket, "200 List end\n");
621 tItem *_GetItemFromString(char *String)
625 char *colon = strchr(String, ':');
637 for( i = 0; i < giNumHandlers; i ++ )
639 if( strcmp(gaHandlers[i]->Name, type) == 0) {
640 handler = gaHandlers[i];
649 for( i = 0; i < giNumItems; i ++ )
651 if( gaItems[i].Handler != handler ) continue;
652 if( gaItems[i].ID != num ) continue;
659 * \brief Fetch information on a specific item
661 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
666 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
667 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
670 item = _GetItemFromString(Args);
673 sendf(Client->Socket, "406 Bad Item ID\n");
677 Server_int_SendItem( Client, item );
680 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
687 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
688 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
692 if( !Client->bIsAuthed ) {
693 sendf(Client->Socket, "401 Not Authenticated\n");
697 item = _GetItemFromString(itemname);
699 sendf(Client->Socket, "406 Bad Item ID\n");
703 if( Client->EffectiveUID != -1 ) {
704 uid = Client->EffectiveUID;
710 switch( ret = DispenseItem( Client->UID, uid, item ) )
712 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
713 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
714 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
716 sendf(Client->Socket, "500 Dispense Error\n");
721 void Server_Cmd_REFUND(tClient *Client, char *Args)
724 int uid, price_override = 0;
725 char *username, *itemname, *price_str;
727 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
728 if( !itemname || price_str ) {
729 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
734 if( !Client->bIsAuthed ) {
735 sendf(Client->Socket, "401 Not Authenticated\n");
739 // Check user permissions
740 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
741 sendf(Client->Socket, "403 Not in coke\n");
745 uid = Bank_GetAcctByName(username);
747 sendf(Client->Socket, "404 Unknown user\n");
751 item = _GetItemFromString(itemname);
753 sendf(Client->Socket, "406 Bad Item ID\n");
758 price_override = atoi(price_str);
760 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
762 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
764 sendf(Client->Socket, "500 Dispense Error\n");
769 void Server_Cmd_GIVE(tClient *Client, char *Args)
771 char *recipient, *ammount, *reason;
776 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
777 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
781 if( !Client->bIsAuthed ) {
782 sendf(Client->Socket, "401 Not Authenticated\n");
787 uid = Bank_GetAcctByName(recipient);
789 sendf(Client->Socket, "404 Invalid target user\n");
793 // You can't alter an internal account
794 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
795 // sendf(Client->Socket, "404 Invalid target user\n");
800 iAmmount = atoi(ammount);
801 if( iAmmount <= 0 ) {
802 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
806 if( Client->EffectiveUID != -1 ) {
807 thisUid = Client->EffectiveUID;
810 thisUid = Client->UID;
814 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
817 sendf(Client->Socket, "200 Give OK\n");
820 sendf(Client->Socket, "402 Poor You\n");
823 sendf(Client->Socket, "500 Unknown error\n");
828 void Server_Cmd_DONATE(tClient *Client, char *Args)
830 char *ammount, *reason;
835 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
836 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
840 if( !Client->bIsAuthed ) {
841 sendf(Client->Socket, "401 Not Authenticated\n");
846 iAmmount = atoi(ammount);
847 if( iAmmount <= 0 ) {
848 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
852 // Handle effective users
853 if( Client->EffectiveUID != -1 ) {
854 thisUid = Client->EffectiveUID;
857 thisUid = Client->UID;
861 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
864 sendf(Client->Socket, "200 Give OK\n");
867 sendf(Client->Socket, "402 Poor You\n");
870 sendf(Client->Socket, "500 Unknown error\n");
875 void Server_Cmd_ADD(tClient *Client, char *Args)
877 char *user, *ammount, *reason;
881 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
882 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
886 if( !Client->bIsAuthed ) {
887 sendf(Client->Socket, "401 Not Authenticated\n");
891 // Check user permissions
892 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
893 sendf(Client->Socket, "403 Not in coke\n");
898 uid = Bank_GetAcctByName(user);
900 sendf(Client->Socket, "404 Invalid user\n");
904 // You can't alter an internal account
905 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
907 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
908 sendf(Client->Socket, "404 Invalid user\n");
911 // TODO: Maybe disallow changes to disabled?
915 iAmmount = atoi(ammount);
916 if( iAmmount == 0 && ammount[0] != '0' ) {
917 sendf(Client->Socket, "407 Invalid Argument\n");
922 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
925 sendf(Client->Socket, "200 Add OK\n");
928 sendf(Client->Socket, "402 Poor Guy\n");
931 sendf(Client->Socket, "500 Unknown error\n");
936 void Server_Cmd_SET(tClient *Client, char *Args)
938 char *user, *ammount, *reason;
942 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
943 sendf(Client->Socket, "407 SET takes 3 arguments\n");
947 if( !Client->bIsAuthed ) {
948 sendf(Client->Socket, "401 Not Authenticated\n");
952 // Check user permissions
953 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
954 sendf(Client->Socket, "403 Not an admin\n");
959 uid = Bank_GetAcctByName(user);
961 sendf(Client->Socket, "404 Invalid user\n");
966 iAmmount = atoi(ammount);
967 if( iAmmount == 0 && ammount[0] != '0' ) {
968 sendf(Client->Socket, "407 Invalid Argument\n");
973 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
976 sendf(Client->Socket, "200 Add OK\n");
979 sendf(Client->Socket, "402 Poor Guy\n");
982 sendf(Client->Socket, "500 Unknown error\n");
987 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
991 int maxBal = INT_MAX, minBal = INT_MIN;
992 int flagMask = 0, flagVal = 0;
993 int sort = BANK_ITFLAG_SORT_NAME;
994 time_t lastSeenAfter=0, lastSeenBefore=0;
996 int flags; // Iterator flags
997 int balValue; // Balance value for iterator
998 time_t timeValue; // Time value for iterator
1001 if( Args && strlen(Args) )
1003 char *space = Args, *type, *val;
1007 while(*type == ' ') type ++;
1009 space = strchr(space, ' ');
1010 if(space) *space = '\0';
1013 val = strchr(type, ':');
1020 if( strcmp(type, "min_balance") == 0 ) {
1023 // - Maximum Balance
1024 else if( strcmp(type, "max_balance") == 0 ) {
1028 else if( strcmp(type, "flags") == 0 ) {
1029 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1032 // - Last seen before timestamp
1033 else if( strcmp(type, "last_seen_before") == 0 ) {
1034 lastSeenAfter = atoll(val);
1036 // - Last seen after timestamp
1037 else if( strcmp(type, "last_seen_after") == 0 ) {
1038 lastSeenAfter = atoll(val);
1041 else if( strcmp(type, "sort") == 0 ) {
1042 char *dash = strchr(val, '-');
1047 if( strcmp(val, "name") == 0 ) {
1048 sort = BANK_ITFLAG_SORT_NAME;
1050 else if( strcmp(val, "balance") == 0 ) {
1051 sort = BANK_ITFLAG_SORT_BAL;
1053 else if( strcmp(val, "lastseen") == 0 ) {
1054 sort = BANK_ITFLAG_SORT_LASTSEEN;
1057 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1060 // Handle sort direction
1062 if( strcmp(dash, "desc") == 0 ) {
1063 sort |= BANK_ITFLAG_REVSORT;
1066 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1073 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1080 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1086 *space = ' '; // Repair (to be nice)
1088 while(*space == ' ') space ++;
1094 if( maxBal != INT_MAX ) {
1095 flags = sort|BANK_ITFLAG_MAXBALANCE;
1098 else if( minBal != INT_MIN ) {
1099 flags = sort|BANK_ITFLAG_MINBALANCE;
1106 if( lastSeenBefore ) {
1107 timeValue = lastSeenBefore;
1108 flags |= BANK_ITFLAG_SEENBEFORE;
1110 else if( lastSeenAfter ) {
1111 timeValue = lastSeenAfter;
1112 flags |= BANK_ITFLAG_SEENAFTER;
1117 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1119 // Get return number
1120 while( (i = Bank_IteratorNext(it)) != -1 )
1122 int bal = Bank_GetBalance(i);
1124 if( bal == INT_MIN ) continue;
1126 if( bal < minBal ) continue;
1127 if( bal > maxBal ) continue;
1132 Bank_DelIterator(it);
1135 sendf(Client->Socket, "201 Users %i\n", numRet);
1139 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1141 while( (i = Bank_IteratorNext(it)) != -1 )
1143 int bal = Bank_GetBalance(i);
1145 if( bal == INT_MIN ) continue;
1147 if( bal < minBal ) continue;
1148 if( bal > maxBal ) continue;
1150 _SendUserInfo(Client, i);
1153 Bank_DelIterator(it);
1155 sendf(Client->Socket, "200 List End\n");
1158 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1164 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1165 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1169 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1172 uid = Bank_GetAcctByName(user);
1174 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1176 sendf(Client->Socket, "404 Invalid user\n");
1180 _SendUserInfo(Client, uid);
1183 void _SendUserInfo(tClient *Client, int UserID)
1185 char *type, *disabled="", *door="";
1186 int flags = Bank_GetFlags(UserID);
1188 if( flags & USER_FLAG_INTERNAL ) {
1191 else if( flags & USER_FLAG_COKE ) {
1192 if( flags & USER_FLAG_ADMIN )
1193 type = "coke,admin";
1197 else if( flags & USER_FLAG_ADMIN ) {
1204 if( flags & USER_FLAG_DISABLED )
1205 disabled = ",disabled";
1206 if( flags & USER_FLAG_DOORGROUP )
1209 // TODO: User flags/type
1211 Client->Socket, "202 User %s %i %s%s%s\n",
1212 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1213 type, disabled, door
1217 void Server_Cmd_USERADD(tClient *Client, char *Args)
1222 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1223 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1227 // Check permissions
1228 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1229 sendf(Client->Socket, "403 Not a coke admin\n");
1233 // Try to create user
1234 if( Bank_CreateAcct(username) == -1 ) {
1235 sendf(Client->Socket, "404 User exists\n");
1240 char *thisName = Bank_GetAcctName(Client->UID);
1241 Log_Info("Account '%s' created by '%s'", username, thisName);
1245 sendf(Client->Socket, "200 User Added\n");
1248 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1250 char *username, *flags;
1251 int mask=0, value=0;
1255 if( Server_int_ParseArgs(0, Args, &username, &flags, NULL) ) {
1256 sendf(Client->Socket, "407 USER_FLAGS takes 2 arguments\n");
1260 // Check permissions
1261 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1262 sendf(Client->Socket, "403 Not a coke admin\n");
1267 uid = Bank_GetAcctByName(username);
1269 sendf(Client->Socket, "404 User '%s' not found\n", username);
1274 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1278 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1279 uid, username, mask, value);
1282 Bank_SetFlags(uid, mask, value);
1285 sendf(Client->Socket, "200 User Updated\n");
1288 // --- INTERNAL HELPERS ---
1289 void Debug(tClient *Client, const char *Format, ...)
1292 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1293 printf("[%i] ", Client->ID);
1294 va_start(args, Format);
1295 vprintf(Format, args);
1300 int sendf(int Socket, const char *Format, ...)
1305 va_start(args, Format);
1306 len = vsnprintf(NULL, 0, Format, args);
1311 va_start(args, Format);
1312 vsnprintf(buf, len+1, Format, args);
1315 #if DEBUG_TRACE_CLIENT
1316 printf("sendf: %s", buf);
1319 return send(Socket, buf, len, 0);
1323 // Takes a series of char *'s in
1325 * \brief Parse space-separated entries into
1327 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1332 va_start(args, ArgStr);
1337 while( (dest = va_arg(args, char **)) )
1343 savedChar = *ArgStr;
1345 while( (dest = va_arg(args, char **)) )
1347 // Trim leading spaces
1348 while( *ArgStr == ' ' || *ArgStr == '\t' )
1351 // ... oops, not enough arguments
1352 if( *ArgStr == '\0' )
1354 // NULL unset arguments
1357 } while( (dest = va_arg(args, char **)) );
1362 if( *ArgStr == '"' )
1367 while( *ArgStr && *ArgStr != '"' )
1374 // Read until a space
1375 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1378 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1384 // Oops, extra arguments, and greedy not set
1385 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1392 *ArgStr = savedChar;
1395 return 0; // Success!
1398 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1405 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1406 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1407 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1408 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1409 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1411 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1423 while( *Str == ' ' ) Str ++; // Eat whitespace
1424 space = strchr(Str, ','); // Find the end of the flag
1430 // Check for inversion/removal
1431 if( *Str == '!' || *Str == '-' ) {
1435 else if( *Str == '+' ) {
1439 // Check flag values
1440 for( i = 0; i < ciNumFlags; i ++ )
1442 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1443 *Mask |= cFLAGS[i].Mask;
1444 *Value &= ~cFLAGS[i].Mask;
1446 *Value |= cFLAGS[i].Value;
1452 if( i == ciNumFlags ) {
1454 strncpy(val, Str, len+1);
1455 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);