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>
17 #include <fcntl.h> // O_*
23 #define DEBUG_TRACE_CLIENT 0
26 #define MAX_CONNECTION_QUEUE 5
27 #define INPUT_BUFFER_SIZE 256
28 #define CLIENT_TIMEOUT 10 // Seconds
30 #define HASH_TYPE SHA1
31 #define HASH_LENGTH 20
33 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
36 typedef struct sClient
38 int Socket; // Client socket ID
41 int bIsTrusted; // Is the connection from a trusted host/port
52 void Server_Start(void);
53 void Server_Cleanup(void);
54 void Server_HandleClient(int Socket, int bTrusted);
55 void Server_ParseClientCommand(tClient *Client, char *CommandString);
57 void Server_Cmd_USER(tClient *Client, char *Args);
58 void Server_Cmd_PASS(tClient *Client, char *Args);
59 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
60 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
61 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
62 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
63 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
64 void Server_Cmd_REFUND(tClient *Client, char *Args);
65 void Server_Cmd_GIVE(tClient *Client, char *Args);
66 void Server_Cmd_DONATE(tClient *Client, char *Args);
67 void Server_Cmd_ADD(tClient *Client, char *Args);
68 void Server_Cmd_SET(tClient *Client, char *Args);
69 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
70 void Server_Cmd_USERINFO(tClient *Client, char *Args);
71 void _SendUserInfo(tClient *Client, int UserID);
72 void Server_Cmd_USERADD(tClient *Client, char *Args);
73 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
74 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args);
76 void Debug(tClient *Client, const char *Format, ...);
77 int sendf(int Socket, const char *Format, ...);
78 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
79 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
83 const struct sClientCommand {
85 void (*Function)(tClient *Client, char *Arguments);
86 } gaServer_Commands[] = {
87 {"USER", Server_Cmd_USER},
88 {"PASS", Server_Cmd_PASS},
89 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
90 {"SETEUSER", Server_Cmd_SETEUSER},
91 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
92 {"ITEM_INFO", Server_Cmd_ITEMINFO},
93 {"DISPENSE", Server_Cmd_DISPENSE},
94 {"REFUND", Server_Cmd_REFUND},
95 {"GIVE", Server_Cmd_GIVE},
96 {"DONATE", Server_Cmd_DONATE},
97 {"ADD", Server_Cmd_ADD},
98 {"SET", Server_Cmd_SET},
99 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
100 {"USER_INFO", Server_Cmd_USERINFO},
101 {"USER_ADD", Server_Cmd_USERADD},
102 {"USER_FLAGS", Server_Cmd_USERFLAGS},
103 {"UPDATE_ITEM", Server_Cmd_UPDATEITEM}
105 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
109 int giServer_Port = 11020;
110 int gbServer_RunInBackground = 0;
111 char *gsServer_LogFile = "/var/log/dispsrv.log";
112 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
114 int giServer_Socket; // Server socket
115 int giServer_NextClientID = 1; // Debug client ID
120 * \brief Open listenting socket and serve connections
122 void Server_Start(void)
125 struct sockaddr_in server_addr, client_addr;
127 atexit(Server_Cleanup);
128 // Ignore SIGPIPE (stops crashes when the client exits early)
129 signal(SIGPIPE, SIG_IGN);
132 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
133 if( giServer_Socket < 0 ) {
134 fprintf(stderr, "ERROR: Unable to create server socket\n");
138 // Make listen address
139 memset(&server_addr, 0, sizeof(server_addr));
140 server_addr.sin_family = AF_INET; // Internet Socket
141 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
142 server_addr.sin_port = htons(giServer_Port); // Port
145 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
146 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
151 // Fork into background
152 if( gbServer_RunInBackground )
154 int newin, newout, newerr;
157 fprintf(stderr, "ERROR: Unable to fork\n");
158 perror("fork background");
166 // - Sort out stdin/stdout
167 newin = open("/dev/null", O_RDONLY);
168 newout = open(gsServer_LogFile, O_CREAT|O_APPEND, 0644);
169 newerr = open(gsServer_ErrorLog, O_CREAT|O_APPEND, 0644);
176 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
177 fprintf(stderr, "ERROR: Unable to listen to socket\n");
182 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
186 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
188 fprintf(fp, "%i", getpid());
195 uint len = sizeof(client_addr);
198 // Accept a connection
199 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
200 if(client_socket < 0) {
201 fprintf(stderr, "ERROR: Unable to accept client connection\n");
205 // Set a timeout on the user conneciton
208 tv.tv_sec = CLIENT_TIMEOUT;
210 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
212 perror("setsockopt");
217 // Debug: Print the connection string
218 if(giDebugLevel >= 2) {
219 char ipstr[INET_ADDRSTRLEN];
220 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
221 printf("Client connection from %s:%i\n",
222 ipstr, ntohs(client_addr.sin_port));
225 // Doesn't matter what, localhost is trusted
226 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
229 // Trusted Connections
230 if( ntohs(client_addr.sin_port) < 1024 )
232 // TODO: Make this runtime configurable
233 switch( ntohl( client_addr.sin_addr.s_addr ) )
235 case 0x7F000001: // 127.0.0.1 localhost
236 // case 0x825F0D00: // 130.95.13.0
237 case 0x825F0D07: // 130.95.13.7 motsugo
238 case 0x825F0D11: // 130.95.13.17 mermaid
239 case 0x825F0D12: // 130.95.13.18 mussel
240 case 0x825F0D17: // 130.95.13.23 martello
241 case 0x825F0D2A: // 130.95.13.42 meersau
242 case 0x825F0D42: // 130.95.13.66 heathred
250 // TODO: Multithread this?
251 Server_HandleClient(client_socket, bTrusted);
253 close(client_socket);
257 void Server_Cleanup(void)
259 printf("\nClose(%i)\n", giServer_Socket);
260 close(giServer_Socket);
261 unlink("/var/run/dispsrv.pid");
265 * \brief Reads from a client socket and parses the command strings
266 * \param Socket Client socket number/handle
267 * \param bTrusted Is the client trusted?
269 void Server_HandleClient(int Socket, int bTrusted)
271 char inbuf[INPUT_BUFFER_SIZE];
273 int remspace = INPUT_BUFFER_SIZE-1;
277 memset(&clientInfo, 0, sizeof(clientInfo));
279 // Initialise Client info
280 clientInfo.Socket = Socket;
281 clientInfo.ID = giServer_NextClientID ++;
282 clientInfo.bIsTrusted = bTrusted;
283 clientInfo.EffectiveUID = -1;
288 * - The `buf` and `remspace` variables allow a line to span several
289 * calls to recv(), if a line is not completed in one recv() call
290 * it is saved to the beginning of `inbuf` and `buf` is updated to
293 // TODO: Use select() instead (to give a timeout)
294 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
297 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
301 while( (eol = strchr(start, '\n')) )
305 Server_ParseClientCommand(&clientInfo, start);
310 // Check if there was an incomplete line
311 if( *start != '\0' ) {
312 int tailBytes = bytes - (start-buf);
313 // Roll back in buffer
314 memcpy(inbuf, start, tailBytes);
315 remspace -= tailBytes;
317 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
319 remspace = INPUT_BUFFER_SIZE - 1;
324 remspace = INPUT_BUFFER_SIZE - 1;
330 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
334 if(giDebugLevel >= 2) {
335 printf("Client %i: Disconnected\n", clientInfo.ID);
340 * \brief Parses a client command and calls the required helper function
341 * \param Client Pointer to client state structure
342 * \param CommandString Command from client (single line of the command)
343 * \return Heap String to return to the client
345 void Server_ParseClientCommand(tClient *Client, char *CommandString)
347 char *command, *args;
350 if( giDebugLevel >= 2 )
351 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
353 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
355 if( command == NULL ) return ;
356 // Is this an error? (just ignore for now)
361 for( i = 0; i < NUM_COMMANDS; i++ )
363 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
364 if( giDebugLevel >= 2 )
365 Debug(Client, "CMD %s - \"%s\"", command, args);
366 gaServer_Commands[i].Function(Client, args);
371 sendf(Client->Socket, "400 Unknown Command\n");
378 * \brief Set client username
380 * Usage: USER <username>
382 void Server_Cmd_USER(tClient *Client, char *Args)
386 if( Server_int_ParseArgs(0, Args, &username, NULL) )
388 sendf(Client->Socket, "407 USER takes 1 argument\n");
394 Debug(Client, "Authenticating as '%s'", username);
398 free(Client->Username);
399 Client->Username = strdup(username);
402 // Create a salt (that changes if the username is changed)
403 // Yes, I know, I'm a little paranoid, but who isn't?
404 Client->Salt[0] = 0x21 + (rand()&0x3F);
405 Client->Salt[1] = 0x21 + (rand()&0x3F);
406 Client->Salt[2] = 0x21 + (rand()&0x3F);
407 Client->Salt[3] = 0x21 + (rand()&0x3F);
408 Client->Salt[4] = 0x21 + (rand()&0x3F);
409 Client->Salt[5] = 0x21 + (rand()&0x3F);
410 Client->Salt[6] = 0x21 + (rand()&0x3F);
411 Client->Salt[7] = 0x21 + (rand()&0x3F);
413 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
414 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
416 sendf(Client->Socket, "100 User Set\n");
421 * \brief Authenticate as a user
425 void Server_Cmd_PASS(tClient *Client, char *Args)
430 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
432 sendf(Client->Socket, "407 PASS takes 1 argument\n");
436 // Pass on to cokebank
437 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
439 if( Client->UID == -1 ) {
440 sendf(Client->Socket, "401 Auth Failure\n");
444 flags = Bank_GetFlags(Client->UID);
445 if( flags & USER_FLAG_DISABLED ) {
447 sendf(Client->Socket, "403 Account Disabled\n");
450 if( flags & USER_FLAG_INTERNAL ) {
452 sendf(Client->Socket, "403 Internal account\n");
456 Client->bIsAuthed = 1;
457 sendf(Client->Socket, "200 Auth OK\n");
461 * \brief Authenticate as a user without a password
463 * Usage: AUTOAUTH <user>
465 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
470 if( Server_int_ParseArgs(0, Args, &username, NULL) )
472 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
477 if( !Client->bIsTrusted ) {
479 Debug(Client, "Untrusted client attempting to AUTOAUTH");
480 sendf(Client->Socket, "401 Untrusted\n");
485 Client->UID = Bank_GetAcctByName( username, 0 );
486 if( Client->UID < 0 ) {
488 Debug(Client, "Unknown user '%s'", username);
489 sendf(Client->Socket, "403 Auth Failure\n");
493 userflags = Bank_GetFlags(Client->UID);
494 // You can't be an internal account
495 if( userflags & USER_FLAG_INTERNAL ) {
497 Debug(Client, "Autoauth as '%s', not allowed", username);
499 sendf(Client->Socket, "403 Account is internal\n");
504 if( userflags & USER_FLAG_DISABLED ) {
506 sendf(Client->Socket, "403 Account disabled\n");
510 Client->bIsAuthed = 1;
513 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
515 sendf(Client->Socket, "200 Auth OK\n");
519 * \brief Set effective user
521 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
524 int eUserFlags, userFlags;
526 if( Server_int_ParseArgs(0, Args, &username, NULL) )
528 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
532 if( !strlen(Args) ) {
533 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
537 // Check authentication
538 if( !Client->bIsAuthed ) {
539 sendf(Client->Socket, "401 Not Authenticated\n");
543 // Check user permissions
544 userFlags = Bank_GetFlags(Client->UID);
545 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
546 sendf(Client->Socket, "403 Not in coke\n");
551 Client->EffectiveUID = Bank_GetAcctByName(username, 0);
552 if( Client->EffectiveUID == -1 ) {
553 sendf(Client->Socket, "404 User not found\n");
557 // You can't be an internal account
558 if( !(userFlags & USER_FLAG_ADMIN) )
560 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
561 if( eUserFlags & USER_FLAG_INTERNAL ) {
562 Client->EffectiveUID = -1;
563 sendf(Client->Socket, "404 User not found\n");
566 // Disabled only avaliable to admins
567 if( eUserFlags & USER_FLAG_DISABLED ) {
568 Client->EffectiveUID = -1;
569 sendf(Client->Socket, "403 Account disabled\n");
574 sendf(Client->Socket, "200 User set\n");
578 * \brief Send an item status to the client
579 * \param Client Who to?
580 * \param Item Item to send
582 void Server_int_SendItem(tClient *Client, tItem *Item)
584 char *status = "avail";
586 if( Item->Handler->CanDispense )
588 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
590 case 0: status = "avail"; break;
591 case 1: status = "sold"; break;
593 case -1: status = "error"; break;
597 // KNOWN HACK: Naming a slot 'dead' disables it
598 if( strcmp(Item->Name, "dead") == 0 )
599 status = "sold"; // Another status?
601 sendf(Client->Socket,
602 "202 Item %s:%i %s %i %s\n",
603 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
608 * \brief Enumerate the items that the server knows about
610 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
614 if( Args != NULL && strlen(Args) ) {
615 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
621 for( i = 0; i < giNumItems; i ++ ) {
622 if( gaItems[i].bHidden ) continue;
626 sendf(Client->Socket, "201 Items %i\n", count);
628 for( i = 0; i < giNumItems; i ++ ) {
629 if( gaItems[i].bHidden ) continue;
630 Server_int_SendItem( Client, &gaItems[i] );
633 sendf(Client->Socket, "200 List end\n");
636 tItem *_GetItemFromString(char *String)
640 char *colon = strchr(String, ':');
652 for( i = 0; i < giNumHandlers; i ++ )
654 if( strcmp(gaHandlers[i]->Name, type) == 0) {
655 handler = gaHandlers[i];
664 for( i = 0; i < giNumItems; i ++ )
666 if( gaItems[i].Handler != handler ) continue;
667 if( gaItems[i].ID != num ) continue;
674 * \brief Fetch information on a specific item
676 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
681 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
682 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
685 item = _GetItemFromString(Args);
688 sendf(Client->Socket, "406 Bad Item ID\n");
692 Server_int_SendItem( Client, item );
695 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
702 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
703 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
707 if( !Client->bIsAuthed ) {
708 sendf(Client->Socket, "401 Not Authenticated\n");
712 item = _GetItemFromString(itemname);
714 sendf(Client->Socket, "406 Bad Item ID\n");
718 if( Client->EffectiveUID != -1 ) {
719 uid = Client->EffectiveUID;
725 switch( ret = DispenseItem( Client->UID, uid, item ) )
727 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
728 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
729 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
731 sendf(Client->Socket, "500 Dispense Error\n");
736 void Server_Cmd_REFUND(tClient *Client, char *Args)
739 int uid, price_override = 0;
740 char *username, *itemname, *price_str;
742 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
743 if( !itemname || price_str ) {
744 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
749 if( !Client->bIsAuthed ) {
750 sendf(Client->Socket, "401 Not Authenticated\n");
754 // Check user permissions
755 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
756 sendf(Client->Socket, "403 Not in coke\n");
760 uid = Bank_GetAcctByName(username, 0);
762 sendf(Client->Socket, "404 Unknown user\n");
766 item = _GetItemFromString(itemname);
768 sendf(Client->Socket, "406 Bad Item ID\n");
773 price_override = atoi(price_str);
775 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
777 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
779 sendf(Client->Socket, "500 Dispense Error\n");
784 void Server_Cmd_GIVE(tClient *Client, char *Args)
786 char *recipient, *ammount, *reason;
791 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
792 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
797 if( !Client->bIsAuthed ) {
798 sendf(Client->Socket, "401 Not Authenticated\n");
803 uid = Bank_GetAcctByName(recipient, 0);
805 sendf(Client->Socket, "404 Invalid target user\n");
809 // You can't alter an internal account
810 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
811 // sendf(Client->Socket, "404 Invalid target user\n");
816 iAmmount = atoi(ammount);
817 if( iAmmount <= 0 ) {
818 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
822 if( Client->EffectiveUID != -1 ) {
823 thisUid = Client->EffectiveUID;
826 thisUid = Client->UID;
830 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
833 sendf(Client->Socket, "200 Give OK\n");
836 sendf(Client->Socket, "402 Poor You\n");
839 sendf(Client->Socket, "500 Unknown error\n");
844 void Server_Cmd_DONATE(tClient *Client, char *Args)
846 char *ammount, *reason;
851 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
852 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
856 if( !Client->bIsAuthed ) {
857 sendf(Client->Socket, "401 Not Authenticated\n");
862 iAmmount = atoi(ammount);
863 if( iAmmount <= 0 ) {
864 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
868 // Handle effective users
869 if( Client->EffectiveUID != -1 ) {
870 thisUid = Client->EffectiveUID;
873 thisUid = Client->UID;
877 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
880 sendf(Client->Socket, "200 Give OK\n");
883 sendf(Client->Socket, "402 Poor You\n");
886 sendf(Client->Socket, "500 Unknown error\n");
891 void Server_Cmd_ADD(tClient *Client, char *Args)
893 char *user, *ammount, *reason;
897 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
898 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
902 if( !Client->bIsAuthed ) {
903 sendf(Client->Socket, "401 Not Authenticated\n");
907 // Check user permissions
908 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
909 sendf(Client->Socket, "403 Not in coke\n");
914 uid = Bank_GetAcctByName(user, 0);
916 sendf(Client->Socket, "404 Invalid user\n");
920 // You can't alter an internal account
921 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
923 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
924 sendf(Client->Socket, "404 Invalid user\n");
927 // TODO: Maybe disallow changes to disabled?
931 iAmmount = atoi(ammount);
932 if( iAmmount == 0 && ammount[0] != '0' ) {
933 sendf(Client->Socket, "407 Invalid Argument\n");
938 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
941 sendf(Client->Socket, "200 Add OK\n");
944 sendf(Client->Socket, "402 Poor Guy\n");
947 sendf(Client->Socket, "500 Unknown error\n");
952 void Server_Cmd_SET(tClient *Client, char *Args)
954 char *user, *ammount, *reason;
958 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
959 sendf(Client->Socket, "407 SET takes 3 arguments\n");
963 if( !Client->bIsAuthed ) {
964 sendf(Client->Socket, "401 Not Authenticated\n");
968 // Check user permissions
969 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
970 sendf(Client->Socket, "403 Not an admin\n");
975 uid = Bank_GetAcctByName(user, 0);
977 sendf(Client->Socket, "404 Invalid user\n");
982 iAmmount = atoi(ammount);
983 if( iAmmount == 0 && ammount[0] != '0' ) {
984 sendf(Client->Socket, "407 Invalid Argument\n");
989 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
992 sendf(Client->Socket, "200 Add OK\n");
995 sendf(Client->Socket, "402 Poor Guy\n");
998 sendf(Client->Socket, "500 Unknown error\n");
1003 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1007 int maxBal = INT_MAX, minBal = INT_MIN;
1008 int flagMask = 0, flagVal = 0;
1009 int sort = BANK_ITFLAG_SORT_NAME;
1010 time_t lastSeenAfter=0, lastSeenBefore=0;
1012 int flags; // Iterator flags
1013 int balValue; // Balance value for iterator
1014 time_t timeValue; // Time value for iterator
1017 if( Args && strlen(Args) )
1019 char *space = Args, *type, *val;
1023 while(*type == ' ') type ++;
1025 space = strchr(space, ' ');
1026 if(space) *space = '\0';
1029 val = strchr(type, ':');
1036 if( strcmp(type, "min_balance") == 0 ) {
1039 // - Maximum Balance
1040 else if( strcmp(type, "max_balance") == 0 ) {
1044 else if( strcmp(type, "flags") == 0 ) {
1045 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1048 // - Last seen before timestamp
1049 else if( strcmp(type, "last_seen_before") == 0 ) {
1050 lastSeenAfter = atoll(val);
1052 // - Last seen after timestamp
1053 else if( strcmp(type, "last_seen_after") == 0 ) {
1054 lastSeenAfter = atoll(val);
1057 else if( strcmp(type, "sort") == 0 ) {
1058 char *dash = strchr(val, '-');
1063 if( strcmp(val, "name") == 0 ) {
1064 sort = BANK_ITFLAG_SORT_NAME;
1066 else if( strcmp(val, "balance") == 0 ) {
1067 sort = BANK_ITFLAG_SORT_BAL;
1069 else if( strcmp(val, "lastseen") == 0 ) {
1070 sort = BANK_ITFLAG_SORT_LASTSEEN;
1073 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1076 // Handle sort direction
1078 if( strcmp(dash, "desc") == 0 ) {
1079 sort |= BANK_ITFLAG_REVSORT;
1082 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1089 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1096 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1102 *space = ' '; // Repair (to be nice)
1104 while(*space == ' ') space ++;
1110 if( maxBal != INT_MAX ) {
1111 flags = sort|BANK_ITFLAG_MAXBALANCE;
1114 else if( minBal != INT_MIN ) {
1115 flags = sort|BANK_ITFLAG_MINBALANCE;
1122 if( lastSeenBefore ) {
1123 timeValue = lastSeenBefore;
1124 flags |= BANK_ITFLAG_SEENBEFORE;
1126 else if( lastSeenAfter ) {
1127 timeValue = lastSeenAfter;
1128 flags |= BANK_ITFLAG_SEENAFTER;
1133 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1135 // Get return number
1136 while( (i = Bank_IteratorNext(it)) != -1 )
1138 int bal = Bank_GetBalance(i);
1140 if( bal == INT_MIN ) continue;
1142 if( bal < minBal ) continue;
1143 if( bal > maxBal ) continue;
1148 Bank_DelIterator(it);
1151 sendf(Client->Socket, "201 Users %i\n", numRet);
1155 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1157 while( (i = Bank_IteratorNext(it)) != -1 )
1159 int bal = Bank_GetBalance(i);
1161 if( bal == INT_MIN ) continue;
1163 if( bal < minBal ) continue;
1164 if( bal > maxBal ) continue;
1166 _SendUserInfo(Client, i);
1169 Bank_DelIterator(it);
1171 sendf(Client->Socket, "200 List End\n");
1174 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1180 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1181 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1185 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1188 uid = Bank_GetAcctByName(user, 0);
1190 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1192 sendf(Client->Socket, "404 Invalid user\n");
1196 _SendUserInfo(Client, uid);
1199 void _SendUserInfo(tClient *Client, int UserID)
1201 char *type, *disabled="", *door="";
1202 int flags = Bank_GetFlags(UserID);
1204 if( flags & USER_FLAG_INTERNAL ) {
1207 else if( flags & USER_FLAG_COKE ) {
1208 if( flags & USER_FLAG_ADMIN )
1209 type = "coke,admin";
1213 else if( flags & USER_FLAG_ADMIN ) {
1220 if( flags & USER_FLAG_DISABLED )
1221 disabled = ",disabled";
1222 if( flags & USER_FLAG_DOORGROUP )
1225 // TODO: User flags/type
1227 Client->Socket, "202 User %s %i %s%s%s\n",
1228 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1229 type, disabled, door
1233 void Server_Cmd_USERADD(tClient *Client, char *Args)
1238 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1239 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1243 // Check authentication
1244 if( !Client->bIsAuthed ) {
1245 sendf(Client->Socket, "401 Not Authenticated\n");
1249 // Check permissions
1250 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1251 sendf(Client->Socket, "403 Not a coke admin\n");
1255 // Try to create user
1256 if( Bank_CreateAcct(username) == -1 ) {
1257 sendf(Client->Socket, "404 User exists\n");
1262 char *thisName = Bank_GetAcctName(Client->UID);
1263 Log_Info("Account '%s' created by '%s'", username, thisName);
1267 sendf(Client->Socket, "200 User Added\n");
1270 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1272 char *username, *flags, *reason=NULL;
1273 int mask=0, value=0;
1277 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1279 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1285 // Check authentication
1286 if( !Client->bIsAuthed ) {
1287 sendf(Client->Socket, "401 Not Authenticated\n");
1291 // Check permissions
1292 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1293 sendf(Client->Socket, "403 Not a coke admin\n");
1298 uid = Bank_GetAcctByName(username, 0);
1300 sendf(Client->Socket, "404 User '%s' not found\n", username);
1305 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1309 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1310 uid, username, mask, value);
1313 Bank_SetFlags(uid, mask, value);
1316 Log_Info("Updated '%s' with flag set '%s' - Reason: %s",
1317 username, flags, reason);
1320 sendf(Client->Socket, "200 User Updated\n");
1323 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1325 char *itemname, *price_str, *description;
1329 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1330 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1334 if( !Client->bIsAuthed ) {
1335 sendf(Client->Socket, "401 Not Authenticated\n");
1339 // Check user permissions
1340 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1341 sendf(Client->Socket, "403 Not in coke\n");
1345 item = _GetItemFromString(itemname);
1347 // TODO: Create item?
1348 sendf(Client->Socket, "406 Bad Item ID\n");
1352 price = atoi(price_str);
1353 if( price <= 0 && price_str[0] != '0' ) {
1354 sendf(Client->Socket, "407 Invalid price set\n");
1357 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1361 sendf(Client->Socket, "200 Item updated\n");
1368 // --- INTERNAL HELPERS ---
1369 void Debug(tClient *Client, const char *Format, ...)
1372 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1373 printf("[%i] ", Client->ID);
1374 va_start(args, Format);
1375 vprintf(Format, args);
1380 int sendf(int Socket, const char *Format, ...)
1385 va_start(args, Format);
1386 len = vsnprintf(NULL, 0, Format, args);
1391 va_start(args, Format);
1392 vsnprintf(buf, len+1, Format, args);
1395 #if DEBUG_TRACE_CLIENT
1396 printf("sendf: %s", buf);
1399 return send(Socket, buf, len, 0);
1403 // Takes a series of char *'s in
1405 * \brief Parse space-separated entries into
1407 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1412 va_start(args, ArgStr);
1417 while( (dest = va_arg(args, char **)) )
1423 savedChar = *ArgStr;
1425 while( (dest = va_arg(args, char **)) )
1427 // Trim leading spaces
1428 while( *ArgStr == ' ' || *ArgStr == '\t' )
1431 // ... oops, not enough arguments
1432 if( *ArgStr == '\0' )
1434 // NULL unset arguments
1437 } while( (dest = va_arg(args, char **)) );
1442 if( *ArgStr == '"' )
1447 while( *ArgStr && *ArgStr != '"' )
1454 // Read until a space
1455 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1458 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1464 // Oops, extra arguments, and greedy not set
1465 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1472 *ArgStr = savedChar;
1475 return 0; // Success!
1478 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1485 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1486 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1487 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1488 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1489 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1491 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1503 while( *Str == ' ' ) Str ++; // Eat whitespace
1504 space = strchr(Str, ','); // Find the end of the flag
1510 // Check for inversion/removal
1511 if( *Str == '!' || *Str == '-' ) {
1515 else if( *Str == '+' ) {
1519 // Check flag values
1520 for( i = 0; i < ciNumFlags; i ++ )
1522 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1523 *Mask |= cFLAGS[i].Mask;
1524 *Value &= ~cFLAGS[i].Mask;
1526 *Value |= cFLAGS[i].Value;
1532 if( i == ciNumFlags ) {
1534 strncpy(val, Str, len+1);
1535 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);