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_*
21 #include <signal.h> // Signal handling
22 #include <ident.h> // AUTHIDENT
23 #include <time.h> // time(2)
26 #define DEBUG_TRACE_CLIENT 0
27 #define HACK_NO_REFUNDS 1
29 #define PIDFILE "/var/run/dispsrv.pid"
32 #define MAX_CONNECTION_QUEUE 5
33 #define INPUT_BUFFER_SIZE 256
34 #define CLIENT_TIMEOUT 10 // Seconds
36 #define HASH_TYPE SHA1
37 #define HASH_LENGTH 20
39 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
41 #define IDENT_TRUSTED_NETWORK 0x825F0D00
42 #define IDENT_TRUSTED_NETMASK 0xFFFFFFC0
45 typedef struct sClient
47 int Socket; // Client socket ID
51 int bCanAutoAuth; // Is the connection from a trusted host/port
62 void Server_Start(void);
63 void Server_Cleanup(void);
64 void Server_HandleClient(int Socket, int bTrustedHost, int bRootPort);
65 void Server_ParseClientCommand(tClient *Client, char *CommandString);
67 void Server_Cmd_USER(tClient *Client, char *Args);
68 void Server_Cmd_PASS(tClient *Client, char *Args);
69 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
70 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args);
71 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
72 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
73 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
74 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
75 void Server_Cmd_REFUND(tClient *Client, char *Args);
76 void Server_Cmd_GIVE(tClient *Client, char *Args);
77 void Server_Cmd_DONATE(tClient *Client, char *Args);
78 void Server_Cmd_ADD(tClient *Client, char *Args);
79 void Server_Cmd_SET(tClient *Client, char *Args);
80 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
81 void Server_Cmd_USERINFO(tClient *Client, char *Args);
82 void _SendUserInfo(tClient *Client, int UserID);
83 void Server_Cmd_USERADD(tClient *Client, char *Args);
84 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
85 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args);
86 void Server_Cmd_PINCHECK(tClient *Client, char *Args);
87 void Server_Cmd_PINSET(tClient *Client, char *Args);
89 void Debug(tClient *Client, const char *Format, ...);
90 int sendf(int Socket, const char *Format, ...);
91 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
92 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
96 const struct sClientCommand {
98 void (*Function)(tClient *Client, char *Arguments);
99 } gaServer_Commands[] = {
100 {"USER", Server_Cmd_USER},
101 {"PASS", Server_Cmd_PASS},
102 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
103 {"AUTHIDENT", Server_Cmd_AUTHIDENT},
104 {"SETEUSER", Server_Cmd_SETEUSER},
105 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
106 {"ITEM_INFO", Server_Cmd_ITEMINFO},
107 {"DISPENSE", Server_Cmd_DISPENSE},
108 {"REFUND", Server_Cmd_REFUND},
109 {"GIVE", Server_Cmd_GIVE},
110 {"DONATE", Server_Cmd_DONATE},
111 {"ADD", Server_Cmd_ADD},
112 {"SET", Server_Cmd_SET},
113 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
114 {"USER_INFO", Server_Cmd_USERINFO},
115 {"USER_ADD", Server_Cmd_USERADD},
116 {"USER_FLAGS", Server_Cmd_USERFLAGS},
117 {"UPDATE_ITEM", Server_Cmd_UPDATEITEM},
118 {"PIN_CHECK", Server_Cmd_PINCHECK},
119 {"PIN_SET", Server_Cmd_PINSET}
121 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
125 int giServer_Port = 11020;
126 int gbServer_RunInBackground = 0;
127 char *gsServer_LogFile = "/var/log/dispsrv.log";
128 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
129 int giServer_NumTrustedHosts;
130 struct in_addr *gaServer_TrustedHosts;
132 int giServer_Socket; // Server socket
133 int giServer_NextClientID = 1; // Debug client ID
138 * \brief Open listenting socket and serve connections
140 void Server_Start(void)
143 struct sockaddr_in server_addr, client_addr;
145 // Parse trusted hosts list
146 giServer_NumTrustedHosts = Config_GetValueCount("trusted_host");
147 gaServer_TrustedHosts = malloc(giServer_NumTrustedHosts * sizeof(*gaServer_TrustedHosts));
148 for( int i = 0; i < giServer_NumTrustedHosts; i ++ )
150 const char *addr = Config_GetValue("trusted_host", i);
152 if( inet_aton(addr, &gaServer_TrustedHosts[i]) == 0 ) {
153 fprintf(stderr, "Invalid IP address '%s'\n", addr);
158 // Ignore SIGPIPE (stops crashes when the client exits early)
159 signal(SIGPIPE, SIG_IGN);
162 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
163 if( giServer_Socket < 0 ) {
164 fprintf(stderr, "ERROR: Unable to create server socket\n");
168 // Make listen address
169 memset(&server_addr, 0, sizeof(server_addr));
170 server_addr.sin_family = AF_INET; // Internet Socket
171 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
172 server_addr.sin_port = htons(giServer_Port); // Port
175 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
176 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
178 close(giServer_Socket);
182 // Fork into background
183 if( gbServer_RunInBackground )
187 fprintf(stderr, "ERROR: Unable to fork\n");
188 perror("fork background");
193 Debug_Notice("Forked child server as PID %i\n", pid);
197 // - Sort out stdin/stdout
199 dup2( open("/dev/null", O_RDONLY, 0644), STDIN_FILENO );
200 dup2( open(gsServer_LogFile, O_CREAT|O_APPEND, 0644), STDOUT_FILENO );
201 dup2( open(gsServer_ErrorLog, O_CREAT|O_APPEND, 0644), STDERR_FILENO );
203 freopen("/dev/null", "r", stdin);
204 freopen(gsServer_LogFile, "a", stdout);
205 freopen(gsServer_ErrorLog, "a", stderr);
206 fprintf(stdout, "OpenDispense 2 Server Started at %lld\n", (long long)time(NULL));
207 fprintf(stderr, "OpenDispense 2 Server Started at %lld\n", (long long)time(NULL));
210 atexit(Server_Cleanup);
212 // Start the helper thread
213 StartPeriodicThread();
216 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
217 fprintf(stderr, "ERROR: Unable to listen to socket\n");
222 Debug_Notice("Listening on 0.0.0.0:%i", giServer_Port);
226 FILE *fp = fopen(PIDFILE, "w");
228 fprintf(fp, "%i", getpid());
235 uint len = sizeof(client_addr);
239 // Accept a connection
240 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
241 if(client_socket < 0) {
242 fprintf(stderr, "ERROR: Unable to accept client connection\n");
246 // Set a timeout on the user conneciton
249 tv.tv_sec = CLIENT_TIMEOUT;
251 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
253 perror("setsockopt");
258 // Debug: Print the connection string
259 if(giDebugLevel >= 2) {
260 char ipstr[INET_ADDRSTRLEN];
261 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
262 Debug_Debug("Client connection from %s:%i",
263 ipstr, ntohs(client_addr.sin_port));
266 // Doesn't matter what, localhost is trusted
267 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
270 // Check if the host is on the trusted list
271 for( int i = 0; i < giServer_NumTrustedHosts; i ++ )
273 if( memcmp(&client_addr.sin_addr, &gaServer_TrustedHosts[i], sizeof(struct in_addr)) == 0 )
280 // Root port (can AUTOAUTH if also a trusted machine
281 if( ntohs(client_addr.sin_port) < 1024 )
286 // TODO: Make this runtime configurable
287 switch( ntohl( client_addr.sin_addr.s_addr ) )
289 case 0x7F000001: // 127.0.0.1 localhost
290 // case 0x825F0D00: // 130.95.13.0
291 case 0x825F0D04: // 130.95.13.4 merlo
292 // case 0x825F0D05: // 130.95.13.5 heathred (MR)
293 case 0x825F0D07: // 130.95.13.7 motsugo
294 case 0x825F0D11: // 130.95.13.17 mermaid
295 case 0x825F0D12: // 130.95.13.18 mussel
296 case 0x825F0D17: // 130.95.13.23 martello
297 case 0x825F0D2A: // 130.95.13.42 meersau
298 // case 0x825F0D42: // 130.95.13.66 heathred (Clubroom)
307 // TODO: Multithread this?
308 Server_HandleClient(client_socket, bTrusted, bRootPort);
310 close(client_socket);
314 void Server_Cleanup(void)
316 Debug_Debug("Close(%i)", giServer_Socket);
317 close(giServer_Socket);
322 * \brief Reads from a client socket and parses the command strings
323 * \param Socket Client socket number/handle
324 * \param bTrusted Is the client trusted?
326 void Server_HandleClient(int Socket, int bTrusted, int bRootPort)
328 char inbuf[INPUT_BUFFER_SIZE];
330 int remspace = INPUT_BUFFER_SIZE-1;
334 memset(&clientInfo, 0, sizeof(clientInfo));
336 // Initialise Client info
337 clientInfo.Socket = Socket;
338 clientInfo.ID = giServer_NextClientID ++;
339 clientInfo.bTrustedHost = bTrusted;
340 clientInfo.bCanAutoAuth = bTrusted && bRootPort;
341 clientInfo.EffectiveUID = -1;
346 * - The `buf` and `remspace` variables allow a line to span several
347 * calls to recv(), if a line is not completed in one recv() call
348 * it is saved to the beginning of `inbuf` and `buf` is updated to
351 // TODO: Use select() instead (to give a timeout)
352 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
355 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
359 while( (eol = strchr(start, '\n')) )
363 Server_ParseClientCommand(&clientInfo, start);
368 // Check if there was an incomplete line
369 if( *start != '\0' ) {
370 int tailBytes = bytes - (start-buf);
371 // Roll back in buffer
372 memcpy(inbuf, start, tailBytes);
373 remspace -= tailBytes;
375 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
377 remspace = INPUT_BUFFER_SIZE - 1;
382 remspace = INPUT_BUFFER_SIZE - 1;
388 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
392 if(giDebugLevel >= 2) {
393 printf("Client %i: Disconnected\n", clientInfo.ID);
398 * \brief Parses a client command and calls the required helper function
399 * \param Client Pointer to client state structure
400 * \param CommandString Command from client (single line of the command)
401 * \return Heap String to return to the client
403 void Server_ParseClientCommand(tClient *Client, char *CommandString)
405 char *command, *args;
408 if( giDebugLevel >= 2 )
409 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
411 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
413 if( command == NULL ) return ;
414 // Is this an error? (just ignore for now)
419 for( i = 0; i < NUM_COMMANDS; i++ )
421 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
422 if( giDebugLevel >= 2 )
423 Debug(Client, "CMD %s - \"%s\"", command, args);
424 gaServer_Commands[i].Function(Client, args);
429 sendf(Client->Socket, "400 Unknown Command\n");
436 * \brief Set client username
438 * Usage: USER <username>
440 void Server_Cmd_USER(tClient *Client, char *Args)
444 if( Server_int_ParseArgs(0, Args, &username, NULL) )
446 sendf(Client->Socket, "407 USER takes 1 argument\n");
452 Debug(Client, "Authenticating as '%s'", username);
456 free(Client->Username);
457 Client->Username = strdup(username);
460 // Create a salt (that changes if the username is changed)
461 // Yes, I know, I'm a little paranoid, but who isn't?
462 Client->Salt[0] = 0x21 + (rand()&0x3F);
463 Client->Salt[1] = 0x21 + (rand()&0x3F);
464 Client->Salt[2] = 0x21 + (rand()&0x3F);
465 Client->Salt[3] = 0x21 + (rand()&0x3F);
466 Client->Salt[4] = 0x21 + (rand()&0x3F);
467 Client->Salt[5] = 0x21 + (rand()&0x3F);
468 Client->Salt[6] = 0x21 + (rand()&0x3F);
469 Client->Salt[7] = 0x21 + (rand()&0x3F);
471 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
472 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
474 sendf(Client->Socket, "100 User Set\n");
479 * \brief Authenticate as a user
483 void Server_Cmd_PASS(tClient *Client, char *Args)
488 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
490 sendf(Client->Socket, "407 PASS takes 1 argument\n");
494 // Pass on to cokebank
495 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
497 if( Client->UID == -1 ) {
498 sendf(Client->Socket, "401 Auth Failure\n");
502 flags = Bank_GetFlags(Client->UID);
503 if( flags & USER_FLAG_DISABLED ) {
505 sendf(Client->Socket, "403 Account Disabled\n");
508 if( flags & USER_FLAG_INTERNAL ) {
510 sendf(Client->Socket, "403 Internal account\n");
514 Client->bIsAuthed = 1;
515 sendf(Client->Socket, "200 Auth OK\n");
519 * \brief Authenticate as a user without a password
521 * Usage: AUTOAUTH <user>
523 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
528 if( Server_int_ParseArgs(0, Args, &username, NULL) )
530 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
535 if( !Client->bCanAutoAuth ) {
537 Debug(Client, "Untrusted client attempting to AUTOAUTH");
538 sendf(Client->Socket, "401 Untrusted\n");
543 Client->UID = Bank_GetAcctByName( username, 0 );
544 if( Client->UID < 0 ) {
546 Debug(Client, "Unknown user '%s'", username);
547 sendf(Client->Socket, "403 Auth Failure\n");
551 userflags = Bank_GetFlags(Client->UID);
552 // You can't be an internal account
553 if( userflags & USER_FLAG_INTERNAL ) {
555 Debug(Client, "Autoauth as '%s', not allowed", username);
557 sendf(Client->Socket, "403 Account is internal\n");
562 if( userflags & USER_FLAG_DISABLED ) {
564 sendf(Client->Socket, "403 Account disabled\n");
570 free(Client->Username);
571 Client->Username = strdup(username);
573 Client->bIsAuthed = 1;
576 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
578 sendf(Client->Socket, "200 Auth OK\n");
582 * \brief Authenticate as a user using the IDENT protocol
586 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args)
590 const int ident_timeout = 5;
592 if( Args != NULL && strlen(Args) ) {
593 sendf(Client->Socket, "407 AUTHIDENT takes no arguments\n");
598 if( !Client->bTrustedHost ) {
600 Debug(Client, "Untrusted client attempting to AUTHIDENT");
601 sendf(Client->Socket, "401 Untrusted\n");
605 // Get username via IDENT
606 username = ident_id(Client->Socket, ident_timeout);
608 perror("AUTHIDENT - IDENT timed out");
609 sendf(Client->Socket, "403 Authentication failure: IDENT auth timed out\n");
614 Client->UID = Bank_GetAcctByName( username, 0 );
615 if( Client->UID < 0 ) {
617 Debug(Client, "Unknown user '%s'", username);
618 sendf(Client->Socket, "403 Authentication failure: unknown account\n");
623 userflags = Bank_GetFlags(Client->UID);
624 // You can't be an internal account
625 if( userflags & USER_FLAG_INTERNAL ) {
627 Debug(Client, "IDENT auth as '%s', not allowed", username);
629 sendf(Client->Socket, "403 Authentication failure: that account is internal\n");
635 if( userflags & USER_FLAG_DISABLED ) {
637 sendf(Client->Socket, "403 Authentication failure: account disabled\n");
644 free(Client->Username);
645 Client->Username = strdup(username);
647 Client->bIsAuthed = 1;
650 Debug(Client, "IDENT authenticated as '%s' (%i)", username, Client->UID);
653 sendf(Client->Socket, "200 Auth OK\n");
657 * \brief Set effective user
659 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
662 int eUserFlags, userFlags;
664 if( Server_int_ParseArgs(0, Args, &username, NULL) )
666 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
670 if( !strlen(Args) ) {
671 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
675 // Check authentication
676 if( !Client->bIsAuthed ) {
677 sendf(Client->Socket, "401 Not Authenticated\n");
681 // Check user permissions
682 userFlags = Bank_GetFlags(Client->UID);
683 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
684 sendf(Client->Socket, "403 Not in coke\n");
689 Client->EffectiveUID = Bank_GetAcctByName(username, 0);
690 if( Client->EffectiveUID == -1 ) {
691 sendf(Client->Socket, "404 User not found\n");
694 // You can't be an internal account (unless you're an admin)
695 if( !(userFlags & USER_FLAG_ADMIN) )
697 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
698 if( eUserFlags & USER_FLAG_INTERNAL ) {
699 Client->EffectiveUID = -1;
700 sendf(Client->Socket, "404 User not found\n");
706 // - If disabled and the actual user is not an admin (and not root)
708 if( (eUserFlags & USER_FLAG_DISABLED) && (Client->UID == 0 || !(userFlags & USER_FLAG_ADMIN)) ) {
709 Client->EffectiveUID = -1;
710 sendf(Client->Socket, "403 Account disabled\n");
714 sendf(Client->Socket, "200 User set\n");
718 * \brief Send an item status to the client
719 * \param Client Who to?
720 * \param Item Item to send
722 void Server_int_SendItem(tClient *Client, tItem *Item)
724 char *status = "avail";
726 if( Item->Handler->CanDispense )
728 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
730 case 0: status = "avail"; break;
731 case 1: status = "sold"; break;
733 case -1: status = "error"; break;
737 if( !gbNoCostMode && Item->Price == 0 )
739 // KNOWN HACK: Naming a slot 'dead' disables it
740 if( strcmp(Item->Name, "dead") == 0 )
741 status = "sold"; // Another status?
743 sendf(Client->Socket,
744 "202 Item %s:%i %s %i %s\n",
745 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
750 * \brief Enumerate the items that the server knows about
752 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
756 if( Args != NULL && strlen(Args) ) {
757 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
763 for( i = 0; i < giNumItems; i ++ ) {
764 if( gaItems[i].bHidden ) continue;
768 sendf(Client->Socket, "201 Items %i\n", count);
770 for( i = 0; i < giNumItems; i ++ ) {
771 if( gaItems[i].bHidden ) continue;
772 Server_int_SendItem( Client, &gaItems[i] );
775 sendf(Client->Socket, "200 List end\n");
778 tItem *_GetItemFromString(char *String)
782 char *colon = strchr(String, ':');
794 for( i = 0; i < giNumHandlers; i ++ )
796 if( strcmp(gaHandlers[i]->Name, type) == 0) {
797 handler = gaHandlers[i];
806 for( i = 0; i < giNumItems; i ++ )
808 if( gaItems[i].Handler != handler ) continue;
809 if( gaItems[i].ID != num ) continue;
816 * \brief Fetch information on a specific item
818 * Usage: ITEMINFO <item ID>
820 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
825 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
826 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
829 item = _GetItemFromString(Args);
832 sendf(Client->Socket, "406 Bad Item ID\n");
836 Server_int_SendItem( Client, item );
840 * \brief Dispense an item
842 * Usage: DISPENSE <Item ID>
844 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
851 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
852 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
856 if( !Client->bIsAuthed ) {
857 sendf(Client->Socket, "401 Not Authenticated\n");
861 item = _GetItemFromString(itemname);
863 sendf(Client->Socket, "406 Bad Item ID\n");
867 if( Client->EffectiveUID != -1 ) {
868 uid = Client->EffectiveUID;
874 // if( Bank_GetFlags(Client->UID) & USER_FLAG_DISABLED ) {
877 switch( ret = DispenseItem( Client->UID, uid, item ) )
879 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
880 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
881 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
883 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
889 * \brief Refund an item to a user
891 * Usage: REFUND <user> <item id> [<price>]
893 void Server_Cmd_REFUND(tClient *Client, char *Args)
896 int uid, price_override = 0;
897 char *username, *itemname, *price_str;
899 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
900 if( !itemname || price_str ) {
901 sendf(Client->Socket, "407 REFUND takes 2 or 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");
917 uid = Bank_GetAcctByName(username, 0);
919 sendf(Client->Socket, "404 Unknown user\n");
923 item = _GetItemFromString(itemname);
925 sendf(Client->Socket, "406 Bad Item ID\n");
930 price_override = atoi(price_str);
932 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
934 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
936 sendf(Client->Socket, "500 Dispense Error\n");
942 * \brief Transfer money to another account
944 * Usage: GIVE <dest> <ammount> <reason...>
946 void Server_Cmd_GIVE(tClient *Client, char *Args)
948 char *recipient, *ammount, *reason;
953 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
954 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
959 if( !Client->bIsAuthed ) {
960 sendf(Client->Socket, "401 Not Authenticated\n");
965 uid = Bank_GetAcctByName(recipient, 0);
967 sendf(Client->Socket, "404 Invalid target user\n");
971 // You can't alter an internal account
972 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
973 // sendf(Client->Socket, "404 Invalid target user\n");
978 iAmmount = atoi(ammount);
979 if( iAmmount <= 0 ) {
980 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
984 if( Client->EffectiveUID != -1 ) {
985 thisUid = Client->EffectiveUID;
988 thisUid = Client->UID;
992 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
995 sendf(Client->Socket, "200 Give OK\n");
998 sendf(Client->Socket, "402 Poor You\n");
1001 sendf(Client->Socket, "500 Unknown error\n");
1006 void Server_Cmd_DONATE(tClient *Client, char *Args)
1008 char *ammount, *reason;
1013 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
1014 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
1018 if( !Client->bIsAuthed ) {
1019 sendf(Client->Socket, "401 Not Authenticated\n");
1024 iAmmount = atoi(ammount);
1025 if( iAmmount <= 0 ) {
1026 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
1030 // Handle effective users
1031 if( Client->EffectiveUID != -1 ) {
1032 thisUid = Client->EffectiveUID;
1035 thisUid = Client->UID;
1039 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
1042 sendf(Client->Socket, "200 Give OK\n");
1045 sendf(Client->Socket, "402 Poor You\n");
1048 sendf(Client->Socket, "500 Unknown error\n");
1053 void Server_Cmd_ADD(tClient *Client, char *Args)
1055 char *user, *ammount, *reason;
1059 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1060 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
1064 if( !Client->bIsAuthed ) {
1065 sendf(Client->Socket, "401 Not Authenticated\n");
1069 // Check user permissions
1070 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1071 sendf(Client->Socket, "403 Not in coke\n");
1076 if( strcmp( Client->Username, "root" ) == 0 ) {
1077 // Allow adding for new users
1078 if( strcmp(reason, "treasurer: new user") != 0 ) {
1079 sendf(Client->Socket, "403 Root may not add\n");
1086 if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
1088 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
1094 uid = Bank_GetAcctByName(user, 0);
1096 sendf(Client->Socket, "404 Invalid user\n");
1100 // You can't alter an internal account
1101 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
1103 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
1104 sendf(Client->Socket, "403 Admin only\n");
1107 // TODO: Maybe disallow changes to disabled?
1111 iAmmount = atoi(ammount);
1112 if( iAmmount == 0 && ammount[0] != '0' ) {
1113 sendf(Client->Socket, "407 Invalid Argument\n");
1118 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
1121 sendf(Client->Socket, "200 Add OK\n");
1124 sendf(Client->Socket, "402 Poor Guy\n");
1127 sendf(Client->Socket, "500 Unknown error\n");
1132 void Server_Cmd_SET(tClient *Client, char *Args)
1134 char *user, *ammount, *reason;
1138 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1139 sendf(Client->Socket, "407 SET takes 3 arguments\n");
1143 if( !Client->bIsAuthed ) {
1144 sendf(Client->Socket, "401 Not Authenticated\n");
1148 // Check user permissions
1149 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1150 sendf(Client->Socket, "403 Not an admin\n");
1155 uid = Bank_GetAcctByName(user, 0);
1157 sendf(Client->Socket, "404 Invalid user\n");
1162 iAmmount = atoi(ammount);
1163 if( iAmmount == 0 && ammount[0] != '0' ) {
1164 sendf(Client->Socket, "407 Invalid Argument\n");
1168 int origBalance, rv;
1170 switch( rv = DispenseSet(Client->UID, uid, iAmmount, reason, &origBalance) )
1173 sendf(Client->Socket, "200 Add OK (%i)\n", origBalance);
1176 sendf(Client->Socket, "500 Unknown error (%i)\n", rv);
1181 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1185 int maxBal = INT_MAX, minBal = INT_MIN;
1186 int flagMask = 0, flagVal = 0;
1187 int sort = BANK_ITFLAG_SORT_NAME;
1188 time_t lastSeenAfter=0, lastSeenBefore=0;
1190 int flags; // Iterator flags
1191 int balValue; // Balance value for iterator
1192 time_t timeValue; // Time value for iterator
1195 if( Args && strlen(Args) )
1197 char *space = Args, *type, *val;
1201 while(*type == ' ') type ++;
1203 space = strchr(space, ' ');
1204 if(space) *space = '\0';
1207 val = strchr(type, ':');
1214 if( strcmp(type, "min_balance") == 0 ) {
1217 // - Maximum Balance
1218 else if( strcmp(type, "max_balance") == 0 ) {
1222 else if( strcmp(type, "flags") == 0 ) {
1223 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1226 // - Last seen before timestamp
1227 else if( strcmp(type, "last_seen_before") == 0 ) {
1228 lastSeenAfter = atoll(val);
1230 // - Last seen after timestamp
1231 else if( strcmp(type, "last_seen_after") == 0 ) {
1232 lastSeenAfter = atoll(val);
1235 else if( strcmp(type, "sort") == 0 ) {
1236 char *dash = strchr(val, '-');
1241 if( strcmp(val, "name") == 0 ) {
1242 sort = BANK_ITFLAG_SORT_NAME;
1244 else if( strcmp(val, "balance") == 0 ) {
1245 sort = BANK_ITFLAG_SORT_BAL;
1247 else if( strcmp(val, "lastseen") == 0 ) {
1248 sort = BANK_ITFLAG_SORT_LASTSEEN;
1251 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1254 // Handle sort direction
1256 if( strcmp(dash, "desc") == 0 ) {
1257 sort |= BANK_ITFLAG_REVSORT;
1260 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1267 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1274 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1280 *space = ' '; // Repair (to be nice)
1282 while(*space == ' ') space ++;
1288 if( maxBal != INT_MAX ) {
1289 flags = sort|BANK_ITFLAG_MAXBALANCE;
1292 else if( minBal != INT_MIN ) {
1293 flags = sort|BANK_ITFLAG_MINBALANCE;
1300 if( lastSeenBefore ) {
1301 timeValue = lastSeenBefore;
1302 flags |= BANK_ITFLAG_SEENBEFORE;
1304 else if( lastSeenAfter ) {
1305 timeValue = lastSeenAfter;
1306 flags |= BANK_ITFLAG_SEENAFTER;
1311 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1313 // Get return number
1314 while( (i = Bank_IteratorNext(it)) != -1 )
1316 int bal = Bank_GetBalance(i);
1318 if( bal == INT_MIN ) continue;
1320 if( bal < minBal ) continue;
1321 if( bal > maxBal ) continue;
1326 Bank_DelIterator(it);
1329 sendf(Client->Socket, "201 Users %i\n", numRet);
1333 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1335 while( (i = Bank_IteratorNext(it)) != -1 )
1337 int bal = Bank_GetBalance(i);
1339 if( bal == INT_MIN ) continue;
1341 if( bal < minBal ) continue;
1342 if( bal > maxBal ) continue;
1344 _SendUserInfo(Client, i);
1347 Bank_DelIterator(it);
1349 sendf(Client->Socket, "200 List End\n");
1352 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1358 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1359 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1363 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1366 uid = Bank_GetAcctByName(user, 0);
1368 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1370 sendf(Client->Socket, "404 Invalid user\n");
1374 _SendUserInfo(Client, uid);
1377 void _SendUserInfo(tClient *Client, int UserID)
1379 char *type, *disabled="", *door="";
1380 int flags = Bank_GetFlags(UserID);
1382 if( flags & USER_FLAG_INTERNAL ) {
1385 else if( flags & USER_FLAG_COKE ) {
1386 if( flags & USER_FLAG_ADMIN )
1387 type = "coke,admin";
1391 else if( flags & USER_FLAG_ADMIN ) {
1398 if( flags & USER_FLAG_DISABLED )
1399 disabled = ",disabled";
1400 if( flags & USER_FLAG_DOORGROUP )
1403 // TODO: User flags/type
1405 Client->Socket, "202 User %s %i %s%s%s\n",
1406 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1407 type, disabled, door
1411 void Server_Cmd_USERADD(tClient *Client, char *Args)
1416 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1417 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1421 // Check authentication
1422 if( !Client->bIsAuthed ) {
1423 sendf(Client->Socket, "401 Not Authenticated\n");
1427 // Check permissions
1428 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1429 sendf(Client->Socket, "403 Not a coke admin\n");
1433 // Try to create user
1434 if( Bank_CreateAcct(username) == -1 ) {
1435 sendf(Client->Socket, "404 User exists\n");
1440 char *thisName = Bank_GetAcctName(Client->UID);
1441 Log_Info("Account '%s' created by '%s'", username, thisName);
1445 sendf(Client->Socket, "200 User Added\n");
1448 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1450 char *username, *flags, *reason=NULL;
1451 int mask=0, value=0;
1455 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1457 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1463 // Check authentication
1464 if( !Client->bIsAuthed ) {
1465 sendf(Client->Socket, "401 Not Authenticated\n");
1469 // Check permissions
1470 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1471 sendf(Client->Socket, "403 Not a coke admin\n");
1476 uid = Bank_GetAcctByName(username, 0);
1478 sendf(Client->Socket, "404 User '%s' not found\n", username);
1483 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1487 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1488 uid, username, mask, value);
1491 Bank_SetFlags(uid, mask, value);
1494 Log_Info("Updated '%s' with flag set '%s' by '%s' - Reason: %s",
1495 username, flags, Client->Username, reason);
1498 sendf(Client->Socket, "200 User Updated\n");
1501 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1503 char *itemname, *price_str, *description;
1507 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1508 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1512 if( !Client->bIsAuthed ) {
1513 sendf(Client->Socket, "401 Not Authenticated\n");
1517 // Check user permissions
1518 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1519 sendf(Client->Socket, "403 Not in coke\n");
1523 item = _GetItemFromString(itemname);
1525 // TODO: Create item?
1526 sendf(Client->Socket, "406 Bad Item ID\n");
1530 price = atoi(price_str);
1531 if( price <= 0 && price_str[0] != '0' ) {
1532 sendf(Client->Socket, "407 Invalid price set\n");
1535 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1539 sendf(Client->Socket, "200 Item updated\n");
1546 void Server_Cmd_PINCHECK(tClient *Client, char *Args)
1548 char *username, *pinstr;
1551 if( Server_int_ParseArgs(0, Args, &username, &pinstr, NULL) ) {
1552 sendf(Client->Socket, "407 PIN_CHECK takes 2 arguments\n");
1556 if( !isdigit(pinstr[0]) || !isdigit(pinstr[1]) || !isdigit(pinstr[2]) || !isdigit(pinstr[3]) || pinstr[4] != '\0' ) {
1557 sendf(Client->Socket, "407 PIN should be four digits\n");
1562 // Not authenticated? go away!
1563 if( !Client->bIsAuthed ) {
1564 sendf(Client->Socket, "401 Not Authenticated\n");
1569 int uid = Bank_GetAcctByName(username, 0);
1571 sendf(Client->Socket, "404 User '%s' not found\n", username);
1575 // Check user permissions
1576 if( uid != Client->UID && !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1577 sendf(Client->Socket, "403 Not in coke\n");
1582 static time_t last_wrong_pin_time;
1583 static int backoff = 1;
1584 if( time(NULL) - last_wrong_pin_time < backoff ) {
1585 sendf(Client->Socket, "407 Rate limited (%i seconds remaining)\n",
1586 backoff - (time(NULL) - last_wrong_pin_time));
1589 last_wrong_pin_time = time(NULL);
1590 if( !Bank_IsPinValid(uid, pin) )
1592 sendf(Client->Socket, "201 Pin incorrect\n");
1593 struct sockaddr_storage addr;
1594 socklen_t len = sizeof(addr);
1595 char ipstr[INET6_ADDRSTRLEN];
1596 getpeername(Client->Socket, (void*)&addr, &len);
1597 struct sockaddr_in *s = (struct sockaddr_in *)&addr;
1598 inet_ntop(addr.ss_family, &s->sin_addr, ipstr, sizeof(ipstr));
1599 Debug_Notice("Bad pin from %s for %s by %i", ipstr, username, Client->UID);
1605 last_wrong_pin_time = 0;
1607 sendf(Client->Socket, "200 Pin correct\n");
1610 void Server_Cmd_PINSET(tClient *Client, char *Args)
1616 if( Server_int_ParseArgs(0, Args, &pinstr, NULL) ) {
1617 sendf(Client->Socket, "407 PIN_SET takes 1 argument\n");
1621 if( !isdigit(pinstr[0]) || !isdigit(pinstr[1]) || !isdigit(pinstr[2]) || !isdigit(pinstr[3]) || pinstr[4] != '\0' ) {
1622 sendf(Client->Socket, "407 PIN should be four digits\n");
1627 if( !Client->bIsAuthed ) {
1628 sendf(Client->Socket, "401 Not Authenticated\n");
1632 int uid = Client->EffectiveUID;
1635 // Can only pinset yourself (well, the effective user)
1636 Bank_SetPin(uid, pin);
1637 sendf(Client->Socket, "200 Pin updated\n");
1641 // --- INTERNAL HELPERS ---
1642 void Debug(tClient *Client, const char *Format, ...)
1645 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1646 printf("[%i] ", Client->ID);
1647 va_start(args, Format);
1648 vprintf(Format, args);
1653 int sendf(int Socket, const char *Format, ...)
1658 va_start(args, Format);
1659 len = vsnprintf(NULL, 0, Format, args);
1664 va_start(args, Format);
1665 vsnprintf(buf, len+1, Format, args);
1668 #if DEBUG_TRACE_CLIENT
1669 printf("sendf: %s", buf);
1672 return send(Socket, buf, len, 0);
1676 // Takes a series of char *'s in
1678 * \brief Parse space-separated entries into
1680 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1685 va_start(args, ArgStr);
1690 while( (dest = va_arg(args, char **)) )
1696 savedChar = *ArgStr;
1698 while( (dest = va_arg(args, char **)) )
1700 // Trim leading spaces
1701 while( *ArgStr == ' ' || *ArgStr == '\t' )
1704 // ... oops, not enough arguments
1705 if( *ArgStr == '\0' )
1707 // NULL unset arguments
1710 } while( (dest = va_arg(args, char **)) );
1715 if( *ArgStr == '"' )
1720 while( *ArgStr && *ArgStr != '"' )
1727 // Read until a space
1728 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1731 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1737 // Oops, extra arguments, and greedy not set
1738 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1745 *ArgStr = savedChar;
1748 return 0; // Success!
1751 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1758 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1759 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1760 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1761 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1762 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1764 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1776 while( *Str == ' ' ) Str ++; // Eat whitespace
1777 space = strchr(Str, ','); // Find the end of the flag
1783 // Check for inversion/removal
1784 if( *Str == '!' || *Str == '-' ) {
1788 else if( *Str == '+' ) {
1792 // Check flag values
1793 for( i = 0; i < ciNumFlags; i ++ )
1795 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1796 *Mask |= cFLAGS[i].Mask;
1797 *Value &= ~cFLAGS[i].Mask;
1799 *Value |= cFLAGS[i].Value;
1805 if( i == ciNumFlags ) {
1807 strncpy(val, Str, len+1);
1808 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);