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");
688 // You can't be an internal account (unless you're an admin)
689 if( !(userFlags & USER_FLAG_ADMIN) )
691 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
692 if( eUserFlags & USER_FLAG_INTERNAL ) {
693 Client->EffectiveUID = -1;
694 sendf(Client->Socket, "404 User not found\n");
697 // Disabled only avaliable to admins
698 if( eUserFlags & USER_FLAG_DISABLED ) {
699 Client->EffectiveUID = -1;
700 sendf(Client->Socket, "403 Account disabled\n");
706 if( userFlags & USER_FLAG_DISABLED ) {
707 Client->EffectiveUID = -1;
708 sendf(Client->Socket, "403 Account disabled\n");
712 sendf(Client->Socket, "200 User set\n");
716 * \brief Send an item status to the client
717 * \param Client Who to?
718 * \param Item Item to send
720 void Server_int_SendItem(tClient *Client, tItem *Item)
722 char *status = "avail";
724 if( Item->Handler->CanDispense )
726 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
728 case 0: status = "avail"; break;
729 case 1: status = "sold"; break;
731 case -1: status = "error"; break;
735 if( !gbNoCostMode && Item->Price == 0 )
737 // KNOWN HACK: Naming a slot 'dead' disables it
738 if( strcmp(Item->Name, "dead") == 0 )
739 status = "sold"; // Another status?
741 sendf(Client->Socket,
742 "202 Item %s:%i %s %i %s\n",
743 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
748 * \brief Enumerate the items that the server knows about
750 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
754 if( Args != NULL && strlen(Args) ) {
755 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
761 for( i = 0; i < giNumItems; i ++ ) {
762 if( gaItems[i].bHidden ) continue;
766 sendf(Client->Socket, "201 Items %i\n", count);
768 for( i = 0; i < giNumItems; i ++ ) {
769 if( gaItems[i].bHidden ) continue;
770 Server_int_SendItem( Client, &gaItems[i] );
773 sendf(Client->Socket, "200 List end\n");
776 tItem *_GetItemFromString(char *String)
780 char *colon = strchr(String, ':');
792 for( i = 0; i < giNumHandlers; i ++ )
794 if( strcmp(gaHandlers[i]->Name, type) == 0) {
795 handler = gaHandlers[i];
804 for( i = 0; i < giNumItems; i ++ )
806 if( gaItems[i].Handler != handler ) continue;
807 if( gaItems[i].ID != num ) continue;
814 * \brief Fetch information on a specific item
816 * Usage: ITEMINFO <item ID>
818 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
823 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
824 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
827 item = _GetItemFromString(Args);
830 sendf(Client->Socket, "406 Bad Item ID\n");
834 Server_int_SendItem( Client, item );
838 * \brief Dispense an item
840 * Usage: DISPENSE <Item ID>
842 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
849 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
850 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
854 if( !Client->bIsAuthed ) {
855 sendf(Client->Socket, "401 Not Authenticated\n");
859 item = _GetItemFromString(itemname);
861 sendf(Client->Socket, "406 Bad Item ID\n");
865 if( Client->EffectiveUID != -1 ) {
866 uid = Client->EffectiveUID;
872 switch( ret = DispenseItem( Client->UID, uid, item ) )
874 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
875 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
876 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
878 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
884 * \brief Refund an item to a user
886 * Usage: REFUND <user> <item id> [<price>]
888 void Server_Cmd_REFUND(tClient *Client, char *Args)
891 int uid, price_override = 0;
892 char *username, *itemname, *price_str;
894 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
895 if( !itemname || price_str ) {
896 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
901 if( !Client->bIsAuthed ) {
902 sendf(Client->Socket, "401 Not Authenticated\n");
906 // Check user permissions
907 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
908 sendf(Client->Socket, "403 Not in coke\n");
912 uid = Bank_GetAcctByName(username, 0);
914 sendf(Client->Socket, "404 Unknown user\n");
918 item = _GetItemFromString(itemname);
920 sendf(Client->Socket, "406 Bad Item ID\n");
925 price_override = atoi(price_str);
927 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
929 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
931 sendf(Client->Socket, "500 Dispense Error\n");
937 * \brief Transfer money to another account
939 * Usage: GIVE <dest> <ammount> <reason...>
941 void Server_Cmd_GIVE(tClient *Client, char *Args)
943 char *recipient, *ammount, *reason;
948 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
949 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
954 if( !Client->bIsAuthed ) {
955 sendf(Client->Socket, "401 Not Authenticated\n");
960 uid = Bank_GetAcctByName(recipient, 0);
962 sendf(Client->Socket, "404 Invalid target user\n");
966 // You can't alter an internal account
967 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
968 // sendf(Client->Socket, "404 Invalid target user\n");
973 iAmmount = atoi(ammount);
974 if( iAmmount <= 0 ) {
975 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
979 if( Client->EffectiveUID != -1 ) {
980 thisUid = Client->EffectiveUID;
983 thisUid = Client->UID;
987 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
990 sendf(Client->Socket, "200 Give OK\n");
993 sendf(Client->Socket, "402 Poor You\n");
996 sendf(Client->Socket, "500 Unknown error\n");
1001 void Server_Cmd_DONATE(tClient *Client, char *Args)
1003 char *ammount, *reason;
1008 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
1009 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
1013 if( !Client->bIsAuthed ) {
1014 sendf(Client->Socket, "401 Not Authenticated\n");
1019 iAmmount = atoi(ammount);
1020 if( iAmmount <= 0 ) {
1021 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
1025 // Handle effective users
1026 if( Client->EffectiveUID != -1 ) {
1027 thisUid = Client->EffectiveUID;
1030 thisUid = Client->UID;
1034 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
1037 sendf(Client->Socket, "200 Give OK\n");
1040 sendf(Client->Socket, "402 Poor You\n");
1043 sendf(Client->Socket, "500 Unknown error\n");
1048 void Server_Cmd_ADD(tClient *Client, char *Args)
1050 char *user, *ammount, *reason;
1054 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1055 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
1059 if( !Client->bIsAuthed ) {
1060 sendf(Client->Socket, "401 Not Authenticated\n");
1064 // Check user permissions
1065 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1066 sendf(Client->Socket, "403 Not in coke\n");
1071 if( strcmp( Client->Username, "root" ) == 0 ) {
1072 // Allow adding for new users
1073 if( strcmp(reason, "treasurer: new user") != 0 ) {
1074 sendf(Client->Socket, "403 Root may not add\n");
1081 if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
1083 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
1089 uid = Bank_GetAcctByName(user, 0);
1091 sendf(Client->Socket, "404 Invalid user\n");
1095 // You can't alter an internal account
1096 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
1098 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
1099 sendf(Client->Socket, "404 Invalid user\n");
1102 // TODO: Maybe disallow changes to disabled?
1106 iAmmount = atoi(ammount);
1107 if( iAmmount == 0 && ammount[0] != '0' ) {
1108 sendf(Client->Socket, "407 Invalid Argument\n");
1113 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
1116 sendf(Client->Socket, "200 Add OK\n");
1119 sendf(Client->Socket, "402 Poor Guy\n");
1122 sendf(Client->Socket, "500 Unknown error\n");
1127 void Server_Cmd_SET(tClient *Client, char *Args)
1129 char *user, *ammount, *reason;
1133 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1134 sendf(Client->Socket, "407 SET takes 3 arguments\n");
1138 if( !Client->bIsAuthed ) {
1139 sendf(Client->Socket, "401 Not Authenticated\n");
1143 // Check user permissions
1144 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1145 sendf(Client->Socket, "403 Not an admin\n");
1150 uid = Bank_GetAcctByName(user, 0);
1152 sendf(Client->Socket, "404 Invalid user\n");
1157 iAmmount = atoi(ammount);
1158 if( iAmmount == 0 && ammount[0] != '0' ) {
1159 sendf(Client->Socket, "407 Invalid Argument\n");
1164 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
1167 sendf(Client->Socket, "200 Add OK\n");
1170 sendf(Client->Socket, "402 Poor Guy\n");
1173 sendf(Client->Socket, "500 Unknown error\n");
1178 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1182 int maxBal = INT_MAX, minBal = INT_MIN;
1183 int flagMask = 0, flagVal = 0;
1184 int sort = BANK_ITFLAG_SORT_NAME;
1185 time_t lastSeenAfter=0, lastSeenBefore=0;
1187 int flags; // Iterator flags
1188 int balValue; // Balance value for iterator
1189 time_t timeValue; // Time value for iterator
1192 if( Args && strlen(Args) )
1194 char *space = Args, *type, *val;
1198 while(*type == ' ') type ++;
1200 space = strchr(space, ' ');
1201 if(space) *space = '\0';
1204 val = strchr(type, ':');
1211 if( strcmp(type, "min_balance") == 0 ) {
1214 // - Maximum Balance
1215 else if( strcmp(type, "max_balance") == 0 ) {
1219 else if( strcmp(type, "flags") == 0 ) {
1220 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1223 // - Last seen before timestamp
1224 else if( strcmp(type, "last_seen_before") == 0 ) {
1225 lastSeenAfter = atoll(val);
1227 // - Last seen after timestamp
1228 else if( strcmp(type, "last_seen_after") == 0 ) {
1229 lastSeenAfter = atoll(val);
1232 else if( strcmp(type, "sort") == 0 ) {
1233 char *dash = strchr(val, '-');
1238 if( strcmp(val, "name") == 0 ) {
1239 sort = BANK_ITFLAG_SORT_NAME;
1241 else if( strcmp(val, "balance") == 0 ) {
1242 sort = BANK_ITFLAG_SORT_BAL;
1244 else if( strcmp(val, "lastseen") == 0 ) {
1245 sort = BANK_ITFLAG_SORT_LASTSEEN;
1248 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1251 // Handle sort direction
1253 if( strcmp(dash, "desc") == 0 ) {
1254 sort |= BANK_ITFLAG_REVSORT;
1257 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1264 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1271 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1277 *space = ' '; // Repair (to be nice)
1279 while(*space == ' ') space ++;
1285 if( maxBal != INT_MAX ) {
1286 flags = sort|BANK_ITFLAG_MAXBALANCE;
1289 else if( minBal != INT_MIN ) {
1290 flags = sort|BANK_ITFLAG_MINBALANCE;
1297 if( lastSeenBefore ) {
1298 timeValue = lastSeenBefore;
1299 flags |= BANK_ITFLAG_SEENBEFORE;
1301 else if( lastSeenAfter ) {
1302 timeValue = lastSeenAfter;
1303 flags |= BANK_ITFLAG_SEENAFTER;
1308 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1310 // Get return number
1311 while( (i = Bank_IteratorNext(it)) != -1 )
1313 int bal = Bank_GetBalance(i);
1315 if( bal == INT_MIN ) continue;
1317 if( bal < minBal ) continue;
1318 if( bal > maxBal ) continue;
1323 Bank_DelIterator(it);
1326 sendf(Client->Socket, "201 Users %i\n", numRet);
1330 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1332 while( (i = Bank_IteratorNext(it)) != -1 )
1334 int bal = Bank_GetBalance(i);
1336 if( bal == INT_MIN ) continue;
1338 if( bal < minBal ) continue;
1339 if( bal > maxBal ) continue;
1341 _SendUserInfo(Client, i);
1344 Bank_DelIterator(it);
1346 sendf(Client->Socket, "200 List End\n");
1349 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1355 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1356 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1360 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1363 uid = Bank_GetAcctByName(user, 0);
1365 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1367 sendf(Client->Socket, "404 Invalid user\n");
1371 _SendUserInfo(Client, uid);
1374 void _SendUserInfo(tClient *Client, int UserID)
1376 char *type, *disabled="", *door="";
1377 int flags = Bank_GetFlags(UserID);
1379 if( flags & USER_FLAG_INTERNAL ) {
1382 else if( flags & USER_FLAG_COKE ) {
1383 if( flags & USER_FLAG_ADMIN )
1384 type = "coke,admin";
1388 else if( flags & USER_FLAG_ADMIN ) {
1395 if( flags & USER_FLAG_DISABLED )
1396 disabled = ",disabled";
1397 if( flags & USER_FLAG_DOORGROUP )
1400 // TODO: User flags/type
1402 Client->Socket, "202 User %s %i %s%s%s\n",
1403 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1404 type, disabled, door
1408 void Server_Cmd_USERADD(tClient *Client, char *Args)
1413 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1414 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1418 // Check authentication
1419 if( !Client->bIsAuthed ) {
1420 sendf(Client->Socket, "401 Not Authenticated\n");
1424 // Check permissions
1425 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1426 sendf(Client->Socket, "403 Not a coke admin\n");
1430 // Try to create user
1431 if( Bank_CreateAcct(username) == -1 ) {
1432 sendf(Client->Socket, "404 User exists\n");
1437 char *thisName = Bank_GetAcctName(Client->UID);
1438 Log_Info("Account '%s' created by '%s'", username, thisName);
1442 sendf(Client->Socket, "200 User Added\n");
1445 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1447 char *username, *flags, *reason=NULL;
1448 int mask=0, value=0;
1452 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1454 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1460 // Check authentication
1461 if( !Client->bIsAuthed ) {
1462 sendf(Client->Socket, "401 Not Authenticated\n");
1466 // Check permissions
1467 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1468 sendf(Client->Socket, "403 Not a coke admin\n");
1473 uid = Bank_GetAcctByName(username, 0);
1475 sendf(Client->Socket, "404 User '%s' not found\n", username);
1480 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1484 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1485 uid, username, mask, value);
1488 Bank_SetFlags(uid, mask, value);
1491 Log_Info("Updated '%s' with flag set '%s' by '%s' - Reason: %s",
1492 username, flags, Client->Username, reason);
1495 sendf(Client->Socket, "200 User Updated\n");
1498 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1500 char *itemname, *price_str, *description;
1504 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1505 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1509 if( !Client->bIsAuthed ) {
1510 sendf(Client->Socket, "401 Not Authenticated\n");
1514 // Check user permissions
1515 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1516 sendf(Client->Socket, "403 Not in coke\n");
1520 item = _GetItemFromString(itemname);
1522 // TODO: Create item?
1523 sendf(Client->Socket, "406 Bad Item ID\n");
1527 price = atoi(price_str);
1528 if( price <= 0 && price_str[0] != '0' ) {
1529 sendf(Client->Socket, "407 Invalid price set\n");
1532 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1536 sendf(Client->Socket, "200 Item updated\n");
1543 // --- INTERNAL HELPERS ---
1544 void Debug(tClient *Client, const char *Format, ...)
1547 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1548 printf("[%i] ", Client->ID);
1549 va_start(args, Format);
1550 vprintf(Format, args);
1555 int sendf(int Socket, const char *Format, ...)
1560 va_start(args, Format);
1561 len = vsnprintf(NULL, 0, Format, args);
1566 va_start(args, Format);
1567 vsnprintf(buf, len+1, Format, args);
1570 #if DEBUG_TRACE_CLIENT
1571 printf("sendf: %s", buf);
1574 return send(Socket, buf, len, 0);
1578 // Takes a series of char *'s in
1580 * \brief Parse space-separated entries into
1582 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1587 va_start(args, ArgStr);
1592 while( (dest = va_arg(args, char **)) )
1598 savedChar = *ArgStr;
1600 while( (dest = va_arg(args, char **)) )
1602 // Trim leading spaces
1603 while( *ArgStr == ' ' || *ArgStr == '\t' )
1606 // ... oops, not enough arguments
1607 if( *ArgStr == '\0' )
1609 // NULL unset arguments
1612 } while( (dest = va_arg(args, char **)) );
1617 if( *ArgStr == '"' )
1622 while( *ArgStr && *ArgStr != '"' )
1629 // Read until a space
1630 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1633 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1639 // Oops, extra arguments, and greedy not set
1640 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1647 *ArgStr = savedChar;
1650 return 0; // Success!
1653 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1660 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1661 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1662 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1663 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1664 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1666 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1678 while( *Str == ' ' ) Str ++; // Eat whitespace
1679 space = strchr(Str, ','); // Find the end of the flag
1685 // Check for inversion/removal
1686 if( *Str == '!' || *Str == '-' ) {
1690 else if( *Str == '+' ) {
1694 // Check flag values
1695 for( i = 0; i < ciNumFlags; i ++ )
1697 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1698 *Mask |= cFLAGS[i].Mask;
1699 *Value &= ~cFLAGS[i].Mask;
1701 *Value |= cFLAGS[i].Value;
1707 if( i == ciNumFlags ) {
1709 strncpy(val, Str, len+1);
1710 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);