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)
25 #define DEBUG_TRACE_CLIENT 0
26 #define HACK_NO_REFUNDS 1
28 #define PIDFILE "/var/run/dispsrv.pid"
31 #define MAX_CONNECTION_QUEUE 5
32 #define INPUT_BUFFER_SIZE 256
33 #define CLIENT_TIMEOUT 10 // Seconds
35 #define HASH_TYPE SHA1
36 #define HASH_LENGTH 20
38 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
40 #define IDENT_TRUSTED_NETWORK 0x825F0D00
41 #define IDENT_TRUSTED_NETMASK 0xFFFFFFC0
44 typedef struct sClient
46 int Socket; // Client socket ID
50 int bCanAutoAuth; // Is the connection from a trusted host/port
61 void Server_Start(void);
62 void Server_Cleanup(void);
63 void Server_HandleClient(int Socket, int bTrustedHost, int bRootPort);
64 void Server_ParseClientCommand(tClient *Client, char *CommandString);
66 void Server_Cmd_USER(tClient *Client, char *Args);
67 void Server_Cmd_PASS(tClient *Client, char *Args);
68 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
69 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args);
70 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
71 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
72 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
73 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
74 void Server_Cmd_REFUND(tClient *Client, char *Args);
75 void Server_Cmd_GIVE(tClient *Client, char *Args);
76 void Server_Cmd_DONATE(tClient *Client, char *Args);
77 void Server_Cmd_ADD(tClient *Client, char *Args);
78 void Server_Cmd_SET(tClient *Client, char *Args);
79 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
80 void Server_Cmd_USERINFO(tClient *Client, char *Args);
81 void _SendUserInfo(tClient *Client, int UserID);
82 void Server_Cmd_USERADD(tClient *Client, char *Args);
83 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
84 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args);
86 void Debug(tClient *Client, const char *Format, ...);
87 int sendf(int Socket, const char *Format, ...);
88 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
89 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
93 const struct sClientCommand {
95 void (*Function)(tClient *Client, char *Arguments);
96 } gaServer_Commands[] = {
97 {"USER", Server_Cmd_USER},
98 {"PASS", Server_Cmd_PASS},
99 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
100 {"AUTHIDENT", Server_Cmd_AUTHIDENT},
101 {"SETEUSER", Server_Cmd_SETEUSER},
102 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
103 {"ITEM_INFO", Server_Cmd_ITEMINFO},
104 {"DISPENSE", Server_Cmd_DISPENSE},
105 {"REFUND", Server_Cmd_REFUND},
106 {"GIVE", Server_Cmd_GIVE},
107 {"DONATE", Server_Cmd_DONATE},
108 {"ADD", Server_Cmd_ADD},
109 {"SET", Server_Cmd_SET},
110 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
111 {"USER_INFO", Server_Cmd_USERINFO},
112 {"USER_ADD", Server_Cmd_USERADD},
113 {"USER_FLAGS", Server_Cmd_USERFLAGS},
114 {"UPDATE_ITEM", Server_Cmd_UPDATEITEM}
116 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
120 int giServer_Port = 11020;
121 int gbServer_RunInBackground = 0;
122 char *gsServer_LogFile = "/var/log/dispsrv.log";
123 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
124 int giServer_NumTrustedHosts;
125 struct in_addr *gaServer_TrustedHosts;
127 int giServer_Socket; // Server socket
128 int giServer_NextClientID = 1; // Debug client ID
133 * \brief Open listenting socket and serve connections
135 void Server_Start(void)
138 struct sockaddr_in server_addr, client_addr;
140 // Parse trusted hosts list
141 giServer_NumTrustedHosts = Config_GetValueCount("trusted_host");
142 gaServer_TrustedHosts = malloc(giServer_NumTrustedHosts * sizeof(*gaServer_TrustedHosts));
143 for( int i = 0; i < giServer_NumTrustedHosts; i ++ )
145 const char *addr = Config_GetValue("trusted_host", i);
147 if( inet_aton(addr, &gaServer_TrustedHosts[i]) == 0 ) {
148 fprintf(stderr, "Invalid IP address '%s'\n", addr);
153 atexit(Server_Cleanup);
154 // Ignore SIGPIPE (stops crashes when the client exits early)
155 signal(SIGPIPE, SIG_IGN);
158 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
159 if( giServer_Socket < 0 ) {
160 fprintf(stderr, "ERROR: Unable to create server socket\n");
164 // Make listen address
165 memset(&server_addr, 0, sizeof(server_addr));
166 server_addr.sin_family = AF_INET; // Internet Socket
167 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
168 server_addr.sin_port = htons(giServer_Port); // Port
171 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
172 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
177 // Fork into background
178 if( gbServer_RunInBackground )
182 fprintf(stderr, "ERROR: Unable to fork\n");
183 perror("fork background");
188 printf("Forked child %i\n", pid);
192 // - Sort out stdin/stdout
194 dup2( open("/dev/null", O_RDONLY, 0644), STDIN_FILENO );
195 dup2( open(gsServer_LogFile, O_CREAT|O_APPEND, 0644), STDOUT_FILENO );
196 dup2( open(gsServer_ErrorLog, O_CREAT|O_APPEND, 0644), STDERR_FILENO );
198 freopen("/dev/null", "r", stdin);
199 freopen(gsServer_LogFile, "a", stdout);
200 freopen(gsServer_ErrorLog, "a", stderr);
201 fprintf(stdout, "OpenDispense 2 Server Started at %lld\n", (long long)time(NULL));
202 fprintf(stderr, "OpenDispense 2 Server Started at %lld\n", (long long)time(NULL));
206 // Start the helper thread
207 StartPeriodicThread();
210 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
211 fprintf(stderr, "ERROR: Unable to listen to socket\n");
216 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
220 FILE *fp = fopen(PIDFILE, "w");
222 fprintf(fp, "%i", getpid());
229 uint len = sizeof(client_addr);
233 // Accept a connection
234 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
235 if(client_socket < 0) {
236 fprintf(stderr, "ERROR: Unable to accept client connection\n");
240 // Set a timeout on the user conneciton
243 tv.tv_sec = CLIENT_TIMEOUT;
245 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
247 perror("setsockopt");
252 // Debug: Print the connection string
253 if(giDebugLevel >= 2) {
254 char ipstr[INET_ADDRSTRLEN];
255 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
256 printf("Client connection from %s:%i\n",
257 ipstr, ntohs(client_addr.sin_port));
260 // Doesn't matter what, localhost is trusted
261 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
264 // Check if the host is on the trusted list
265 for( int i = 0; i < giServer_NumTrustedHosts; i ++ )
267 if( memcmp(&client_addr.sin_addr, &gaServer_TrustedHosts[i], sizeof(struct in_addr)) == 0 )
274 // Root port (can AUTOAUTH if also a trusted machine
275 if( ntohs(client_addr.sin_port) < 1024 )
280 // TODO: Make this runtime configurable
281 switch( ntohl( client_addr.sin_addr.s_addr ) )
283 case 0x7F000001: // 127.0.0.1 localhost
284 // case 0x825F0D00: // 130.95.13.0
285 case 0x825F0D04: // 130.95.13.4 merlo
286 // case 0x825F0D05: // 130.95.13.5 heathred (MR)
287 case 0x825F0D07: // 130.95.13.7 motsugo
288 case 0x825F0D11: // 130.95.13.17 mermaid
289 case 0x825F0D12: // 130.95.13.18 mussel
290 case 0x825F0D17: // 130.95.13.23 martello
291 case 0x825F0D2A: // 130.95.13.42 meersau
292 // case 0x825F0D42: // 130.95.13.66 heathred (Clubroom)
301 // TODO: Multithread this?
302 Server_HandleClient(client_socket, bTrusted, bRootPort);
304 close(client_socket);
308 void Server_Cleanup(void)
310 printf("\nClose(%i)\n", giServer_Socket);
311 close(giServer_Socket);
316 * \brief Reads from a client socket and parses the command strings
317 * \param Socket Client socket number/handle
318 * \param bTrusted Is the client trusted?
320 void Server_HandleClient(int Socket, int bTrusted, int bRootPort)
322 char inbuf[INPUT_BUFFER_SIZE];
324 int remspace = INPUT_BUFFER_SIZE-1;
328 memset(&clientInfo, 0, sizeof(clientInfo));
330 // Initialise Client info
331 clientInfo.Socket = Socket;
332 clientInfo.ID = giServer_NextClientID ++;
333 clientInfo.bTrustedHost = bTrusted;
334 clientInfo.bCanAutoAuth = bTrusted && bRootPort;
335 clientInfo.EffectiveUID = -1;
340 * - The `buf` and `remspace` variables allow a line to span several
341 * calls to recv(), if a line is not completed in one recv() call
342 * it is saved to the beginning of `inbuf` and `buf` is updated to
345 // TODO: Use select() instead (to give a timeout)
346 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
349 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
353 while( (eol = strchr(start, '\n')) )
357 Server_ParseClientCommand(&clientInfo, start);
362 // Check if there was an incomplete line
363 if( *start != '\0' ) {
364 int tailBytes = bytes - (start-buf);
365 // Roll back in buffer
366 memcpy(inbuf, start, tailBytes);
367 remspace -= tailBytes;
369 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
371 remspace = INPUT_BUFFER_SIZE - 1;
376 remspace = INPUT_BUFFER_SIZE - 1;
382 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
386 if(giDebugLevel >= 2) {
387 printf("Client %i: Disconnected\n", clientInfo.ID);
392 * \brief Parses a client command and calls the required helper function
393 * \param Client Pointer to client state structure
394 * \param CommandString Command from client (single line of the command)
395 * \return Heap String to return to the client
397 void Server_ParseClientCommand(tClient *Client, char *CommandString)
399 char *command, *args;
402 if( giDebugLevel >= 2 )
403 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
405 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
407 if( command == NULL ) return ;
408 // Is this an error? (just ignore for now)
413 for( i = 0; i < NUM_COMMANDS; i++ )
415 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
416 if( giDebugLevel >= 2 )
417 Debug(Client, "CMD %s - \"%s\"", command, args);
418 gaServer_Commands[i].Function(Client, args);
423 sendf(Client->Socket, "400 Unknown Command\n");
430 * \brief Set client username
432 * Usage: USER <username>
434 void Server_Cmd_USER(tClient *Client, char *Args)
438 if( Server_int_ParseArgs(0, Args, &username, NULL) )
440 sendf(Client->Socket, "407 USER takes 1 argument\n");
446 Debug(Client, "Authenticating as '%s'", username);
450 free(Client->Username);
451 Client->Username = strdup(username);
454 // Create a salt (that changes if the username is changed)
455 // Yes, I know, I'm a little paranoid, but who isn't?
456 Client->Salt[0] = 0x21 + (rand()&0x3F);
457 Client->Salt[1] = 0x21 + (rand()&0x3F);
458 Client->Salt[2] = 0x21 + (rand()&0x3F);
459 Client->Salt[3] = 0x21 + (rand()&0x3F);
460 Client->Salt[4] = 0x21 + (rand()&0x3F);
461 Client->Salt[5] = 0x21 + (rand()&0x3F);
462 Client->Salt[6] = 0x21 + (rand()&0x3F);
463 Client->Salt[7] = 0x21 + (rand()&0x3F);
465 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
466 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
468 sendf(Client->Socket, "100 User Set\n");
473 * \brief Authenticate as a user
477 void Server_Cmd_PASS(tClient *Client, char *Args)
482 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
484 sendf(Client->Socket, "407 PASS takes 1 argument\n");
488 // Pass on to cokebank
489 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
491 if( Client->UID == -1 ) {
492 sendf(Client->Socket, "401 Auth Failure\n");
496 flags = Bank_GetFlags(Client->UID);
497 if( flags & USER_FLAG_DISABLED ) {
499 sendf(Client->Socket, "403 Account Disabled\n");
502 if( flags & USER_FLAG_INTERNAL ) {
504 sendf(Client->Socket, "403 Internal account\n");
508 Client->bIsAuthed = 1;
509 sendf(Client->Socket, "200 Auth OK\n");
513 * \brief Authenticate as a user without a password
515 * Usage: AUTOAUTH <user>
517 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
522 if( Server_int_ParseArgs(0, Args, &username, NULL) )
524 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
529 if( !Client->bCanAutoAuth ) {
531 Debug(Client, "Untrusted client attempting to AUTOAUTH");
532 sendf(Client->Socket, "401 Untrusted\n");
537 Client->UID = Bank_GetAcctByName( username, 0 );
538 if( Client->UID < 0 ) {
540 Debug(Client, "Unknown user '%s'", username);
541 sendf(Client->Socket, "403 Auth Failure\n");
545 userflags = Bank_GetFlags(Client->UID);
546 // You can't be an internal account
547 if( userflags & USER_FLAG_INTERNAL ) {
549 Debug(Client, "Autoauth as '%s', not allowed", username);
551 sendf(Client->Socket, "403 Account is internal\n");
556 if( userflags & USER_FLAG_DISABLED ) {
558 sendf(Client->Socket, "403 Account disabled\n");
564 free(Client->Username);
565 Client->Username = strdup(username);
567 Client->bIsAuthed = 1;
570 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
572 sendf(Client->Socket, "200 Auth OK\n");
576 * \brief Authenticate as a user using the IDENT protocol
580 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args)
584 const int ident_timeout = 5;
586 if( Args != NULL && strlen(Args) ) {
587 sendf(Client->Socket, "407 AUTHIDENT takes no arguments\n");
592 if( !Client->bTrustedHost ) {
594 Debug(Client, "Untrusted client attempting to AUTHIDENT");
595 sendf(Client->Socket, "401 Untrusted\n");
599 // Get username via IDENT
600 username = ident_id(Client->Socket, ident_timeout);
602 perror("AUTHIDENT - IDENT timed out");
603 sendf(Client->Socket, "403 Authentication failure: IDENT auth timed out\n");
608 Client->UID = Bank_GetAcctByName( username, 0 );
609 if( Client->UID < 0 ) {
611 Debug(Client, "Unknown user '%s'", username);
612 sendf(Client->Socket, "403 Authentication failure: unknown account\n");
617 userflags = Bank_GetFlags(Client->UID);
618 // You can't be an internal account
619 if( userflags & USER_FLAG_INTERNAL ) {
621 Debug(Client, "IDENT auth as '%s', not allowed", username);
623 sendf(Client->Socket, "403 Authentication failure: that account is internal\n");
629 if( userflags & USER_FLAG_DISABLED ) {
631 sendf(Client->Socket, "403 Authentication failure: account disabled\n");
638 free(Client->Username);
639 Client->Username = strdup(username);
641 Client->bIsAuthed = 1;
644 Debug(Client, "IDENT authenticated as '%s' (%i)", username, Client->UID);
647 sendf(Client->Socket, "200 Auth OK\n");
651 * \brief Set effective user
653 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
656 int eUserFlags, userFlags;
658 if( Server_int_ParseArgs(0, Args, &username, NULL) )
660 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
664 if( !strlen(Args) ) {
665 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
669 // Check authentication
670 if( !Client->bIsAuthed ) {
671 sendf(Client->Socket, "401 Not Authenticated\n");
675 // Check user permissions
676 userFlags = Bank_GetFlags(Client->UID);
677 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
678 sendf(Client->Socket, "403 Not in coke\n");
683 Client->EffectiveUID = Bank_GetAcctByName(username, 0);
684 if( Client->EffectiveUID == -1 ) {
685 sendf(Client->Socket, "404 User not found\n");
689 // You can't be an internal account
690 if( !(userFlags & USER_FLAG_ADMIN) )
692 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
693 if( eUserFlags & USER_FLAG_INTERNAL ) {
694 Client->EffectiveUID = -1;
695 sendf(Client->Socket, "404 User not found\n");
698 // Disabled only avaliable to admins
699 if( eUserFlags & USER_FLAG_DISABLED ) {
700 Client->EffectiveUID = -1;
701 sendf(Client->Socket, "403 Account disabled\n");
707 if( userFlags & USER_FLAG_DISABLED ) {
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 switch( ret = DispenseItem( Client->UID, uid, item ) )
875 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
876 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
877 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
879 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
885 * \brief Refund an item to a user
887 * Usage: REFUND <user> <item id> [<price>]
889 void Server_Cmd_REFUND(tClient *Client, char *Args)
892 int uid, price_override = 0;
893 char *username, *itemname, *price_str;
895 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
896 if( !itemname || price_str ) {
897 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
902 if( !Client->bIsAuthed ) {
903 sendf(Client->Socket, "401 Not Authenticated\n");
907 // Check user permissions
908 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
909 sendf(Client->Socket, "403 Not in coke\n");
913 uid = Bank_GetAcctByName(username, 0);
915 sendf(Client->Socket, "404 Unknown user\n");
919 item = _GetItemFromString(itemname);
921 sendf(Client->Socket, "406 Bad Item ID\n");
926 price_override = atoi(price_str);
928 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
930 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
932 sendf(Client->Socket, "500 Dispense Error\n");
938 * \brief Transfer money to another account
940 * Usage: GIVE <dest> <ammount> <reason...>
942 void Server_Cmd_GIVE(tClient *Client, char *Args)
944 char *recipient, *ammount, *reason;
949 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
950 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
955 if( !Client->bIsAuthed ) {
956 sendf(Client->Socket, "401 Not Authenticated\n");
961 uid = Bank_GetAcctByName(recipient, 0);
963 sendf(Client->Socket, "404 Invalid target user\n");
967 // You can't alter an internal account
968 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
969 // sendf(Client->Socket, "404 Invalid target user\n");
974 iAmmount = atoi(ammount);
975 if( iAmmount <= 0 ) {
976 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
980 if( Client->EffectiveUID != -1 ) {
981 thisUid = Client->EffectiveUID;
984 thisUid = Client->UID;
988 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
991 sendf(Client->Socket, "200 Give OK\n");
994 sendf(Client->Socket, "402 Poor You\n");
997 sendf(Client->Socket, "500 Unknown error\n");
1002 void Server_Cmd_DONATE(tClient *Client, char *Args)
1004 char *ammount, *reason;
1009 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
1010 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
1014 if( !Client->bIsAuthed ) {
1015 sendf(Client->Socket, "401 Not Authenticated\n");
1020 iAmmount = atoi(ammount);
1021 if( iAmmount <= 0 ) {
1022 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
1026 // Handle effective users
1027 if( Client->EffectiveUID != -1 ) {
1028 thisUid = Client->EffectiveUID;
1031 thisUid = Client->UID;
1035 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
1038 sendf(Client->Socket, "200 Give OK\n");
1041 sendf(Client->Socket, "402 Poor You\n");
1044 sendf(Client->Socket, "500 Unknown error\n");
1049 void Server_Cmd_ADD(tClient *Client, char *Args)
1051 char *user, *ammount, *reason;
1055 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1056 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
1060 if( !Client->bIsAuthed ) {
1061 sendf(Client->Socket, "401 Not Authenticated\n");
1065 // Check user permissions
1066 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1067 sendf(Client->Socket, "403 Not in coke\n");
1072 if( strcmp( Client->Username, "root" ) == 0 ) {
1073 // Allow adding for new users
1074 if( strcmp(reason, "treasurer: new user") != 0 ) {
1075 sendf(Client->Socket, "403 Root may not add\n");
1082 if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
1084 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
1090 uid = Bank_GetAcctByName(user, 0);
1092 sendf(Client->Socket, "404 Invalid user\n");
1096 // You can't alter an internal account
1097 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
1099 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
1100 sendf(Client->Socket, "404 Invalid user\n");
1103 // TODO: Maybe disallow changes to disabled?
1107 iAmmount = atoi(ammount);
1108 if( iAmmount == 0 && ammount[0] != '0' ) {
1109 sendf(Client->Socket, "407 Invalid Argument\n");
1114 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
1117 sendf(Client->Socket, "200 Add OK\n");
1120 sendf(Client->Socket, "402 Poor Guy\n");
1123 sendf(Client->Socket, "500 Unknown error\n");
1128 void Server_Cmd_SET(tClient *Client, char *Args)
1130 char *user, *ammount, *reason;
1134 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1135 sendf(Client->Socket, "407 SET takes 3 arguments\n");
1139 if( !Client->bIsAuthed ) {
1140 sendf(Client->Socket, "401 Not Authenticated\n");
1144 // Check user permissions
1145 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1146 sendf(Client->Socket, "403 Not an admin\n");
1151 uid = Bank_GetAcctByName(user, 0);
1153 sendf(Client->Socket, "404 Invalid user\n");
1158 iAmmount = atoi(ammount);
1159 if( iAmmount == 0 && ammount[0] != '0' ) {
1160 sendf(Client->Socket, "407 Invalid Argument\n");
1165 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
1168 sendf(Client->Socket, "200 Add OK\n");
1171 sendf(Client->Socket, "402 Poor Guy\n");
1174 sendf(Client->Socket, "500 Unknown error\n");
1179 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1183 int maxBal = INT_MAX, minBal = INT_MIN;
1184 int flagMask = 0, flagVal = 0;
1185 int sort = BANK_ITFLAG_SORT_NAME;
1186 time_t lastSeenAfter=0, lastSeenBefore=0;
1188 int flags; // Iterator flags
1189 int balValue; // Balance value for iterator
1190 time_t timeValue; // Time value for iterator
1193 if( Args && strlen(Args) )
1195 char *space = Args, *type, *val;
1199 while(*type == ' ') type ++;
1201 space = strchr(space, ' ');
1202 if(space) *space = '\0';
1205 val = strchr(type, ':');
1212 if( strcmp(type, "min_balance") == 0 ) {
1215 // - Maximum Balance
1216 else if( strcmp(type, "max_balance") == 0 ) {
1220 else if( strcmp(type, "flags") == 0 ) {
1221 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1224 // - Last seen before timestamp
1225 else if( strcmp(type, "last_seen_before") == 0 ) {
1226 lastSeenAfter = atoll(val);
1228 // - Last seen after timestamp
1229 else if( strcmp(type, "last_seen_after") == 0 ) {
1230 lastSeenAfter = atoll(val);
1233 else if( strcmp(type, "sort") == 0 ) {
1234 char *dash = strchr(val, '-');
1239 if( strcmp(val, "name") == 0 ) {
1240 sort = BANK_ITFLAG_SORT_NAME;
1242 else if( strcmp(val, "balance") == 0 ) {
1243 sort = BANK_ITFLAG_SORT_BAL;
1245 else if( strcmp(val, "lastseen") == 0 ) {
1246 sort = BANK_ITFLAG_SORT_LASTSEEN;
1249 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1252 // Handle sort direction
1254 if( strcmp(dash, "desc") == 0 ) {
1255 sort |= BANK_ITFLAG_REVSORT;
1258 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1265 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1272 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1278 *space = ' '; // Repair (to be nice)
1280 while(*space == ' ') space ++;
1286 if( maxBal != INT_MAX ) {
1287 flags = sort|BANK_ITFLAG_MAXBALANCE;
1290 else if( minBal != INT_MIN ) {
1291 flags = sort|BANK_ITFLAG_MINBALANCE;
1298 if( lastSeenBefore ) {
1299 timeValue = lastSeenBefore;
1300 flags |= BANK_ITFLAG_SEENBEFORE;
1302 else if( lastSeenAfter ) {
1303 timeValue = lastSeenAfter;
1304 flags |= BANK_ITFLAG_SEENAFTER;
1309 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1311 // Get return number
1312 while( (i = Bank_IteratorNext(it)) != -1 )
1314 int bal = Bank_GetBalance(i);
1316 if( bal == INT_MIN ) continue;
1318 if( bal < minBal ) continue;
1319 if( bal > maxBal ) continue;
1324 Bank_DelIterator(it);
1327 sendf(Client->Socket, "201 Users %i\n", numRet);
1331 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1333 while( (i = Bank_IteratorNext(it)) != -1 )
1335 int bal = Bank_GetBalance(i);
1337 if( bal == INT_MIN ) continue;
1339 if( bal < minBal ) continue;
1340 if( bal > maxBal ) continue;
1342 _SendUserInfo(Client, i);
1345 Bank_DelIterator(it);
1347 sendf(Client->Socket, "200 List End\n");
1350 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1356 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1357 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1361 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1364 uid = Bank_GetAcctByName(user, 0);
1366 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1368 sendf(Client->Socket, "404 Invalid user\n");
1372 _SendUserInfo(Client, uid);
1375 void _SendUserInfo(tClient *Client, int UserID)
1377 char *type, *disabled="", *door="";
1378 int flags = Bank_GetFlags(UserID);
1380 if( flags & USER_FLAG_INTERNAL ) {
1383 else if( flags & USER_FLAG_COKE ) {
1384 if( flags & USER_FLAG_ADMIN )
1385 type = "coke,admin";
1389 else if( flags & USER_FLAG_ADMIN ) {
1396 if( flags & USER_FLAG_DISABLED )
1397 disabled = ",disabled";
1398 if( flags & USER_FLAG_DOORGROUP )
1401 // TODO: User flags/type
1403 Client->Socket, "202 User %s %i %s%s%s\n",
1404 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1405 type, disabled, door
1409 void Server_Cmd_USERADD(tClient *Client, char *Args)
1414 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1415 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1419 // Check authentication
1420 if( !Client->bIsAuthed ) {
1421 sendf(Client->Socket, "401 Not Authenticated\n");
1425 // Check permissions
1426 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1427 sendf(Client->Socket, "403 Not a coke admin\n");
1431 // Try to create user
1432 if( Bank_CreateAcct(username) == -1 ) {
1433 sendf(Client->Socket, "404 User exists\n");
1438 char *thisName = Bank_GetAcctName(Client->UID);
1439 Log_Info("Account '%s' created by '%s'", username, thisName);
1443 sendf(Client->Socket, "200 User Added\n");
1446 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1448 char *username, *flags, *reason=NULL;
1449 int mask=0, value=0;
1453 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1455 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1461 // Check authentication
1462 if( !Client->bIsAuthed ) {
1463 sendf(Client->Socket, "401 Not Authenticated\n");
1467 // Check permissions
1468 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1469 sendf(Client->Socket, "403 Not a coke admin\n");
1474 uid = Bank_GetAcctByName(username, 0);
1476 sendf(Client->Socket, "404 User '%s' not found\n", username);
1481 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1485 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1486 uid, username, mask, value);
1489 Bank_SetFlags(uid, mask, value);
1492 Log_Info("Updated '%s' with flag set '%s' by '%s' - Reason: %s",
1493 username, flags, Client->Username, reason);
1496 sendf(Client->Socket, "200 User Updated\n");
1499 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1501 char *itemname, *price_str, *description;
1505 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1506 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1510 if( !Client->bIsAuthed ) {
1511 sendf(Client->Socket, "401 Not Authenticated\n");
1515 // Check user permissions
1516 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1517 sendf(Client->Socket, "403 Not in coke\n");
1521 item = _GetItemFromString(itemname);
1523 // TODO: Create item?
1524 sendf(Client->Socket, "406 Bad Item ID\n");
1528 price = atoi(price_str);
1529 if( price <= 0 && price_str[0] != '0' ) {
1530 sendf(Client->Socket, "407 Invalid price set\n");
1533 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1537 sendf(Client->Socket, "200 Item updated\n");
1544 // --- INTERNAL HELPERS ---
1545 void Debug(tClient *Client, const char *Format, ...)
1548 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1549 printf("[%i] ", Client->ID);
1550 va_start(args, Format);
1551 vprintf(Format, args);
1556 int sendf(int Socket, const char *Format, ...)
1561 va_start(args, Format);
1562 len = vsnprintf(NULL, 0, Format, args);
1567 va_start(args, Format);
1568 vsnprintf(buf, len+1, Format, args);
1571 #if DEBUG_TRACE_CLIENT
1572 printf("sendf: %s", buf);
1575 return send(Socket, buf, len, 0);
1579 // Takes a series of char *'s in
1581 * \brief Parse space-separated entries into
1583 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1588 va_start(args, ArgStr);
1593 while( (dest = va_arg(args, char **)) )
1599 savedChar = *ArgStr;
1601 while( (dest = va_arg(args, char **)) )
1603 // Trim leading spaces
1604 while( *ArgStr == ' ' || *ArgStr == '\t' )
1607 // ... oops, not enough arguments
1608 if( *ArgStr == '\0' )
1610 // NULL unset arguments
1613 } while( (dest = va_arg(args, char **)) );
1618 if( *ArgStr == '"' )
1623 while( *ArgStr && *ArgStr != '"' )
1630 // Read until a space
1631 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1634 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1640 // Oops, extra arguments, and greedy not set
1641 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1648 *ArgStr = savedChar;
1651 return 0; // Success!
1654 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1661 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1662 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1663 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1664 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1665 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1667 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1679 while( *Str == ' ' ) Str ++; // Eat whitespace
1680 space = strchr(Str, ','); // Find the end of the flag
1686 // Check for inversion/removal
1687 if( *Str == '!' || *Str == '-' ) {
1691 else if( *Str == '+' ) {
1695 // Check flag values
1696 for( i = 0; i < ciNumFlags; i ++ )
1698 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1699 *Mask |= cFLAGS[i].Mask;
1700 *Value &= ~cFLAGS[i].Mask;
1702 *Value |= cFLAGS[i].Value;
1708 if( i == ciNumFlags ) {
1710 strncpy(val, Str, len+1);
1711 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);