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
24 #define HACK_NO_REFUNDS 1
27 #define MAX_CONNECTION_QUEUE 5
28 #define INPUT_BUFFER_SIZE 256
29 #define CLIENT_TIMEOUT 10 // Seconds
31 #define HASH_TYPE SHA1
32 #define HASH_LENGTH 20
34 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
37 typedef struct sClient
39 int Socket; // Client socket ID
42 int bIsTrusted; // Is the connection from a trusted host/port
53 void Server_Start(void);
54 void Server_Cleanup(void);
55 void Server_HandleClient(int Socket, int bTrusted);
56 void Server_ParseClientCommand(tClient *Client, char *CommandString);
58 void Server_Cmd_USER(tClient *Client, char *Args);
59 void Server_Cmd_PASS(tClient *Client, char *Args);
60 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
61 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
62 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
63 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
64 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
65 void Server_Cmd_REFUND(tClient *Client, char *Args);
66 void Server_Cmd_GIVE(tClient *Client, char *Args);
67 void Server_Cmd_DONATE(tClient *Client, char *Args);
68 void Server_Cmd_ADD(tClient *Client, char *Args);
69 void Server_Cmd_SET(tClient *Client, char *Args);
70 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
71 void Server_Cmd_USERINFO(tClient *Client, char *Args);
72 void _SendUserInfo(tClient *Client, int UserID);
73 void Server_Cmd_USERADD(tClient *Client, char *Args);
74 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
75 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args);
77 void Debug(tClient *Client, const char *Format, ...);
78 int sendf(int Socket, const char *Format, ...);
79 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
80 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
84 const struct sClientCommand {
86 void (*Function)(tClient *Client, char *Arguments);
87 } gaServer_Commands[] = {
88 {"USER", Server_Cmd_USER},
89 {"PASS", Server_Cmd_PASS},
90 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
91 {"SETEUSER", Server_Cmd_SETEUSER},
92 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
93 {"ITEM_INFO", Server_Cmd_ITEMINFO},
94 {"DISPENSE", Server_Cmd_DISPENSE},
95 {"REFUND", Server_Cmd_REFUND},
96 {"GIVE", Server_Cmd_GIVE},
97 {"DONATE", Server_Cmd_DONATE},
98 {"ADD", Server_Cmd_ADD},
99 {"SET", Server_Cmd_SET},
100 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
101 {"USER_INFO", Server_Cmd_USERINFO},
102 {"USER_ADD", Server_Cmd_USERADD},
103 {"USER_FLAGS", Server_Cmd_USERFLAGS},
104 {"UPDATE_ITEM", Server_Cmd_UPDATEITEM}
106 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
110 int giServer_Port = 11020;
111 int gbServer_RunInBackground = 0;
112 char *gsServer_LogFile = "/var/log/dispsrv.log";
113 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
115 int giServer_Socket; // Server socket
116 int giServer_NextClientID = 1; // Debug client ID
121 * \brief Open listenting socket and serve connections
123 void Server_Start(void)
126 struct sockaddr_in server_addr, client_addr;
128 atexit(Server_Cleanup);
129 // Ignore SIGPIPE (stops crashes when the client exits early)
130 signal(SIGPIPE, SIG_IGN);
133 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
134 if( giServer_Socket < 0 ) {
135 fprintf(stderr, "ERROR: Unable to create server socket\n");
139 // Make listen address
140 memset(&server_addr, 0, sizeof(server_addr));
141 server_addr.sin_family = AF_INET; // Internet Socket
142 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
143 server_addr.sin_port = htons(giServer_Port); // Port
146 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
147 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
152 // Fork into background
153 if( gbServer_RunInBackground )
155 int newin, newout, newerr;
158 fprintf(stderr, "ERROR: Unable to fork\n");
159 perror("fork background");
167 // - Sort out stdin/stdout
168 newin = open("/dev/null", O_RDONLY);
169 newout = open(gsServer_LogFile, O_CREAT|O_APPEND, 0644);
170 newerr = open(gsServer_ErrorLog, O_CREAT|O_APPEND, 0644);
176 // Start the helper thread
177 StartPeriodicThread();
180 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
181 fprintf(stderr, "ERROR: Unable to listen to socket\n");
186 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
190 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
192 fprintf(fp, "%i", getpid());
199 uint len = sizeof(client_addr);
202 // Accept a connection
203 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
204 if(client_socket < 0) {
205 fprintf(stderr, "ERROR: Unable to accept client connection\n");
209 // Set a timeout on the user conneciton
212 tv.tv_sec = CLIENT_TIMEOUT;
214 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
216 perror("setsockopt");
221 // Debug: Print the connection string
222 if(giDebugLevel >= 2) {
223 char ipstr[INET_ADDRSTRLEN];
224 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
225 printf("Client connection from %s:%i\n",
226 ipstr, ntohs(client_addr.sin_port));
229 // Doesn't matter what, localhost is trusted
230 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
233 // Trusted Connections
234 if( ntohs(client_addr.sin_port) < 1024 )
236 // TODO: Make this runtime configurable
237 switch( ntohl( client_addr.sin_addr.s_addr ) )
239 case 0x7F000001: // 127.0.0.1 localhost
240 // case 0x825F0D00: // 130.95.13.0
241 case 0x825F0D07: // 130.95.13.7 motsugo
242 case 0x825F0D11: // 130.95.13.17 mermaid
243 case 0x825F0D12: // 130.95.13.18 mussel
244 case 0x825F0D17: // 130.95.13.23 martello
245 case 0x825F0D2A: // 130.95.13.42 meersau
246 case 0x825F0D42: // 130.95.13.66 heathred
254 // TODO: Multithread this?
255 Server_HandleClient(client_socket, bTrusted);
257 close(client_socket);
261 void Server_Cleanup(void)
263 printf("\nClose(%i)\n", giServer_Socket);
264 close(giServer_Socket);
265 unlink("/var/run/dispsrv.pid");
269 * \brief Reads from a client socket and parses the command strings
270 * \param Socket Client socket number/handle
271 * \param bTrusted Is the client trusted?
273 void Server_HandleClient(int Socket, int bTrusted)
275 char inbuf[INPUT_BUFFER_SIZE];
277 int remspace = INPUT_BUFFER_SIZE-1;
281 memset(&clientInfo, 0, sizeof(clientInfo));
283 // Initialise Client info
284 clientInfo.Socket = Socket;
285 clientInfo.ID = giServer_NextClientID ++;
286 clientInfo.bIsTrusted = bTrusted;
287 clientInfo.EffectiveUID = -1;
292 * - The `buf` and `remspace` variables allow a line to span several
293 * calls to recv(), if a line is not completed in one recv() call
294 * it is saved to the beginning of `inbuf` and `buf` is updated to
297 // TODO: Use select() instead (to give a timeout)
298 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
301 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
305 while( (eol = strchr(start, '\n')) )
309 Server_ParseClientCommand(&clientInfo, start);
314 // Check if there was an incomplete line
315 if( *start != '\0' ) {
316 int tailBytes = bytes - (start-buf);
317 // Roll back in buffer
318 memcpy(inbuf, start, tailBytes);
319 remspace -= tailBytes;
321 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
323 remspace = INPUT_BUFFER_SIZE - 1;
328 remspace = INPUT_BUFFER_SIZE - 1;
334 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
338 if(giDebugLevel >= 2) {
339 printf("Client %i: Disconnected\n", clientInfo.ID);
344 * \brief Parses a client command and calls the required helper function
345 * \param Client Pointer to client state structure
346 * \param CommandString Command from client (single line of the command)
347 * \return Heap String to return to the client
349 void Server_ParseClientCommand(tClient *Client, char *CommandString)
351 char *command, *args;
354 if( giDebugLevel >= 2 )
355 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
357 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
359 if( command == NULL ) return ;
360 // Is this an error? (just ignore for now)
365 for( i = 0; i < NUM_COMMANDS; i++ )
367 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
368 if( giDebugLevel >= 2 )
369 Debug(Client, "CMD %s - \"%s\"", command, args);
370 gaServer_Commands[i].Function(Client, args);
375 sendf(Client->Socket, "400 Unknown Command\n");
382 * \brief Set client username
384 * Usage: USER <username>
386 void Server_Cmd_USER(tClient *Client, char *Args)
390 if( Server_int_ParseArgs(0, Args, &username, NULL) )
392 sendf(Client->Socket, "407 USER takes 1 argument\n");
398 Debug(Client, "Authenticating as '%s'", username);
402 free(Client->Username);
403 Client->Username = strdup(username);
406 // Create a salt (that changes if the username is changed)
407 // Yes, I know, I'm a little paranoid, but who isn't?
408 Client->Salt[0] = 0x21 + (rand()&0x3F);
409 Client->Salt[1] = 0x21 + (rand()&0x3F);
410 Client->Salt[2] = 0x21 + (rand()&0x3F);
411 Client->Salt[3] = 0x21 + (rand()&0x3F);
412 Client->Salt[4] = 0x21 + (rand()&0x3F);
413 Client->Salt[5] = 0x21 + (rand()&0x3F);
414 Client->Salt[6] = 0x21 + (rand()&0x3F);
415 Client->Salt[7] = 0x21 + (rand()&0x3F);
417 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
418 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
420 sendf(Client->Socket, "100 User Set\n");
425 * \brief Authenticate as a user
429 void Server_Cmd_PASS(tClient *Client, char *Args)
434 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
436 sendf(Client->Socket, "407 PASS takes 1 argument\n");
440 // Pass on to cokebank
441 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
443 if( Client->UID == -1 ) {
444 sendf(Client->Socket, "401 Auth Failure\n");
448 flags = Bank_GetFlags(Client->UID);
449 if( flags & USER_FLAG_DISABLED ) {
451 sendf(Client->Socket, "403 Account Disabled\n");
454 if( flags & USER_FLAG_INTERNAL ) {
456 sendf(Client->Socket, "403 Internal account\n");
460 Client->bIsAuthed = 1;
461 sendf(Client->Socket, "200 Auth OK\n");
465 * \brief Authenticate as a user without a password
467 * Usage: AUTOAUTH <user>
469 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
474 if( Server_int_ParseArgs(0, Args, &username, NULL) )
476 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
481 if( !Client->bIsTrusted ) {
483 Debug(Client, "Untrusted client attempting to AUTOAUTH");
484 sendf(Client->Socket, "401 Untrusted\n");
489 Client->UID = Bank_GetAcctByName( username, 0 );
490 if( Client->UID < 0 ) {
492 Debug(Client, "Unknown user '%s'", username);
493 sendf(Client->Socket, "403 Auth Failure\n");
497 userflags = Bank_GetFlags(Client->UID);
498 // You can't be an internal account
499 if( userflags & USER_FLAG_INTERNAL ) {
501 Debug(Client, "Autoauth as '%s', not allowed", username);
503 sendf(Client->Socket, "403 Account is internal\n");
508 if( userflags & USER_FLAG_DISABLED ) {
510 sendf(Client->Socket, "403 Account disabled\n");
514 Client->bIsAuthed = 1;
517 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
519 sendf(Client->Socket, "200 Auth OK\n");
523 * \brief Set effective user
525 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
528 int eUserFlags, userFlags;
530 if( Server_int_ParseArgs(0, Args, &username, NULL) )
532 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
536 if( !strlen(Args) ) {
537 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
541 // Check authentication
542 if( !Client->bIsAuthed ) {
543 sendf(Client->Socket, "401 Not Authenticated\n");
547 // Check user permissions
548 userFlags = Bank_GetFlags(Client->UID);
549 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
550 sendf(Client->Socket, "403 Not in coke\n");
555 Client->EffectiveUID = Bank_GetAcctByName(username, 0);
556 if( Client->EffectiveUID == -1 ) {
557 sendf(Client->Socket, "404 User not found\n");
561 // You can't be an internal account
562 if( !(userFlags & USER_FLAG_ADMIN) )
564 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
565 if( eUserFlags & USER_FLAG_INTERNAL ) {
566 Client->EffectiveUID = -1;
567 sendf(Client->Socket, "404 User not found\n");
570 // Disabled only avaliable to admins
571 if( eUserFlags & USER_FLAG_DISABLED ) {
572 Client->EffectiveUID = -1;
573 sendf(Client->Socket, "403 Account disabled\n");
578 sendf(Client->Socket, "200 User set\n");
582 * \brief Send an item status to the client
583 * \param Client Who to?
584 * \param Item Item to send
586 void Server_int_SendItem(tClient *Client, tItem *Item)
588 char *status = "avail";
590 if( Item->Handler->CanDispense )
592 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
594 case 0: status = "avail"; break;
595 case 1: status = "sold"; break;
597 case -1: status = "error"; break;
601 // KNOWN HACK: Naming a slot 'dead' disables it
602 if( strcmp(Item->Name, "dead") == 0 )
603 status = "sold"; // Another status?
605 sendf(Client->Socket,
606 "202 Item %s:%i %s %i %s\n",
607 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
612 * \brief Enumerate the items that the server knows about
614 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
618 if( Args != NULL && strlen(Args) ) {
619 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
625 for( i = 0; i < giNumItems; i ++ ) {
626 if( gaItems[i].bHidden ) continue;
630 sendf(Client->Socket, "201 Items %i\n", count);
632 for( i = 0; i < giNumItems; i ++ ) {
633 if( gaItems[i].bHidden ) continue;
634 Server_int_SendItem( Client, &gaItems[i] );
637 sendf(Client->Socket, "200 List end\n");
640 tItem *_GetItemFromString(char *String)
644 char *colon = strchr(String, ':');
656 for( i = 0; i < giNumHandlers; i ++ )
658 if( strcmp(gaHandlers[i]->Name, type) == 0) {
659 handler = gaHandlers[i];
668 for( i = 0; i < giNumItems; i ++ )
670 if( gaItems[i].Handler != handler ) continue;
671 if( gaItems[i].ID != num ) continue;
678 * \brief Fetch information on a specific item
680 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
685 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
686 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
689 item = _GetItemFromString(Args);
692 sendf(Client->Socket, "406 Bad Item ID\n");
696 Server_int_SendItem( Client, item );
699 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
706 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
707 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
711 if( !Client->bIsAuthed ) {
712 sendf(Client->Socket, "401 Not Authenticated\n");
716 item = _GetItemFromString(itemname);
718 sendf(Client->Socket, "406 Bad Item ID\n");
722 if( Client->EffectiveUID != -1 ) {
723 uid = Client->EffectiveUID;
729 switch( ret = DispenseItem( Client->UID, uid, item ) )
731 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
732 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
733 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
735 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
740 void Server_Cmd_REFUND(tClient *Client, char *Args)
743 int uid, price_override = 0;
744 char *username, *itemname, *price_str;
746 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
747 if( !itemname || price_str ) {
748 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
753 if( !Client->bIsAuthed ) {
754 sendf(Client->Socket, "401 Not Authenticated\n");
758 // Check user permissions
759 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
760 sendf(Client->Socket, "403 Not in coke\n");
764 uid = Bank_GetAcctByName(username, 0);
766 sendf(Client->Socket, "404 Unknown user\n");
770 item = _GetItemFromString(itemname);
772 sendf(Client->Socket, "406 Bad Item ID\n");
777 price_override = atoi(price_str);
779 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
781 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
783 sendf(Client->Socket, "500 Dispense Error\n");
788 void Server_Cmd_GIVE(tClient *Client, char *Args)
790 char *recipient, *ammount, *reason;
795 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
796 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
801 if( !Client->bIsAuthed ) {
802 sendf(Client->Socket, "401 Not Authenticated\n");
807 uid = Bank_GetAcctByName(recipient, 0);
809 sendf(Client->Socket, "404 Invalid target user\n");
813 // You can't alter an internal account
814 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
815 // sendf(Client->Socket, "404 Invalid target user\n");
820 iAmmount = atoi(ammount);
821 if( iAmmount <= 0 ) {
822 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
826 if( Client->EffectiveUID != -1 ) {
827 thisUid = Client->EffectiveUID;
830 thisUid = Client->UID;
834 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
837 sendf(Client->Socket, "200 Give OK\n");
840 sendf(Client->Socket, "402 Poor You\n");
843 sendf(Client->Socket, "500 Unknown error\n");
848 void Server_Cmd_DONATE(tClient *Client, char *Args)
850 char *ammount, *reason;
855 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
856 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
860 if( !Client->bIsAuthed ) {
861 sendf(Client->Socket, "401 Not Authenticated\n");
866 iAmmount = atoi(ammount);
867 if( iAmmount <= 0 ) {
868 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
872 // Handle effective users
873 if( Client->EffectiveUID != -1 ) {
874 thisUid = Client->EffectiveUID;
877 thisUid = Client->UID;
881 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
884 sendf(Client->Socket, "200 Give OK\n");
887 sendf(Client->Socket, "402 Poor You\n");
890 sendf(Client->Socket, "500 Unknown error\n");
895 void Server_Cmd_ADD(tClient *Client, char *Args)
897 char *user, *ammount, *reason;
901 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
902 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
906 if( !Client->bIsAuthed ) {
907 sendf(Client->Socket, "401 Not Authenticated\n");
911 // Check user permissions
912 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
913 sendf(Client->Socket, "403 Not in coke\n");
918 if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
920 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
926 uid = Bank_GetAcctByName(user, 0);
928 sendf(Client->Socket, "404 Invalid user\n");
932 // You can't alter an internal account
933 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
935 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
936 sendf(Client->Socket, "404 Invalid user\n");
939 // TODO: Maybe disallow changes to disabled?
943 iAmmount = atoi(ammount);
944 if( iAmmount == 0 && ammount[0] != '0' ) {
945 sendf(Client->Socket, "407 Invalid Argument\n");
950 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
953 sendf(Client->Socket, "200 Add OK\n");
956 sendf(Client->Socket, "402 Poor Guy\n");
959 sendf(Client->Socket, "500 Unknown error\n");
964 void Server_Cmd_SET(tClient *Client, char *Args)
966 char *user, *ammount, *reason;
970 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
971 sendf(Client->Socket, "407 SET takes 3 arguments\n");
975 if( !Client->bIsAuthed ) {
976 sendf(Client->Socket, "401 Not Authenticated\n");
980 // Check user permissions
981 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
982 sendf(Client->Socket, "403 Not an admin\n");
987 uid = Bank_GetAcctByName(user, 0);
989 sendf(Client->Socket, "404 Invalid user\n");
994 iAmmount = atoi(ammount);
995 if( iAmmount == 0 && ammount[0] != '0' ) {
996 sendf(Client->Socket, "407 Invalid Argument\n");
1001 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
1004 sendf(Client->Socket, "200 Add OK\n");
1007 sendf(Client->Socket, "402 Poor Guy\n");
1010 sendf(Client->Socket, "500 Unknown error\n");
1015 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1019 int maxBal = INT_MAX, minBal = INT_MIN;
1020 int flagMask = 0, flagVal = 0;
1021 int sort = BANK_ITFLAG_SORT_NAME;
1022 time_t lastSeenAfter=0, lastSeenBefore=0;
1024 int flags; // Iterator flags
1025 int balValue; // Balance value for iterator
1026 time_t timeValue; // Time value for iterator
1029 if( Args && strlen(Args) )
1031 char *space = Args, *type, *val;
1035 while(*type == ' ') type ++;
1037 space = strchr(space, ' ');
1038 if(space) *space = '\0';
1041 val = strchr(type, ':');
1048 if( strcmp(type, "min_balance") == 0 ) {
1051 // - Maximum Balance
1052 else if( strcmp(type, "max_balance") == 0 ) {
1056 else if( strcmp(type, "flags") == 0 ) {
1057 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1060 // - Last seen before timestamp
1061 else if( strcmp(type, "last_seen_before") == 0 ) {
1062 lastSeenAfter = atoll(val);
1064 // - Last seen after timestamp
1065 else if( strcmp(type, "last_seen_after") == 0 ) {
1066 lastSeenAfter = atoll(val);
1069 else if( strcmp(type, "sort") == 0 ) {
1070 char *dash = strchr(val, '-');
1075 if( strcmp(val, "name") == 0 ) {
1076 sort = BANK_ITFLAG_SORT_NAME;
1078 else if( strcmp(val, "balance") == 0 ) {
1079 sort = BANK_ITFLAG_SORT_BAL;
1081 else if( strcmp(val, "lastseen") == 0 ) {
1082 sort = BANK_ITFLAG_SORT_LASTSEEN;
1085 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1088 // Handle sort direction
1090 if( strcmp(dash, "desc") == 0 ) {
1091 sort |= BANK_ITFLAG_REVSORT;
1094 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1101 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1108 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1114 *space = ' '; // Repair (to be nice)
1116 while(*space == ' ') space ++;
1122 if( maxBal != INT_MAX ) {
1123 flags = sort|BANK_ITFLAG_MAXBALANCE;
1126 else if( minBal != INT_MIN ) {
1127 flags = sort|BANK_ITFLAG_MINBALANCE;
1134 if( lastSeenBefore ) {
1135 timeValue = lastSeenBefore;
1136 flags |= BANK_ITFLAG_SEENBEFORE;
1138 else if( lastSeenAfter ) {
1139 timeValue = lastSeenAfter;
1140 flags |= BANK_ITFLAG_SEENAFTER;
1145 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1147 // Get return number
1148 while( (i = Bank_IteratorNext(it)) != -1 )
1150 int bal = Bank_GetBalance(i);
1152 if( bal == INT_MIN ) continue;
1154 if( bal < minBal ) continue;
1155 if( bal > maxBal ) continue;
1160 Bank_DelIterator(it);
1163 sendf(Client->Socket, "201 Users %i\n", numRet);
1167 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1169 while( (i = Bank_IteratorNext(it)) != -1 )
1171 int bal = Bank_GetBalance(i);
1173 if( bal == INT_MIN ) continue;
1175 if( bal < minBal ) continue;
1176 if( bal > maxBal ) continue;
1178 _SendUserInfo(Client, i);
1181 Bank_DelIterator(it);
1183 sendf(Client->Socket, "200 List End\n");
1186 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1192 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1193 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1197 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1200 uid = Bank_GetAcctByName(user, 0);
1202 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1204 sendf(Client->Socket, "404 Invalid user\n");
1208 _SendUserInfo(Client, uid);
1211 void _SendUserInfo(tClient *Client, int UserID)
1213 char *type, *disabled="", *door="";
1214 int flags = Bank_GetFlags(UserID);
1216 if( flags & USER_FLAG_INTERNAL ) {
1219 else if( flags & USER_FLAG_COKE ) {
1220 if( flags & USER_FLAG_ADMIN )
1221 type = "coke,admin";
1225 else if( flags & USER_FLAG_ADMIN ) {
1232 if( flags & USER_FLAG_DISABLED )
1233 disabled = ",disabled";
1234 if( flags & USER_FLAG_DOORGROUP )
1237 // TODO: User flags/type
1239 Client->Socket, "202 User %s %i %s%s%s\n",
1240 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1241 type, disabled, door
1245 void Server_Cmd_USERADD(tClient *Client, char *Args)
1250 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1251 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1255 // Check authentication
1256 if( !Client->bIsAuthed ) {
1257 sendf(Client->Socket, "401 Not Authenticated\n");
1261 // Check permissions
1262 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1263 sendf(Client->Socket, "403 Not a coke admin\n");
1267 // Try to create user
1268 if( Bank_CreateAcct(username) == -1 ) {
1269 sendf(Client->Socket, "404 User exists\n");
1274 char *thisName = Bank_GetAcctName(Client->UID);
1275 Log_Info("Account '%s' created by '%s'", username, thisName);
1279 sendf(Client->Socket, "200 User Added\n");
1282 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1284 char *username, *flags, *reason=NULL;
1285 int mask=0, value=0;
1289 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1291 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1297 // Check authentication
1298 if( !Client->bIsAuthed ) {
1299 sendf(Client->Socket, "401 Not Authenticated\n");
1303 // Check permissions
1304 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1305 sendf(Client->Socket, "403 Not a coke admin\n");
1310 uid = Bank_GetAcctByName(username, 0);
1312 sendf(Client->Socket, "404 User '%s' not found\n", username);
1317 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1321 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1322 uid, username, mask, value);
1325 Bank_SetFlags(uid, mask, value);
1328 Log_Info("Updated '%s' with flag set '%s' - Reason: %s",
1329 username, flags, reason);
1332 sendf(Client->Socket, "200 User Updated\n");
1335 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1337 char *itemname, *price_str, *description;
1341 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1342 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1346 if( !Client->bIsAuthed ) {
1347 sendf(Client->Socket, "401 Not Authenticated\n");
1351 // Check user permissions
1352 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1353 sendf(Client->Socket, "403 Not in coke\n");
1357 item = _GetItemFromString(itemname);
1359 // TODO: Create item?
1360 sendf(Client->Socket, "406 Bad Item ID\n");
1364 price = atoi(price_str);
1365 if( price <= 0 && price_str[0] != '0' ) {
1366 sendf(Client->Socket, "407 Invalid price set\n");
1369 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1373 sendf(Client->Socket, "200 Item updated\n");
1380 // --- INTERNAL HELPERS ---
1381 void Debug(tClient *Client, const char *Format, ...)
1384 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1385 printf("[%i] ", Client->ID);
1386 va_start(args, Format);
1387 vprintf(Format, args);
1392 int sendf(int Socket, const char *Format, ...)
1397 va_start(args, Format);
1398 len = vsnprintf(NULL, 0, Format, args);
1403 va_start(args, Format);
1404 vsnprintf(buf, len+1, Format, args);
1407 #if DEBUG_TRACE_CLIENT
1408 printf("sendf: %s", buf);
1411 return send(Socket, buf, len, 0);
1415 // Takes a series of char *'s in
1417 * \brief Parse space-separated entries into
1419 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1424 va_start(args, ArgStr);
1429 while( (dest = va_arg(args, char **)) )
1435 savedChar = *ArgStr;
1437 while( (dest = va_arg(args, char **)) )
1439 // Trim leading spaces
1440 while( *ArgStr == ' ' || *ArgStr == '\t' )
1443 // ... oops, not enough arguments
1444 if( *ArgStr == '\0' )
1446 // NULL unset arguments
1449 } while( (dest = va_arg(args, char **)) );
1454 if( *ArgStr == '"' )
1459 while( *ArgStr && *ArgStr != '"' )
1466 // Read until a space
1467 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1470 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1476 // Oops, extra arguments, and greedy not set
1477 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1484 *ArgStr = savedChar;
1487 return 0; // Success!
1490 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1497 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1498 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1499 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1500 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1501 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1503 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1515 while( *Str == ' ' ) Str ++; // Eat whitespace
1516 space = strchr(Str, ','); // Find the end of the flag
1522 // Check for inversion/removal
1523 if( *Str == '!' || *Str == '-' ) {
1527 else if( *Str == '+' ) {
1531 // Check flag values
1532 for( i = 0; i < ciNumFlags; i ++ )
1534 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1535 *Mask |= cFLAGS[i].Mask;
1536 *Value &= ~cFLAGS[i].Mask;
1538 *Value |= cFLAGS[i].Value;
1544 if( i == ciNumFlags ) {
1546 strncpy(val, Str, len+1);
1547 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);