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_*
24 #define DEBUG_TRACE_CLIENT 0
25 #define HACK_NO_REFUNDS 1
28 #define MAX_CONNECTION_QUEUE 5
29 #define INPUT_BUFFER_SIZE 256
30 #define CLIENT_TIMEOUT 10 // Seconds
32 #define HASH_TYPE SHA1
33 #define HASH_LENGTH 20
35 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
37 #define IDENT_TRUSTED_NETWORK 0x825F0D00
38 #define IDENT_TRUSTED_NETMASK 0xFFFFFFC0
41 typedef struct sClient
43 int Socket; // Client socket ID
46 int bIsTrusted; // Is the connection from a trusted host/port
57 void Server_Start(void);
58 void Server_Cleanup(void);
59 void Server_HandleClient(int Socket, int bTrusted);
60 void Server_ParseClientCommand(tClient *Client, char *CommandString);
62 void Server_Cmd_USER(tClient *Client, char *Args);
63 void Server_Cmd_PASS(tClient *Client, char *Args);
64 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
65 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args);
66 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
67 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
68 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
69 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
70 void Server_Cmd_REFUND(tClient *Client, char *Args);
71 void Server_Cmd_GIVE(tClient *Client, char *Args);
72 void Server_Cmd_DONATE(tClient *Client, char *Args);
73 void Server_Cmd_ADD(tClient *Client, char *Args);
74 void Server_Cmd_SET(tClient *Client, char *Args);
75 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
76 void Server_Cmd_USERINFO(tClient *Client, char *Args);
77 void _SendUserInfo(tClient *Client, int UserID);
78 void Server_Cmd_USERADD(tClient *Client, char *Args);
79 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
80 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args);
82 void Debug(tClient *Client, const char *Format, ...);
83 int sendf(int Socket, const char *Format, ...);
84 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
85 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
89 const struct sClientCommand {
91 void (*Function)(tClient *Client, char *Arguments);
92 } gaServer_Commands[] = {
93 {"USER", Server_Cmd_USER},
94 {"PASS", Server_Cmd_PASS},
95 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
96 {"AUTHIDENT", Server_Cmd_AUTHIDENT},
97 {"SETEUSER", Server_Cmd_SETEUSER},
98 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
99 {"ITEM_INFO", Server_Cmd_ITEMINFO},
100 {"DISPENSE", Server_Cmd_DISPENSE},
101 {"REFUND", Server_Cmd_REFUND},
102 {"GIVE", Server_Cmd_GIVE},
103 {"DONATE", Server_Cmd_DONATE},
104 {"ADD", Server_Cmd_ADD},
105 {"SET", Server_Cmd_SET},
106 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
107 {"USER_INFO", Server_Cmd_USERINFO},
108 {"USER_ADD", Server_Cmd_USERADD},
109 {"USER_FLAGS", Server_Cmd_USERFLAGS},
110 {"UPDATE_ITEM", Server_Cmd_UPDATEITEM}
112 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
116 int giServer_Port = 11020;
117 int gbServer_RunInBackground = 0;
118 char *gsServer_LogFile = "/var/log/dispsrv.log";
119 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
121 int giServer_Socket; // Server socket
122 int giServer_NextClientID = 1; // Debug client ID
127 * \brief Open listenting socket and serve connections
129 void Server_Start(void)
132 struct sockaddr_in server_addr, client_addr;
134 atexit(Server_Cleanup);
135 // Ignore SIGPIPE (stops crashes when the client exits early)
136 signal(SIGPIPE, SIG_IGN);
139 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
140 if( giServer_Socket < 0 ) {
141 fprintf(stderr, "ERROR: Unable to create server socket\n");
145 // Make listen address
146 memset(&server_addr, 0, sizeof(server_addr));
147 server_addr.sin_family = AF_INET; // Internet Socket
148 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
149 server_addr.sin_port = htons(giServer_Port); // Port
152 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
153 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
158 // Fork into background
159 if( gbServer_RunInBackground )
163 fprintf(stderr, "ERROR: Unable to fork\n");
164 perror("fork background");
172 // - Sort out stdin/stdout
174 dup2( open("/dev/null", O_RDONLY, 0644), STDIN_FILENO );
175 dup2( open(gsServer_LogFile, O_CREAT|O_APPEND, 0644), STDOUT_FILENO );
176 dup2( open(gsServer_ErrorLog, O_CREAT|O_APPEND, 0644), STDERR_FILENO );
178 freopen("/dev/null", "r", stdin);
179 freopen(gsServer_LogFile, "a", stdout);
180 freopen(gsServer_ErrorLog, "a", stderr);
184 // Start the helper thread
185 StartPeriodicThread();
188 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
189 fprintf(stderr, "ERROR: Unable to listen to socket\n");
194 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
198 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
200 fprintf(fp, "%i", getpid());
207 uint len = sizeof(client_addr);
210 // Accept a connection
211 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
212 if(client_socket < 0) {
213 fprintf(stderr, "ERROR: Unable to accept client connection\n");
217 // Set a timeout on the user conneciton
220 tv.tv_sec = CLIENT_TIMEOUT;
222 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
224 perror("setsockopt");
229 // Debug: Print the connection string
230 if(giDebugLevel >= 2) {
231 char ipstr[INET_ADDRSTRLEN];
232 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
233 printf("Client connection from %s:%i\n",
234 ipstr, ntohs(client_addr.sin_port));
237 // Doesn't matter what, localhost is trusted
238 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
241 // Trusted Connections
242 if( ntohs(client_addr.sin_port) < 1024 )
244 // TODO: Make this runtime configurable
245 switch( ntohl( client_addr.sin_addr.s_addr ) )
247 case 0x7F000001: // 127.0.0.1 localhost
248 // case 0x825F0D00: // 130.95.13.0
249 case 0x825F0D04: // 130.95.13.4 merlo
250 // case 0x825F0D05: // 130.95.13.5 heathred (MR)
251 case 0x825F0D07: // 130.95.13.7 motsugo
252 case 0x825F0D11: // 130.95.13.17 mermaid
253 case 0x825F0D12: // 130.95.13.18 mussel
254 case 0x825F0D17: // 130.95.13.23 martello
255 case 0x825F0D2A: // 130.95.13.42 meersau
256 // case 0x825F0D42: // 130.95.13.66 heathred (Clubroom)
264 // TODO: Multithread this?
265 Server_HandleClient(client_socket, bTrusted);
267 close(client_socket);
271 void Server_Cleanup(void)
273 printf("\nClose(%i)\n", giServer_Socket);
274 close(giServer_Socket);
275 unlink("/var/run/dispsrv.pid");
279 * \brief Reads from a client socket and parses the command strings
280 * \param Socket Client socket number/handle
281 * \param bTrusted Is the client trusted?
283 void Server_HandleClient(int Socket, int bTrusted)
285 char inbuf[INPUT_BUFFER_SIZE];
287 int remspace = INPUT_BUFFER_SIZE-1;
291 memset(&clientInfo, 0, sizeof(clientInfo));
293 // Initialise Client info
294 clientInfo.Socket = Socket;
295 clientInfo.ID = giServer_NextClientID ++;
296 clientInfo.bIsTrusted = bTrusted;
297 clientInfo.EffectiveUID = -1;
302 * - The `buf` and `remspace` variables allow a line to span several
303 * calls to recv(), if a line is not completed in one recv() call
304 * it is saved to the beginning of `inbuf` and `buf` is updated to
307 // TODO: Use select() instead (to give a timeout)
308 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
311 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
315 while( (eol = strchr(start, '\n')) )
319 Server_ParseClientCommand(&clientInfo, start);
324 // Check if there was an incomplete line
325 if( *start != '\0' ) {
326 int tailBytes = bytes - (start-buf);
327 // Roll back in buffer
328 memcpy(inbuf, start, tailBytes);
329 remspace -= tailBytes;
331 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
333 remspace = INPUT_BUFFER_SIZE - 1;
338 remspace = INPUT_BUFFER_SIZE - 1;
344 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
348 if(giDebugLevel >= 2) {
349 printf("Client %i: Disconnected\n", clientInfo.ID);
354 * \brief Parses a client command and calls the required helper function
355 * \param Client Pointer to client state structure
356 * \param CommandString Command from client (single line of the command)
357 * \return Heap String to return to the client
359 void Server_ParseClientCommand(tClient *Client, char *CommandString)
361 char *command, *args;
364 if( giDebugLevel >= 2 )
365 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
367 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
369 if( command == NULL ) return ;
370 // Is this an error? (just ignore for now)
375 for( i = 0; i < NUM_COMMANDS; i++ )
377 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
378 if( giDebugLevel >= 2 )
379 Debug(Client, "CMD %s - \"%s\"", command, args);
380 gaServer_Commands[i].Function(Client, args);
385 sendf(Client->Socket, "400 Unknown Command\n");
392 * \brief Set client username
394 * Usage: USER <username>
396 void Server_Cmd_USER(tClient *Client, char *Args)
400 if( Server_int_ParseArgs(0, Args, &username, NULL) )
402 sendf(Client->Socket, "407 USER takes 1 argument\n");
408 Debug(Client, "Authenticating as '%s'", username);
412 free(Client->Username);
413 Client->Username = strdup(username);
416 // Create a salt (that changes if the username is changed)
417 // Yes, I know, I'm a little paranoid, but who isn't?
418 Client->Salt[0] = 0x21 + (rand()&0x3F);
419 Client->Salt[1] = 0x21 + (rand()&0x3F);
420 Client->Salt[2] = 0x21 + (rand()&0x3F);
421 Client->Salt[3] = 0x21 + (rand()&0x3F);
422 Client->Salt[4] = 0x21 + (rand()&0x3F);
423 Client->Salt[5] = 0x21 + (rand()&0x3F);
424 Client->Salt[6] = 0x21 + (rand()&0x3F);
425 Client->Salt[7] = 0x21 + (rand()&0x3F);
427 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
428 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
430 sendf(Client->Socket, "100 User Set\n");
435 * \brief Authenticate as a user
439 void Server_Cmd_PASS(tClient *Client, char *Args)
444 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
446 sendf(Client->Socket, "407 PASS takes 1 argument\n");
450 // Pass on to cokebank
451 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
453 if( Client->UID == -1 ) {
454 sendf(Client->Socket, "401 Auth Failure\n");
458 flags = Bank_GetFlags(Client->UID);
459 if( flags & USER_FLAG_DISABLED ) {
461 sendf(Client->Socket, "403 Account Disabled\n");
464 if( flags & USER_FLAG_INTERNAL ) {
466 sendf(Client->Socket, "403 Internal account\n");
470 Client->bIsAuthed = 1;
471 sendf(Client->Socket, "200 Auth OK\n");
475 * \brief Authenticate as a user without a password
477 * Usage: AUTOAUTH <user>
479 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
484 if( Server_int_ParseArgs(0, Args, &username, NULL) )
486 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
491 if( !Client->bIsTrusted ) {
493 Debug(Client, "Untrusted client attempting to AUTOAUTH");
494 sendf(Client->Socket, "401 Untrusted\n");
499 Client->UID = Bank_GetAcctByName( username, 0 );
500 if( Client->UID < 0 ) {
502 Debug(Client, "Unknown user '%s'", username);
503 sendf(Client->Socket, "403 Auth Failure\n");
507 userflags = Bank_GetFlags(Client->UID);
508 // You can't be an internal account
509 if( userflags & USER_FLAG_INTERNAL ) {
511 Debug(Client, "Autoauth as '%s', not allowed", username);
513 sendf(Client->Socket, "403 Account is internal\n");
518 if( userflags & USER_FLAG_DISABLED ) {
520 sendf(Client->Socket, "403 Account disabled\n");
526 free(Client->Username);
527 Client->Username = strdup(username);
529 Client->bIsAuthed = 1;
532 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
534 sendf(Client->Socket, "200 Auth OK\n");
538 * \brief Authenticate as a user using the IDENT protocol
542 void Server_Cmd_AUTHIDENT(tClient *Client, char *Args)
546 const int ident_timeout = 5;
548 struct sockaddr_in client_addr;
551 if( Args != NULL && strlen(Args) ) {
552 sendf(Client->Socket, "407 AUTHIDENT takes no arguments\n");
556 // Check if trusted (only works with INET sockets at present)
557 len = sizeof(client_addr);
558 if( getpeername(Client->Socket, (struct sockaddr*)&client_addr, &len) == -1 ) {
559 Debug(Client, "500 getpeername() failed\n");
560 perror("Getting AUTHIDENT peer name");
561 sendf(Client->Socket, "500 getpeername() failed\n");
565 client_ip = client_addr.sin_addr.s_addr;
566 if(giDebugLevel >= 2) {
567 Debug(Client, "client_ip = %x, ntohl(client_ip) = %x", client_ip, ntohl(client_ip));
569 if( ntohl(client_ip) != 0x7F000001 && (ntohl(client_ip) & IDENT_TRUSTED_NETMASK) != IDENT_TRUSTED_NETWORK ) {
571 Debug(Client, "Untrusted client attempting to AUTHIDENT");
572 sendf(Client->Socket, "401 Untrusted\n");
576 // Get username via IDENT
577 username = ident_id(Client->Socket, ident_timeout);
579 sendf(Client->Socket, "403 Authentication failure: IDENT auth timed out\n");
584 Client->UID = Bank_GetAcctByName( username, 0 );
585 if( Client->UID < 0 ) {
587 Debug(Client, "Unknown user '%s'", username);
588 sendf(Client->Socket, "403 Authentication failure: unknown account\n");
593 userflags = Bank_GetFlags(Client->UID);
594 // You can't be an internal account
595 if( userflags & USER_FLAG_INTERNAL ) {
597 Debug(Client, "IDENT auth as '%s', not allowed", username);
599 sendf(Client->Socket, "403 Authentication failure: that account is internal\n");
605 if( userflags & USER_FLAG_DISABLED ) {
607 sendf(Client->Socket, "403 Authentication failure: account disabled\n");
614 free(Client->Username);
615 Client->Username = strdup(username);
617 Client->bIsAuthed = 1;
620 Debug(Client, "IDENT authenticated as '%s' (%i)", username, Client->UID);
623 sendf(Client->Socket, "200 Auth OK\n");
627 * \brief Set effective user
629 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
632 int eUserFlags, userFlags;
634 if( Server_int_ParseArgs(0, Args, &username, NULL) )
636 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
640 if( !strlen(Args) ) {
641 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
645 // Check authentication
646 if( !Client->bIsAuthed ) {
647 sendf(Client->Socket, "401 Not Authenticated\n");
651 // Check user permissions
652 userFlags = Bank_GetFlags(Client->UID);
653 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
654 sendf(Client->Socket, "403 Not in coke\n");
659 Client->EffectiveUID = Bank_GetAcctByName(username, 0);
660 if( Client->EffectiveUID == -1 ) {
661 sendf(Client->Socket, "404 User not found\n");
665 // You can't be an internal account
666 if( !(userFlags & USER_FLAG_ADMIN) )
668 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
669 if( eUserFlags & USER_FLAG_INTERNAL ) {
670 Client->EffectiveUID = -1;
671 sendf(Client->Socket, "404 User not found\n");
674 // Disabled only avaliable to admins
675 if( eUserFlags & USER_FLAG_DISABLED ) {
676 Client->EffectiveUID = -1;
677 sendf(Client->Socket, "403 Account disabled\n");
682 sendf(Client->Socket, "200 User set\n");
686 * \brief Send an item status to the client
687 * \param Client Who to?
688 * \param Item Item to send
690 void Server_int_SendItem(tClient *Client, tItem *Item)
692 char *status = "avail";
694 if( Item->Handler->CanDispense )
696 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
698 case 0: status = "avail"; break;
699 case 1: status = "sold"; break;
701 case -1: status = "error"; break;
705 // KNOWN HACK: Naming a slot 'dead' disables it
706 if( strcmp(Item->Name, "dead") == 0 )
707 status = "sold"; // Another status?
709 sendf(Client->Socket,
710 "202 Item %s:%i %s %i %s\n",
711 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
716 * \brief Enumerate the items that the server knows about
718 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
722 if( Args != NULL && strlen(Args) ) {
723 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
729 for( i = 0; i < giNumItems; i ++ ) {
730 if( gaItems[i].bHidden ) continue;
734 sendf(Client->Socket, "201 Items %i\n", count);
736 for( i = 0; i < giNumItems; i ++ ) {
737 if( gaItems[i].bHidden ) continue;
738 Server_int_SendItem( Client, &gaItems[i] );
741 sendf(Client->Socket, "200 List end\n");
744 tItem *_GetItemFromString(char *String)
748 char *colon = strchr(String, ':');
760 for( i = 0; i < giNumHandlers; i ++ )
762 if( strcmp(gaHandlers[i]->Name, type) == 0) {
763 handler = gaHandlers[i];
772 for( i = 0; i < giNumItems; i ++ )
774 if( gaItems[i].Handler != handler ) continue;
775 if( gaItems[i].ID != num ) continue;
782 * \brief Fetch information on a specific item
784 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
789 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
790 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
793 item = _GetItemFromString(Args);
796 sendf(Client->Socket, "406 Bad Item ID\n");
800 Server_int_SendItem( Client, item );
803 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
810 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
811 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
815 if( !Client->bIsAuthed ) {
816 sendf(Client->Socket, "401 Not Authenticated\n");
820 item = _GetItemFromString(itemname);
822 sendf(Client->Socket, "406 Bad Item ID\n");
826 if( Client->EffectiveUID != -1 ) {
827 uid = Client->EffectiveUID;
833 switch( ret = DispenseItem( Client->UID, uid, item ) )
835 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
836 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
837 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
839 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
844 void Server_Cmd_REFUND(tClient *Client, char *Args)
847 int uid, price_override = 0;
848 char *username, *itemname, *price_str;
850 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
851 if( !itemname || price_str ) {
852 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
857 if( !Client->bIsAuthed ) {
858 sendf(Client->Socket, "401 Not Authenticated\n");
862 // Check user permissions
863 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
864 sendf(Client->Socket, "403 Not in coke\n");
868 uid = Bank_GetAcctByName(username, 0);
870 sendf(Client->Socket, "404 Unknown user\n");
874 item = _GetItemFromString(itemname);
876 sendf(Client->Socket, "406 Bad Item ID\n");
881 price_override = atoi(price_str);
883 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
885 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
887 sendf(Client->Socket, "500 Dispense Error\n");
892 void Server_Cmd_GIVE(tClient *Client, char *Args)
894 char *recipient, *ammount, *reason;
899 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
900 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
905 if( !Client->bIsAuthed ) {
906 sendf(Client->Socket, "401 Not Authenticated\n");
911 uid = Bank_GetAcctByName(recipient, 0);
913 sendf(Client->Socket, "404 Invalid target user\n");
917 // You can't alter an internal account
918 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
919 // sendf(Client->Socket, "404 Invalid target user\n");
924 iAmmount = atoi(ammount);
925 if( iAmmount <= 0 ) {
926 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
930 if( Client->EffectiveUID != -1 ) {
931 thisUid = Client->EffectiveUID;
934 thisUid = Client->UID;
938 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
941 sendf(Client->Socket, "200 Give OK\n");
944 sendf(Client->Socket, "402 Poor You\n");
947 sendf(Client->Socket, "500 Unknown error\n");
952 void Server_Cmd_DONATE(tClient *Client, char *Args)
954 char *ammount, *reason;
959 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
960 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
964 if( !Client->bIsAuthed ) {
965 sendf(Client->Socket, "401 Not Authenticated\n");
970 iAmmount = atoi(ammount);
971 if( iAmmount <= 0 ) {
972 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
976 // Handle effective users
977 if( Client->EffectiveUID != -1 ) {
978 thisUid = Client->EffectiveUID;
981 thisUid = Client->UID;
985 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
988 sendf(Client->Socket, "200 Give OK\n");
991 sendf(Client->Socket, "402 Poor You\n");
994 sendf(Client->Socket, "500 Unknown error\n");
999 void Server_Cmd_ADD(tClient *Client, char *Args)
1001 char *user, *ammount, *reason;
1005 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1006 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
1010 if( !Client->bIsAuthed ) {
1011 sendf(Client->Socket, "401 Not Authenticated\n");
1015 // Check user permissions
1016 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1017 sendf(Client->Socket, "403 Not in coke\n");
1022 if( strcmp( Client->Username, "root" ) == 0 ) {
1023 // Allow adding for new users
1024 if( strcmp(reason, "treasurer: new user") != 0 ) {
1025 sendf(Client->Socket, "403 Root may not add\n");
1032 if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
1034 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
1040 uid = Bank_GetAcctByName(user, 0);
1042 sendf(Client->Socket, "404 Invalid user\n");
1046 // You can't alter an internal account
1047 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
1049 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
1050 sendf(Client->Socket, "404 Invalid user\n");
1053 // TODO: Maybe disallow changes to disabled?
1057 iAmmount = atoi(ammount);
1058 if( iAmmount == 0 && ammount[0] != '0' ) {
1059 sendf(Client->Socket, "407 Invalid Argument\n");
1064 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
1067 sendf(Client->Socket, "200 Add OK\n");
1070 sendf(Client->Socket, "402 Poor Guy\n");
1073 sendf(Client->Socket, "500 Unknown error\n");
1078 void Server_Cmd_SET(tClient *Client, char *Args)
1080 char *user, *ammount, *reason;
1084 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
1085 sendf(Client->Socket, "407 SET takes 3 arguments\n");
1089 if( !Client->bIsAuthed ) {
1090 sendf(Client->Socket, "401 Not Authenticated\n");
1094 // Check user permissions
1095 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1096 sendf(Client->Socket, "403 Not an admin\n");
1101 uid = Bank_GetAcctByName(user, 0);
1103 sendf(Client->Socket, "404 Invalid user\n");
1108 iAmmount = atoi(ammount);
1109 if( iAmmount == 0 && ammount[0] != '0' ) {
1110 sendf(Client->Socket, "407 Invalid Argument\n");
1115 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
1118 sendf(Client->Socket, "200 Add OK\n");
1121 sendf(Client->Socket, "402 Poor Guy\n");
1124 sendf(Client->Socket, "500 Unknown error\n");
1129 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1133 int maxBal = INT_MAX, minBal = INT_MIN;
1134 int flagMask = 0, flagVal = 0;
1135 int sort = BANK_ITFLAG_SORT_NAME;
1136 time_t lastSeenAfter=0, lastSeenBefore=0;
1138 int flags; // Iterator flags
1139 int balValue; // Balance value for iterator
1140 time_t timeValue; // Time value for iterator
1143 if( Args && strlen(Args) )
1145 char *space = Args, *type, *val;
1149 while(*type == ' ') type ++;
1151 space = strchr(space, ' ');
1152 if(space) *space = '\0';
1155 val = strchr(type, ':');
1162 if( strcmp(type, "min_balance") == 0 ) {
1165 // - Maximum Balance
1166 else if( strcmp(type, "max_balance") == 0 ) {
1170 else if( strcmp(type, "flags") == 0 ) {
1171 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1174 // - Last seen before timestamp
1175 else if( strcmp(type, "last_seen_before") == 0 ) {
1176 lastSeenAfter = atoll(val);
1178 // - Last seen after timestamp
1179 else if( strcmp(type, "last_seen_after") == 0 ) {
1180 lastSeenAfter = atoll(val);
1183 else if( strcmp(type, "sort") == 0 ) {
1184 char *dash = strchr(val, '-');
1189 if( strcmp(val, "name") == 0 ) {
1190 sort = BANK_ITFLAG_SORT_NAME;
1192 else if( strcmp(val, "balance") == 0 ) {
1193 sort = BANK_ITFLAG_SORT_BAL;
1195 else if( strcmp(val, "lastseen") == 0 ) {
1196 sort = BANK_ITFLAG_SORT_LASTSEEN;
1199 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1202 // Handle sort direction
1204 if( strcmp(dash, "desc") == 0 ) {
1205 sort |= BANK_ITFLAG_REVSORT;
1208 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1215 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1222 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1228 *space = ' '; // Repair (to be nice)
1230 while(*space == ' ') space ++;
1236 if( maxBal != INT_MAX ) {
1237 flags = sort|BANK_ITFLAG_MAXBALANCE;
1240 else if( minBal != INT_MIN ) {
1241 flags = sort|BANK_ITFLAG_MINBALANCE;
1248 if( lastSeenBefore ) {
1249 timeValue = lastSeenBefore;
1250 flags |= BANK_ITFLAG_SEENBEFORE;
1252 else if( lastSeenAfter ) {
1253 timeValue = lastSeenAfter;
1254 flags |= BANK_ITFLAG_SEENAFTER;
1259 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1261 // Get return number
1262 while( (i = Bank_IteratorNext(it)) != -1 )
1264 int bal = Bank_GetBalance(i);
1266 if( bal == INT_MIN ) continue;
1268 if( bal < minBal ) continue;
1269 if( bal > maxBal ) continue;
1274 Bank_DelIterator(it);
1277 sendf(Client->Socket, "201 Users %i\n", numRet);
1281 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1283 while( (i = Bank_IteratorNext(it)) != -1 )
1285 int bal = Bank_GetBalance(i);
1287 if( bal == INT_MIN ) continue;
1289 if( bal < minBal ) continue;
1290 if( bal > maxBal ) continue;
1292 _SendUserInfo(Client, i);
1295 Bank_DelIterator(it);
1297 sendf(Client->Socket, "200 List End\n");
1300 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1306 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1307 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1311 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1314 uid = Bank_GetAcctByName(user, 0);
1316 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1318 sendf(Client->Socket, "404 Invalid user\n");
1322 _SendUserInfo(Client, uid);
1325 void _SendUserInfo(tClient *Client, int UserID)
1327 char *type, *disabled="", *door="";
1328 int flags = Bank_GetFlags(UserID);
1330 if( flags & USER_FLAG_INTERNAL ) {
1333 else if( flags & USER_FLAG_COKE ) {
1334 if( flags & USER_FLAG_ADMIN )
1335 type = "coke,admin";
1339 else if( flags & USER_FLAG_ADMIN ) {
1346 if( flags & USER_FLAG_DISABLED )
1347 disabled = ",disabled";
1348 if( flags & USER_FLAG_DOORGROUP )
1351 // TODO: User flags/type
1353 Client->Socket, "202 User %s %i %s%s%s\n",
1354 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1355 type, disabled, door
1359 void Server_Cmd_USERADD(tClient *Client, char *Args)
1364 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1365 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1369 // Check authentication
1370 if( !Client->bIsAuthed ) {
1371 sendf(Client->Socket, "401 Not Authenticated\n");
1375 // Check permissions
1376 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1377 sendf(Client->Socket, "403 Not a coke admin\n");
1381 // Try to create user
1382 if( Bank_CreateAcct(username) == -1 ) {
1383 sendf(Client->Socket, "404 User exists\n");
1388 char *thisName = Bank_GetAcctName(Client->UID);
1389 Log_Info("Account '%s' created by '%s'", username, thisName);
1393 sendf(Client->Socket, "200 User Added\n");
1396 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1398 char *username, *flags, *reason=NULL;
1399 int mask=0, value=0;
1403 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1405 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1411 // Check authentication
1412 if( !Client->bIsAuthed ) {
1413 sendf(Client->Socket, "401 Not Authenticated\n");
1417 // Check permissions
1418 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1419 sendf(Client->Socket, "403 Not a coke admin\n");
1424 uid = Bank_GetAcctByName(username, 0);
1426 sendf(Client->Socket, "404 User '%s' not found\n", username);
1431 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1435 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1436 uid, username, mask, value);
1439 Bank_SetFlags(uid, mask, value);
1442 Log_Info("Updated '%s' with flag set '%s' by '%s' - Reason: %s",
1443 username, flags, Client->Username, reason);
1446 sendf(Client->Socket, "200 User Updated\n");
1449 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1451 char *itemname, *price_str, *description;
1455 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1456 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1460 if( !Client->bIsAuthed ) {
1461 sendf(Client->Socket, "401 Not Authenticated\n");
1465 // Check user permissions
1466 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1467 sendf(Client->Socket, "403 Not in coke\n");
1471 item = _GetItemFromString(itemname);
1473 // TODO: Create item?
1474 sendf(Client->Socket, "406 Bad Item ID\n");
1478 price = atoi(price_str);
1479 if( price <= 0 && price_str[0] != '0' ) {
1480 sendf(Client->Socket, "407 Invalid price set\n");
1483 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1487 sendf(Client->Socket, "200 Item updated\n");
1494 // --- INTERNAL HELPERS ---
1495 void Debug(tClient *Client, const char *Format, ...)
1498 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1499 printf("[%i] ", Client->ID);
1500 va_start(args, Format);
1501 vprintf(Format, args);
1506 int sendf(int Socket, const char *Format, ...)
1511 va_start(args, Format);
1512 len = vsnprintf(NULL, 0, Format, args);
1517 va_start(args, Format);
1518 vsnprintf(buf, len+1, Format, args);
1521 #if DEBUG_TRACE_CLIENT
1522 printf("sendf: %s", buf);
1525 return send(Socket, buf, len, 0);
1529 // Takes a series of char *'s in
1531 * \brief Parse space-separated entries into
1533 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1538 va_start(args, ArgStr);
1543 while( (dest = va_arg(args, char **)) )
1549 savedChar = *ArgStr;
1551 while( (dest = va_arg(args, char **)) )
1553 // Trim leading spaces
1554 while( *ArgStr == ' ' || *ArgStr == '\t' )
1557 // ... oops, not enough arguments
1558 if( *ArgStr == '\0' )
1560 // NULL unset arguments
1563 } while( (dest = va_arg(args, char **)) );
1568 if( *ArgStr == '"' )
1573 while( *ArgStr && *ArgStr != '"' )
1580 // Read until a space
1581 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1584 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1590 // Oops, extra arguments, and greedy not set
1591 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1598 *ArgStr = savedChar;
1601 return 0; // Success!
1604 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1611 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1612 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1613 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1614 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1615 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1617 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1629 while( *Str == ' ' ) Str ++; // Eat whitespace
1630 space = strchr(Str, ','); // Find the end of the flag
1636 // Check for inversion/removal
1637 if( *Str == '!' || *Str == '-' ) {
1641 else if( *Str == '+' ) {
1645 // Check flag values
1646 for( i = 0; i < ciNumFlags; i ++ )
1648 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1649 *Mask |= cFLAGS[i].Mask;
1650 *Value &= ~cFLAGS[i].Mask;
1652 *Value |= cFLAGS[i].Value;
1658 if( i == ciNumFlags ) {
1660 strncpy(val, Str, len+1);
1661 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);