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 )
157 fprintf(stderr, "ERROR: Unable to fork\n");
158 perror("fork background");
166 // - Sort out stdin/stdout
168 dup2( open("/dev/null", O_RDONLY, 0644), STDIN_FILENO );
169 dup2( open(gsServer_LogFile, O_CREAT|O_APPEND, 0644), STDOUT_FILENO );
170 dup2( open(gsServer_ErrorLog, O_CREAT|O_APPEND, 0644), STDERR_FILENO );
172 freopen("/dev/null", "r", stdin);
173 freopen(gsServer_LogFile, "a", stdout);
174 freopen(gsServer_ErrorLog, "a", stderr);
178 // Start the helper thread
179 StartPeriodicThread();
182 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
183 fprintf(stderr, "ERROR: Unable to listen to socket\n");
188 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
192 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
194 fprintf(fp, "%i", getpid());
201 uint len = sizeof(client_addr);
204 // Accept a connection
205 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
206 if(client_socket < 0) {
207 fprintf(stderr, "ERROR: Unable to accept client connection\n");
211 // Set a timeout on the user conneciton
214 tv.tv_sec = CLIENT_TIMEOUT;
216 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
218 perror("setsockopt");
223 // Debug: Print the connection string
224 if(giDebugLevel >= 2) {
225 char ipstr[INET_ADDRSTRLEN];
226 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
227 printf("Client connection from %s:%i\n",
228 ipstr, ntohs(client_addr.sin_port));
231 // Doesn't matter what, localhost is trusted
232 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
235 // Trusted Connections
236 if( ntohs(client_addr.sin_port) < 1024 )
238 // TODO: Make this runtime configurable
239 switch( ntohl( client_addr.sin_addr.s_addr ) )
241 case 0x7F000001: // 127.0.0.1 localhost
242 // case 0x825F0D00: // 130.95.13.0
243 case 0x825F0D04: // 130.95.13.4 merlo
244 // case 0x825F0D05: // 130.95.13.5 heathred (MR)
245 case 0x825F0D07: // 130.95.13.7 motsugo
246 case 0x825F0D11: // 130.95.13.17 mermaid
247 case 0x825F0D12: // 130.95.13.18 mussel
248 case 0x825F0D17: // 130.95.13.23 martello
249 case 0x825F0D2A: // 130.95.13.42 meersau
250 // case 0x825F0D42: // 130.95.13.66 heathred (Clubroom)
258 // TODO: Multithread this?
259 Server_HandleClient(client_socket, bTrusted);
261 close(client_socket);
265 void Server_Cleanup(void)
267 printf("\nClose(%i)\n", giServer_Socket);
268 close(giServer_Socket);
269 unlink("/var/run/dispsrv.pid");
273 * \brief Reads from a client socket and parses the command strings
274 * \param Socket Client socket number/handle
275 * \param bTrusted Is the client trusted?
277 void Server_HandleClient(int Socket, int bTrusted)
279 char inbuf[INPUT_BUFFER_SIZE];
281 int remspace = INPUT_BUFFER_SIZE-1;
285 memset(&clientInfo, 0, sizeof(clientInfo));
287 // Initialise Client info
288 clientInfo.Socket = Socket;
289 clientInfo.ID = giServer_NextClientID ++;
290 clientInfo.bIsTrusted = bTrusted;
291 clientInfo.EffectiveUID = -1;
296 * - The `buf` and `remspace` variables allow a line to span several
297 * calls to recv(), if a line is not completed in one recv() call
298 * it is saved to the beginning of `inbuf` and `buf` is updated to
301 // TODO: Use select() instead (to give a timeout)
302 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
305 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
309 while( (eol = strchr(start, '\n')) )
313 Server_ParseClientCommand(&clientInfo, start);
318 // Check if there was an incomplete line
319 if( *start != '\0' ) {
320 int tailBytes = bytes - (start-buf);
321 // Roll back in buffer
322 memcpy(inbuf, start, tailBytes);
323 remspace -= tailBytes;
325 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
327 remspace = INPUT_BUFFER_SIZE - 1;
332 remspace = INPUT_BUFFER_SIZE - 1;
338 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
342 if(giDebugLevel >= 2) {
343 printf("Client %i: Disconnected\n", clientInfo.ID);
348 * \brief Parses a client command and calls the required helper function
349 * \param Client Pointer to client state structure
350 * \param CommandString Command from client (single line of the command)
351 * \return Heap String to return to the client
353 void Server_ParseClientCommand(tClient *Client, char *CommandString)
355 char *command, *args;
358 if( giDebugLevel >= 2 )
359 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
361 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
363 if( command == NULL ) return ;
364 // Is this an error? (just ignore for now)
369 for( i = 0; i < NUM_COMMANDS; i++ )
371 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
372 if( giDebugLevel >= 2 )
373 Debug(Client, "CMD %s - \"%s\"", command, args);
374 gaServer_Commands[i].Function(Client, args);
379 sendf(Client->Socket, "400 Unknown Command\n");
386 * \brief Set client username
388 * Usage: USER <username>
390 void Server_Cmd_USER(tClient *Client, char *Args)
394 if( Server_int_ParseArgs(0, Args, &username, NULL) )
396 sendf(Client->Socket, "407 USER takes 1 argument\n");
402 Debug(Client, "Authenticating as '%s'", username);
406 free(Client->Username);
407 Client->Username = strdup(username);
410 // Create a salt (that changes if the username is changed)
411 // Yes, I know, I'm a little paranoid, but who isn't?
412 Client->Salt[0] = 0x21 + (rand()&0x3F);
413 Client->Salt[1] = 0x21 + (rand()&0x3F);
414 Client->Salt[2] = 0x21 + (rand()&0x3F);
415 Client->Salt[3] = 0x21 + (rand()&0x3F);
416 Client->Salt[4] = 0x21 + (rand()&0x3F);
417 Client->Salt[5] = 0x21 + (rand()&0x3F);
418 Client->Salt[6] = 0x21 + (rand()&0x3F);
419 Client->Salt[7] = 0x21 + (rand()&0x3F);
421 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
422 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
424 sendf(Client->Socket, "100 User Set\n");
429 * \brief Authenticate as a user
433 void Server_Cmd_PASS(tClient *Client, char *Args)
438 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
440 sendf(Client->Socket, "407 PASS takes 1 argument\n");
444 // Pass on to cokebank
445 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
447 if( Client->UID == -1 ) {
448 sendf(Client->Socket, "401 Auth Failure\n");
452 flags = Bank_GetFlags(Client->UID);
453 if( flags & USER_FLAG_DISABLED ) {
455 sendf(Client->Socket, "403 Account Disabled\n");
458 if( flags & USER_FLAG_INTERNAL ) {
460 sendf(Client->Socket, "403 Internal account\n");
464 Client->bIsAuthed = 1;
465 sendf(Client->Socket, "200 Auth OK\n");
469 * \brief Authenticate as a user without a password
471 * Usage: AUTOAUTH <user>
473 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
478 if( Server_int_ParseArgs(0, Args, &username, NULL) )
480 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
485 if( !Client->bIsTrusted ) {
487 Debug(Client, "Untrusted client attempting to AUTOAUTH");
488 sendf(Client->Socket, "401 Untrusted\n");
493 Client->UID = Bank_GetAcctByName( username, 0 );
494 if( Client->UID < 0 ) {
496 Debug(Client, "Unknown user '%s'", username);
497 sendf(Client->Socket, "403 Auth Failure\n");
501 userflags = Bank_GetFlags(Client->UID);
502 // You can't be an internal account
503 if( userflags & USER_FLAG_INTERNAL ) {
505 Debug(Client, "Autoauth as '%s', not allowed", username);
507 sendf(Client->Socket, "403 Account is internal\n");
512 if( userflags & USER_FLAG_DISABLED ) {
514 sendf(Client->Socket, "403 Account disabled\n");
520 free(Client->Username);
521 Client->Username = strdup(username);
523 Client->bIsAuthed = 1;
526 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
528 sendf(Client->Socket, "200 Auth OK\n");
532 * \brief Set effective user
534 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
537 int eUserFlags, userFlags;
539 if( Server_int_ParseArgs(0, Args, &username, NULL) )
541 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
545 if( !strlen(Args) ) {
546 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
550 // Check authentication
551 if( !Client->bIsAuthed ) {
552 sendf(Client->Socket, "401 Not Authenticated\n");
556 // Check user permissions
557 userFlags = Bank_GetFlags(Client->UID);
558 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
559 sendf(Client->Socket, "403 Not in coke\n");
564 Client->EffectiveUID = Bank_GetAcctByName(username, 0);
565 if( Client->EffectiveUID == -1 ) {
566 sendf(Client->Socket, "404 User not found\n");
570 // You can't be an internal account
571 if( !(userFlags & USER_FLAG_ADMIN) )
573 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
574 if( eUserFlags & USER_FLAG_INTERNAL ) {
575 Client->EffectiveUID = -1;
576 sendf(Client->Socket, "404 User not found\n");
579 // Disabled only avaliable to admins
580 if( eUserFlags & USER_FLAG_DISABLED ) {
581 Client->EffectiveUID = -1;
582 sendf(Client->Socket, "403 Account disabled\n");
587 sendf(Client->Socket, "200 User set\n");
591 * \brief Send an item status to the client
592 * \param Client Who to?
593 * \param Item Item to send
595 void Server_int_SendItem(tClient *Client, tItem *Item)
597 char *status = "avail";
599 if( Item->Handler->CanDispense )
601 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
603 case 0: status = "avail"; break;
604 case 1: status = "sold"; break;
606 case -1: status = "error"; break;
610 // KNOWN HACK: Naming a slot 'dead' disables it
611 if( strcmp(Item->Name, "dead") == 0 )
612 status = "sold"; // Another status?
614 sendf(Client->Socket,
615 "202 Item %s:%i %s %i %s\n",
616 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
621 * \brief Enumerate the items that the server knows about
623 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
627 if( Args != NULL && strlen(Args) ) {
628 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
634 for( i = 0; i < giNumItems; i ++ ) {
635 if( gaItems[i].bHidden ) continue;
639 sendf(Client->Socket, "201 Items %i\n", count);
641 for( i = 0; i < giNumItems; i ++ ) {
642 if( gaItems[i].bHidden ) continue;
643 Server_int_SendItem( Client, &gaItems[i] );
646 sendf(Client->Socket, "200 List end\n");
649 tItem *_GetItemFromString(char *String)
653 char *colon = strchr(String, ':');
665 for( i = 0; i < giNumHandlers; i ++ )
667 if( strcmp(gaHandlers[i]->Name, type) == 0) {
668 handler = gaHandlers[i];
677 for( i = 0; i < giNumItems; i ++ )
679 if( gaItems[i].Handler != handler ) continue;
680 if( gaItems[i].ID != num ) continue;
687 * \brief Fetch information on a specific item
689 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
694 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
695 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
698 item = _GetItemFromString(Args);
701 sendf(Client->Socket, "406 Bad Item ID\n");
705 Server_int_SendItem( Client, item );
708 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
715 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
716 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
720 if( !Client->bIsAuthed ) {
721 sendf(Client->Socket, "401 Not Authenticated\n");
725 item = _GetItemFromString(itemname);
727 sendf(Client->Socket, "406 Bad Item ID\n");
731 if( Client->EffectiveUID != -1 ) {
732 uid = Client->EffectiveUID;
738 switch( ret = DispenseItem( Client->UID, uid, item ) )
740 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
741 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
742 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
744 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
749 void Server_Cmd_REFUND(tClient *Client, char *Args)
752 int uid, price_override = 0;
753 char *username, *itemname, *price_str;
755 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
756 if( !itemname || price_str ) {
757 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
762 if( !Client->bIsAuthed ) {
763 sendf(Client->Socket, "401 Not Authenticated\n");
767 // Check user permissions
768 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
769 sendf(Client->Socket, "403 Not in coke\n");
773 uid = Bank_GetAcctByName(username, 0);
775 sendf(Client->Socket, "404 Unknown user\n");
779 item = _GetItemFromString(itemname);
781 sendf(Client->Socket, "406 Bad Item ID\n");
786 price_override = atoi(price_str);
788 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
790 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
792 sendf(Client->Socket, "500 Dispense Error\n");
797 void Server_Cmd_GIVE(tClient *Client, char *Args)
799 char *recipient, *ammount, *reason;
804 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
805 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
810 if( !Client->bIsAuthed ) {
811 sendf(Client->Socket, "401 Not Authenticated\n");
816 uid = Bank_GetAcctByName(recipient, 0);
818 sendf(Client->Socket, "404 Invalid target user\n");
822 // You can't alter an internal account
823 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
824 // sendf(Client->Socket, "404 Invalid target user\n");
829 iAmmount = atoi(ammount);
830 if( iAmmount <= 0 ) {
831 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
835 if( Client->EffectiveUID != -1 ) {
836 thisUid = Client->EffectiveUID;
839 thisUid = Client->UID;
843 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
846 sendf(Client->Socket, "200 Give OK\n");
849 sendf(Client->Socket, "402 Poor You\n");
852 sendf(Client->Socket, "500 Unknown error\n");
857 void Server_Cmd_DONATE(tClient *Client, char *Args)
859 char *ammount, *reason;
864 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
865 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
869 if( !Client->bIsAuthed ) {
870 sendf(Client->Socket, "401 Not Authenticated\n");
875 iAmmount = atoi(ammount);
876 if( iAmmount <= 0 ) {
877 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
881 // Handle effective users
882 if( Client->EffectiveUID != -1 ) {
883 thisUid = Client->EffectiveUID;
886 thisUid = Client->UID;
890 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
893 sendf(Client->Socket, "200 Give OK\n");
896 sendf(Client->Socket, "402 Poor You\n");
899 sendf(Client->Socket, "500 Unknown error\n");
904 void Server_Cmd_ADD(tClient *Client, char *Args)
906 char *user, *ammount, *reason;
910 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
911 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
915 if( !Client->bIsAuthed ) {
916 sendf(Client->Socket, "401 Not Authenticated\n");
920 // Check user permissions
921 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
922 sendf(Client->Socket, "403 Not in coke\n");
927 if( strcmp( Client->Username, "root" ) == 0 ) {
928 // Allow adding for new users
929 if( strcmp(reason, "treasurer: new user") != 0 ) {
930 sendf(Client->Socket, "403 Root may not add\n");
937 if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
939 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
945 uid = Bank_GetAcctByName(user, 0);
947 sendf(Client->Socket, "404 Invalid user\n");
951 // You can't alter an internal account
952 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
954 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
955 sendf(Client->Socket, "404 Invalid user\n");
958 // TODO: Maybe disallow changes to disabled?
962 iAmmount = atoi(ammount);
963 if( iAmmount == 0 && ammount[0] != '0' ) {
964 sendf(Client->Socket, "407 Invalid Argument\n");
969 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
972 sendf(Client->Socket, "200 Add OK\n");
975 sendf(Client->Socket, "402 Poor Guy\n");
978 sendf(Client->Socket, "500 Unknown error\n");
983 void Server_Cmd_SET(tClient *Client, char *Args)
985 char *user, *ammount, *reason;
989 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
990 sendf(Client->Socket, "407 SET takes 3 arguments\n");
994 if( !Client->bIsAuthed ) {
995 sendf(Client->Socket, "401 Not Authenticated\n");
999 // Check user permissions
1000 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1001 sendf(Client->Socket, "403 Not an admin\n");
1006 uid = Bank_GetAcctByName(user, 0);
1008 sendf(Client->Socket, "404 Invalid user\n");
1013 iAmmount = atoi(ammount);
1014 if( iAmmount == 0 && ammount[0] != '0' ) {
1015 sendf(Client->Socket, "407 Invalid Argument\n");
1020 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
1023 sendf(Client->Socket, "200 Add OK\n");
1026 sendf(Client->Socket, "402 Poor Guy\n");
1029 sendf(Client->Socket, "500 Unknown error\n");
1034 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1038 int maxBal = INT_MAX, minBal = INT_MIN;
1039 int flagMask = 0, flagVal = 0;
1040 int sort = BANK_ITFLAG_SORT_NAME;
1041 time_t lastSeenAfter=0, lastSeenBefore=0;
1043 int flags; // Iterator flags
1044 int balValue; // Balance value for iterator
1045 time_t timeValue; // Time value for iterator
1048 if( Args && strlen(Args) )
1050 char *space = Args, *type, *val;
1054 while(*type == ' ') type ++;
1056 space = strchr(space, ' ');
1057 if(space) *space = '\0';
1060 val = strchr(type, ':');
1067 if( strcmp(type, "min_balance") == 0 ) {
1070 // - Maximum Balance
1071 else if( strcmp(type, "max_balance") == 0 ) {
1075 else if( strcmp(type, "flags") == 0 ) {
1076 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1079 // - Last seen before timestamp
1080 else if( strcmp(type, "last_seen_before") == 0 ) {
1081 lastSeenAfter = atoll(val);
1083 // - Last seen after timestamp
1084 else if( strcmp(type, "last_seen_after") == 0 ) {
1085 lastSeenAfter = atoll(val);
1088 else if( strcmp(type, "sort") == 0 ) {
1089 char *dash = strchr(val, '-');
1094 if( strcmp(val, "name") == 0 ) {
1095 sort = BANK_ITFLAG_SORT_NAME;
1097 else if( strcmp(val, "balance") == 0 ) {
1098 sort = BANK_ITFLAG_SORT_BAL;
1100 else if( strcmp(val, "lastseen") == 0 ) {
1101 sort = BANK_ITFLAG_SORT_LASTSEEN;
1104 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1107 // Handle sort direction
1109 if( strcmp(dash, "desc") == 0 ) {
1110 sort |= BANK_ITFLAG_REVSORT;
1113 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1120 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1127 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1133 *space = ' '; // Repair (to be nice)
1135 while(*space == ' ') space ++;
1141 if( maxBal != INT_MAX ) {
1142 flags = sort|BANK_ITFLAG_MAXBALANCE;
1145 else if( minBal != INT_MIN ) {
1146 flags = sort|BANK_ITFLAG_MINBALANCE;
1153 if( lastSeenBefore ) {
1154 timeValue = lastSeenBefore;
1155 flags |= BANK_ITFLAG_SEENBEFORE;
1157 else if( lastSeenAfter ) {
1158 timeValue = lastSeenAfter;
1159 flags |= BANK_ITFLAG_SEENAFTER;
1164 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1166 // Get return number
1167 while( (i = Bank_IteratorNext(it)) != -1 )
1169 int bal = Bank_GetBalance(i);
1171 if( bal == INT_MIN ) continue;
1173 if( bal < minBal ) continue;
1174 if( bal > maxBal ) continue;
1179 Bank_DelIterator(it);
1182 sendf(Client->Socket, "201 Users %i\n", numRet);
1186 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1188 while( (i = Bank_IteratorNext(it)) != -1 )
1190 int bal = Bank_GetBalance(i);
1192 if( bal == INT_MIN ) continue;
1194 if( bal < minBal ) continue;
1195 if( bal > maxBal ) continue;
1197 _SendUserInfo(Client, i);
1200 Bank_DelIterator(it);
1202 sendf(Client->Socket, "200 List End\n");
1205 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1211 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1212 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1216 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1219 uid = Bank_GetAcctByName(user, 0);
1221 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1223 sendf(Client->Socket, "404 Invalid user\n");
1227 _SendUserInfo(Client, uid);
1230 void _SendUserInfo(tClient *Client, int UserID)
1232 char *type, *disabled="", *door="";
1233 int flags = Bank_GetFlags(UserID);
1235 if( flags & USER_FLAG_INTERNAL ) {
1238 else if( flags & USER_FLAG_COKE ) {
1239 if( flags & USER_FLAG_ADMIN )
1240 type = "coke,admin";
1244 else if( flags & USER_FLAG_ADMIN ) {
1251 if( flags & USER_FLAG_DISABLED )
1252 disabled = ",disabled";
1253 if( flags & USER_FLAG_DOORGROUP )
1256 // TODO: User flags/type
1258 Client->Socket, "202 User %s %i %s%s%s\n",
1259 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1260 type, disabled, door
1264 void Server_Cmd_USERADD(tClient *Client, char *Args)
1269 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1270 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1274 // Check authentication
1275 if( !Client->bIsAuthed ) {
1276 sendf(Client->Socket, "401 Not Authenticated\n");
1280 // Check permissions
1281 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1282 sendf(Client->Socket, "403 Not a coke admin\n");
1286 // Try to create user
1287 if( Bank_CreateAcct(username) == -1 ) {
1288 sendf(Client->Socket, "404 User exists\n");
1293 char *thisName = Bank_GetAcctName(Client->UID);
1294 Log_Info("Account '%s' created by '%s'", username, thisName);
1298 sendf(Client->Socket, "200 User Added\n");
1301 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1303 char *username, *flags, *reason=NULL;
1304 int mask=0, value=0;
1308 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1310 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1316 // Check authentication
1317 if( !Client->bIsAuthed ) {
1318 sendf(Client->Socket, "401 Not Authenticated\n");
1322 // Check permissions
1323 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1324 sendf(Client->Socket, "403 Not a coke admin\n");
1329 uid = Bank_GetAcctByName(username, 0);
1331 sendf(Client->Socket, "404 User '%s' not found\n", username);
1336 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1340 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1341 uid, username, mask, value);
1344 Bank_SetFlags(uid, mask, value);
1347 Log_Info("Updated '%s' with flag set '%s' - Reason: %s",
1348 username, flags, reason);
1351 sendf(Client->Socket, "200 User Updated\n");
1354 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1356 char *itemname, *price_str, *description;
1360 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1361 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1365 if( !Client->bIsAuthed ) {
1366 sendf(Client->Socket, "401 Not Authenticated\n");
1370 // Check user permissions
1371 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1372 sendf(Client->Socket, "403 Not in coke\n");
1376 item = _GetItemFromString(itemname);
1378 // TODO: Create item?
1379 sendf(Client->Socket, "406 Bad Item ID\n");
1383 price = atoi(price_str);
1384 if( price <= 0 && price_str[0] != '0' ) {
1385 sendf(Client->Socket, "407 Invalid price set\n");
1388 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1392 sendf(Client->Socket, "200 Item updated\n");
1399 // --- INTERNAL HELPERS ---
1400 void Debug(tClient *Client, const char *Format, ...)
1403 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1404 printf("[%i] ", Client->ID);
1405 va_start(args, Format);
1406 vprintf(Format, args);
1411 int sendf(int Socket, const char *Format, ...)
1416 va_start(args, Format);
1417 len = vsnprintf(NULL, 0, Format, args);
1422 va_start(args, Format);
1423 vsnprintf(buf, len+1, Format, args);
1426 #if DEBUG_TRACE_CLIENT
1427 printf("sendf: %s", buf);
1430 return send(Socket, buf, len, 0);
1434 // Takes a series of char *'s in
1436 * \brief Parse space-separated entries into
1438 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1443 va_start(args, ArgStr);
1448 while( (dest = va_arg(args, char **)) )
1454 savedChar = *ArgStr;
1456 while( (dest = va_arg(args, char **)) )
1458 // Trim leading spaces
1459 while( *ArgStr == ' ' || *ArgStr == '\t' )
1462 // ... oops, not enough arguments
1463 if( *ArgStr == '\0' )
1465 // NULL unset arguments
1468 } while( (dest = va_arg(args, char **)) );
1473 if( *ArgStr == '"' )
1478 while( *ArgStr && *ArgStr != '"' )
1485 // Read until a space
1486 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1489 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1495 // Oops, extra arguments, and greedy not set
1496 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1503 *ArgStr = savedChar;
1506 return 0; // Success!
1509 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1516 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1517 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1518 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1519 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1520 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1522 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1534 while( *Str == ' ' ) Str ++; // Eat whitespace
1535 space = strchr(Str, ','); // Find the end of the flag
1541 // Check for inversion/removal
1542 if( *Str == '!' || *Str == '-' ) {
1546 else if( *Str == '+' ) {
1550 // Check flag values
1551 for( i = 0; i < ciNumFlags; i ++ )
1553 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1554 *Mask |= cFLAGS[i].Mask;
1555 *Value &= ~cFLAGS[i].Mask;
1557 *Value |= cFLAGS[i].Value;
1563 if( i == ciNumFlags ) {
1565 strncpy(val, Str, len+1);
1566 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);