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);
73 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args);
75 void Debug(tClient *Client, const char *Format, ...);
76 int sendf(int Socket, const char *Format, ...);
77 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
78 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
82 const struct sClientCommand {
84 void (*Function)(tClient *Client, char *Arguments);
85 } gaServer_Commands[] = {
86 {"USER", Server_Cmd_USER},
87 {"PASS", Server_Cmd_PASS},
88 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
89 {"SETEUSER", Server_Cmd_SETEUSER},
90 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
91 {"ITEM_INFO", Server_Cmd_ITEMINFO},
92 {"DISPENSE", Server_Cmd_DISPENSE},
93 {"REFUND", Server_Cmd_REFUND},
94 {"GIVE", Server_Cmd_GIVE},
95 {"DONATE", Server_Cmd_DONATE},
96 {"ADD", Server_Cmd_ADD},
97 {"SET", Server_Cmd_SET},
98 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
99 {"USER_INFO", Server_Cmd_USERINFO},
100 {"USER_ADD", Server_Cmd_USERADD},
101 {"USER_FLAGS", Server_Cmd_USERFLAGS},
102 {"UPDATE_ITEM", Server_Cmd_UPDATEITEM}
104 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
108 int giServer_Port = 11020;
109 int gbServer_RunInBackground = 0;
110 char *gsServer_LogFile = "/var/log/dispsrv.log";
111 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
113 int giServer_Socket; // Server socket
114 int giServer_NextClientID = 1; // Debug client ID
119 * \brief Open listenting socket and serve connections
121 void Server_Start(void)
124 struct sockaddr_in server_addr, client_addr;
126 atexit(Server_Cleanup);
127 // Ignore SIGPIPE (stops crashes when the client exits early)
128 signal(SIGPIPE, SIG_IGN);
131 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
132 if( giServer_Socket < 0 ) {
133 fprintf(stderr, "ERROR: Unable to create server socket\n");
137 // Make listen address
138 memset(&server_addr, 0, sizeof(server_addr));
139 server_addr.sin_family = AF_INET; // Internet Socket
140 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
141 server_addr.sin_port = htons(giServer_Port); // Port
144 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
145 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
151 if( gbServer_RunInBackground )
155 fprintf(stderr, "ERROR: Unable to fork\n");
156 perror("fork background");
163 // In child, sort out stdin/stdout
164 reopen(0, "/dev/null", O_READ);
165 reopen(1, gsServer_LogFile, O_CREAT|O_APPEND);
166 reopen(2, gsServer_ErrorLog, O_CREAT|O_APPEND);
171 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
172 fprintf(stderr, "ERROR: Unable to listen to socket\n");
177 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
181 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
183 fprintf(fp, "%i", getpid());
190 uint len = sizeof(client_addr);
193 // Accept a connection
194 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
195 if(client_socket < 0) {
196 fprintf(stderr, "ERROR: Unable to accept client connection\n");
200 // Set a timeout on the user conneciton
203 tv.tv_sec = CLIENT_TIMEOUT;
205 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
207 perror("setsockopt");
212 // Debug: Print the connection string
213 if(giDebugLevel >= 2) {
214 char ipstr[INET_ADDRSTRLEN];
215 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
216 printf("Client connection from %s:%i\n",
217 ipstr, ntohs(client_addr.sin_port));
220 // Doesn't matter what, localhost is trusted
221 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
224 // Trusted Connections
225 if( ntohs(client_addr.sin_port) < 1024 )
227 // TODO: Make this runtime configurable
228 switch( ntohl( client_addr.sin_addr.s_addr ) )
230 case 0x7F000001: // 127.0.0.1 localhost
231 // case 0x825F0D00: // 130.95.13.0
232 case 0x825F0D07: // 130.95.13.7 motsugo
233 case 0x825F0D11: // 130.95.13.17 mermaid
234 case 0x825F0D12: // 130.95.13.18 mussel
235 case 0x825F0D17: // 130.95.13.23 martello
236 case 0x825F0D2A: // 130.95.13.42 meersau
237 case 0x825F0D42: // 130.95.13.66 heathred
245 // TODO: Multithread this?
246 Server_HandleClient(client_socket, bTrusted);
248 close(client_socket);
252 void Server_Cleanup(void)
254 printf("\nClose(%i)\n", giServer_Socket);
255 close(giServer_Socket);
256 unlink("/var/run/dispsrv");
260 * \brief Reads from a client socket and parses the command strings
261 * \param Socket Client socket number/handle
262 * \param bTrusted Is the client trusted?
264 void Server_HandleClient(int Socket, int bTrusted)
266 char inbuf[INPUT_BUFFER_SIZE];
268 int remspace = INPUT_BUFFER_SIZE-1;
272 memset(&clientInfo, 0, sizeof(clientInfo));
274 // Initialise Client info
275 clientInfo.Socket = Socket;
276 clientInfo.ID = giServer_NextClientID ++;
277 clientInfo.bIsTrusted = bTrusted;
278 clientInfo.EffectiveUID = -1;
283 * - The `buf` and `remspace` variables allow a line to span several
284 * calls to recv(), if a line is not completed in one recv() call
285 * it is saved to the beginning of `inbuf` and `buf` is updated to
288 // TODO: Use select() instead (to give a timeout)
289 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
292 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
296 while( (eol = strchr(start, '\n')) )
300 Server_ParseClientCommand(&clientInfo, start);
305 // Check if there was an incomplete line
306 if( *start != '\0' ) {
307 int tailBytes = bytes - (start-buf);
308 // Roll back in buffer
309 memcpy(inbuf, start, tailBytes);
310 remspace -= tailBytes;
312 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
314 remspace = INPUT_BUFFER_SIZE - 1;
319 remspace = INPUT_BUFFER_SIZE - 1;
325 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
329 if(giDebugLevel >= 2) {
330 printf("Client %i: Disconnected\n", clientInfo.ID);
335 * \brief Parses a client command and calls the required helper function
336 * \param Client Pointer to client state structure
337 * \param CommandString Command from client (single line of the command)
338 * \return Heap String to return to the client
340 void Server_ParseClientCommand(tClient *Client, char *CommandString)
342 char *command, *args;
345 if( giDebugLevel >= 2 )
346 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
348 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
350 if( command == NULL ) return ;
351 // printf("command=%s, args=%s\n", command, args);
352 // Is this an error? (just ignore for now)
358 for( i = 0; i < NUM_COMMANDS; i++ )
360 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
361 if( giDebugLevel >= 2 )
362 Debug(Client, "CMD %s - \"%s\"", command, args);
363 gaServer_Commands[i].Function(Client, args);
368 sendf(Client->Socket, "400 Unknown Command\n");
375 * \brief Set client username
377 * Usage: USER <username>
379 void Server_Cmd_USER(tClient *Client, char *Args)
383 if( Server_int_ParseArgs(0, Args, &username, NULL) )
385 sendf(Client->Socket, "407 USER takes 1 argument\n");
391 Debug(Client, "Authenticating as '%s'", username);
395 free(Client->Username);
396 Client->Username = strdup(username);
399 // Create a salt (that changes if the username is changed)
400 // Yes, I know, I'm a little paranoid, but who isn't?
401 Client->Salt[0] = 0x21 + (rand()&0x3F);
402 Client->Salt[1] = 0x21 + (rand()&0x3F);
403 Client->Salt[2] = 0x21 + (rand()&0x3F);
404 Client->Salt[3] = 0x21 + (rand()&0x3F);
405 Client->Salt[4] = 0x21 + (rand()&0x3F);
406 Client->Salt[5] = 0x21 + (rand()&0x3F);
407 Client->Salt[6] = 0x21 + (rand()&0x3F);
408 Client->Salt[7] = 0x21 + (rand()&0x3F);
410 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
411 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
413 sendf(Client->Socket, "100 User Set\n");
418 * \brief Authenticate as a user
422 void Server_Cmd_PASS(tClient *Client, char *Args)
427 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
429 sendf(Client->Socket, "407 PASS takes 1 argument\n");
433 // Pass on to cokebank
434 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
436 if( Client->UID == -1 ) {
437 sendf(Client->Socket, "401 Auth Failure\n");
441 flags = Bank_GetFlags(Client->UID);
442 if( flags & USER_FLAG_DISABLED ) {
444 sendf(Client->Socket, "403 Account Disabled\n");
447 if( flags & USER_FLAG_INTERNAL ) {
449 sendf(Client->Socket, "403 Internal account\n");
453 Client->bIsAuthed = 1;
454 sendf(Client->Socket, "200 Auth OK\n");
458 * \brief Authenticate as a user without a password
460 * Usage: AUTOAUTH <user>
462 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
467 if( Server_int_ParseArgs(0, Args, &username, NULL) )
469 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
474 if( !Client->bIsTrusted ) {
476 Debug(Client, "Untrusted client attempting to AUTOAUTH");
477 sendf(Client->Socket, "401 Untrusted\n");
482 Client->UID = Bank_GetAcctByName( username );
483 if( Client->UID < 0 ) {
485 Debug(Client, "Unknown user '%s'", username);
486 sendf(Client->Socket, "403 Auth Failure\n");
490 userflags = Bank_GetFlags(Client->UID);
491 // You can't be an internal account
492 if( userflags & USER_FLAG_INTERNAL ) {
494 Debug(Client, "Autoauth as '%s', not allowed", username);
496 sendf(Client->Socket, "403 Account is internal\n");
501 if( userflags & USER_FLAG_DISABLED ) {
503 sendf(Client->Socket, "403 Account disabled\n");
507 Client->bIsAuthed = 1;
510 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
512 sendf(Client->Socket, "200 Auth OK\n");
516 * \brief Set effective user
518 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
521 int eUserFlags, userFlags;
523 if( Server_int_ParseArgs(0, Args, &username, NULL) )
525 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
529 if( !strlen(Args) ) {
530 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
534 // Check user permissions
535 userFlags = Bank_GetFlags(Client->UID);
536 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
537 sendf(Client->Socket, "403 Not in coke\n");
542 Client->EffectiveUID = Bank_GetAcctByName(username);
543 if( Client->EffectiveUID == -1 ) {
544 sendf(Client->Socket, "404 User not found\n");
548 // You can't be an internal account
549 if( !(userFlags & USER_FLAG_ADMIN) )
551 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
552 if( eUserFlags & USER_FLAG_INTERNAL ) {
553 Client->EffectiveUID = -1;
554 sendf(Client->Socket, "404 User not found\n");
557 // Disabled only avaliable to admins
558 if( eUserFlags & USER_FLAG_DISABLED ) {
559 Client->EffectiveUID = -1;
560 sendf(Client->Socket, "403 Account disabled\n");
565 sendf(Client->Socket, "200 User set\n");
569 * \brief Send an item status to the client
570 * \param Client Who to?
571 * \param Item Item to send
573 void Server_int_SendItem(tClient *Client, tItem *Item)
575 char *status = "avail";
577 if( Item->Handler->CanDispense )
579 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
581 case 0: status = "avail"; break;
582 case 1: status = "sold"; break;
584 case -1: status = "error"; break;
588 sendf(Client->Socket,
589 "202 Item %s:%i %s %i %s\n",
590 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
595 * \brief Enumerate the items that the server knows about
597 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
601 if( Args != NULL && strlen(Args) ) {
602 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
608 for( i = 0; i < giNumItems; i ++ ) {
609 if( gaItems[i].bHidden ) continue;
613 sendf(Client->Socket, "201 Items %i\n", count);
615 for( i = 0; i < giNumItems; i ++ ) {
616 if( gaItems[i].bHidden ) continue;
617 Server_int_SendItem( Client, &gaItems[i] );
620 sendf(Client->Socket, "200 List end\n");
623 tItem *_GetItemFromString(char *String)
627 char *colon = strchr(String, ':');
639 for( i = 0; i < giNumHandlers; i ++ )
641 if( strcmp(gaHandlers[i]->Name, type) == 0) {
642 handler = gaHandlers[i];
651 for( i = 0; i < giNumItems; i ++ )
653 if( gaItems[i].Handler != handler ) continue;
654 if( gaItems[i].ID != num ) continue;
661 * \brief Fetch information on a specific item
663 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
668 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
669 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
672 item = _GetItemFromString(Args);
675 sendf(Client->Socket, "406 Bad Item ID\n");
679 Server_int_SendItem( Client, item );
682 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
689 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
690 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
694 if( !Client->bIsAuthed ) {
695 sendf(Client->Socket, "401 Not Authenticated\n");
699 item = _GetItemFromString(itemname);
701 sendf(Client->Socket, "406 Bad Item ID\n");
705 if( Client->EffectiveUID != -1 ) {
706 uid = Client->EffectiveUID;
712 switch( ret = DispenseItem( Client->UID, uid, item ) )
714 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
715 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
716 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
718 sendf(Client->Socket, "500 Dispense Error\n");
723 void Server_Cmd_REFUND(tClient *Client, char *Args)
726 int uid, price_override = 0;
727 char *username, *itemname, *price_str;
729 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
730 if( !itemname || price_str ) {
731 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
736 if( !Client->bIsAuthed ) {
737 sendf(Client->Socket, "401 Not Authenticated\n");
741 // Check user permissions
742 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
743 sendf(Client->Socket, "403 Not in coke\n");
747 uid = Bank_GetAcctByName(username);
749 sendf(Client->Socket, "404 Unknown user\n");
753 item = _GetItemFromString(itemname);
755 sendf(Client->Socket, "406 Bad Item ID\n");
760 price_override = atoi(price_str);
762 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
764 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
766 sendf(Client->Socket, "500 Dispense Error\n");
771 void Server_Cmd_GIVE(tClient *Client, char *Args)
773 char *recipient, *ammount, *reason;
778 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
779 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
783 if( !Client->bIsAuthed ) {
784 sendf(Client->Socket, "401 Not Authenticated\n");
789 uid = Bank_GetAcctByName(recipient);
791 sendf(Client->Socket, "404 Invalid target user\n");
795 // You can't alter an internal account
796 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
797 // sendf(Client->Socket, "404 Invalid target user\n");
802 iAmmount = atoi(ammount);
803 if( iAmmount <= 0 ) {
804 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
808 if( Client->EffectiveUID != -1 ) {
809 thisUid = Client->EffectiveUID;
812 thisUid = Client->UID;
816 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
819 sendf(Client->Socket, "200 Give OK\n");
822 sendf(Client->Socket, "402 Poor You\n");
825 sendf(Client->Socket, "500 Unknown error\n");
830 void Server_Cmd_DONATE(tClient *Client, char *Args)
832 char *ammount, *reason;
837 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
838 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
842 if( !Client->bIsAuthed ) {
843 sendf(Client->Socket, "401 Not Authenticated\n");
848 iAmmount = atoi(ammount);
849 if( iAmmount <= 0 ) {
850 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
854 // Handle effective users
855 if( Client->EffectiveUID != -1 ) {
856 thisUid = Client->EffectiveUID;
859 thisUid = Client->UID;
863 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
866 sendf(Client->Socket, "200 Give OK\n");
869 sendf(Client->Socket, "402 Poor You\n");
872 sendf(Client->Socket, "500 Unknown error\n");
877 void Server_Cmd_ADD(tClient *Client, char *Args)
879 char *user, *ammount, *reason;
883 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
884 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
888 if( !Client->bIsAuthed ) {
889 sendf(Client->Socket, "401 Not Authenticated\n");
893 // Check user permissions
894 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
895 sendf(Client->Socket, "403 Not in coke\n");
900 uid = Bank_GetAcctByName(user);
902 sendf(Client->Socket, "404 Invalid user\n");
906 // You can't alter an internal account
907 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
909 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
910 sendf(Client->Socket, "404 Invalid user\n");
913 // TODO: Maybe disallow changes to disabled?
917 iAmmount = atoi(ammount);
918 if( iAmmount == 0 && ammount[0] != '0' ) {
919 sendf(Client->Socket, "407 Invalid Argument\n");
924 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
927 sendf(Client->Socket, "200 Add OK\n");
930 sendf(Client->Socket, "402 Poor Guy\n");
933 sendf(Client->Socket, "500 Unknown error\n");
938 void Server_Cmd_SET(tClient *Client, char *Args)
940 char *user, *ammount, *reason;
944 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
945 sendf(Client->Socket, "407 SET takes 3 arguments\n");
949 if( !Client->bIsAuthed ) {
950 sendf(Client->Socket, "401 Not Authenticated\n");
954 // Check user permissions
955 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
956 sendf(Client->Socket, "403 Not an admin\n");
961 uid = Bank_GetAcctByName(user);
963 sendf(Client->Socket, "404 Invalid user\n");
968 iAmmount = atoi(ammount);
969 if( iAmmount == 0 && ammount[0] != '0' ) {
970 sendf(Client->Socket, "407 Invalid Argument\n");
975 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
978 sendf(Client->Socket, "200 Add OK\n");
981 sendf(Client->Socket, "402 Poor Guy\n");
984 sendf(Client->Socket, "500 Unknown error\n");
989 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
993 int maxBal = INT_MAX, minBal = INT_MIN;
994 int flagMask = 0, flagVal = 0;
995 int sort = BANK_ITFLAG_SORT_NAME;
996 time_t lastSeenAfter=0, lastSeenBefore=0;
998 int flags; // Iterator flags
999 int balValue; // Balance value for iterator
1000 time_t timeValue; // Time value for iterator
1003 if( Args && strlen(Args) )
1005 char *space = Args, *type, *val;
1009 while(*type == ' ') type ++;
1011 space = strchr(space, ' ');
1012 if(space) *space = '\0';
1015 val = strchr(type, ':');
1022 if( strcmp(type, "min_balance") == 0 ) {
1025 // - Maximum Balance
1026 else if( strcmp(type, "max_balance") == 0 ) {
1030 else if( strcmp(type, "flags") == 0 ) {
1031 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1034 // - Last seen before timestamp
1035 else if( strcmp(type, "last_seen_before") == 0 ) {
1036 lastSeenAfter = atoll(val);
1038 // - Last seen after timestamp
1039 else if( strcmp(type, "last_seen_after") == 0 ) {
1040 lastSeenAfter = atoll(val);
1043 else if( strcmp(type, "sort") == 0 ) {
1044 char *dash = strchr(val, '-');
1049 if( strcmp(val, "name") == 0 ) {
1050 sort = BANK_ITFLAG_SORT_NAME;
1052 else if( strcmp(val, "balance") == 0 ) {
1053 sort = BANK_ITFLAG_SORT_BAL;
1055 else if( strcmp(val, "lastseen") == 0 ) {
1056 sort = BANK_ITFLAG_SORT_LASTSEEN;
1059 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1062 // Handle sort direction
1064 if( strcmp(dash, "desc") == 0 ) {
1065 sort |= BANK_ITFLAG_REVSORT;
1068 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1075 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1082 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1088 *space = ' '; // Repair (to be nice)
1090 while(*space == ' ') space ++;
1096 if( maxBal != INT_MAX ) {
1097 flags = sort|BANK_ITFLAG_MAXBALANCE;
1100 else if( minBal != INT_MIN ) {
1101 flags = sort|BANK_ITFLAG_MINBALANCE;
1108 if( lastSeenBefore ) {
1109 timeValue = lastSeenBefore;
1110 flags |= BANK_ITFLAG_SEENBEFORE;
1112 else if( lastSeenAfter ) {
1113 timeValue = lastSeenAfter;
1114 flags |= BANK_ITFLAG_SEENAFTER;
1119 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1121 // Get return number
1122 while( (i = Bank_IteratorNext(it)) != -1 )
1124 int bal = Bank_GetBalance(i);
1126 if( bal == INT_MIN ) continue;
1128 if( bal < minBal ) continue;
1129 if( bal > maxBal ) continue;
1134 Bank_DelIterator(it);
1137 sendf(Client->Socket, "201 Users %i\n", numRet);
1141 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1143 while( (i = Bank_IteratorNext(it)) != -1 )
1145 int bal = Bank_GetBalance(i);
1147 if( bal == INT_MIN ) continue;
1149 if( bal < minBal ) continue;
1150 if( bal > maxBal ) continue;
1152 _SendUserInfo(Client, i);
1155 Bank_DelIterator(it);
1157 sendf(Client->Socket, "200 List End\n");
1160 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1166 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1167 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1171 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1174 uid = Bank_GetAcctByName(user);
1176 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1178 sendf(Client->Socket, "404 Invalid user\n");
1182 _SendUserInfo(Client, uid);
1185 void _SendUserInfo(tClient *Client, int UserID)
1187 char *type, *disabled="", *door="";
1188 int flags = Bank_GetFlags(UserID);
1190 if( flags & USER_FLAG_INTERNAL ) {
1193 else if( flags & USER_FLAG_COKE ) {
1194 if( flags & USER_FLAG_ADMIN )
1195 type = "coke,admin";
1199 else if( flags & USER_FLAG_ADMIN ) {
1206 if( flags & USER_FLAG_DISABLED )
1207 disabled = ",disabled";
1208 if( flags & USER_FLAG_DOORGROUP )
1211 // TODO: User flags/type
1213 Client->Socket, "202 User %s %i %s%s%s\n",
1214 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1215 type, disabled, door
1219 void Server_Cmd_USERADD(tClient *Client, char *Args)
1224 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1225 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1229 // Check permissions
1230 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1231 sendf(Client->Socket, "403 Not a coke admin\n");
1235 // Try to create user
1236 if( Bank_CreateAcct(username) == -1 ) {
1237 sendf(Client->Socket, "404 User exists\n");
1242 char *thisName = Bank_GetAcctName(Client->UID);
1243 Log_Info("Account '%s' created by '%s'", username, thisName);
1247 sendf(Client->Socket, "200 User Added\n");
1250 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1252 char *username, *flags;
1253 int mask=0, value=0;
1257 if( Server_int_ParseArgs(0, Args, &username, &flags, NULL) ) {
1258 sendf(Client->Socket, "407 USER_FLAGS takes 2 arguments\n");
1262 // Check permissions
1263 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1264 sendf(Client->Socket, "403 Not a coke admin\n");
1269 uid = Bank_GetAcctByName(username);
1271 sendf(Client->Socket, "404 User '%s' not found\n", username);
1276 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1280 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1281 uid, username, mask, value);
1284 Bank_SetFlags(uid, mask, value);
1287 sendf(Client->Socket, "200 User Updated\n");
1290 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1292 char *itemname, *price_str, *description;
1296 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1297 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1301 if( !Client->bIsAuthed ) {
1302 sendf(Client->Socket, "401 Not Authenticated\n");
1306 // Check user permissions
1307 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1308 sendf(Client->Socket, "403 Not in coke\n");
1312 item = _GetItemFromString(itemname);
1314 // TODO: Create item?
1315 sendf(Client->Socket, "406 Bad Item ID\n");
1319 price = atoi(price_str);
1320 if( price <= 0 && price_str[0] != '0' ) {
1321 sendf(CLient->Socket, "407 Invalid price set\n");
1326 item->Name = strdup(description);
1327 item->Price = price;
1333 sendf(Client->Socket, "200 Item updated\n");
1336 // --- INTERNAL HELPERS ---
1337 void Debug(tClient *Client, const char *Format, ...)
1340 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1341 printf("[%i] ", Client->ID);
1342 va_start(args, Format);
1343 vprintf(Format, args);
1348 int sendf(int Socket, const char *Format, ...)
1353 va_start(args, Format);
1354 len = vsnprintf(NULL, 0, Format, args);
1359 va_start(args, Format);
1360 vsnprintf(buf, len+1, Format, args);
1363 #if DEBUG_TRACE_CLIENT
1364 printf("sendf: %s", buf);
1367 return send(Socket, buf, len, 0);
1371 // Takes a series of char *'s in
1373 * \brief Parse space-separated entries into
1375 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1380 va_start(args, ArgStr);
1385 while( (dest = va_arg(args, char **)) )
1391 savedChar = *ArgStr;
1393 while( (dest = va_arg(args, char **)) )
1395 // Trim leading spaces
1396 while( *ArgStr == ' ' || *ArgStr == '\t' )
1399 // ... oops, not enough arguments
1400 if( *ArgStr == '\0' )
1402 // NULL unset arguments
1405 } while( (dest = va_arg(args, char **)) );
1410 if( *ArgStr == '"' )
1415 while( *ArgStr && *ArgStr != '"' )
1422 // Read until a space
1423 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1426 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1432 // Oops, extra arguments, and greedy not set
1433 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1440 *ArgStr = savedChar;
1443 return 0; // Success!
1446 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1453 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1454 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1455 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1456 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1457 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1459 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1471 while( *Str == ' ' ) Str ++; // Eat whitespace
1472 space = strchr(Str, ','); // Find the end of the flag
1478 // Check for inversion/removal
1479 if( *Str == '!' || *Str == '-' ) {
1483 else if( *Str == '+' ) {
1487 // Check flag values
1488 for( i = 0; i < ciNumFlags; i ++ )
1490 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1491 *Mask |= cFLAGS[i].Mask;
1492 *Value &= ~cFLAGS[i].Mask;
1494 *Value |= cFLAGS[i].Value;
1500 if( i == ciNumFlags ) {
1502 strncpy(val, Str, len+1);
1503 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);