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_*
23 #define DEBUG_TRACE_CLIENT 0
24 #define HACK_NO_REFUNDS 1
27 #define MAX_CONNECTION_QUEUE 5
28 #define INPUT_BUFFER_SIZE 256
29 #define CLIENT_TIMEOUT 10 // Seconds
31 #define HASH_TYPE SHA1
32 #define HASH_LENGTH 20
34 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
37 typedef struct sClient
39 int Socket; // Client socket ID
42 int bIsTrusted; // Is the connection from a trusted host/port
53 void Server_Start(void);
54 void Server_Cleanup(void);
55 void Server_HandleClient(int Socket, int bTrusted);
56 void Server_ParseClientCommand(tClient *Client, char *CommandString);
58 void Server_Cmd_USER(tClient *Client, char *Args);
59 void Server_Cmd_PASS(tClient *Client, char *Args);
60 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
61 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
62 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
63 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
64 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
65 void Server_Cmd_REFUND(tClient *Client, char *Args);
66 void Server_Cmd_GIVE(tClient *Client, char *Args);
67 void Server_Cmd_DONATE(tClient *Client, char *Args);
68 void Server_Cmd_ADD(tClient *Client, char *Args);
69 void Server_Cmd_SET(tClient *Client, char *Args);
70 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
71 void Server_Cmd_USERINFO(tClient *Client, char *Args);
72 void _SendUserInfo(tClient *Client, int UserID);
73 void Server_Cmd_USERADD(tClient *Client, char *Args);
74 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
75 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args);
77 void Debug(tClient *Client, const char *Format, ...);
78 int sendf(int Socket, const char *Format, ...);
79 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
80 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
84 const struct sClientCommand {
86 void (*Function)(tClient *Client, char *Arguments);
87 } gaServer_Commands[] = {
88 {"USER", Server_Cmd_USER},
89 {"PASS", Server_Cmd_PASS},
90 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
91 {"SETEUSER", Server_Cmd_SETEUSER},
92 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
93 {"ITEM_INFO", Server_Cmd_ITEMINFO},
94 {"DISPENSE", Server_Cmd_DISPENSE},
95 {"REFUND", Server_Cmd_REFUND},
96 {"GIVE", Server_Cmd_GIVE},
97 {"DONATE", Server_Cmd_DONATE},
98 {"ADD", Server_Cmd_ADD},
99 {"SET", Server_Cmd_SET},
100 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
101 {"USER_INFO", Server_Cmd_USERINFO},
102 {"USER_ADD", Server_Cmd_USERADD},
103 {"USER_FLAGS", Server_Cmd_USERFLAGS},
104 {"UPDATE_ITEM", Server_Cmd_UPDATEITEM}
106 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
110 int giServer_Port = 11020;
111 int gbServer_RunInBackground = 0;
112 char *gsServer_LogFile = "/var/log/dispsrv.log";
113 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
115 int giServer_Socket; // Server socket
116 int giServer_NextClientID = 1; // Debug client ID
121 * \brief Open listenting socket and serve connections
123 void Server_Start(void)
126 struct sockaddr_in server_addr, client_addr;
128 atexit(Server_Cleanup);
129 // Ignore SIGPIPE (stops crashes when the client exits early)
130 signal(SIGPIPE, SIG_IGN);
133 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
134 if( giServer_Socket < 0 ) {
135 fprintf(stderr, "ERROR: Unable to create server socket\n");
139 // Make listen address
140 memset(&server_addr, 0, sizeof(server_addr));
141 server_addr.sin_family = AF_INET; // Internet Socket
142 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
143 server_addr.sin_port = htons(giServer_Port); // Port
146 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
147 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
152 // Fork into background
153 if( gbServer_RunInBackground )
155 int newin, newout, newerr;
158 fprintf(stderr, "ERROR: Unable to fork\n");
159 perror("fork background");
167 // - Sort out stdin/stdout
168 newin = open("/dev/null", O_RDONLY);
169 newout = open(gsServer_LogFile, O_CREAT|O_APPEND, 0644);
170 newerr = open(gsServer_ErrorLog, O_CREAT|O_APPEND, 0644);
176 // Start the helper thread
177 StartPeriodicThread();
180 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
181 fprintf(stderr, "ERROR: Unable to listen to socket\n");
186 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
190 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
192 fprintf(fp, "%i", getpid());
199 uint len = sizeof(client_addr);
202 // Accept a connection
203 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
204 if(client_socket < 0) {
205 fprintf(stderr, "ERROR: Unable to accept client connection\n");
209 // Set a timeout on the user conneciton
212 tv.tv_sec = CLIENT_TIMEOUT;
214 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
216 perror("setsockopt");
221 // Debug: Print the connection string
222 if(giDebugLevel >= 2) {
223 char ipstr[INET_ADDRSTRLEN];
224 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
225 printf("Client connection from %s:%i\n",
226 ipstr, ntohs(client_addr.sin_port));
229 // Doesn't matter what, localhost is trusted
230 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
233 // Trusted Connections
234 if( ntohs(client_addr.sin_port) < 1024 )
236 // TODO: Make this runtime configurable
237 switch( ntohl( client_addr.sin_addr.s_addr ) )
239 case 0x7F000001: // 127.0.0.1 localhost
240 // case 0x825F0D00: // 130.95.13.0
241 case 0x825F0D04: // 130.95.13.4 merlo
242 case 0x825F0D05: // 130.95.13.5 heathred (MR)
243 case 0x825F0D07: // 130.95.13.7 motsugo
244 case 0x825F0D11: // 130.95.13.17 mermaid
245 case 0x825F0D12: // 130.95.13.18 mussel
246 case 0x825F0D17: // 130.95.13.23 martello
247 case 0x825F0D2A: // 130.95.13.42 meersau
248 case 0x825F0D42: // 130.95.13.66 heathred (Clubroom)
256 // TODO: Multithread this?
257 Server_HandleClient(client_socket, bTrusted);
259 close(client_socket);
263 void Server_Cleanup(void)
265 printf("\nClose(%i)\n", giServer_Socket);
266 close(giServer_Socket);
267 unlink("/var/run/dispsrv.pid");
271 * \brief Reads from a client socket and parses the command strings
272 * \param Socket Client socket number/handle
273 * \param bTrusted Is the client trusted?
275 void Server_HandleClient(int Socket, int bTrusted)
277 char inbuf[INPUT_BUFFER_SIZE];
279 int remspace = INPUT_BUFFER_SIZE-1;
283 memset(&clientInfo, 0, sizeof(clientInfo));
285 // Initialise Client info
286 clientInfo.Socket = Socket;
287 clientInfo.ID = giServer_NextClientID ++;
288 clientInfo.bIsTrusted = bTrusted;
289 clientInfo.EffectiveUID = -1;
294 * - The `buf` and `remspace` variables allow a line to span several
295 * calls to recv(), if a line is not completed in one recv() call
296 * it is saved to the beginning of `inbuf` and `buf` is updated to
299 // TODO: Use select() instead (to give a timeout)
300 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
303 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
307 while( (eol = strchr(start, '\n')) )
311 Server_ParseClientCommand(&clientInfo, start);
316 // Check if there was an incomplete line
317 if( *start != '\0' ) {
318 int tailBytes = bytes - (start-buf);
319 // Roll back in buffer
320 memcpy(inbuf, start, tailBytes);
321 remspace -= tailBytes;
323 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
325 remspace = INPUT_BUFFER_SIZE - 1;
330 remspace = INPUT_BUFFER_SIZE - 1;
336 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
340 if(giDebugLevel >= 2) {
341 printf("Client %i: Disconnected\n", clientInfo.ID);
346 * \brief Parses a client command and calls the required helper function
347 * \param Client Pointer to client state structure
348 * \param CommandString Command from client (single line of the command)
349 * \return Heap String to return to the client
351 void Server_ParseClientCommand(tClient *Client, char *CommandString)
353 char *command, *args;
356 if( giDebugLevel >= 2 )
357 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
359 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
361 if( command == NULL ) return ;
362 // Is this an error? (just ignore for now)
367 for( i = 0; i < NUM_COMMANDS; i++ )
369 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
370 if( giDebugLevel >= 2 )
371 Debug(Client, "CMD %s - \"%s\"", command, args);
372 gaServer_Commands[i].Function(Client, args);
377 sendf(Client->Socket, "400 Unknown Command\n");
384 * \brief Set client username
386 * Usage: USER <username>
388 void Server_Cmd_USER(tClient *Client, char *Args)
392 if( Server_int_ParseArgs(0, Args, &username, NULL) )
394 sendf(Client->Socket, "407 USER takes 1 argument\n");
400 Debug(Client, "Authenticating as '%s'", username);
404 free(Client->Username);
405 Client->Username = strdup(username);
408 // Create a salt (that changes if the username is changed)
409 // Yes, I know, I'm a little paranoid, but who isn't?
410 Client->Salt[0] = 0x21 + (rand()&0x3F);
411 Client->Salt[1] = 0x21 + (rand()&0x3F);
412 Client->Salt[2] = 0x21 + (rand()&0x3F);
413 Client->Salt[3] = 0x21 + (rand()&0x3F);
414 Client->Salt[4] = 0x21 + (rand()&0x3F);
415 Client->Salt[5] = 0x21 + (rand()&0x3F);
416 Client->Salt[6] = 0x21 + (rand()&0x3F);
417 Client->Salt[7] = 0x21 + (rand()&0x3F);
419 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
420 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
422 sendf(Client->Socket, "100 User Set\n");
427 * \brief Authenticate as a user
431 void Server_Cmd_PASS(tClient *Client, char *Args)
436 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
438 sendf(Client->Socket, "407 PASS takes 1 argument\n");
442 // Pass on to cokebank
443 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
445 if( Client->UID == -1 ) {
446 sendf(Client->Socket, "401 Auth Failure\n");
450 flags = Bank_GetFlags(Client->UID);
451 if( flags & USER_FLAG_DISABLED ) {
453 sendf(Client->Socket, "403 Account Disabled\n");
456 if( flags & USER_FLAG_INTERNAL ) {
458 sendf(Client->Socket, "403 Internal account\n");
462 Client->bIsAuthed = 1;
463 sendf(Client->Socket, "200 Auth OK\n");
467 * \brief Authenticate as a user without a password
469 * Usage: AUTOAUTH <user>
471 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
476 if( Server_int_ParseArgs(0, Args, &username, NULL) )
478 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
483 if( !Client->bIsTrusted ) {
485 Debug(Client, "Untrusted client attempting to AUTOAUTH");
486 sendf(Client->Socket, "401 Untrusted\n");
491 Client->UID = Bank_GetAcctByName( username, 0 );
492 if( Client->UID < 0 ) {
494 Debug(Client, "Unknown user '%s'", username);
495 sendf(Client->Socket, "403 Auth Failure\n");
499 userflags = Bank_GetFlags(Client->UID);
500 // You can't be an internal account
501 if( userflags & USER_FLAG_INTERNAL ) {
503 Debug(Client, "Autoauth as '%s', not allowed", username);
505 sendf(Client->Socket, "403 Account is internal\n");
510 if( userflags & USER_FLAG_DISABLED ) {
512 sendf(Client->Socket, "403 Account disabled\n");
516 Client->bIsAuthed = 1;
519 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
521 sendf(Client->Socket, "200 Auth OK\n");
525 * \brief Set effective user
527 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
530 int eUserFlags, userFlags;
532 if( Server_int_ParseArgs(0, Args, &username, NULL) )
534 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
538 if( !strlen(Args) ) {
539 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
543 // Check authentication
544 if( !Client->bIsAuthed ) {
545 sendf(Client->Socket, "401 Not Authenticated\n");
549 // Check user permissions
550 userFlags = Bank_GetFlags(Client->UID);
551 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
552 sendf(Client->Socket, "403 Not in coke\n");
557 Client->EffectiveUID = Bank_GetAcctByName(username, 0);
558 if( Client->EffectiveUID == -1 ) {
559 sendf(Client->Socket, "404 User not found\n");
563 // You can't be an internal account
564 if( !(userFlags & USER_FLAG_ADMIN) )
566 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
567 if( eUserFlags & USER_FLAG_INTERNAL ) {
568 Client->EffectiveUID = -1;
569 sendf(Client->Socket, "404 User not found\n");
572 // Disabled only avaliable to admins
573 if( eUserFlags & USER_FLAG_DISABLED ) {
574 Client->EffectiveUID = -1;
575 sendf(Client->Socket, "403 Account disabled\n");
580 sendf(Client->Socket, "200 User set\n");
584 * \brief Send an item status to the client
585 * \param Client Who to?
586 * \param Item Item to send
588 void Server_int_SendItem(tClient *Client, tItem *Item)
590 char *status = "avail";
592 if( Item->Handler->CanDispense )
594 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
596 case 0: status = "avail"; break;
597 case 1: status = "sold"; break;
599 case -1: status = "error"; break;
603 // KNOWN HACK: Naming a slot 'dead' disables it
604 if( strcmp(Item->Name, "dead") == 0 )
605 status = "sold"; // Another status?
607 sendf(Client->Socket,
608 "202 Item %s:%i %s %i %s\n",
609 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
614 * \brief Enumerate the items that the server knows about
616 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
620 if( Args != NULL && strlen(Args) ) {
621 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
627 for( i = 0; i < giNumItems; i ++ ) {
628 if( gaItems[i].bHidden ) continue;
632 sendf(Client->Socket, "201 Items %i\n", count);
634 for( i = 0; i < giNumItems; i ++ ) {
635 if( gaItems[i].bHidden ) continue;
636 Server_int_SendItem( Client, &gaItems[i] );
639 sendf(Client->Socket, "200 List end\n");
642 tItem *_GetItemFromString(char *String)
646 char *colon = strchr(String, ':');
658 for( i = 0; i < giNumHandlers; i ++ )
660 if( strcmp(gaHandlers[i]->Name, type) == 0) {
661 handler = gaHandlers[i];
670 for( i = 0; i < giNumItems; i ++ )
672 if( gaItems[i].Handler != handler ) continue;
673 if( gaItems[i].ID != num ) continue;
680 * \brief Fetch information on a specific item
682 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
687 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
688 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
691 item = _GetItemFromString(Args);
694 sendf(Client->Socket, "406 Bad Item ID\n");
698 Server_int_SendItem( Client, item );
701 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
708 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
709 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
713 if( !Client->bIsAuthed ) {
714 sendf(Client->Socket, "401 Not Authenticated\n");
718 item = _GetItemFromString(itemname);
720 sendf(Client->Socket, "406 Bad Item ID\n");
724 if( Client->EffectiveUID != -1 ) {
725 uid = Client->EffectiveUID;
731 switch( ret = DispenseItem( Client->UID, uid, item ) )
733 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
734 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
735 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
737 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
742 void Server_Cmd_REFUND(tClient *Client, char *Args)
745 int uid, price_override = 0;
746 char *username, *itemname, *price_str;
748 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
749 if( !itemname || price_str ) {
750 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
755 if( !Client->bIsAuthed ) {
756 sendf(Client->Socket, "401 Not Authenticated\n");
760 // Check user permissions
761 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
762 sendf(Client->Socket, "403 Not in coke\n");
766 uid = Bank_GetAcctByName(username, 0);
768 sendf(Client->Socket, "404 Unknown user\n");
772 item = _GetItemFromString(itemname);
774 sendf(Client->Socket, "406 Bad Item ID\n");
779 price_override = atoi(price_str);
781 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
783 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
785 sendf(Client->Socket, "500 Dispense Error\n");
790 void Server_Cmd_GIVE(tClient *Client, char *Args)
792 char *recipient, *ammount, *reason;
797 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
798 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
803 if( !Client->bIsAuthed ) {
804 sendf(Client->Socket, "401 Not Authenticated\n");
809 uid = Bank_GetAcctByName(recipient, 0);
811 sendf(Client->Socket, "404 Invalid target user\n");
815 // You can't alter an internal account
816 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
817 // sendf(Client->Socket, "404 Invalid target user\n");
822 iAmmount = atoi(ammount);
823 if( iAmmount <= 0 ) {
824 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
828 if( Client->EffectiveUID != -1 ) {
829 thisUid = Client->EffectiveUID;
832 thisUid = Client->UID;
836 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
839 sendf(Client->Socket, "200 Give OK\n");
842 sendf(Client->Socket, "402 Poor You\n");
845 sendf(Client->Socket, "500 Unknown error\n");
850 void Server_Cmd_DONATE(tClient *Client, char *Args)
852 char *ammount, *reason;
857 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
858 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
862 if( !Client->bIsAuthed ) {
863 sendf(Client->Socket, "401 Not Authenticated\n");
868 iAmmount = atoi(ammount);
869 if( iAmmount <= 0 ) {
870 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
874 // Handle effective users
875 if( Client->EffectiveUID != -1 ) {
876 thisUid = Client->EffectiveUID;
879 thisUid = Client->UID;
883 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
886 sendf(Client->Socket, "200 Give OK\n");
889 sendf(Client->Socket, "402 Poor You\n");
892 sendf(Client->Socket, "500 Unknown error\n");
897 void Server_Cmd_ADD(tClient *Client, char *Args)
899 char *user, *ammount, *reason;
903 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
904 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
908 if( !Client->bIsAuthed ) {
909 sendf(Client->Socket, "401 Not Authenticated\n");
913 // Check user permissions
914 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
915 sendf(Client->Socket, "403 Not in coke\n");
920 if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
922 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
928 uid = Bank_GetAcctByName(user, 0);
930 sendf(Client->Socket, "404 Invalid user\n");
934 // You can't alter an internal account
935 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
937 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
938 sendf(Client->Socket, "404 Invalid user\n");
941 // TODO: Maybe disallow changes to disabled?
945 iAmmount = atoi(ammount);
946 if( iAmmount == 0 && ammount[0] != '0' ) {
947 sendf(Client->Socket, "407 Invalid Argument\n");
952 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
955 sendf(Client->Socket, "200 Add OK\n");
958 sendf(Client->Socket, "402 Poor Guy\n");
961 sendf(Client->Socket, "500 Unknown error\n");
966 void Server_Cmd_SET(tClient *Client, char *Args)
968 char *user, *ammount, *reason;
972 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
973 sendf(Client->Socket, "407 SET takes 3 arguments\n");
977 if( !Client->bIsAuthed ) {
978 sendf(Client->Socket, "401 Not Authenticated\n");
982 // Check user permissions
983 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
984 sendf(Client->Socket, "403 Not an admin\n");
989 uid = Bank_GetAcctByName(user, 0);
991 sendf(Client->Socket, "404 Invalid user\n");
996 iAmmount = atoi(ammount);
997 if( iAmmount == 0 && ammount[0] != '0' ) {
998 sendf(Client->Socket, "407 Invalid Argument\n");
1003 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
1006 sendf(Client->Socket, "200 Add OK\n");
1009 sendf(Client->Socket, "402 Poor Guy\n");
1012 sendf(Client->Socket, "500 Unknown error\n");
1017 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1021 int maxBal = INT_MAX, minBal = INT_MIN;
1022 int flagMask = 0, flagVal = 0;
1023 int sort = BANK_ITFLAG_SORT_NAME;
1024 time_t lastSeenAfter=0, lastSeenBefore=0;
1026 int flags; // Iterator flags
1027 int balValue; // Balance value for iterator
1028 time_t timeValue; // Time value for iterator
1031 if( Args && strlen(Args) )
1033 char *space = Args, *type, *val;
1037 while(*type == ' ') type ++;
1039 space = strchr(space, ' ');
1040 if(space) *space = '\0';
1043 val = strchr(type, ':');
1050 if( strcmp(type, "min_balance") == 0 ) {
1053 // - Maximum Balance
1054 else if( strcmp(type, "max_balance") == 0 ) {
1058 else if( strcmp(type, "flags") == 0 ) {
1059 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1062 // - Last seen before timestamp
1063 else if( strcmp(type, "last_seen_before") == 0 ) {
1064 lastSeenAfter = atoll(val);
1066 // - Last seen after timestamp
1067 else if( strcmp(type, "last_seen_after") == 0 ) {
1068 lastSeenAfter = atoll(val);
1071 else if( strcmp(type, "sort") == 0 ) {
1072 char *dash = strchr(val, '-');
1077 if( strcmp(val, "name") == 0 ) {
1078 sort = BANK_ITFLAG_SORT_NAME;
1080 else if( strcmp(val, "balance") == 0 ) {
1081 sort = BANK_ITFLAG_SORT_BAL;
1083 else if( strcmp(val, "lastseen") == 0 ) {
1084 sort = BANK_ITFLAG_SORT_LASTSEEN;
1087 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1090 // Handle sort direction
1092 if( strcmp(dash, "desc") == 0 ) {
1093 sort |= BANK_ITFLAG_REVSORT;
1096 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1103 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1110 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1116 *space = ' '; // Repair (to be nice)
1118 while(*space == ' ') space ++;
1124 if( maxBal != INT_MAX ) {
1125 flags = sort|BANK_ITFLAG_MAXBALANCE;
1128 else if( minBal != INT_MIN ) {
1129 flags = sort|BANK_ITFLAG_MINBALANCE;
1136 if( lastSeenBefore ) {
1137 timeValue = lastSeenBefore;
1138 flags |= BANK_ITFLAG_SEENBEFORE;
1140 else if( lastSeenAfter ) {
1141 timeValue = lastSeenAfter;
1142 flags |= BANK_ITFLAG_SEENAFTER;
1147 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1149 // Get return number
1150 while( (i = Bank_IteratorNext(it)) != -1 )
1152 int bal = Bank_GetBalance(i);
1154 if( bal == INT_MIN ) continue;
1156 if( bal < minBal ) continue;
1157 if( bal > maxBal ) continue;
1162 Bank_DelIterator(it);
1165 sendf(Client->Socket, "201 Users %i\n", numRet);
1169 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1171 while( (i = Bank_IteratorNext(it)) != -1 )
1173 int bal = Bank_GetBalance(i);
1175 if( bal == INT_MIN ) continue;
1177 if( bal < minBal ) continue;
1178 if( bal > maxBal ) continue;
1180 _SendUserInfo(Client, i);
1183 Bank_DelIterator(it);
1185 sendf(Client->Socket, "200 List End\n");
1188 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1194 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1195 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1199 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1202 uid = Bank_GetAcctByName(user, 0);
1204 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1206 sendf(Client->Socket, "404 Invalid user\n");
1210 _SendUserInfo(Client, uid);
1213 void _SendUserInfo(tClient *Client, int UserID)
1215 char *type, *disabled="", *door="";
1216 int flags = Bank_GetFlags(UserID);
1218 if( flags & USER_FLAG_INTERNAL ) {
1221 else if( flags & USER_FLAG_COKE ) {
1222 if( flags & USER_FLAG_ADMIN )
1223 type = "coke,admin";
1227 else if( flags & USER_FLAG_ADMIN ) {
1234 if( flags & USER_FLAG_DISABLED )
1235 disabled = ",disabled";
1236 if( flags & USER_FLAG_DOORGROUP )
1239 // TODO: User flags/type
1241 Client->Socket, "202 User %s %i %s%s%s\n",
1242 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1243 type, disabled, door
1247 void Server_Cmd_USERADD(tClient *Client, char *Args)
1252 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1253 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1257 // Check authentication
1258 if( !Client->bIsAuthed ) {
1259 sendf(Client->Socket, "401 Not Authenticated\n");
1263 // Check permissions
1264 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1265 sendf(Client->Socket, "403 Not a coke admin\n");
1269 // Try to create user
1270 if( Bank_CreateAcct(username) == -1 ) {
1271 sendf(Client->Socket, "404 User exists\n");
1276 char *thisName = Bank_GetAcctName(Client->UID);
1277 Log_Info("Account '%s' created by '%s'", username, thisName);
1281 sendf(Client->Socket, "200 User Added\n");
1284 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1286 char *username, *flags, *reason=NULL;
1287 int mask=0, value=0;
1291 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1293 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1299 // Check authentication
1300 if( !Client->bIsAuthed ) {
1301 sendf(Client->Socket, "401 Not Authenticated\n");
1305 // Check permissions
1306 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1307 sendf(Client->Socket, "403 Not a coke admin\n");
1312 uid = Bank_GetAcctByName(username, 0);
1314 sendf(Client->Socket, "404 User '%s' not found\n", username);
1319 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1323 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1324 uid, username, mask, value);
1327 Bank_SetFlags(uid, mask, value);
1330 Log_Info("Updated '%s' with flag set '%s' - Reason: %s",
1331 username, flags, reason);
1334 sendf(Client->Socket, "200 User Updated\n");
1337 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1339 char *itemname, *price_str, *description;
1343 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1344 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1348 if( !Client->bIsAuthed ) {
1349 sendf(Client->Socket, "401 Not Authenticated\n");
1353 // Check user permissions
1354 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1355 sendf(Client->Socket, "403 Not in coke\n");
1359 item = _GetItemFromString(itemname);
1361 // TODO: Create item?
1362 sendf(Client->Socket, "406 Bad Item ID\n");
1366 price = atoi(price_str);
1367 if( price <= 0 && price_str[0] != '0' ) {
1368 sendf(Client->Socket, "407 Invalid price set\n");
1371 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1375 sendf(Client->Socket, "200 Item updated\n");
1382 // --- INTERNAL HELPERS ---
1383 void Debug(tClient *Client, const char *Format, ...)
1386 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1387 printf("[%i] ", Client->ID);
1388 va_start(args, Format);
1389 vprintf(Format, args);
1394 int sendf(int Socket, const char *Format, ...)
1399 va_start(args, Format);
1400 len = vsnprintf(NULL, 0, Format, args);
1405 va_start(args, Format);
1406 vsnprintf(buf, len+1, Format, args);
1409 #if DEBUG_TRACE_CLIENT
1410 printf("sendf: %s", buf);
1413 return send(Socket, buf, len, 0);
1417 // Takes a series of char *'s in
1419 * \brief Parse space-separated entries into
1421 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1426 va_start(args, ArgStr);
1431 while( (dest = va_arg(args, char **)) )
1437 savedChar = *ArgStr;
1439 while( (dest = va_arg(args, char **)) )
1441 // Trim leading spaces
1442 while( *ArgStr == ' ' || *ArgStr == '\t' )
1445 // ... oops, not enough arguments
1446 if( *ArgStr == '\0' )
1448 // NULL unset arguments
1451 } while( (dest = va_arg(args, char **)) );
1456 if( *ArgStr == '"' )
1461 while( *ArgStr && *ArgStr != '"' )
1468 // Read until a space
1469 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1472 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1478 // Oops, extra arguments, and greedy not set
1479 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1486 *ArgStr = savedChar;
1489 return 0; // Success!
1492 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1499 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1500 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1501 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1502 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1503 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1505 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1517 while( *Str == ' ' ) Str ++; // Eat whitespace
1518 space = strchr(Str, ','); // Find the end of the flag
1524 // Check for inversion/removal
1525 if( *Str == '!' || *Str == '-' ) {
1529 else if( *Str == '+' ) {
1533 // Check flag values
1534 for( i = 0; i < ciNumFlags; i ++ )
1536 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1537 *Mask |= cFLAGS[i].Mask;
1538 *Value &= ~cFLAGS[i].Mask;
1540 *Value |= cFLAGS[i].Value;
1546 if( i == ciNumFlags ) {
1548 strncpy(val, Str, len+1);
1549 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);