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 )
157 fprintf(stderr, "ERROR: Unable to fork\n");
158 perror("fork background");
166 // - Sort out stdin/stdout
168 dup2( open("/dev/null", O_RDONLY, 0644), STDIN_FILENO );
169 dup2( open(gsServer_LogFile, O_CREAT|O_APPEND, 0644), STDOUT_FILENO );
170 dup2( open(gsServer_ErrorLog, O_CREAT|O_APPEND, 0644), STDERR_FILENO );
172 freopen("/dev/null", "r", stdin);
173 freopen(gsServer_LogFile, "a", stdout);
174 freopen(gsServer_ErrorLog, "a", stderr);
178 // Start the helper thread
179 StartPeriodicThread();
182 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
183 fprintf(stderr, "ERROR: Unable to listen to socket\n");
188 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
192 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
194 fprintf(fp, "%i", getpid());
201 uint len = sizeof(client_addr);
204 // Accept a connection
205 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
206 if(client_socket < 0) {
207 fprintf(stderr, "ERROR: Unable to accept client connection\n");
211 // Set a timeout on the user conneciton
214 tv.tv_sec = CLIENT_TIMEOUT;
216 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
218 perror("setsockopt");
223 // Debug: Print the connection string
224 if(giDebugLevel >= 2) {
225 char ipstr[INET_ADDRSTRLEN];
226 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
227 printf("Client connection from %s:%i\n",
228 ipstr, ntohs(client_addr.sin_port));
231 // Doesn't matter what, localhost is trusted
232 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
235 // Trusted Connections
236 if( ntohs(client_addr.sin_port) < 1024 )
238 // TODO: Make this runtime configurable
239 switch( ntohl( client_addr.sin_addr.s_addr ) )
241 case 0x7F000001: // 127.0.0.1 localhost
242 // case 0x825F0D00: // 130.95.13.0
243 case 0x825F0D04: // 130.95.13.4 merlo
244 case 0x825F0D05: // 130.95.13.5 heathred (MR)
245 case 0x825F0D07: // 130.95.13.7 motsugo
246 case 0x825F0D11: // 130.95.13.17 mermaid
247 case 0x825F0D12: // 130.95.13.18 mussel
248 case 0x825F0D17: // 130.95.13.23 martello
249 case 0x825F0D2A: // 130.95.13.42 meersau
250 case 0x825F0D42: // 130.95.13.66 heathred (Clubroom)
258 // TODO: Multithread this?
259 Server_HandleClient(client_socket, bTrusted);
261 close(client_socket);
265 void Server_Cleanup(void)
267 printf("\nClose(%i)\n", giServer_Socket);
268 close(giServer_Socket);
269 unlink("/var/run/dispsrv.pid");
273 * \brief Reads from a client socket and parses the command strings
274 * \param Socket Client socket number/handle
275 * \param bTrusted Is the client trusted?
277 void Server_HandleClient(int Socket, int bTrusted)
279 char inbuf[INPUT_BUFFER_SIZE];
281 int remspace = INPUT_BUFFER_SIZE-1;
285 memset(&clientInfo, 0, sizeof(clientInfo));
287 // Initialise Client info
288 clientInfo.Socket = Socket;
289 clientInfo.ID = giServer_NextClientID ++;
290 clientInfo.bIsTrusted = bTrusted;
291 clientInfo.EffectiveUID = -1;
296 * - The `buf` and `remspace` variables allow a line to span several
297 * calls to recv(), if a line is not completed in one recv() call
298 * it is saved to the beginning of `inbuf` and `buf` is updated to
301 // TODO: Use select() instead (to give a timeout)
302 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
305 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
309 while( (eol = strchr(start, '\n')) )
313 Server_ParseClientCommand(&clientInfo, start);
318 // Check if there was an incomplete line
319 if( *start != '\0' ) {
320 int tailBytes = bytes - (start-buf);
321 // Roll back in buffer
322 memcpy(inbuf, start, tailBytes);
323 remspace -= tailBytes;
325 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
327 remspace = INPUT_BUFFER_SIZE - 1;
332 remspace = INPUT_BUFFER_SIZE - 1;
338 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
342 if(giDebugLevel >= 2) {
343 printf("Client %i: Disconnected\n", clientInfo.ID);
348 * \brief Parses a client command and calls the required helper function
349 * \param Client Pointer to client state structure
350 * \param CommandString Command from client (single line of the command)
351 * \return Heap String to return to the client
353 void Server_ParseClientCommand(tClient *Client, char *CommandString)
355 char *command, *args;
358 if( giDebugLevel >= 2 )
359 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
361 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
363 if( command == NULL ) return ;
364 // Is this an error? (just ignore for now)
369 for( i = 0; i < NUM_COMMANDS; i++ )
371 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
372 if( giDebugLevel >= 2 )
373 Debug(Client, "CMD %s - \"%s\"", command, args);
374 gaServer_Commands[i].Function(Client, args);
379 sendf(Client->Socket, "400 Unknown Command\n");
386 * \brief Set client username
388 * Usage: USER <username>
390 void Server_Cmd_USER(tClient *Client, char *Args)
394 if( Server_int_ParseArgs(0, Args, &username, NULL) )
396 sendf(Client->Socket, "407 USER takes 1 argument\n");
402 Debug(Client, "Authenticating as '%s'", username);
406 free(Client->Username);
407 Client->Username = strdup(username);
410 // Create a salt (that changes if the username is changed)
411 // Yes, I know, I'm a little paranoid, but who isn't?
412 Client->Salt[0] = 0x21 + (rand()&0x3F);
413 Client->Salt[1] = 0x21 + (rand()&0x3F);
414 Client->Salt[2] = 0x21 + (rand()&0x3F);
415 Client->Salt[3] = 0x21 + (rand()&0x3F);
416 Client->Salt[4] = 0x21 + (rand()&0x3F);
417 Client->Salt[5] = 0x21 + (rand()&0x3F);
418 Client->Salt[6] = 0x21 + (rand()&0x3F);
419 Client->Salt[7] = 0x21 + (rand()&0x3F);
421 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
422 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
424 sendf(Client->Socket, "100 User Set\n");
429 * \brief Authenticate as a user
433 void Server_Cmd_PASS(tClient *Client, char *Args)
438 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
440 sendf(Client->Socket, "407 PASS takes 1 argument\n");
444 // Pass on to cokebank
445 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
447 if( Client->UID == -1 ) {
448 sendf(Client->Socket, "401 Auth Failure\n");
452 flags = Bank_GetFlags(Client->UID);
453 if( flags & USER_FLAG_DISABLED ) {
455 sendf(Client->Socket, "403 Account Disabled\n");
458 if( flags & USER_FLAG_INTERNAL ) {
460 sendf(Client->Socket, "403 Internal account\n");
464 Client->bIsAuthed = 1;
465 sendf(Client->Socket, "200 Auth OK\n");
469 * \brief Authenticate as a user without a password
471 * Usage: AUTOAUTH <user>
473 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
478 if( Server_int_ParseArgs(0, Args, &username, NULL) )
480 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
485 if( !Client->bIsTrusted ) {
487 Debug(Client, "Untrusted client attempting to AUTOAUTH");
488 sendf(Client->Socket, "401 Untrusted\n");
493 Client->UID = Bank_GetAcctByName( username, 0 );
494 if( Client->UID < 0 ) {
496 Debug(Client, "Unknown user '%s'", username);
497 sendf(Client->Socket, "403 Auth Failure\n");
501 userflags = Bank_GetFlags(Client->UID);
502 // You can't be an internal account
503 if( userflags & USER_FLAG_INTERNAL ) {
505 Debug(Client, "Autoauth as '%s', not allowed", username);
507 sendf(Client->Socket, "403 Account is internal\n");
512 if( userflags & USER_FLAG_DISABLED ) {
514 sendf(Client->Socket, "403 Account disabled\n");
518 Client->bIsAuthed = 1;
521 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
523 sendf(Client->Socket, "200 Auth OK\n");
527 * \brief Set effective user
529 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
532 int eUserFlags, userFlags;
534 if( Server_int_ParseArgs(0, Args, &username, NULL) )
536 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
540 if( !strlen(Args) ) {
541 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
545 // Check authentication
546 if( !Client->bIsAuthed ) {
547 sendf(Client->Socket, "401 Not Authenticated\n");
551 // Check user permissions
552 userFlags = Bank_GetFlags(Client->UID);
553 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
554 sendf(Client->Socket, "403 Not in coke\n");
559 Client->EffectiveUID = Bank_GetAcctByName(username, 0);
560 if( Client->EffectiveUID == -1 ) {
561 sendf(Client->Socket, "404 User not found\n");
565 // You can't be an internal account
566 if( !(userFlags & USER_FLAG_ADMIN) )
568 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
569 if( eUserFlags & USER_FLAG_INTERNAL ) {
570 Client->EffectiveUID = -1;
571 sendf(Client->Socket, "404 User not found\n");
574 // Disabled only avaliable to admins
575 if( eUserFlags & USER_FLAG_DISABLED ) {
576 Client->EffectiveUID = -1;
577 sendf(Client->Socket, "403 Account disabled\n");
582 sendf(Client->Socket, "200 User set\n");
586 * \brief Send an item status to the client
587 * \param Client Who to?
588 * \param Item Item to send
590 void Server_int_SendItem(tClient *Client, tItem *Item)
592 char *status = "avail";
594 if( Item->Handler->CanDispense )
596 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
598 case 0: status = "avail"; break;
599 case 1: status = "sold"; break;
601 case -1: status = "error"; break;
605 // KNOWN HACK: Naming a slot 'dead' disables it
606 if( strcmp(Item->Name, "dead") == 0 )
607 status = "sold"; // Another status?
609 sendf(Client->Socket,
610 "202 Item %s:%i %s %i %s\n",
611 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
616 * \brief Enumerate the items that the server knows about
618 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
622 if( Args != NULL && strlen(Args) ) {
623 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
629 for( i = 0; i < giNumItems; i ++ ) {
630 if( gaItems[i].bHidden ) continue;
634 sendf(Client->Socket, "201 Items %i\n", count);
636 for( i = 0; i < giNumItems; i ++ ) {
637 if( gaItems[i].bHidden ) continue;
638 Server_int_SendItem( Client, &gaItems[i] );
641 sendf(Client->Socket, "200 List end\n");
644 tItem *_GetItemFromString(char *String)
648 char *colon = strchr(String, ':');
660 for( i = 0; i < giNumHandlers; i ++ )
662 if( strcmp(gaHandlers[i]->Name, type) == 0) {
663 handler = gaHandlers[i];
672 for( i = 0; i < giNumItems; i ++ )
674 if( gaItems[i].Handler != handler ) continue;
675 if( gaItems[i].ID != num ) continue;
682 * \brief Fetch information on a specific item
684 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
689 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
690 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
693 item = _GetItemFromString(Args);
696 sendf(Client->Socket, "406 Bad Item ID\n");
700 Server_int_SendItem( Client, item );
703 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
710 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
711 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
715 if( !Client->bIsAuthed ) {
716 sendf(Client->Socket, "401 Not Authenticated\n");
720 item = _GetItemFromString(itemname);
722 sendf(Client->Socket, "406 Bad Item ID\n");
726 if( Client->EffectiveUID != -1 ) {
727 uid = Client->EffectiveUID;
733 switch( ret = DispenseItem( Client->UID, uid, item ) )
735 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
736 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
737 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
739 sendf(Client->Socket, "500 Dispense Error (%i)\n", ret);
744 void Server_Cmd_REFUND(tClient *Client, char *Args)
747 int uid, price_override = 0;
748 char *username, *itemname, *price_str;
750 if( Server_int_ParseArgs(0, Args, &username, &itemname, &price_str, NULL) ) {
751 if( !itemname || price_str ) {
752 sendf(Client->Socket, "407 REFUND takes 2 or 3 arguments\n");
757 if( !Client->bIsAuthed ) {
758 sendf(Client->Socket, "401 Not Authenticated\n");
762 // Check user permissions
763 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
764 sendf(Client->Socket, "403 Not in coke\n");
768 uid = Bank_GetAcctByName(username, 0);
770 sendf(Client->Socket, "404 Unknown user\n");
774 item = _GetItemFromString(itemname);
776 sendf(Client->Socket, "406 Bad Item ID\n");
781 price_override = atoi(price_str);
783 switch( DispenseRefund( Client->UID, uid, item, price_override ) )
785 case 0: sendf(Client->Socket, "200 Item Refunded\n"); return ;
787 sendf(Client->Socket, "500 Dispense Error\n");
792 void Server_Cmd_GIVE(tClient *Client, char *Args)
794 char *recipient, *ammount, *reason;
799 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
800 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
805 if( !Client->bIsAuthed ) {
806 sendf(Client->Socket, "401 Not Authenticated\n");
811 uid = Bank_GetAcctByName(recipient, 0);
813 sendf(Client->Socket, "404 Invalid target user\n");
817 // You can't alter an internal account
818 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
819 // sendf(Client->Socket, "404 Invalid target user\n");
824 iAmmount = atoi(ammount);
825 if( iAmmount <= 0 ) {
826 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
830 if( Client->EffectiveUID != -1 ) {
831 thisUid = Client->EffectiveUID;
834 thisUid = Client->UID;
838 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
841 sendf(Client->Socket, "200 Give OK\n");
844 sendf(Client->Socket, "402 Poor You\n");
847 sendf(Client->Socket, "500 Unknown error\n");
852 void Server_Cmd_DONATE(tClient *Client, char *Args)
854 char *ammount, *reason;
859 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
860 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
864 if( !Client->bIsAuthed ) {
865 sendf(Client->Socket, "401 Not Authenticated\n");
870 iAmmount = atoi(ammount);
871 if( iAmmount <= 0 ) {
872 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
876 // Handle effective users
877 if( Client->EffectiveUID != -1 ) {
878 thisUid = Client->EffectiveUID;
881 thisUid = Client->UID;
885 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
888 sendf(Client->Socket, "200 Give OK\n");
891 sendf(Client->Socket, "402 Poor You\n");
894 sendf(Client->Socket, "500 Unknown error\n");
899 void Server_Cmd_ADD(tClient *Client, char *Args)
901 char *user, *ammount, *reason;
905 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
906 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
910 if( !Client->bIsAuthed ) {
911 sendf(Client->Socket, "401 Not Authenticated\n");
915 // Check user permissions
916 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
917 sendf(Client->Socket, "403 Not in coke\n");
922 if( strstr(reason, "refund") != NULL || strstr(reason, "misdispense") != NULL )
924 sendf(Client->Socket, "499 Don't use `dispense acct` for refunds, use `dispense refund` (and `dispense -G` to get item IDs)\n");
930 uid = Bank_GetAcctByName(user, 0);
932 sendf(Client->Socket, "404 Invalid user\n");
936 // You can't alter an internal account
937 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
939 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
940 sendf(Client->Socket, "404 Invalid user\n");
943 // TODO: Maybe disallow changes to disabled?
947 iAmmount = atoi(ammount);
948 if( iAmmount == 0 && ammount[0] != '0' ) {
949 sendf(Client->Socket, "407 Invalid Argument\n");
954 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
957 sendf(Client->Socket, "200 Add OK\n");
960 sendf(Client->Socket, "402 Poor Guy\n");
963 sendf(Client->Socket, "500 Unknown error\n");
968 void Server_Cmd_SET(tClient *Client, char *Args)
970 char *user, *ammount, *reason;
974 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
975 sendf(Client->Socket, "407 SET takes 3 arguments\n");
979 if( !Client->bIsAuthed ) {
980 sendf(Client->Socket, "401 Not Authenticated\n");
984 // Check user permissions
985 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
986 sendf(Client->Socket, "403 Not an admin\n");
991 uid = Bank_GetAcctByName(user, 0);
993 sendf(Client->Socket, "404 Invalid user\n");
998 iAmmount = atoi(ammount);
999 if( iAmmount == 0 && ammount[0] != '0' ) {
1000 sendf(Client->Socket, "407 Invalid Argument\n");
1005 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
1008 sendf(Client->Socket, "200 Add OK\n");
1011 sendf(Client->Socket, "402 Poor Guy\n");
1014 sendf(Client->Socket, "500 Unknown error\n");
1019 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
1023 int maxBal = INT_MAX, minBal = INT_MIN;
1024 int flagMask = 0, flagVal = 0;
1025 int sort = BANK_ITFLAG_SORT_NAME;
1026 time_t lastSeenAfter=0, lastSeenBefore=0;
1028 int flags; // Iterator flags
1029 int balValue; // Balance value for iterator
1030 time_t timeValue; // Time value for iterator
1033 if( Args && strlen(Args) )
1035 char *space = Args, *type, *val;
1039 while(*type == ' ') type ++;
1041 space = strchr(space, ' ');
1042 if(space) *space = '\0';
1045 val = strchr(type, ':');
1052 if( strcmp(type, "min_balance") == 0 ) {
1055 // - Maximum Balance
1056 else if( strcmp(type, "max_balance") == 0 ) {
1060 else if( strcmp(type, "flags") == 0 ) {
1061 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
1064 // - Last seen before timestamp
1065 else if( strcmp(type, "last_seen_before") == 0 ) {
1066 lastSeenAfter = atoll(val);
1068 // - Last seen after timestamp
1069 else if( strcmp(type, "last_seen_after") == 0 ) {
1070 lastSeenAfter = atoll(val);
1073 else if( strcmp(type, "sort") == 0 ) {
1074 char *dash = strchr(val, '-');
1079 if( strcmp(val, "name") == 0 ) {
1080 sort = BANK_ITFLAG_SORT_NAME;
1082 else if( strcmp(val, "balance") == 0 ) {
1083 sort = BANK_ITFLAG_SORT_BAL;
1085 else if( strcmp(val, "lastseen") == 0 ) {
1086 sort = BANK_ITFLAG_SORT_LASTSEEN;
1089 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1092 // Handle sort direction
1094 if( strcmp(dash, "desc") == 0 ) {
1095 sort |= BANK_ITFLAG_REVSORT;
1098 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1105 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1112 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1118 *space = ' '; // Repair (to be nice)
1120 while(*space == ' ') space ++;
1126 if( maxBal != INT_MAX ) {
1127 flags = sort|BANK_ITFLAG_MAXBALANCE;
1130 else if( minBal != INT_MIN ) {
1131 flags = sort|BANK_ITFLAG_MINBALANCE;
1138 if( lastSeenBefore ) {
1139 timeValue = lastSeenBefore;
1140 flags |= BANK_ITFLAG_SEENBEFORE;
1142 else if( lastSeenAfter ) {
1143 timeValue = lastSeenAfter;
1144 flags |= BANK_ITFLAG_SEENAFTER;
1149 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1151 // Get return number
1152 while( (i = Bank_IteratorNext(it)) != -1 )
1154 int bal = Bank_GetBalance(i);
1156 if( bal == INT_MIN ) continue;
1158 if( bal < minBal ) continue;
1159 if( bal > maxBal ) continue;
1164 Bank_DelIterator(it);
1167 sendf(Client->Socket, "201 Users %i\n", numRet);
1171 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1173 while( (i = Bank_IteratorNext(it)) != -1 )
1175 int bal = Bank_GetBalance(i);
1177 if( bal == INT_MIN ) continue;
1179 if( bal < minBal ) continue;
1180 if( bal > maxBal ) continue;
1182 _SendUserInfo(Client, i);
1185 Bank_DelIterator(it);
1187 sendf(Client->Socket, "200 List End\n");
1190 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1196 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1197 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1201 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1204 uid = Bank_GetAcctByName(user, 0);
1206 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1208 sendf(Client->Socket, "404 Invalid user\n");
1212 _SendUserInfo(Client, uid);
1215 void _SendUserInfo(tClient *Client, int UserID)
1217 char *type, *disabled="", *door="";
1218 int flags = Bank_GetFlags(UserID);
1220 if( flags & USER_FLAG_INTERNAL ) {
1223 else if( flags & USER_FLAG_COKE ) {
1224 if( flags & USER_FLAG_ADMIN )
1225 type = "coke,admin";
1229 else if( flags & USER_FLAG_ADMIN ) {
1236 if( flags & USER_FLAG_DISABLED )
1237 disabled = ",disabled";
1238 if( flags & USER_FLAG_DOORGROUP )
1241 // TODO: User flags/type
1243 Client->Socket, "202 User %s %i %s%s%s\n",
1244 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1245 type, disabled, door
1249 void Server_Cmd_USERADD(tClient *Client, char *Args)
1254 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1255 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1259 // Check authentication
1260 if( !Client->bIsAuthed ) {
1261 sendf(Client->Socket, "401 Not Authenticated\n");
1265 // Check permissions
1266 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1267 sendf(Client->Socket, "403 Not a coke admin\n");
1271 // Try to create user
1272 if( Bank_CreateAcct(username) == -1 ) {
1273 sendf(Client->Socket, "404 User exists\n");
1278 char *thisName = Bank_GetAcctName(Client->UID);
1279 Log_Info("Account '%s' created by '%s'", username, thisName);
1283 sendf(Client->Socket, "200 User Added\n");
1286 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1288 char *username, *flags, *reason=NULL;
1289 int mask=0, value=0;
1293 if( Server_int_ParseArgs(1, Args, &username, &flags, &reason, NULL) ) {
1295 sendf(Client->Socket, "407 USER_FLAGS takes at least 2 arguments\n");
1301 // Check authentication
1302 if( !Client->bIsAuthed ) {
1303 sendf(Client->Socket, "401 Not Authenticated\n");
1307 // Check permissions
1308 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1309 sendf(Client->Socket, "403 Not a coke admin\n");
1314 uid = Bank_GetAcctByName(username, 0);
1316 sendf(Client->Socket, "404 User '%s' not found\n", username);
1321 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1325 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1326 uid, username, mask, value);
1329 Bank_SetFlags(uid, mask, value);
1332 Log_Info("Updated '%s' with flag set '%s' - Reason: %s",
1333 username, flags, reason);
1336 sendf(Client->Socket, "200 User Updated\n");
1339 void Server_Cmd_UPDATEITEM(tClient *Client, char *Args)
1341 char *itemname, *price_str, *description;
1345 if( Server_int_ParseArgs(1, Args, &itemname, &price_str, &description, NULL) ) {
1346 sendf(Client->Socket, "407 UPDATE_ITEM takes 3 arguments\n");
1350 if( !Client->bIsAuthed ) {
1351 sendf(Client->Socket, "401 Not Authenticated\n");
1355 // Check user permissions
1356 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
1357 sendf(Client->Socket, "403 Not in coke\n");
1361 item = _GetItemFromString(itemname);
1363 // TODO: Create item?
1364 sendf(Client->Socket, "406 Bad Item ID\n");
1368 price = atoi(price_str);
1369 if( price <= 0 && price_str[0] != '0' ) {
1370 sendf(Client->Socket, "407 Invalid price set\n");
1373 switch( DispenseUpdateItem( Client->UID, item, description, price ) )
1377 sendf(Client->Socket, "200 Item updated\n");
1384 // --- INTERNAL HELPERS ---
1385 void Debug(tClient *Client, const char *Format, ...)
1388 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1389 printf("[%i] ", Client->ID);
1390 va_start(args, Format);
1391 vprintf(Format, args);
1396 int sendf(int Socket, const char *Format, ...)
1401 va_start(args, Format);
1402 len = vsnprintf(NULL, 0, Format, args);
1407 va_start(args, Format);
1408 vsnprintf(buf, len+1, Format, args);
1411 #if DEBUG_TRACE_CLIENT
1412 printf("sendf: %s", buf);
1415 return send(Socket, buf, len, 0);
1419 // Takes a series of char *'s in
1421 * \brief Parse space-separated entries into
1423 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1428 va_start(args, ArgStr);
1433 while( (dest = va_arg(args, char **)) )
1439 savedChar = *ArgStr;
1441 while( (dest = va_arg(args, char **)) )
1443 // Trim leading spaces
1444 while( *ArgStr == ' ' || *ArgStr == '\t' )
1447 // ... oops, not enough arguments
1448 if( *ArgStr == '\0' )
1450 // NULL unset arguments
1453 } while( (dest = va_arg(args, char **)) );
1458 if( *ArgStr == '"' )
1463 while( *ArgStr && *ArgStr != '"' )
1470 // Read until a space
1471 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1474 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1480 // Oops, extra arguments, and greedy not set
1481 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1488 *ArgStr = savedChar;
1491 return 0; // Success!
1494 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1501 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1502 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1503 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1504 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1505 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1507 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1519 while( *Str == ' ' ) Str ++; // Eat whitespace
1520 space = strchr(Str, ','); // Find the end of the flag
1526 // Check for inversion/removal
1527 if( *Str == '!' || *Str == '-' ) {
1531 else if( *Str == '+' ) {
1535 // Check flag values
1536 for( i = 0; i < ciNumFlags; i ++ )
1538 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1539 *Mask |= cFLAGS[i].Mask;
1540 *Value &= ~cFLAGS[i].Mask;
1542 *Value |= cFLAGS[i].Value;
1548 if( i == ciNumFlags ) {
1550 strncpy(val, Str, len+1);
1551 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);