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 atexit(Server_Cleanup);
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);
182 // Fork into background
183 if( gbServer_RunInBackground )
187 fprintf(stderr, "ERROR: Unable to fork\n");
188 perror("fork background");
193 printf("Forked child %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));
211 // Start the helper thread
212 StartPeriodicThread();
215 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
216 fprintf(stderr, "ERROR: Unable to listen to socket\n");
221 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
225 FILE *fp = fopen(PIDFILE, "w");
227 fprintf(fp, "%i", getpid());
234 uint len = sizeof(client_addr);
238 // Accept a connection
239 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
240 if(client_socket < 0) {
241 fprintf(stderr, "ERROR: Unable to accept client connection\n");
245 // Set a timeout on the user conneciton
248 tv.tv_sec = CLIENT_TIMEOUT;
250 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
252 perror("setsockopt");
257 // Debug: Print the connection string
258 if(giDebugLevel >= 2) {
259 char ipstr[INET_ADDRSTRLEN];
260 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
261 printf("Client connection from %s:%i\n",
262 ipstr, ntohs(client_addr.sin_port));
265 // Doesn't matter what, localhost is trusted
266 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
269 // Check if the host is on the trusted list
270 for( int i = 0; i < giServer_NumTrustedHosts; i ++ )
272 if( memcmp(&client_addr.sin_addr, &gaServer_TrustedHosts[i], sizeof(struct in_addr)) == 0 )
279 // Root port (can AUTOAUTH if also a trusted machine
280 if( ntohs(client_addr.sin_port) < 1024 )
285 // TODO: Make this runtime configurable
286 switch( ntohl( client_addr.sin_addr.s_addr ) )
288 case 0x7F000001: // 127.0.0.1 localhost
289 // case 0x825F0D00: // 130.95.13.0
290 case 0x825F0D04: // 130.95.13.4 merlo
291 // case 0x825F0D05: // 130.95.13.5 heathred (MR)
292 case 0x825F0D07: // 130.95.13.7 motsugo
293 case 0x825F0D11: // 130.95.13.17 mermaid
294 case 0x825F0D12: // 130.95.13.18 mussel
295 case 0x825F0D17: // 130.95.13.23 martello
296 case 0x825F0D2A: // 130.95.13.42 meersau
297 // case 0x825F0D42: // 130.95.13.66 heathred (Clubroom)
306 // TODO: Multithread this?
307 Server_HandleClient(client_socket, bTrusted, bRootPort);
309 close(client_socket);
313 void Server_Cleanup(void)
315 printf("\nClose(%i)\n", giServer_Socket);
316 close(giServer_Socket);
321 * \brief Reads from a client socket and parses the command strings
322 * \param Socket Client socket number/handle
323 * \param bTrusted Is the client trusted?
325 void Server_HandleClient(int Socket, int bTrusted, int bRootPort)
327 char inbuf[INPUT_BUFFER_SIZE];
329 int remspace = INPUT_BUFFER_SIZE-1;
333 memset(&clientInfo, 0, sizeof(clientInfo));
335 // Initialise Client info
336 clientInfo.Socket = Socket;
337 clientInfo.ID = giServer_NextClientID ++;
338 clientInfo.bTrustedHost = bTrusted;
339 clientInfo.bCanAutoAuth = bTrusted && bRootPort;
340 clientInfo.EffectiveUID = -1;
345 * - The `buf` and `remspace` variables allow a line to span several
346 * calls to recv(), if a line is not completed in one recv() call
347 * it is saved to the beginning of `inbuf` and `buf` is updated to
350 // TODO: Use select() instead (to give a timeout)
351 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
354 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
358 while( (eol = strchr(start, '\n')) )
362 Server_ParseClientCommand(&clientInfo, start);
367 // Check if there was an incomplete line
368 if( *start != '\0' ) {
369 int tailBytes = bytes - (start-buf);
370 // Roll back in buffer
371 memcpy(inbuf, start, tailBytes);
372 remspace -= tailBytes;
374 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
376 remspace = INPUT_BUFFER_SIZE - 1;
381 remspace = INPUT_BUFFER_SIZE - 1;
387 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
391 if(giDebugLevel >= 2) {
392 printf("Client %i: Disconnected\n", clientInfo.ID);
397 * \brief Parses a client command and calls the required helper function
398 * \param Client Pointer to client state structure
399 * \param CommandString Command from client (single line of the command)
400 * \return Heap String to return to the client
402 void Server_ParseClientCommand(tClient *Client, char *CommandString)
404 char *command, *args;
407 if( giDebugLevel >= 2 )
408 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
410 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
412 if( command == NULL ) return ;
413 // Is this an error? (just ignore for now)
418 for( i = 0; i < NUM_COMMANDS; i++ )
420 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
421 if( giDebugLevel >= 2 )
422 Debug(Client, "CMD %s - \"%s\"", command, args);
423 gaServer_Commands[i].Function(Client, args);
428 sendf(Client->Socket, "400 Unknown Command\n");
435 * \brief Set client username
437 * Usage: USER <username>
439 void Server_Cmd_USER(tClient *Client, char *Args)
443 if( Server_int_ParseArgs(0, Args, &username, NULL) )
445 sendf(Client->Socket, "407 USER takes 1 argument\n");
451 Debug(Client, "Authenticating as '%s'", username);
455 free(Client->Username);
456 Client->Username = strdup(username);
459 // Create a salt (that changes if the username is changed)
460 // Yes, I know, I'm a little paranoid, but who isn't?
461 Client->Salt[0] = 0x21 + (rand()&0x3F);
462 Client->Salt[1] = 0x21 + (rand()&0x3F);
463 Client->Salt[2] = 0x21 + (rand()&0x3F);
464 Client->Salt[3] = 0x21 + (rand()&0x3F);
465 Client->Salt[4] = 0x21 + (rand()&0x3F);
466 Client->Salt[5] = 0x21 + (rand()&0x3F);
467 Client->Salt[6] = 0x21 + (rand()&0x3F);
468 Client->Salt[7] = 0x21 + (rand()&0x3F);
470 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
471 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
473 sendf(Client->Socket, "100 User Set\n");
478 * \brief Authenticate as a user
482 void Server_Cmd_PASS(tClient *Client, char *Args)
487 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
489 sendf(Client->Socket, "407 PASS takes 1 argument\n");
493 // Pass on to cokebank
494 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
496 if( Client->UID == -1 ) {
497 sendf(Client->Socket, "401 Auth Failure\n");
501 flags = Bank_GetFlags(Client->UID);
502 if( flags & USER_FLAG_DISABLED ) {
504 sendf(Client->Socket, "403 Account Disabled\n");
507 if( flags & USER_FLAG_INTERNAL ) {
509 sendf(Client->Socket, "403 Internal account\n");
513 Client->bIsAuthed = 1;
514 sendf(Client->Socket, "200 Auth OK\n");
518 * \brief Authenticate as a user without a password
520 * Usage: AUTOAUTH <user>
522 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
527 if( Server_int_ParseArgs(0, Args, &username, NULL) )
529 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
534 if( !Client->bCanAutoAuth ) {
536 Debug(Client, "Untrusted client attempting to AUTOAUTH");
537 sendf(Client->Socket, "401 Untrusted\n");
542 Client->UID = Bank_GetAcctByName( username, 0 );
543 if( Client->UID < 0 ) {
545 Debug(Client, "Unknown user '%s'", username);
546 sendf(Client->Socket, "403 Auth Failure\n");
550 userflags = Bank_GetFlags(Client->UID);
551 // You can't be an internal account
552 if( userflags & USER_FLAG_INTERNAL ) {
554 Debug(Client, "Autoauth as '%s', not allowed", username);
556 sendf(Client->Socket, "403 Account is internal\n");
561 if( userflags & USER_FLAG_DISABLED ) {
563 sendf(Client->Socket, "403 Account disabled\n");
569 free(Client->Username);
570 Client->Username = strdup(username);
572 Client->bIsAuthed = 1;
575 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
577 sendf(Client->Socket, "200 Auth OK\n");
581 * \brief Authenticate as a user using the IDENT protocol
585 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args)
589 const int ident_timeout = 5;
591 if( Args != NULL && strlen(Args) ) {
592 sendf(Client->Socket, "407 AUTHIDENT takes no arguments\n");
597 if( !Client->bTrustedHost ) {
599 Debug(Client, "Untrusted client attempting to AUTHIDENT");
600 sendf(Client->Socket, "401 Untrusted\n");
604 // Get username via IDENT
605 username = ident_id(Client->Socket, ident_timeout);
607 perror("AUTHIDENT - IDENT timed out");
608 sendf(Client->Socket, "403 Authentication failure: IDENT auth timed out\n");
613 Client->UID = Bank_GetAcctByName( username, 0 );
614 if( Client->UID < 0 ) {
616 Debug(Client, "Unknown user '%s'", username);
617 sendf(Client->Socket, "403 Authentication failure: unknown account\n");
622 userflags = Bank_GetFlags(Client->UID);
623 // You can't be an internal account
624 if( userflags & USER_FLAG_INTERNAL ) {
626 Debug(Client, "IDENT auth as '%s', not allowed", username);
628 sendf(Client->Socket, "403 Authentication failure: that account is internal\n");
634 if( userflags & USER_FLAG_DISABLED ) {
636 sendf(Client->Socket, "403 Authentication failure: account disabled\n");
643 free(Client->Username);
644 Client->Username = strdup(username);
646 Client->bIsAuthed = 1;
649 Debug(Client, "IDENT authenticated as '%s' (%i)", username, Client->UID);
652 sendf(Client->Socket, "200 Auth OK\n");
656 * \brief Set effective user
658 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
661 int eUserFlags, userFlags;
663 if( Server_int_ParseArgs(0, Args, &username, NULL) )
665 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
669 if( !strlen(Args) ) {
670 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
674 // Check authentication
675 if( !Client->bIsAuthed ) {
676 sendf(Client->Socket, "401 Not Authenticated\n");
680 // Check user permissions
681 userFlags = Bank_GetFlags(Client->UID);
682 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
683 sendf(Client->Socket, "403 Not in coke\n");
688 Client->EffectiveUID = Bank_GetAcctByName(username, 0);
689 if( Client->EffectiveUID == -1 ) {
690 sendf(Client->Socket, "404 User not found\n");
693 // You can't be an internal account (unless you're an admin)
694 if( !(userFlags & USER_FLAG_ADMIN) )
696 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
697 if( eUserFlags & USER_FLAG_INTERNAL ) {
698 Client->EffectiveUID = -1;
699 sendf(Client->Socket, "404 User not found\n");
702 // Disabled only avaliable to admins
703 if( eUserFlags & USER_FLAG_DISABLED ) {
704 Client->EffectiveUID = -1;
705 sendf(Client->Socket, "403 Account disabled\n");
711 if( userFlags & USER_FLAG_DISABLED ) {
712 Client->EffectiveUID = -1;
713 sendf(Client->Socket, "403 Account disabled\n");
717 sendf(Client->Socket, "200 User set\n");
721 * \brief Send an item status to the client
722 * \param Client Who to?
723 * \param Item Item to send
725 void Server_int_SendItem(tClient *Client, tItem *Item)
727 char *status = "avail";
729 if( Item->Handler->CanDispense )
731 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
733 case 0: status = "avail"; break;
734 case 1: status = "sold"; break;
736 case -1: status = "error"; break;
740 if( !gbNoCostMode && Item->Price == 0 )
742 // KNOWN HACK: Naming a slot 'dead' disables it
743 if( strcmp(Item->Name, "dead") == 0 )
744 status = "sold"; // Another status?
746 sendf(Client->Socket,
747 "202 Item %s:%i %s %i %s\n",
748 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
753 * \brief Enumerate the items that the server knows about
755 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
759 if( Args != NULL && strlen(Args) ) {
760 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
766 for( i = 0; i < giNumItems; i ++ ) {
767 if( gaItems[i].bHidden ) continue;
771 sendf(Client->Socket, "201 Items %i\n", count);
773 for( i = 0; i < giNumItems; i ++ ) {
774 if( gaItems[i].bHidden ) continue;
775 Server_int_SendItem( Client, &gaItems[i] );
778 sendf(Client->Socket, "200 List end\n");
781 tItem *_GetItemFromString(char *String)
785 char *colon = strchr(String, ':');
797 for( i = 0; i < giNumHandlers; i ++ )
799 if( strcmp(gaHandlers[i]->Name, type) == 0) {
800 handler = gaHandlers[i];
809 for( i = 0; i < giNumItems; i ++ )
811 if( gaItems[i].Handler != handler ) continue;
812 if( gaItems[i].ID != num ) continue;
819 * \brief Fetch information on a specific item
821 * Usage: ITEMINFO <item ID>
823 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
828 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
829 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
832 item = _GetItemFromString(Args);
835 sendf(Client->Socket, "406 Bad Item ID\n");
839 Server_int_SendItem( Client, item );
843 * \brief Dispense an item
845 * Usage: DISPENSE <Item ID>
847 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
854 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
855 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
859 if( !Client->bIsAuthed ) {
860 sendf(Client->Socket, "401 Not Authenticated\n");
864 item = _GetItemFromString(itemname);
866 sendf(Client->Socket, "406 Bad Item ID\n");
870 if( Client->EffectiveUID != -1 ) {
871 uid = Client->EffectiveUID;
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, "404 Invalid user\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");
1169 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
1172 sendf(Client->Socket, "200 Add OK\n");
1175 sendf(Client->Socket, "402 Poor Guy\n");
1178 sendf(Client->Socket, "500 Unknown error\n");
1183 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1187 int maxBal = INT_MAX, minBal = INT_MIN;
1188 int flagMask = 0, flagVal = 0;
1189 int sort = BANK_ITFLAG_SORT_NAME;
1190 time_t lastSeenAfter=0, lastSeenBefore=0;
1192 int flags; // Iterator flags
1193 int balValue; // Balance value for iterator
1194 time_t timeValue; // Time value for iterator
1197 if( Args && strlen(Args) )
1199 char *space = Args, *type, *val;
1203 while(*type == ' ') type ++;
1205 space = strchr(space, ' ');
1206 if(space) *space = '\0';
1209 val = strchr(type, ':');
1216 if( strcmp(type, "min_balance") == 0 ) {
1219 // - Maximum Balance
1220 else if( strcmp(type, "max_balance") == 0 ) {
1224 else if( strcmp(type, "flags") == 0 ) {
1225 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1228 // - Last seen before timestamp
1229 else if( strcmp(type, "last_seen_before") == 0 ) {
1230 lastSeenAfter = atoll(val);
1232 // - Last seen after timestamp
1233 else if( strcmp(type, "last_seen_after") == 0 ) {
1234 lastSeenAfter = atoll(val);
1237 else if( strcmp(type, "sort") == 0 ) {
1238 char *dash = strchr(val, '-');
1243 if( strcmp(val, "name") == 0 ) {
1244 sort = BANK_ITFLAG_SORT_NAME;
1246 else if( strcmp(val, "balance") == 0 ) {
1247 sort = BANK_ITFLAG_SORT_BAL;
1249 else if( strcmp(val, "lastseen") == 0 ) {
1250 sort = BANK_ITFLAG_SORT_LASTSEEN;
1253 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1256 // Handle sort direction
1258 if( strcmp(dash, "desc") == 0 ) {
1259 sort |= BANK_ITFLAG_REVSORT;
1262 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1269 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1276 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1282 *space = ' '; // Repair (to be nice)
1284 while(*space == ' ') space ++;
1290 if( maxBal != INT_MAX ) {
1291 flags = sort|BANK_ITFLAG_MAXBALANCE;
1294 else if( minBal != INT_MIN ) {
1295 flags = sort|BANK_ITFLAG_MINBALANCE;
1302 if( lastSeenBefore ) {
1303 timeValue = lastSeenBefore;
1304 flags |= BANK_ITFLAG_SEENBEFORE;
1306 else if( lastSeenAfter ) {
1307 timeValue = lastSeenAfter;
1308 flags |= BANK_ITFLAG_SEENAFTER;
1313 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1315 // Get return number
1316 while( (i = Bank_IteratorNext(it)) != -1 )
1318 int bal = Bank_GetBalance(i);
1320 if( bal == INT_MIN ) continue;
1322 if( bal < minBal ) continue;
1323 if( bal > maxBal ) continue;
1328 Bank_DelIterator(it);
1331 sendf(Client->Socket, "201 Users %i\n", numRet);
1335 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1337 while( (i = Bank_IteratorNext(it)) != -1 )
1339 int bal = Bank_GetBalance(i);
1341 if( bal == INT_MIN ) continue;
1343 if( bal < minBal ) continue;
1344 if( bal > maxBal ) continue;
1346 _SendUserInfo(Client, i);
1349 Bank_DelIterator(it);
1351 sendf(Client->Socket, "200 List End\n");
1354 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1360 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1361 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1365 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1368 uid = Bank_GetAcctByName(user, 0);
1370 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1372 sendf(Client->Socket, "404 Invalid user\n");
1376 _SendUserInfo(Client, uid);
1379 void _SendUserInfo(tClient *Client, int UserID)
1381 char *type, *disabled="", *door="";
1382 int flags = Bank_GetFlags(UserID);
1384 if( flags & USER_FLAG_INTERNAL ) {
1387 else if( flags & USER_FLAG_COKE ) {
1388 if( flags & USER_FLAG_ADMIN )
1389 type = "coke,admin";
1393 else if( flags & USER_FLAG_ADMIN ) {
1400 if( flags & USER_FLAG_DISABLED )
1401 disabled = ",disabled";
1402 if( flags & USER_FLAG_DOORGROUP )
1405 // TODO: User flags/type
1407 Client->Socket, "202 User %s %i %s%s%s\n",
1408 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1409 type, disabled, door
1413 void Server_Cmd_USERADD(tClient *Client, char *Args)
1418 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1419 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1423 // Check authentication
1424 if( !Client->bIsAuthed ) {
1425 sendf(Client->Socket, "401 Not Authenticated\n");
1429 // Check permissions
1430 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1431 sendf(Client->Socket, "403 Not a coke admin\n");
1435 // Try to create user
1436 if( Bank_CreateAcct(username) == -1 ) {
1437 sendf(Client->Socket, "404 User exists\n");
1442 char *thisName = Bank_GetAcctName(Client->UID);
1443 Log_Info("Account '%s' created by '%s'", username, thisName);
1447 sendf(Client->Socket, "200 User Added\n");
1450 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1452 char *username, *flags, *reason=NULL;
1453 int mask=0, value=0;
1457 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1459 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1465 // Check authentication
1466 if( !Client->bIsAuthed ) {
1467 sendf(Client->Socket, "401 Not Authenticated\n");
1471 // Check permissions
1472 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1473 sendf(Client->Socket, "403 Not a coke admin\n");
1478 uid = Bank_GetAcctByName(username, 0);
1480 sendf(Client->Socket, "404 User '%s' not found\n", username);
1485 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1489 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1490 uid, username, mask, value);
1493 Bank_SetFlags(uid, mask, value);
1496 Log_Info("Updated '%s' with flag set '%s' by '%s' - Reason: %s",
1497 username, flags, Client->Username, reason);
1500 sendf(Client->Socket, "200 User Updated\n");
1503 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1505 char *itemname, *price_str, *description;
1509 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1510 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1514 if( !Client->bIsAuthed ) {
1515 sendf(Client->Socket, "401 Not Authenticated\n");
1519 // Check user permissions
1520 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1521 sendf(Client->Socket, "403 Not in coke\n");
1525 item = _GetItemFromString(itemname);
1527 // TODO: Create item?
1528 sendf(Client->Socket, "406 Bad Item ID\n");
1532 price = atoi(price_str);
1533 if( price <= 0 && price_str[0] != '0' ) {
1534 sendf(Client->Socket, "407 Invalid price set\n");
1537 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1541 sendf(Client->Socket, "200 Item updated\n");
1548 void Server_Cmd_PINCHECK(tClient *Client, char *Args)
1550 char *username, *pinstr;
1553 if( Server_int_ParseArgs(0, Args, &username, &pinstr, NULL) ) {
1554 sendf(Client->Socket, "407 PIN_CHECK takes 2 arguments\n");
1558 if( !isdigit(pinstr[0]) || !isdigit(pinstr[1]) || !isdigit(pinstr[2]) || !isdigit(pinstr[3]) || pinstr[4] != '\0' ) {
1559 sendf(Client->Socket, "407 PIN should be four digits\n");
1564 // Not strictly needed, but ensures that randoms don't do brute forcing
1565 if( !Client->bIsAuthed ) {
1566 sendf(Client->Socket, "401 Not Authenticated\n");
1570 // Check user permissions
1571 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1572 sendf(Client->Socket, "403 Not in coke\n");
1577 int uid = Bank_GetAcctByName(username, 0);
1579 sendf(Client->Socket, "404 User '%s' not found\n", username);
1584 static time_t last_wrong_pin_time;
1585 static int backoff = 1;
1586 if( time(NULL) - last_wrong_pin_time < backoff ) {
1587 sendf(Client->Socket, "407 Rate limited (%i seconds remaining)\n",
1588 backoff - (time(NULL) - last_wrong_pin_time));
1591 last_wrong_pin_time = time(NULL);
1592 if( !Bank_IsPinValid(uid, pin) )
1594 sendf(Client->Socket, "403 Pin incorrect\n");
1600 last_wrong_pin_time = 0;
1602 sendf(Client->Socket, "200 Pin correct\n");
1605 void Server_Cmd_PINSET(tClient *Client, char *Args)
1611 if( Server_int_ParseArgs(0, Args, &pinstr, NULL) ) {
1612 sendf(Client->Socket, "407 PIN_SET takes 2 arguments\n");
1616 if( !isdigit(pinstr[0]) || !isdigit(pinstr[1]) || !isdigit(pinstr[2]) || !isdigit(pinstr[3]) || pinstr[4] != '\0' ) {
1617 sendf(Client->Socket, "407 PIN should be four digits\n");
1622 // Not strictly needed, but ensures that randoms don't do brute forcing
1623 if( !Client->bIsAuthed ) {
1624 sendf(Client->Socket, "401 Not Authenticated\n");
1628 int uid = Client->EffectiveUID;
1631 // Can only pinset yourself (well, the effective user)
1632 Bank_SetPin(uid, pin);
1633 sendf(Client->Socket, "200 Pin updated\n");
1637 // --- INTERNAL HELPERS ---
1638 void Debug(tClient *Client, const char *Format, ...)
1641 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1642 printf("[%i] ", Client->ID);
1643 va_start(args, Format);
1644 vprintf(Format, args);
1649 int sendf(int Socket, const char *Format, ...)
1654 va_start(args, Format);
1655 len = vsnprintf(NULL, 0, Format, args);
1660 va_start(args, Format);
1661 vsnprintf(buf, len+1, Format, args);
1664 #if DEBUG_TRACE_CLIENT
1665 printf("sendf: %s", buf);
1668 return send(Socket, buf, len, 0);
1672 // Takes a series of char *'s in
1674 * \brief Parse space-separated entries into
1676 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1681 va_start(args, ArgStr);
1686 while( (dest = va_arg(args, char **)) )
1692 savedChar = *ArgStr;
1694 while( (dest = va_arg(args, char **)) )
1696 // Trim leading spaces
1697 while( *ArgStr == ' ' || *ArgStr == '\t' )
1700 // ... oops, not enough arguments
1701 if( *ArgStr == '\0' )
1703 // NULL unset arguments
1706 } while( (dest = va_arg(args, char **)) );
1711 if( *ArgStr == '"' )
1716 while( *ArgStr && *ArgStr != '"' )
1723 // Read until a space
1724 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1727 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1733 // Oops, extra arguments, and greedy not set
1734 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1741 *ArgStr = savedChar;
1744 return 0; // Success!
1747 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1754 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1755 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1756 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1757 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1758 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1760 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1772 while( *Str == ' ' ) Str ++; // Eat whitespace
1773 space = strchr(Str, ','); // Find the end of the flag
1779 // Check for inversion/removal
1780 if( *Str == '!' || *Str == '-' ) {
1784 else if( *Str == '+' ) {
1788 // Check flag values
1789 for( i = 0; i < ciNumFlags; i ++ )
1791 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1792 *Mask |= cFLAGS[i].Mask;
1793 *Value &= ~cFLAGS[i].Mask;
1795 *Value |= cFLAGS[i].Value;
1801 if( i == ciNumFlags ) {
1803 strncpy(val, Str, len+1);
1804 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);