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 "../common/config.h"
14 #include <sys/socket.h>
15 #include <netinet/in.h>
16 #include <arpa/inet.h>
18 #include <fcntl.h> // O_*
22 #include <signal.h> // Signal handling
23 #include <ident.h> // AUTHIDENT
24 #include <time.h> // time(2)
27 #define DEBUG_TRACE_CLIENT 0
28 #define HACK_NO_REFUNDS 1
30 #define PIDFILE "/var/run/dispsrv.pid"
33 #define MAX_CONNECTION_QUEUE 5
34 #define INPUT_BUFFER_SIZE 256
35 #define CLIENT_TIMEOUT 10 // Seconds
37 #define HASH_TYPE SHA1
38 #define HASH_LENGTH 20
40 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
42 #define IDENT_TRUSTED_NETWORK 0x825F0D00
43 #define IDENT_TRUSTED_NETMASK 0xFFFFFFC0
46 typedef struct sClient
48 int Socket; // Client socket ID
52 int bCanAutoAuth; // Is the connection from a trusted host/port
63 void Server_Start(void);
64 void Server_Cleanup(void);
65 void Server_HandleClient(int Socket, int bTrustedHost, int bRootPort);
66 void Server_ParseClientCommand(tClient *Client, char *CommandString);
68 void Server_Cmd_USER(tClient *Client, char *Args);
69 void Server_Cmd_PASS(tClient *Client, char *Args);
70 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
71 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args);
72 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
73 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
74 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
75 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
76 void Server_Cmd_REFUND(tClient *Client, char *Args);
77 void Server_Cmd_GIVE(tClient *Client, char *Args);
78 void Server_Cmd_DONATE(tClient *Client, char *Args);
79 void Server_Cmd_ADD(tClient *Client, char *Args);
80 void Server_Cmd_SET(tClient *Client, char *Args);
81 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
82 void Server_Cmd_USERINFO(tClient *Client, char *Args);
83 void _SendUserInfo(tClient *Client, int UserID);
84 void Server_Cmd_USERADD(tClient *Client, char *Args);
85 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
86 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args);
87 void Server_Cmd_PINCHECK(tClient *Client, char *Args);
88 void Server_Cmd_PINSET(tClient *Client, char *Args);
90 void Debug(tClient *Client, const char *Format, ...);
91 int sendf(int Socket, const char *Format, ...);
92 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
93 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
97 const struct sClientCommand {
99 void (*Function)(tClient *Client, char *Arguments);
100 } gaServer_Commands[] = {
101 {"USER", Server_Cmd_USER},
102 {"PASS", Server_Cmd_PASS},
103 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
104 {"AUTHIDENT", Server_Cmd_AUTHIDENT},
105 {"SETEUSER", Server_Cmd_SETEUSER},
106 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
107 {"ITEM_INFO", Server_Cmd_ITEMINFO},
108 {"DISPENSE", Server_Cmd_DISPENSE},
109 {"REFUND", Server_Cmd_REFUND},
110 {"GIVE", Server_Cmd_GIVE},
111 {"DONATE", Server_Cmd_DONATE},
112 {"ADD", Server_Cmd_ADD},
113 {"SET", Server_Cmd_SET},
114 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
115 {"USER_INFO", Server_Cmd_USERINFO},
116 {"USER_ADD", Server_Cmd_USERADD},
117 {"USER_FLAGS", Server_Cmd_USERFLAGS},
118 {"UPDATE_ITEM", Server_Cmd_UPDATEITEM},
119 {"PIN_CHECK", Server_Cmd_PINCHECK},
120 {"PIN_SET", Server_Cmd_PINSET}
122 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
126 int giServer_Port = 11020;
127 int gbServer_RunInBackground = 0;
128 char *gsServer_LogFile = "/var/log/dispsrv.log";
129 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
130 int giServer_NumTrustedHosts;
131 struct in_addr *gaServer_TrustedHosts;
133 int giServer_Socket; // Server socket
134 int giServer_NextClientID = 1; // Debug client ID
139 * \brief Open listenting socket and serve connections
141 void Server_Start(void)
144 struct sockaddr_in server_addr, client_addr;
146 // Parse trusted hosts list
147 giServer_NumTrustedHosts = Config_GetValueCount("trusted_host");
148 gaServer_TrustedHosts = malloc(giServer_NumTrustedHosts * sizeof(*gaServer_TrustedHosts));
149 for( int i = 0; i < giServer_NumTrustedHosts; i ++ )
151 const char *addr = Config_GetValue("trusted_host", i);
153 if( inet_aton(addr, &gaServer_TrustedHosts[i]) == 0 ) {
154 fprintf(stderr, "Invalid IP address '%s'\n", addr);
159 // Ignore SIGPIPE (stops crashes when the client exits early)
160 signal(SIGPIPE, SIG_IGN);
163 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
164 if( giServer_Socket < 0 ) {
165 fprintf(stderr, "ERROR: Unable to create server socket\n");
169 // Make listen address
170 memset(&server_addr, 0, sizeof(server_addr));
171 server_addr.sin_family = AF_INET; // Internet Socket
172 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
173 server_addr.sin_port = htons(giServer_Port); // Port
176 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
177 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
179 close(giServer_Socket);
183 // Fork into background
184 if( gbServer_RunInBackground )
188 fprintf(stderr, "ERROR: Unable to fork\n");
189 perror("fork background");
194 Debug_Notice("Forked child server as PID %i\n", pid);
198 // - Sort out stdin/stdout
200 dup2( open("/dev/null", O_RDONLY, 0644), STDIN_FILENO );
201 dup2( open(gsServer_LogFile, O_CREAT|O_APPEND, 0644), STDOUT_FILENO );
202 dup2( open(gsServer_ErrorLog, O_CREAT|O_APPEND, 0644), STDERR_FILENO );
204 freopen("/dev/null", "r", stdin);
205 freopen(gsServer_LogFile, "a", stdout);
206 freopen(gsServer_ErrorLog, "a", stderr);
207 fprintf(stdout, "OpenDispense 2 Server Started at %lld\n", (long long)time(NULL));
208 fprintf(stderr, "OpenDispense 2 Server Started at %lld\n", (long long)time(NULL));
211 atexit(Server_Cleanup);
213 // Start the helper thread
214 StartPeriodicThread();
217 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
218 fprintf(stderr, "ERROR: Unable to listen to socket\n");
223 Debug_Notice("Listening on 0.0.0.0:%i", giServer_Port);
227 FILE *fp = fopen(PIDFILE, "w");
229 fprintf(fp, "%i", getpid());
236 uint len = sizeof(client_addr);
240 // Accept a connection
241 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
242 if(client_socket < 0) {
243 fprintf(stderr, "ERROR: Unable to accept client connection\n");
247 // Set a timeout on the user conneciton
250 tv.tv_sec = CLIENT_TIMEOUT;
252 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
254 perror("setsockopt");
259 // Debug: Print the connection string
260 if(giDebugLevel >= 2) {
261 char ipstr[INET_ADDRSTRLEN];
262 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
263 Debug_Debug("Client connection from %s:%i",
264 ipstr, ntohs(client_addr.sin_port));
267 // Doesn't matter what, localhost is trusted
268 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
271 // Check if the host is on the trusted list
272 for( int i = 0; i < giServer_NumTrustedHosts; i ++ )
274 if( memcmp(&client_addr.sin_addr, &gaServer_TrustedHosts[i], sizeof(struct in_addr)) == 0 )
281 // Root port (can AUTOAUTH if also a trusted machine
282 if( ntohs(client_addr.sin_port) < 1024 )
287 // TODO: Make this runtime configurable
288 switch( ntohl( client_addr.sin_addr.s_addr ) )
290 case 0x7F000001: // 127.0.0.1 localhost
291 // case 0x825F0D00: // 130.95.13.0
292 case 0x825F0D04: // 130.95.13.4 merlo
293 // case 0x825F0D05: // 130.95.13.5 heathred (MR)
294 case 0x825F0D07: // 130.95.13.7 motsugo
295 case 0x825F0D11: // 130.95.13.17 mermaid
296 case 0x825F0D12: // 130.95.13.18 mussel
297 case 0x825F0D17: // 130.95.13.23 martello
298 case 0x825F0D2A: // 130.95.13.42 meersau
299 // case 0x825F0D42: // 130.95.13.66 heathred (Clubroom)
308 // TODO: Multithread this?
309 Server_HandleClient(client_socket, bTrusted, bRootPort);
311 close(client_socket);
315 void Server_Cleanup(void)
317 Debug_Debug("Close(%i)", giServer_Socket);
318 close(giServer_Socket);
323 * \brief Reads from a client socket and parses the command strings
324 * \param Socket Client socket number/handle
325 * \param bTrusted Is the client trusted?
327 void Server_HandleClient(int Socket, int bTrusted, int bRootPort)
329 char inbuf[INPUT_BUFFER_SIZE];
331 int remspace = INPUT_BUFFER_SIZE-1;
335 memset(&clientInfo, 0, sizeof(clientInfo));
337 // Initialise Client info
338 clientInfo.Socket = Socket;
339 clientInfo.ID = giServer_NextClientID ++;
340 clientInfo.bTrustedHost = bTrusted;
341 clientInfo.bCanAutoAuth = bTrusted && bRootPort;
342 clientInfo.EffectiveUID = -1;
347 * - The `buf` and `remspace` variables allow a line to span several
348 * calls to recv(), if a line is not completed in one recv() call
349 * it is saved to the beginning of `inbuf` and `buf` is updated to
352 // TODO: Use select() instead (to give a timeout)
353 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
356 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
360 while( (eol = strchr(start, '\n')) )
364 Server_ParseClientCommand(&clientInfo, start);
369 // Check if there was an incomplete line
370 if( *start != '\0' ) {
371 int tailBytes = bytes - (start-buf);
372 // Roll back in buffer
373 memcpy(inbuf, start, tailBytes);
374 remspace -= tailBytes;
376 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
378 remspace = INPUT_BUFFER_SIZE - 1;
383 remspace = INPUT_BUFFER_SIZE - 1;
389 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
393 if(giDebugLevel >= 2) {
394 printf("Client %i: Disconnected\n", clientInfo.ID);
399 * \brief Parses a client command and calls the required helper function
400 * \param Client Pointer to client state structure
401 * \param CommandString Command from client (single line of the command)
402 * \return Heap String to return to the client
404 void Server_ParseClientCommand(tClient *Client, char *CommandString)
406 char *command, *args;
409 if( giDebugLevel >= 2 )
410 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
412 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
414 if( command == NULL ) return ;
415 // Is this an error? (just ignore for now)
420 for( i = 0; i < NUM_COMMANDS; i++ )
422 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
423 if( giDebugLevel >= 2 )
424 Debug(Client, "CMD %s - \"%s\"", command, args);
425 gaServer_Commands[i].Function(Client, args);
430 sendf(Client->Socket, "400 Unknown Command\n");
437 * \brief Set client username
439 * Usage: USER <username>
441 void Server_Cmd_USER(tClient *Client, char *Args)
445 if( Server_int_ParseArgs(0, Args, &username, NULL) )
447 sendf(Client->Socket, "407 USER takes 1 argument\n");
453 Debug(Client, "Authenticating as '%s'", username);
457 free(Client->Username);
458 Client->Username = strdup(username);
461 // Create a salt (that changes if the username is changed)
462 // Yes, I know, I'm a little paranoid, but who isn't?
463 Client->Salt[0] = 0x21 + (rand()&0x3F);
464 Client->Salt[1] = 0x21 + (rand()&0x3F);
465 Client->Salt[2] = 0x21 + (rand()&0x3F);
466 Client->Salt[3] = 0x21 + (rand()&0x3F);
467 Client->Salt[4] = 0x21 + (rand()&0x3F);
468 Client->Salt[5] = 0x21 + (rand()&0x3F);
469 Client->Salt[6] = 0x21 + (rand()&0x3F);
470 Client->Salt[7] = 0x21 + (rand()&0x3F);
472 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
473 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
475 sendf(Client->Socket, "100 User Set\n");
480 * \brief Authenticate as a user
484 void Server_Cmd_PASS(tClient *Client, char *Args)
489 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
491 sendf(Client->Socket, "407 PASS takes 1 argument\n");
495 // Pass on to cokebank
496 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
498 if( Client->UID == -1 ) {
499 sendf(Client->Socket, "401 Auth Failure\n");
503 flags = Bank_GetFlags(Client->UID);
504 if( flags & USER_FLAG_DISABLED ) {
506 sendf(Client->Socket, "403 Account Disabled\n");
509 if( flags & USER_FLAG_INTERNAL ) {
511 sendf(Client->Socket, "403 Internal account\n");
515 Client->bIsAuthed = 1;
516 sendf(Client->Socket, "200 Auth OK\n");
520 * \brief Authenticate as a user without a password
522 * Usage: AUTOAUTH <user>
524 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
529 if( Server_int_ParseArgs(0, Args, &username, NULL) )
531 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
536 if( !Client->bCanAutoAuth ) {
538 Debug(Client, "Untrusted client attempting to AUTOAUTH");
539 sendf(Client->Socket, "401 Untrusted\n");
544 Client->UID = Bank_GetAcctByName( username, 0 );
545 if( Client->UID < 0 ) {
547 Debug(Client, "Unknown user '%s'", username);
548 sendf(Client->Socket, "403 Auth Failure\n");
552 userflags = Bank_GetFlags(Client->UID);
553 // You can't be an internal account
554 if( userflags & USER_FLAG_INTERNAL ) {
556 Debug(Client, "Autoauth as '%s', not allowed", username);
558 sendf(Client->Socket, "403 Account is internal\n");
563 if( userflags & USER_FLAG_DISABLED ) {
565 sendf(Client->Socket, "403 Account disabled\n");
571 free(Client->Username);
572 Client->Username = strdup(username);
574 Client->bIsAuthed = 1;
577 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
579 sendf(Client->Socket, "200 Auth OK\n");
583 * \brief Authenticate as a user using the IDENT protocol
587 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args)
591 const int ident_timeout = 5;
593 if( Args != NULL && strlen(Args) ) {
594 sendf(Client->Socket, "407 AUTHIDENT takes no arguments\n");
599 if( !Client->bTrustedHost ) {
601 Debug(Client, "Untrusted client attempting to AUTHIDENT");
602 sendf(Client->Socket, "401 Untrusted\n");
606 // Get username via IDENT
607 username = ident_id(Client->Socket, ident_timeout);
609 perror("AUTHIDENT - IDENT timed out");
610 sendf(Client->Socket, "403 Authentication failure: IDENT auth timed out\n");
615 Client->UID = Bank_GetAcctByName( username, 0 );
616 if( Client->UID < 0 ) {
618 Debug(Client, "Unknown user '%s'", username);
619 sendf(Client->Socket, "403 Authentication failure: unknown account\n");
624 userflags = Bank_GetFlags(Client->UID);
625 // You can't be an internal account
626 if( userflags & USER_FLAG_INTERNAL ) {
628 Debug(Client, "IDENT auth as '%s', not allowed", username);
630 sendf(Client->Socket, "403 Authentication failure: that account is internal\n");
636 if( userflags & USER_FLAG_DISABLED ) {
638 sendf(Client->Socket, "403 Authentication failure: account disabled\n");
645 free(Client->Username);
646 Client->Username = strdup(username);
648 Client->bIsAuthed = 1;
651 Debug(Client, "IDENT authenticated as '%s' (%i)", username, Client->UID);
654 sendf(Client->Socket, "200 Auth OK\n");
658 * \brief Set effective user
660 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
663 int eUserFlags, userFlags;
665 if( Server_int_ParseArgs(0, Args, &username, NULL) )
667 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
671 if( !strlen(Args) ) {
672 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
676 // Check authentication
677 if( !Client->bIsAuthed ) {
678 sendf(Client->Socket, "401 Not Authenticated\n");
682 // Check user permissions
683 userFlags = Bank_GetFlags(Client->UID);
684 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
685 sendf(Client->Socket, "403 Not in coke\n");
690 Client->EffectiveUID = Bank_GetAcctByName(username, 0);
691 if( Client->EffectiveUID == -1 ) {
692 sendf(Client->Socket, "404 User not found\n");
695 // You can't be an internal account (unless you're an admin)
696 if( !(userFlags & USER_FLAG_ADMIN) )
698 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
699 if( eUserFlags & USER_FLAG_INTERNAL ) {
700 Client->EffectiveUID = -1;
701 sendf(Client->Socket, "404 User not found\n");
707 // - If disabled and the actual user is not an admin (and not root)
709 if( (eUserFlags & USER_FLAG_DISABLED) && (Client->UID == 0 || !(userFlags & USER_FLAG_ADMIN)) ) {
710 Client->EffectiveUID = -1;
711 sendf(Client->Socket, "403 Account disabled\n");
715 sendf(Client->Socket, "200 User set\n");
719 * \brief Send an item status to the client
720 * \param Client Who to?
721 * \param Item Item to send
723 void Server_int_SendItem(tClient *Client, tItem *Item)
725 char *status = "avail";
727 if( Item->Handler->CanDispense )
729 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
731 case 0: status = "avail"; break;
732 case 1: status = "sold"; break;
734 case -1: status = "error"; break;
738 if( !gbNoCostMode && Item->Price == 0 )
740 // KNOWN HACK: Naming a slot 'dead' disables it
741 if( strcmp(Item->Name, "dead") == 0 )
742 status = "sold"; // Another status?
744 sendf(Client->Socket,
745 "202 Item %s:%i %s %i %s\n",
746 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
751 * \brief Enumerate the items that the server knows about
753 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
757 if( Args != NULL && strlen(Args) ) {
758 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
764 for( i = 0; i < giNumItems; i ++ ) {
765 if( gaItems[i].bHidden ) continue;
769 sendf(Client->Socket, "201 Items %i\n", count);
771 for( i = 0; i < giNumItems; i ++ ) {
772 if( gaItems[i].bHidden ) continue;
773 Server_int_SendItem( Client, &gaItems[i] );
776 sendf(Client->Socket, "200 List end\n");
779 tItem *_GetItemFromString(char *String)
783 char *colon = strchr(String, ':');
795 for( i = 0; i < giNumHandlers; i ++ )
797 if( strcmp(gaHandlers[i]->Name, type) == 0) {
798 handler = gaHandlers[i];
807 for( i = 0; i < giNumItems; i ++ )
809 if( gaItems[i].Handler != handler ) continue;
810 if( gaItems[i].ID != num ) continue;
817 * \brief Fetch information on a specific item
819 * Usage: ITEMINFO <item ID>
821 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
826 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
827 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
830 item = _GetItemFromString(Args);
833 sendf(Client->Socket, "406 Bad Item ID\n");
837 Server_int_SendItem( Client, item );
841 * \brief Dispense an item
843 * Usage: DISPENSE <Item ID>
845 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
852 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
853 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
857 if( !Client->bIsAuthed ) {
858 sendf(Client->Socket, "401 Not Authenticated\n");
862 item = _GetItemFromString(itemname);
864 sendf(Client->Socket, "406 Bad Item ID\n");
868 if( Client->EffectiveUID != -1 ) {
869 uid = Client->EffectiveUID;
875 // if( Bank_GetFlags(Client->UID) & USER_FLAG_DISABLED ) {
878 switch( ret = DispenseItem( Client->UID, uid, item ) )
880 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
881 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
882 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
884 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
890 * \brief Refund an item to a user
892 * Usage: REFUND <user> <item id> [<price>]
894 void Server_Cmd_REFUND(tClient *Client, char *Args)
897 int uid, price_override = 0;
898 char *username, *itemname, *price_str;
900 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
901 if( !itemname || price_str ) {
902 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
907 if( !Client->bIsAuthed ) {
908 sendf(Client->Socket, "401 Not Authenticated\n");
912 // Check user permissions
913 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
914 sendf(Client->Socket, "403 Not in coke\n");
918 uid = Bank_GetAcctByName(username, 0);
920 sendf(Client->Socket, "404 Unknown user\n");
924 item = _GetItemFromString(itemname);
926 sendf(Client->Socket, "406 Bad Item ID\n");
931 price_override = atoi(price_str);
933 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
935 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
937 sendf(Client->Socket, "500 Dispense Error\n");
943 * \brief Transfer money to another account
945 * Usage: GIVE <dest> <ammount> <reason...>
947 void Server_Cmd_GIVE(tClient *Client, char *Args)
949 char *recipient, *ammount, *reason;
954 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
955 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
960 if( !Client->bIsAuthed ) {
961 sendf(Client->Socket, "401 Not Authenticated\n");
966 uid = Bank_GetAcctByName(recipient, 0);
968 sendf(Client->Socket, "404 Invalid target user\n");
972 // You can't alter an internal account
973 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
974 // sendf(Client->Socket, "404 Invalid target user\n");
979 iAmmount = atoi(ammount);
980 if( iAmmount <= 0 ) {
981 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
985 if( Client->EffectiveUID != -1 ) {
986 thisUid = Client->EffectiveUID;
989 thisUid = Client->UID;
993 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
996 sendf(Client->Socket, "200 Give OK\n");
999 sendf(Client->Socket, "402 Poor You\n");
1002 sendf(Client->Socket, "500 Unknown error\n");
1007 void Server_Cmd_DONATE(tClient *Client, char *Args)
1009 char *ammount, *reason;
1014 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
1015 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
1019 if( !Client->bIsAuthed ) {
1020 sendf(Client->Socket, "401 Not Authenticated\n");
1025 iAmmount = atoi(ammount);
1026 if( iAmmount <= 0 ) {
1027 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
1031 // Handle effective users
1032 if( Client->EffectiveUID != -1 ) {
1033 thisUid = Client->EffectiveUID;
1036 thisUid = Client->UID;
1040 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
1043 sendf(Client->Socket, "200 Give OK\n");
1046 sendf(Client->Socket, "402 Poor You\n");
1049 sendf(Client->Socket, "500 Unknown error\n");
1054 void Server_Cmd_ADD(tClient *Client, char *Args)
1056 char *user, *ammount, *reason;
1060 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1061 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
1065 if( !Client->bIsAuthed ) {
1066 sendf(Client->Socket, "401 Not Authenticated\n");
1070 // Check user permissions
1071 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1072 sendf(Client->Socket, "403 Not in coke\n");
1077 if( strcmp( Client->Username, "root" ) == 0 ) {
1078 // Allow adding for new users
1079 if( strcmp(reason, "treasurer: new user") != 0 ) {
1080 sendf(Client->Socket, "403 Root may not add\n");
1087 if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
1089 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
1095 uid = Bank_GetAcctByName(user, 0);
1097 sendf(Client->Socket, "404 Invalid user\n");
1101 // You can't alter an internal account
1102 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
1104 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
1105 sendf(Client->Socket, "403 Admin only\n");
1108 // TODO: Maybe disallow changes to disabled?
1112 iAmmount = atoi(ammount);
1113 if( iAmmount == 0 && ammount[0] != '0' ) {
1114 sendf(Client->Socket, "407 Invalid Argument\n");
1119 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
1122 sendf(Client->Socket, "200 Add OK\n");
1125 sendf(Client->Socket, "402 Poor Guy\n");
1128 sendf(Client->Socket, "500 Unknown error\n");
1133 void Server_Cmd_SET(tClient *Client, char *Args)
1135 char *user, *ammount, *reason;
1139 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1140 sendf(Client->Socket, "407 SET takes 3 arguments\n");
1144 if( !Client->bIsAuthed ) {
1145 sendf(Client->Socket, "401 Not Authenticated\n");
1149 // Check user permissions
1150 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1151 sendf(Client->Socket, "403 Not an admin\n");
1156 uid = Bank_GetAcctByName(user, 0);
1158 sendf(Client->Socket, "404 Invalid user\n");
1163 iAmmount = atoi(ammount);
1164 if( iAmmount == 0 && ammount[0] != '0' ) {
1165 sendf(Client->Socket, "407 Invalid Argument\n");
1169 int origBalance, rv;
1171 switch( rv = DispenseSet(Client->UID, uid, iAmmount, reason, &origBalance) )
1174 sendf(Client->Socket, "200 Add OK (%i)\n", origBalance);
1177 sendf(Client->Socket, "500 Unknown error (%i)\n", rv);
1182 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1186 int maxBal = INT_MAX, minBal = INT_MIN;
1187 int flagMask = 0, flagVal = 0;
1188 int sort = BANK_ITFLAG_SORT_NAME;
1189 time_t lastSeenAfter=0, lastSeenBefore=0;
1191 int flags; // Iterator flags
1192 int balValue; // Balance value for iterator
1193 time_t timeValue; // Time value for iterator
1196 if( Args && strlen(Args) )
1198 char *space = Args, *type, *val;
1202 while(*type == ' ') type ++;
1204 space = strchr(space, ' ');
1205 if(space) *space = '\0';
1208 val = strchr(type, ':');
1215 if( strcmp(type, "min_balance") == 0 ) {
1218 // - Maximum Balance
1219 else if( strcmp(type, "max_balance") == 0 ) {
1223 else if( strcmp(type, "flags") == 0 ) {
1224 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1227 // - Last seen before timestamp
1228 else if( strcmp(type, "last_seen_before") == 0 ) {
1229 lastSeenAfter = atoll(val);
1231 // - Last seen after timestamp
1232 else if( strcmp(type, "last_seen_after") == 0 ) {
1233 lastSeenAfter = atoll(val);
1236 else if( strcmp(type, "sort") == 0 ) {
1237 char *dash = strchr(val, '-');
1242 if( strcmp(val, "name") == 0 ) {
1243 sort = BANK_ITFLAG_SORT_NAME;
1245 else if( strcmp(val, "balance") == 0 ) {
1246 sort = BANK_ITFLAG_SORT_BAL;
1248 else if( strcmp(val, "lastseen") == 0 ) {
1249 sort = BANK_ITFLAG_SORT_LASTSEEN;
1252 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1255 // Handle sort direction
1257 if( strcmp(dash, "desc") == 0 ) {
1258 sort |= BANK_ITFLAG_REVSORT;
1261 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1268 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1275 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1281 *space = ' '; // Repair (to be nice)
1283 while(*space == ' ') space ++;
1289 if( maxBal != INT_MAX ) {
1290 flags = sort|BANK_ITFLAG_MAXBALANCE;
1293 else if( minBal != INT_MIN ) {
1294 flags = sort|BANK_ITFLAG_MINBALANCE;
1301 if( lastSeenBefore ) {
1302 timeValue = lastSeenBefore;
1303 flags |= BANK_ITFLAG_SEENBEFORE;
1305 else if( lastSeenAfter ) {
1306 timeValue = lastSeenAfter;
1307 flags |= BANK_ITFLAG_SEENAFTER;
1312 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1314 // Get return number
1315 while( (i = Bank_IteratorNext(it)) != -1 )
1317 int bal = Bank_GetBalance(i);
1319 if( bal == INT_MIN ) continue;
1321 if( bal < minBal ) continue;
1322 if( bal > maxBal ) continue;
1327 Bank_DelIterator(it);
1330 sendf(Client->Socket, "201 Users %i\n", numRet);
1334 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1336 while( (i = Bank_IteratorNext(it)) != -1 )
1338 int bal = Bank_GetBalance(i);
1340 if( bal == INT_MIN ) continue;
1342 if( bal < minBal ) continue;
1343 if( bal > maxBal ) continue;
1345 _SendUserInfo(Client, i);
1348 Bank_DelIterator(it);
1350 sendf(Client->Socket, "200 List End\n");
1353 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1359 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1360 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1364 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1367 uid = Bank_GetAcctByName(user, 0);
1369 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1371 sendf(Client->Socket, "404 Invalid user\n");
1375 _SendUserInfo(Client, uid);
1378 void _SendUserInfo(tClient *Client, int UserID)
1380 char *type, *disabled="", *door="";
1381 int flags = Bank_GetFlags(UserID);
1383 if( flags & USER_FLAG_INTERNAL ) {
1386 else if( flags & USER_FLAG_COKE ) {
1387 if( flags & USER_FLAG_ADMIN )
1388 type = "coke,admin";
1392 else if( flags & USER_FLAG_ADMIN ) {
1399 if( flags & USER_FLAG_DISABLED )
1400 disabled = ",disabled";
1401 if( flags & USER_FLAG_DOORGROUP )
1404 // TODO: User flags/type
1406 Client->Socket, "202 User %s %i %s%s%s\n",
1407 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1408 type, disabled, door
1412 void Server_Cmd_USERADD(tClient *Client, char *Args)
1417 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1418 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1422 // Check authentication
1423 if( !Client->bIsAuthed ) {
1424 sendf(Client->Socket, "401 Not Authenticated\n");
1428 // Check permissions
1429 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1430 sendf(Client->Socket, "403 Not a coke admin\n");
1434 // Try to create user
1435 if( Bank_CreateAcct(username) == -1 ) {
1436 sendf(Client->Socket, "404 User exists\n");
1441 char *thisName = Bank_GetAcctName(Client->UID);
1442 Log_Info("Account '%s' created by '%s'", username, thisName);
1446 sendf(Client->Socket, "200 User Added\n");
1449 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1451 char *username, *flags, *reason=NULL;
1452 int mask=0, value=0;
1456 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1458 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1464 // Check authentication
1465 if( !Client->bIsAuthed ) {
1466 sendf(Client->Socket, "401 Not Authenticated\n");
1470 // Check permissions
1471 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1472 sendf(Client->Socket, "403 Not a coke admin\n");
1477 uid = Bank_GetAcctByName(username, 0);
1479 sendf(Client->Socket, "404 User '%s' not found\n", username);
1484 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1488 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1489 uid, username, mask, value);
1492 Bank_SetFlags(uid, mask, value);
1495 Log_Info("Updated '%s' with flag set '%s' by '%s' - Reason: %s",
1496 username, flags, Client->Username, reason);
1499 sendf(Client->Socket, "200 User Updated\n");
1502 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1504 char *itemname, *price_str, *description;
1508 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1509 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1513 if( !Client->bIsAuthed ) {
1514 sendf(Client->Socket, "401 Not Authenticated\n");
1518 // Check user permissions
1519 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1520 sendf(Client->Socket, "403 Not in coke\n");
1524 item = _GetItemFromString(itemname);
1526 // TODO: Create item?
1527 sendf(Client->Socket, "406 Bad Item ID\n");
1531 price = atoi(price_str);
1532 if( price <= 0 && price_str[0] != '0' ) {
1533 sendf(Client->Socket, "407 Invalid price set\n");
1536 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1540 sendf(Client->Socket, "200 Item updated\n");
1547 void Server_Cmd_PINCHECK(tClient *Client, char *Args)
1549 char *username, *pinstr;
1552 if( Server_int_ParseArgs(0, Args, &username, &pinstr, NULL) ) {
1553 sendf(Client->Socket, "407 PIN_CHECK takes 2 arguments\n");
1557 if( !isdigit(pinstr[0]) || !isdigit(pinstr[1]) || !isdigit(pinstr[2]) || !isdigit(pinstr[3]) || pinstr[4] != '\0' ) {
1558 sendf(Client->Socket, "407 PIN should be four digits\n");
1563 // Not authenticated? go away!
1564 if( !Client->bIsAuthed ) {
1565 sendf(Client->Socket, "401 Not Authenticated\n");
1570 int uid = Bank_GetAcctByName(username, 0);
1572 sendf(Client->Socket, "404 User '%s' not found\n", username);
1576 // Check user permissions
1577 if( uid != Client->UID && !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1578 sendf(Client->Socket, "403 Not in coke\n");
1583 static time_t last_wrong_pin_time;
1584 static int backoff = 1;
1585 if( time(NULL) - last_wrong_pin_time < backoff ) {
1586 sendf(Client->Socket, "407 Rate limited (%i seconds remaining)\n",
1587 backoff - (time(NULL) - last_wrong_pin_time));
1590 last_wrong_pin_time = time(NULL);
1591 if( !Bank_IsPinValid(uid, pin) )
1593 sendf(Client->Socket, "201 Pin incorrect\n");
1594 struct sockaddr_storage addr;
1595 socklen_t len = sizeof(addr);
1596 char ipstr[INET6_ADDRSTRLEN];
1597 getpeername(Client->Socket, (void*)&addr, &len);
1598 struct sockaddr_in *s = (struct sockaddr_in *)&addr;
1599 inet_ntop(addr.ss_family, &s->sin_addr, ipstr, sizeof(ipstr));
1600 Debug_Notice("Bad pin from %s for %s by %i", ipstr, username, Client->UID);
1606 last_wrong_pin_time = 0;
1608 sendf(Client->Socket, "200 Pin correct\n");
1611 void Server_Cmd_PINSET(tClient *Client, char *Args)
1617 if( Server_int_ParseArgs(0, Args, &pinstr, NULL) ) {
1618 sendf(Client->Socket, "407 PIN_SET takes 1 argument\n");
1622 if( !isdigit(pinstr[0]) || !isdigit(pinstr[1]) || !isdigit(pinstr[2]) || !isdigit(pinstr[3]) || pinstr[4] != '\0' ) {
1623 sendf(Client->Socket, "407 PIN should be four digits\n");
1628 if( !Client->bIsAuthed ) {
1629 sendf(Client->Socket, "401 Not Authenticated\n");
1633 int uid = Client->EffectiveUID;
1636 // Can only pinset yourself (well, the effective user)
1637 Bank_SetPin(uid, pin);
1638 sendf(Client->Socket, "200 Pin updated\n");
1642 // --- INTERNAL HELPERS ---
1643 void Debug(tClient *Client, const char *Format, ...)
1646 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1647 printf("[%i] ", Client->ID);
1648 va_start(args, Format);
1649 vprintf(Format, args);
1654 int sendf(int Socket, const char *Format, ...)
1659 va_start(args, Format);
1660 len = vsnprintf(NULL, 0, Format, args);
1665 va_start(args, Format);
1666 vsnprintf(buf, len+1, Format, args);
1669 #if DEBUG_TRACE_CLIENT
1670 printf("sendf: %s", buf);
1673 return send(Socket, buf, len, 0);
1677 // Takes a series of char *'s in
1679 * \brief Parse space-separated entries into
1681 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1686 va_start(args, ArgStr);
1691 while( (dest = va_arg(args, char **)) )
1697 savedChar = *ArgStr;
1699 while( (dest = va_arg(args, char **)) )
1701 // Trim leading spaces
1702 while( *ArgStr == ' ' || *ArgStr == '\t' )
1705 // ... oops, not enough arguments
1706 if( *ArgStr == '\0' )
1708 // NULL unset arguments
1711 } while( (dest = va_arg(args, char **)) );
1716 if( *ArgStr == '"' )
1721 while( *ArgStr && *ArgStr != '"' )
1728 // Read until a space
1729 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1732 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1738 // Oops, extra arguments, and greedy not set
1739 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1746 *ArgStr = savedChar;
1749 return 0; // Success!
1752 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1759 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1760 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1761 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1762 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1763 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1765 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1777 while( *Str == ' ' ) Str ++; // Eat whitespace
1778 space = strchr(Str, ','); // Find the end of the flag
1784 // Check for inversion/removal
1785 if( *Str == '!' || *Str == '-' ) {
1789 else if( *Str == '+' ) {
1793 // Check flag values
1794 for( i = 0; i < ciNumFlags; i ++ )
1796 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1797 *Mask |= cFLAGS[i].Mask;
1798 *Value &= ~cFLAGS[i].Mask;
1800 *Value |= cFLAGS[i].Value;
1806 if( i == ciNumFlags ) {
1808 strncpy(val, Str, len+1);
1809 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);