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
29 #define MAX_CONNECTION_QUEUE 5
30 #define INPUT_BUFFER_SIZE 256
31 #define CLIENT_TIMEOUT 10 // Seconds
33 #define HASH_TYPE SHA1
34 #define HASH_LENGTH 20
36 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
38 #define IDENT_TRUSTED_NETWORK 0x825F0D00
39 #define IDENT_TRUSTED_NETMASK 0xFFFFFFC0
42 typedef struct sClient
44 int Socket; // Client socket ID
48 int bCanAutoAuth; // Is the connection from a trusted host/port
59 void Server_Start(void);
60 void Server_Cleanup(void);
61 void Server_HandleClient(int Socket, int bTrustedHost, int bRootPort);
62 void Server_ParseClientCommand(tClient *Client, char *CommandString);
64 void Server_Cmd_USER(tClient *Client, char *Args);
65 void Server_Cmd_PASS(tClient *Client, char *Args);
66 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
67 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args);
68 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
69 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
70 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
71 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
72 void Server_Cmd_REFUND(tClient *Client, char *Args);
73 void Server_Cmd_GIVE(tClient *Client, char *Args);
74 void Server_Cmd_DONATE(tClient *Client, char *Args);
75 void Server_Cmd_ADD(tClient *Client, char *Args);
76 void Server_Cmd_SET(tClient *Client, char *Args);
77 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
78 void Server_Cmd_USERINFO(tClient *Client, char *Args);
79 void _SendUserInfo(tClient *Client, int UserID);
80 void Server_Cmd_USERADD(tClient *Client, char *Args);
81 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
82 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args);
84 void Debug(tClient *Client, const char *Format, ...);
85 int sendf(int Socket, const char *Format, ...);
86 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
87 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
91 const struct sClientCommand {
93 void (*Function)(tClient *Client, char *Arguments);
94 } gaServer_Commands[] = {
95 {"USER", Server_Cmd_USER},
96 {"PASS", Server_Cmd_PASS},
97 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
98 {"AUTHIDENT", Server_Cmd_AUTHIDENT},
99 {"SETEUSER", Server_Cmd_SETEUSER},
100 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
101 {"ITEM_INFO", Server_Cmd_ITEMINFO},
102 {"DISPENSE", Server_Cmd_DISPENSE},
103 {"REFUND", Server_Cmd_REFUND},
104 {"GIVE", Server_Cmd_GIVE},
105 {"DONATE", Server_Cmd_DONATE},
106 {"ADD", Server_Cmd_ADD},
107 {"SET", Server_Cmd_SET},
108 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
109 {"USER_INFO", Server_Cmd_USERINFO},
110 {"USER_ADD", Server_Cmd_USERADD},
111 {"USER_FLAGS", Server_Cmd_USERFLAGS},
112 {"UPDATE_ITEM", Server_Cmd_UPDATEITEM}
114 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
118 int giServer_Port = 11020;
119 int gbServer_RunInBackground = 0;
120 char *gsServer_LogFile = "/var/log/dispsrv.log";
121 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
122 int giServer_NumTrustedHosts;
123 struct in_addr *gaServer_TrustedHosts;
125 int giServer_Socket; // Server socket
126 int giServer_NextClientID = 1; // Debug client ID
131 * \brief Open listenting socket and serve connections
133 void Server_Start(void)
136 struct sockaddr_in server_addr, client_addr;
138 // Parse trusted hosts list
139 giServer_NumTrustedHosts = Config_GetValueCount("trusted_host");
140 gaServer_TrustedHosts = malloc(giServer_NumTrustedHosts * sizeof(*gaServer_TrustedHosts));
141 for( int i = 0; i < giServer_NumTrustedHosts; i ++ )
143 const char *addr = Config_GetValue("trusted_host", i);
145 if( inet_aton(addr, &gaServer_TrustedHosts[i]) == 0 ) {
146 fprintf(stderr, "Invalid IP address '%s'\n", addr);
151 atexit(Server_Cleanup);
152 // Ignore SIGPIPE (stops crashes when the client exits early)
153 signal(SIGPIPE, SIG_IGN);
156 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
157 if( giServer_Socket < 0 ) {
158 fprintf(stderr, "ERROR: Unable to create server socket\n");
162 // Make listen address
163 memset(&server_addr, 0, sizeof(server_addr));
164 server_addr.sin_family = AF_INET; // Internet Socket
165 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
166 server_addr.sin_port = htons(giServer_Port); // Port
169 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
170 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
175 // Fork into background
176 if( gbServer_RunInBackground )
180 fprintf(stderr, "ERROR: Unable to fork\n");
181 perror("fork background");
186 printf("Forked child %i\n", pid);
190 // - Sort out stdin/stdout
192 dup2( open("/dev/null", O_RDONLY, 0644), STDIN_FILENO );
193 dup2( open(gsServer_LogFile, O_CREAT|O_APPEND, 0644), STDOUT_FILENO );
194 dup2( open(gsServer_ErrorLog, O_CREAT|O_APPEND, 0644), STDERR_FILENO );
196 freopen("/dev/null", "r", stdin);
197 freopen(gsServer_LogFile, "a", stdout);
198 freopen(gsServer_ErrorLog, "a", stderr);
199 fprintf(stdout, "OpenDispense 2 Server Started at %lld\n", (long long)time(NULL));
200 fprintf(stderr, "OpenDispense 2 Server Started at %lld\n", (long long)time(NULL));
204 // Start the helper thread
205 StartPeriodicThread();
208 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
209 fprintf(stderr, "ERROR: Unable to listen to socket\n");
214 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
218 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
220 fprintf(fp, "%i", getpid());
227 uint len = sizeof(client_addr);
231 // Accept a connection
232 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
233 if(client_socket < 0) {
234 fprintf(stderr, "ERROR: Unable to accept client connection\n");
238 // Set a timeout on the user conneciton
241 tv.tv_sec = CLIENT_TIMEOUT;
243 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
245 perror("setsockopt");
250 // Debug: Print the connection string
251 if(giDebugLevel >= 2) {
252 char ipstr[INET_ADDRSTRLEN];
253 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
254 printf("Client connection from %s:%i\n",
255 ipstr, ntohs(client_addr.sin_port));
258 // Doesn't matter what, localhost is trusted
259 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
262 // Check if the host is on the trusted list
263 for( int i = 0; i < giServer_NumTrustedHosts; i ++ )
265 if( memcmp(&client_addr.sin_addr, &gaServer_TrustedHosts[i], sizeof(struct in_addr)) == 0 )
272 // Root port (can AUTOAUTH if also a trusted machine
273 if( ntohs(client_addr.sin_port) < 1024 )
278 // TODO: Make this runtime configurable
279 switch( ntohl( client_addr.sin_addr.s_addr ) )
281 case 0x7F000001: // 127.0.0.1 localhost
282 // case 0x825F0D00: // 130.95.13.0
283 case 0x825F0D04: // 130.95.13.4 merlo
284 // case 0x825F0D05: // 130.95.13.5 heathred (MR)
285 case 0x825F0D07: // 130.95.13.7 motsugo
286 case 0x825F0D11: // 130.95.13.17 mermaid
287 case 0x825F0D12: // 130.95.13.18 mussel
288 case 0x825F0D17: // 130.95.13.23 martello
289 case 0x825F0D2A: // 130.95.13.42 meersau
290 // case 0x825F0D42: // 130.95.13.66 heathred (Clubroom)
299 // TODO: Multithread this?
300 Server_HandleClient(client_socket, bTrusted, bRootPort);
302 close(client_socket);
306 void Server_Cleanup(void)
308 printf("\nClose(%i)\n", giServer_Socket);
309 close(giServer_Socket);
310 unlink("/var/run/dispsrv.pid");
314 * \brief Reads from a client socket and parses the command strings
315 * \param Socket Client socket number/handle
316 * \param bTrusted Is the client trusted?
318 void Server_HandleClient(int Socket, int bTrusted, int bRootPort)
320 char inbuf[INPUT_BUFFER_SIZE];
322 int remspace = INPUT_BUFFER_SIZE-1;
326 memset(&clientInfo, 0, sizeof(clientInfo));
328 // Initialise Client info
329 clientInfo.Socket = Socket;
330 clientInfo.ID = giServer_NextClientID ++;
331 clientInfo.bTrustedHost = bTrusted;
332 clientInfo.bCanAutoAuth = bTrusted && bRootPort;
333 clientInfo.EffectiveUID = -1;
338 * - The `buf` and `remspace` variables allow a line to span several
339 * calls to recv(), if a line is not completed in one recv() call
340 * it is saved to the beginning of `inbuf` and `buf` is updated to
343 // TODO: Use select() instead (to give a timeout)
344 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
347 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
351 while( (eol = strchr(start, '\n')) )
355 Server_ParseClientCommand(&clientInfo, start);
360 // Check if there was an incomplete line
361 if( *start != '\0' ) {
362 int tailBytes = bytes - (start-buf);
363 // Roll back in buffer
364 memcpy(inbuf, start, tailBytes);
365 remspace -= tailBytes;
367 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
369 remspace = INPUT_BUFFER_SIZE - 1;
374 remspace = INPUT_BUFFER_SIZE - 1;
380 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
384 if(giDebugLevel >= 2) {
385 printf("Client %i: Disconnected\n", clientInfo.ID);
390 * \brief Parses a client command and calls the required helper function
391 * \param Client Pointer to client state structure
392 * \param CommandString Command from client (single line of the command)
393 * \return Heap String to return to the client
395 void Server_ParseClientCommand(tClient *Client, char *CommandString)
397 char *command, *args;
400 if( giDebugLevel >= 2 )
401 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
403 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
405 if( command == NULL ) return ;
406 // Is this an error? (just ignore for now)
411 for( i = 0; i < NUM_COMMANDS; i++ )
413 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
414 if( giDebugLevel >= 2 )
415 Debug(Client, "CMD %s - \"%s\"", command, args);
416 gaServer_Commands[i].Function(Client, args);
421 sendf(Client->Socket, "400 Unknown Command\n");
428 * \brief Set client username
430 * Usage: USER <username>
432 void Server_Cmd_USER(tClient *Client, char *Args)
436 if( Server_int_ParseArgs(0, Args, &username, NULL) )
438 sendf(Client->Socket, "407 USER takes 1 argument\n");
444 Debug(Client, "Authenticating as '%s'", username);
448 free(Client->Username);
449 Client->Username = strdup(username);
452 // Create a salt (that changes if the username is changed)
453 // Yes, I know, I'm a little paranoid, but who isn't?
454 Client->Salt[0] = 0x21 + (rand()&0x3F);
455 Client->Salt[1] = 0x21 + (rand()&0x3F);
456 Client->Salt[2] = 0x21 + (rand()&0x3F);
457 Client->Salt[3] = 0x21 + (rand()&0x3F);
458 Client->Salt[4] = 0x21 + (rand()&0x3F);
459 Client->Salt[5] = 0x21 + (rand()&0x3F);
460 Client->Salt[6] = 0x21 + (rand()&0x3F);
461 Client->Salt[7] = 0x21 + (rand()&0x3F);
463 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
464 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
466 sendf(Client->Socket, "100 User Set\n");
471 * \brief Authenticate as a user
475 void Server_Cmd_PASS(tClient *Client, char *Args)
480 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
482 sendf(Client->Socket, "407 PASS takes 1 argument\n");
486 // Pass on to cokebank
487 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
489 if( Client->UID == -1 ) {
490 sendf(Client->Socket, "401 Auth Failure\n");
494 flags = Bank_GetFlags(Client->UID);
495 if( flags & USER_FLAG_DISABLED ) {
497 sendf(Client->Socket, "403 Account Disabled\n");
500 if( flags & USER_FLAG_INTERNAL ) {
502 sendf(Client->Socket, "403 Internal account\n");
506 Client->bIsAuthed = 1;
507 sendf(Client->Socket, "200 Auth OK\n");
511 * \brief Authenticate as a user without a password
513 * Usage: AUTOAUTH <user>
515 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
520 if( Server_int_ParseArgs(0, Args, &username, NULL) )
522 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
527 if( !Client->bCanAutoAuth ) {
529 Debug(Client, "Untrusted client attempting to AUTOAUTH");
530 sendf(Client->Socket, "401 Untrusted\n");
535 Client->UID = Bank_GetAcctByName( username, 0 );
536 if( Client->UID < 0 ) {
538 Debug(Client, "Unknown user '%s'", username);
539 sendf(Client->Socket, "403 Auth Failure\n");
543 userflags = Bank_GetFlags(Client->UID);
544 // You can't be an internal account
545 if( userflags & USER_FLAG_INTERNAL ) {
547 Debug(Client, "Autoauth as '%s', not allowed", username);
549 sendf(Client->Socket, "403 Account is internal\n");
554 if( userflags & USER_FLAG_DISABLED ) {
556 sendf(Client->Socket, "403 Account disabled\n");
562 free(Client->Username);
563 Client->Username = strdup(username);
565 Client->bIsAuthed = 1;
568 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
570 sendf(Client->Socket, "200 Auth OK\n");
574 * \brief Authenticate as a user using the IDENT protocol
578 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args)
582 const int ident_timeout = 5;
584 if( Args != NULL && strlen(Args) ) {
585 sendf(Client->Socket, "407 AUTHIDENT takes no arguments\n");
590 if( !Client->bTrustedHost ) {
592 Debug(Client, "Untrusted client attempting to AUTHIDENT");
593 sendf(Client->Socket, "401 Untrusted\n");
597 // Get username via IDENT
598 username = ident_id(Client->Socket, ident_timeout);
600 sendf(Client->Socket, "403 Authentication failure: IDENT auth timed out\n");
605 Client->UID = Bank_GetAcctByName( username, 0 );
606 if( Client->UID < 0 ) {
608 Debug(Client, "Unknown user '%s'", username);
609 sendf(Client->Socket, "403 Authentication failure: unknown account\n");
614 userflags = Bank_GetFlags(Client->UID);
615 // You can't be an internal account
616 if( userflags & USER_FLAG_INTERNAL ) {
618 Debug(Client, "IDENT auth as '%s', not allowed", username);
620 sendf(Client->Socket, "403 Authentication failure: that account is internal\n");
626 if( userflags & USER_FLAG_DISABLED ) {
628 sendf(Client->Socket, "403 Authentication failure: account disabled\n");
635 free(Client->Username);
636 Client->Username = strdup(username);
638 Client->bIsAuthed = 1;
641 Debug(Client, "IDENT authenticated as '%s' (%i)", username, Client->UID);
644 sendf(Client->Socket, "200 Auth OK\n");
648 * \brief Set effective user
650 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
653 int eUserFlags, userFlags;
655 if( Server_int_ParseArgs(0, Args, &username, NULL) )
657 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
661 if( !strlen(Args) ) {
662 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
666 // Check authentication
667 if( !Client->bIsAuthed ) {
668 sendf(Client->Socket, "401 Not Authenticated\n");
672 // Check user permissions
673 userFlags = Bank_GetFlags(Client->UID);
674 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
675 sendf(Client->Socket, "403 Not in coke\n");
680 Client->EffectiveUID = Bank_GetAcctByName(username, 0);
681 if( Client->EffectiveUID == -1 ) {
682 sendf(Client->Socket, "404 User not found\n");
686 // You can't be an internal account
687 if( !(userFlags & USER_FLAG_ADMIN) )
689 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
690 if( eUserFlags & USER_FLAG_INTERNAL ) {
691 Client->EffectiveUID = -1;
692 sendf(Client->Socket, "404 User not found\n");
695 // Disabled only avaliable to admins
696 if( eUserFlags & USER_FLAG_DISABLED ) {
697 Client->EffectiveUID = -1;
698 sendf(Client->Socket, "403 Account disabled\n");
704 if( userFlags & USER_FLAG_DISABLED ) {
706 sendf(Client->Socket, "403 Account disabled\n");
710 sendf(Client->Socket, "200 User set\n");
714 * \brief Send an item status to the client
715 * \param Client Who to?
716 * \param Item Item to send
718 void Server_int_SendItem(tClient *Client, tItem *Item)
720 char *status = "avail";
722 if( Item->Handler->CanDispense )
724 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
726 case 0: status = "avail"; break;
727 case 1: status = "sold"; break;
729 case -1: status = "error"; break;
733 if( Item->Price == 0 )
735 // KNOWN HACK: Naming a slot 'dead' disables it
736 if( strcmp(Item->Name, "dead") == 0 )
737 status = "sold"; // Another status?
739 sendf(Client->Socket,
740 "202 Item %s:%i %s %i %s\n",
741 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
746 * \brief Enumerate the items that the server knows about
748 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
752 if( Args != NULL && strlen(Args) ) {
753 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
759 for( i = 0; i < giNumItems; i ++ ) {
760 if( gaItems[i].bHidden ) continue;
764 sendf(Client->Socket, "201 Items %i\n", count);
766 for( i = 0; i < giNumItems; i ++ ) {
767 if( gaItems[i].bHidden ) continue;
768 Server_int_SendItem( Client, &gaItems[i] );
771 sendf(Client->Socket, "200 List end\n");
774 tItem *_GetItemFromString(char *String)
778 char *colon = strchr(String, ':');
790 for( i = 0; i < giNumHandlers; i ++ )
792 if( strcmp(gaHandlers[i]->Name, type) == 0) {
793 handler = gaHandlers[i];
802 for( i = 0; i < giNumItems; i ++ )
804 if( gaItems[i].Handler != handler ) continue;
805 if( gaItems[i].ID != num ) continue;
812 * \brief Fetch information on a specific item
814 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
819 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
820 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
823 item = _GetItemFromString(Args);
826 sendf(Client->Socket, "406 Bad Item ID\n");
830 Server_int_SendItem( Client, item );
833 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
840 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
841 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
845 if( !Client->bIsAuthed ) {
846 sendf(Client->Socket, "401 Not Authenticated\n");
850 item = _GetItemFromString(itemname);
852 sendf(Client->Socket, "406 Bad Item ID\n");
856 if( Client->EffectiveUID != -1 ) {
857 uid = Client->EffectiveUID;
863 switch( ret = DispenseItem( Client->UID, uid, item ) )
865 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
866 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
867 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
869 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
874 void Server_Cmd_REFUND(tClient *Client, char *Args)
877 int uid, price_override = 0;
878 char *username, *itemname, *price_str;
880 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
881 if( !itemname || price_str ) {
882 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
887 if( !Client->bIsAuthed ) {
888 sendf(Client->Socket, "401 Not Authenticated\n");
892 // Check user permissions
893 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
894 sendf(Client->Socket, "403 Not in coke\n");
898 uid = Bank_GetAcctByName(username, 0);
900 sendf(Client->Socket, "404 Unknown user\n");
904 item = _GetItemFromString(itemname);
906 sendf(Client->Socket, "406 Bad Item ID\n");
911 price_override = atoi(price_str);
913 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
915 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
917 sendf(Client->Socket, "500 Dispense Error\n");
922 void Server_Cmd_GIVE(tClient *Client, char *Args)
924 char *recipient, *ammount, *reason;
929 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
930 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
935 if( !Client->bIsAuthed ) {
936 sendf(Client->Socket, "401 Not Authenticated\n");
941 uid = Bank_GetAcctByName(recipient, 0);
943 sendf(Client->Socket, "404 Invalid target user\n");
947 // You can't alter an internal account
948 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
949 // sendf(Client->Socket, "404 Invalid target user\n");
954 iAmmount = atoi(ammount);
955 if( iAmmount <= 0 ) {
956 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
960 if( Client->EffectiveUID != -1 ) {
961 thisUid = Client->EffectiveUID;
964 thisUid = Client->UID;
968 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
971 sendf(Client->Socket, "200 Give OK\n");
974 sendf(Client->Socket, "402 Poor You\n");
977 sendf(Client->Socket, "500 Unknown error\n");
982 void Server_Cmd_DONATE(tClient *Client, char *Args)
984 char *ammount, *reason;
989 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
990 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
994 if( !Client->bIsAuthed ) {
995 sendf(Client->Socket, "401 Not Authenticated\n");
1000 iAmmount = atoi(ammount);
1001 if( iAmmount <= 0 ) {
1002 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
1006 // Handle effective users
1007 if( Client->EffectiveUID != -1 ) {
1008 thisUid = Client->EffectiveUID;
1011 thisUid = Client->UID;
1015 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
1018 sendf(Client->Socket, "200 Give OK\n");
1021 sendf(Client->Socket, "402 Poor You\n");
1024 sendf(Client->Socket, "500 Unknown error\n");
1029 void Server_Cmd_ADD(tClient *Client, char *Args)
1031 char *user, *ammount, *reason;
1035 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1036 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
1040 if( !Client->bIsAuthed ) {
1041 sendf(Client->Socket, "401 Not Authenticated\n");
1045 // Check user permissions
1046 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1047 sendf(Client->Socket, "403 Not in coke\n");
1052 if( strcmp( Client->Username, "root" ) == 0 ) {
1053 // Allow adding for new users
1054 if( strcmp(reason, "treasurer: new user") != 0 ) {
1055 sendf(Client->Socket, "403 Root may not add\n");
1062 if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
1064 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
1070 uid = Bank_GetAcctByName(user, 0);
1072 sendf(Client->Socket, "404 Invalid user\n");
1076 // You can't alter an internal account
1077 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
1079 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
1080 sendf(Client->Socket, "404 Invalid user\n");
1083 // TODO: Maybe disallow changes to disabled?
1087 iAmmount = atoi(ammount);
1088 if( iAmmount == 0 && ammount[0] != '0' ) {
1089 sendf(Client->Socket, "407 Invalid Argument\n");
1094 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
1097 sendf(Client->Socket, "200 Add OK\n");
1100 sendf(Client->Socket, "402 Poor Guy\n");
1103 sendf(Client->Socket, "500 Unknown error\n");
1108 void Server_Cmd_SET(tClient *Client, char *Args)
1110 char *user, *ammount, *reason;
1114 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1115 sendf(Client->Socket, "407 SET takes 3 arguments\n");
1119 if( !Client->bIsAuthed ) {
1120 sendf(Client->Socket, "401 Not Authenticated\n");
1124 // Check user permissions
1125 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1126 sendf(Client->Socket, "403 Not an admin\n");
1131 uid = Bank_GetAcctByName(user, 0);
1133 sendf(Client->Socket, "404 Invalid user\n");
1138 iAmmount = atoi(ammount);
1139 if( iAmmount == 0 && ammount[0] != '0' ) {
1140 sendf(Client->Socket, "407 Invalid Argument\n");
1145 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
1148 sendf(Client->Socket, "200 Add OK\n");
1151 sendf(Client->Socket, "402 Poor Guy\n");
1154 sendf(Client->Socket, "500 Unknown error\n");
1159 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1163 int maxBal = INT_MAX, minBal = INT_MIN;
1164 int flagMask = 0, flagVal = 0;
1165 int sort = BANK_ITFLAG_SORT_NAME;
1166 time_t lastSeenAfter=0, lastSeenBefore=0;
1168 int flags; // Iterator flags
1169 int balValue; // Balance value for iterator
1170 time_t timeValue; // Time value for iterator
1173 if( Args && strlen(Args) )
1175 char *space = Args, *type, *val;
1179 while(*type == ' ') type ++;
1181 space = strchr(space, ' ');
1182 if(space) *space = '\0';
1185 val = strchr(type, ':');
1192 if( strcmp(type, "min_balance") == 0 ) {
1195 // - Maximum Balance
1196 else if( strcmp(type, "max_balance") == 0 ) {
1200 else if( strcmp(type, "flags") == 0 ) {
1201 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1204 // - Last seen before timestamp
1205 else if( strcmp(type, "last_seen_before") == 0 ) {
1206 lastSeenAfter = atoll(val);
1208 // - Last seen after timestamp
1209 else if( strcmp(type, "last_seen_after") == 0 ) {
1210 lastSeenAfter = atoll(val);
1213 else if( strcmp(type, "sort") == 0 ) {
1214 char *dash = strchr(val, '-');
1219 if( strcmp(val, "name") == 0 ) {
1220 sort = BANK_ITFLAG_SORT_NAME;
1222 else if( strcmp(val, "balance") == 0 ) {
1223 sort = BANK_ITFLAG_SORT_BAL;
1225 else if( strcmp(val, "lastseen") == 0 ) {
1226 sort = BANK_ITFLAG_SORT_LASTSEEN;
1229 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1232 // Handle sort direction
1234 if( strcmp(dash, "desc") == 0 ) {
1235 sort |= BANK_ITFLAG_REVSORT;
1238 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1245 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1252 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1258 *space = ' '; // Repair (to be nice)
1260 while(*space == ' ') space ++;
1266 if( maxBal != INT_MAX ) {
1267 flags = sort|BANK_ITFLAG_MAXBALANCE;
1270 else if( minBal != INT_MIN ) {
1271 flags = sort|BANK_ITFLAG_MINBALANCE;
1278 if( lastSeenBefore ) {
1279 timeValue = lastSeenBefore;
1280 flags |= BANK_ITFLAG_SEENBEFORE;
1282 else if( lastSeenAfter ) {
1283 timeValue = lastSeenAfter;
1284 flags |= BANK_ITFLAG_SEENAFTER;
1289 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1291 // Get return number
1292 while( (i = Bank_IteratorNext(it)) != -1 )
1294 int bal = Bank_GetBalance(i);
1296 if( bal == INT_MIN ) continue;
1298 if( bal < minBal ) continue;
1299 if( bal > maxBal ) continue;
1304 Bank_DelIterator(it);
1307 sendf(Client->Socket, "201 Users %i\n", numRet);
1311 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1313 while( (i = Bank_IteratorNext(it)) != -1 )
1315 int bal = Bank_GetBalance(i);
1317 if( bal == INT_MIN ) continue;
1319 if( bal < minBal ) continue;
1320 if( bal > maxBal ) continue;
1322 _SendUserInfo(Client, i);
1325 Bank_DelIterator(it);
1327 sendf(Client->Socket, "200 List End\n");
1330 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1336 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1337 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1341 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1344 uid = Bank_GetAcctByName(user, 0);
1346 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1348 sendf(Client->Socket, "404 Invalid user\n");
1352 _SendUserInfo(Client, uid);
1355 void _SendUserInfo(tClient *Client, int UserID)
1357 char *type, *disabled="", *door="";
1358 int flags = Bank_GetFlags(UserID);
1360 if( flags & USER_FLAG_INTERNAL ) {
1363 else if( flags & USER_FLAG_COKE ) {
1364 if( flags & USER_FLAG_ADMIN )
1365 type = "coke,admin";
1369 else if( flags & USER_FLAG_ADMIN ) {
1376 if( flags & USER_FLAG_DISABLED )
1377 disabled = ",disabled";
1378 if( flags & USER_FLAG_DOORGROUP )
1381 // TODO: User flags/type
1383 Client->Socket, "202 User %s %i %s%s%s\n",
1384 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1385 type, disabled, door
1389 void Server_Cmd_USERADD(tClient *Client, char *Args)
1394 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1395 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1399 // Check authentication
1400 if( !Client->bIsAuthed ) {
1401 sendf(Client->Socket, "401 Not Authenticated\n");
1405 // Check permissions
1406 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1407 sendf(Client->Socket, "403 Not a coke admin\n");
1411 // Try to create user
1412 if( Bank_CreateAcct(username) == -1 ) {
1413 sendf(Client->Socket, "404 User exists\n");
1418 char *thisName = Bank_GetAcctName(Client->UID);
1419 Log_Info("Account '%s' created by '%s'", username, thisName);
1423 sendf(Client->Socket, "200 User Added\n");
1426 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1428 char *username, *flags, *reason=NULL;
1429 int mask=0, value=0;
1433 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1435 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1441 // Check authentication
1442 if( !Client->bIsAuthed ) {
1443 sendf(Client->Socket, "401 Not Authenticated\n");
1447 // Check permissions
1448 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1449 sendf(Client->Socket, "403 Not a coke admin\n");
1454 uid = Bank_GetAcctByName(username, 0);
1456 sendf(Client->Socket, "404 User '%s' not found\n", username);
1461 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1465 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1466 uid, username, mask, value);
1469 Bank_SetFlags(uid, mask, value);
1472 Log_Info("Updated '%s' with flag set '%s' by '%s' - Reason: %s",
1473 username, flags, Client->Username, reason);
1476 sendf(Client->Socket, "200 User Updated\n");
1479 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1481 char *itemname, *price_str, *description;
1485 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1486 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1490 if( !Client->bIsAuthed ) {
1491 sendf(Client->Socket, "401 Not Authenticated\n");
1495 // Check user permissions
1496 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1497 sendf(Client->Socket, "403 Not in coke\n");
1501 item = _GetItemFromString(itemname);
1503 // TODO: Create item?
1504 sendf(Client->Socket, "406 Bad Item ID\n");
1508 price = atoi(price_str);
1509 if( price <= 0 && price_str[0] != '0' ) {
1510 sendf(Client->Socket, "407 Invalid price set\n");
1513 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1517 sendf(Client->Socket, "200 Item updated\n");
1524 // --- INTERNAL HELPERS ---
1525 void Debug(tClient *Client, const char *Format, ...)
1528 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1529 printf("[%i] ", Client->ID);
1530 va_start(args, Format);
1531 vprintf(Format, args);
1536 int sendf(int Socket, const char *Format, ...)
1541 va_start(args, Format);
1542 len = vsnprintf(NULL, 0, Format, args);
1547 va_start(args, Format);
1548 vsnprintf(buf, len+1, Format, args);
1551 #if DEBUG_TRACE_CLIENT
1552 printf("sendf: %s", buf);
1555 return send(Socket, buf, len, 0);
1559 // Takes a series of char *'s in
1561 * \brief Parse space-separated entries into
1563 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1568 va_start(args, ArgStr);
1573 while( (dest = va_arg(args, char **)) )
1579 savedChar = *ArgStr;
1581 while( (dest = va_arg(args, char **)) )
1583 // Trim leading spaces
1584 while( *ArgStr == ' ' || *ArgStr == '\t' )
1587 // ... oops, not enough arguments
1588 if( *ArgStr == '\0' )
1590 // NULL unset arguments
1593 } while( (dest = va_arg(args, char **)) );
1598 if( *ArgStr == '"' )
1603 while( *ArgStr && *ArgStr != '"' )
1610 // Read until a space
1611 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1614 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1620 // Oops, extra arguments, and greedy not set
1621 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1628 *ArgStr = savedChar;
1631 return 0; // Success!
1634 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1641 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1642 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1643 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1644 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1645 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1647 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1659 while( *Str == ' ' ) Str ++; // Eat whitespace
1660 space = strchr(Str, ','); // Find the end of the flag
1666 // Check for inversion/removal
1667 if( *Str == '!' || *Str == '-' ) {
1671 else if( *Str == '+' ) {
1675 // Check flag values
1676 for( i = 0; i < ciNumFlags; i ++ )
1678 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1679 *Mask |= cFLAGS[i].Mask;
1680 *Value &= ~cFLAGS[i].Mask;
1682 *Value |= cFLAGS[i].Value;
1688 if( i == ciNumFlags ) {
1690 strncpy(val, Str, len+1);
1691 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);