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");
705 // - If disabled and the actual user is not an admin (and not root)
707 if( (eUserFlags & USER_FLAG_DISABLED) && (Client->UID == 0 || !(userFlags & USER_FLAG_ADMIN)) ) {
708 Client->EffectiveUID = -1;
709 sendf(Client->Socket, "403 Account disabled\n");
713 sendf(Client->Socket, "200 User set\n");
717 * \brief Send an item status to the client
718 * \param Client Who to?
719 * \param Item Item to send
721 void Server_int_SendItem(tClient *Client, tItem *Item)
723 char *status = "avail";
725 if( Item->Handler->CanDispense )
727 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
729 case 0: status = "avail"; break;
730 case 1: status = "sold"; break;
732 case -1: status = "error"; break;
736 if( !gbNoCostMode && Item->Price == 0 )
738 // KNOWN HACK: Naming a slot 'dead' disables it
739 if( strcmp(Item->Name, "dead") == 0 )
740 status = "sold"; // Another status?
742 sendf(Client->Socket,
743 "202 Item %s:%i %s %i %s\n",
744 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
749 * \brief Enumerate the items that the server knows about
751 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
755 if( Args != NULL && strlen(Args) ) {
756 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
762 for( i = 0; i < giNumItems; i ++ ) {
763 if( gaItems[i].bHidden ) continue;
767 sendf(Client->Socket, "201 Items %i\n", count);
769 for( i = 0; i < giNumItems; i ++ ) {
770 if( gaItems[i].bHidden ) continue;
771 Server_int_SendItem( Client, &gaItems[i] );
774 sendf(Client->Socket, "200 List end\n");
777 tItem *_GetItemFromString(char *String)
781 char *colon = strchr(String, ':');
793 for( i = 0; i < giNumHandlers; i ++ )
795 if( strcmp(gaHandlers[i]->Name, type) == 0) {
796 handler = gaHandlers[i];
805 for( i = 0; i < giNumItems; i ++ )
807 if( gaItems[i].Handler != handler ) continue;
808 if( gaItems[i].ID != num ) continue;
815 * \brief Fetch information on a specific item
817 * Usage: ITEMINFO <item ID>
819 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
824 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
825 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
828 item = _GetItemFromString(Args);
831 sendf(Client->Socket, "406 Bad Item ID\n");
835 Server_int_SendItem( Client, item );
839 * \brief Dispense an item
841 * Usage: DISPENSE <Item ID>
843 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
850 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
851 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
855 if( !Client->bIsAuthed ) {
856 sendf(Client->Socket, "401 Not Authenticated\n");
860 item = _GetItemFromString(itemname);
862 sendf(Client->Socket, "406 Bad Item ID\n");
866 if( Client->EffectiveUID != -1 ) {
867 uid = Client->EffectiveUID;
873 // if( Bank_GetFlags(Client->UID) & USER_FLAG_DISABLED ) {
876 switch( ret = DispenseItem( Client->UID, uid, item ) )
878 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
879 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
880 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
882 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
888 * \brief Refund an item to a user
890 * Usage: REFUND <user> <item id> [<price>]
892 void Server_Cmd_REFUND(tClient *Client, char *Args)
895 int uid, price_override = 0;
896 char *username, *itemname, *price_str;
898 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
899 if( !itemname || price_str ) {
900 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
905 if( !Client->bIsAuthed ) {
906 sendf(Client->Socket, "401 Not Authenticated\n");
910 // Check user permissions
911 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
912 sendf(Client->Socket, "403 Not in coke\n");
916 uid = Bank_GetAcctByName(username, 0);
918 sendf(Client->Socket, "404 Unknown user\n");
922 item = _GetItemFromString(itemname);
924 sendf(Client->Socket, "406 Bad Item ID\n");
929 price_override = atoi(price_str);
931 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
933 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
935 sendf(Client->Socket, "500 Dispense Error\n");
941 * \brief Transfer money to another account
943 * Usage: GIVE <dest> <ammount> <reason...>
945 void Server_Cmd_GIVE(tClient *Client, char *Args)
947 char *recipient, *ammount, *reason;
952 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
953 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
958 if( !Client->bIsAuthed ) {
959 sendf(Client->Socket, "401 Not Authenticated\n");
964 uid = Bank_GetAcctByName(recipient, 0);
966 sendf(Client->Socket, "404 Invalid target user\n");
970 // You can't alter an internal account
971 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
972 // sendf(Client->Socket, "404 Invalid target user\n");
977 iAmmount = atoi(ammount);
978 if( iAmmount <= 0 ) {
979 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
983 if( Client->EffectiveUID != -1 ) {
984 thisUid = Client->EffectiveUID;
987 thisUid = Client->UID;
991 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
994 sendf(Client->Socket, "200 Give OK\n");
997 sendf(Client->Socket, "402 Poor You\n");
1000 sendf(Client->Socket, "500 Unknown error\n");
1005 void Server_Cmd_DONATE(tClient *Client, char *Args)
1007 char *ammount, *reason;
1012 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
1013 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
1017 if( !Client->bIsAuthed ) {
1018 sendf(Client->Socket, "401 Not Authenticated\n");
1023 iAmmount = atoi(ammount);
1024 if( iAmmount <= 0 ) {
1025 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
1029 // Handle effective users
1030 if( Client->EffectiveUID != -1 ) {
1031 thisUid = Client->EffectiveUID;
1034 thisUid = Client->UID;
1038 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
1041 sendf(Client->Socket, "200 Give OK\n");
1044 sendf(Client->Socket, "402 Poor You\n");
1047 sendf(Client->Socket, "500 Unknown error\n");
1052 void Server_Cmd_ADD(tClient *Client, char *Args)
1054 char *user, *ammount, *reason;
1058 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1059 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
1063 if( !Client->bIsAuthed ) {
1064 sendf(Client->Socket, "401 Not Authenticated\n");
1068 // Check user permissions
1069 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1070 sendf(Client->Socket, "403 Not in coke\n");
1075 if( strcmp( Client->Username, "root" ) == 0 ) {
1076 // Allow adding for new users
1077 if( strcmp(reason, "treasurer: new user") != 0 ) {
1078 sendf(Client->Socket, "403 Root may not add\n");
1085 if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
1087 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
1093 uid = Bank_GetAcctByName(user, 0);
1095 sendf(Client->Socket, "404 Invalid user\n");
1099 // You can't alter an internal account
1100 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
1102 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
1103 sendf(Client->Socket, "404 Invalid user\n");
1106 // TODO: Maybe disallow changes to disabled?
1110 iAmmount = atoi(ammount);
1111 if( iAmmount == 0 && ammount[0] != '0' ) {
1112 sendf(Client->Socket, "407 Invalid Argument\n");
1117 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
1120 sendf(Client->Socket, "200 Add OK\n");
1123 sendf(Client->Socket, "402 Poor Guy\n");
1126 sendf(Client->Socket, "500 Unknown error\n");
1131 void Server_Cmd_SET(tClient *Client, char *Args)
1133 char *user, *ammount, *reason;
1137 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1138 sendf(Client->Socket, "407 SET takes 3 arguments\n");
1142 if( !Client->bIsAuthed ) {
1143 sendf(Client->Socket, "401 Not Authenticated\n");
1147 // Check user permissions
1148 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1149 sendf(Client->Socket, "403 Not an admin\n");
1154 uid = Bank_GetAcctByName(user, 0);
1156 sendf(Client->Socket, "404 Invalid user\n");
1161 iAmmount = atoi(ammount);
1162 if( iAmmount == 0 && ammount[0] != '0' ) {
1163 sendf(Client->Socket, "407 Invalid Argument\n");
1168 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
1171 sendf(Client->Socket, "200 Add OK\n");
1174 sendf(Client->Socket, "402 Poor Guy\n");
1177 sendf(Client->Socket, "500 Unknown error\n");
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 strictly needed, but ensures that randoms don't do brute forcing
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");
1599 last_wrong_pin_time = 0;
1601 sendf(Client->Socket, "200 Pin correct\n");
1604 void Server_Cmd_PINSET(tClient *Client, char *Args)
1610 if( Server_int_ParseArgs(0, Args, &pinstr, NULL) ) {
1611 sendf(Client->Socket, "407 PIN_SET takes 2 arguments\n");
1615 if( !isdigit(pinstr[0]) || !isdigit(pinstr[1]) || !isdigit(pinstr[2]) || !isdigit(pinstr[3]) || pinstr[4] != '\0' ) {
1616 sendf(Client->Socket, "407 PIN should be four digits\n");
1621 // Not strictly needed, but ensures that randoms don't do brute forcing
1622 if( !Client->bIsAuthed ) {
1623 sendf(Client->Socket, "401 Not Authenticated\n");
1627 int uid = Client->EffectiveUID;
1630 // Can only pinset yourself (well, the effective user)
1631 Bank_SetPin(uid, pin);
1632 sendf(Client->Socket, "200 Pin updated\n");
1636 // --- INTERNAL HELPERS ---
1637 void Debug(tClient *Client, const char *Format, ...)
1640 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1641 printf("[%i] ", Client->ID);
1642 va_start(args, Format);
1643 vprintf(Format, args);
1648 int sendf(int Socket, const char *Format, ...)
1653 va_start(args, Format);
1654 len = vsnprintf(NULL, 0, Format, args);
1659 va_start(args, Format);
1660 vsnprintf(buf, len+1, Format, args);
1663 #if DEBUG_TRACE_CLIENT
1664 printf("sendf: %s", buf);
1667 return send(Socket, buf, len, 0);
1671 // Takes a series of char *'s in
1673 * \brief Parse space-separated entries into
1675 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1680 va_start(args, ArgStr);
1685 while( (dest = va_arg(args, char **)) )
1691 savedChar = *ArgStr;
1693 while( (dest = va_arg(args, char **)) )
1695 // Trim leading spaces
1696 while( *ArgStr == ' ' || *ArgStr == '\t' )
1699 // ... oops, not enough arguments
1700 if( *ArgStr == '\0' )
1702 // NULL unset arguments
1705 } while( (dest = va_arg(args, char **)) );
1710 if( *ArgStr == '"' )
1715 while( *ArgStr && *ArgStr != '"' )
1722 // Read until a space
1723 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1726 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1732 // Oops, extra arguments, and greedy not set
1733 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1740 *ArgStr = savedChar;
1743 return 0; // Success!
1746 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1753 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1754 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1755 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1756 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1757 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1759 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1771 while( *Str == ' ' ) Str ++; // Eat whitespace
1772 space = strchr(Str, ','); // Find the end of the flag
1778 // Check for inversion/removal
1779 if( *Str == '!' || *Str == '-' ) {
1783 else if( *Str == '+' ) {
1787 // Check flag values
1788 for( i = 0; i < ciNumFlags; i ++ )
1790 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1791 *Mask |= cFLAGS[i].Mask;
1792 *Value &= ~cFLAGS[i].Mask;
1794 *Value |= cFLAGS[i].Value;
1800 if( i == ciNumFlags ) {
1802 strncpy(val, Str, len+1);
1803 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);