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>
22 #define DEBUG_TRACE_CLIENT 0
25 #define MAX_CONNECTION_QUEUE 5
26 #define INPUT_BUFFER_SIZE 256
27 #define CLIENT_TIMEOUT 10 // Seconds
29 #define HASH_TYPE SHA1
30 #define HASH_LENGTH 20
32 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
35 typedef struct sClient
37 int Socket; // Client socket ID
40 int bIsTrusted; // Is the connection from a trusted host/port
51 void Server_Start(void);
52 void Server_Cleanup(void);
53 void Server_HandleClient(int Socket, int bTrusted);
54 void Server_ParseClientCommand(tClient *Client, char *CommandString);
56 void Server_Cmd_USER(tClient *Client, char *Args);
57 void Server_Cmd_PASS(tClient *Client, char *Args);
58 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
59 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
60 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
61 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
62 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
63 void Server_Cmd_GIVE(tClient *Client, char *Args);
64 void Server_Cmd_DONATE(tClient *Client, char *Args);
65 void Server_Cmd_ADD(tClient *Client, char *Args);
66 void Server_Cmd_SET(tClient *Client, char *Args);
67 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
68 void Server_Cmd_USERINFO(tClient *Client, char *Args);
69 void _SendUserInfo(tClient *Client, int UserID);
70 void Server_Cmd_USERADD(tClient *Client, char *Args);
71 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
73 void Debug(tClient *Client, const char *Format, ...);
74 int sendf(int Socket, const char *Format, ...);
75 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
76 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
80 const struct sClientCommand {
82 void (*Function)(tClient *Client, char *Arguments);
83 } gaServer_Commands[] = {
84 {"USER", Server_Cmd_USER},
85 {"PASS", Server_Cmd_PASS},
86 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
87 {"SETEUSER", Server_Cmd_SETEUSER},
88 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
89 {"ITEM_INFO", Server_Cmd_ITEMINFO},
90 {"DISPENSE", Server_Cmd_DISPENSE},
91 {"GIVE", Server_Cmd_GIVE},
92 {"DONATE", Server_Cmd_DONATE},
93 {"ADD", Server_Cmd_ADD},
94 {"SET", Server_Cmd_SET},
95 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
96 {"USER_INFO", Server_Cmd_USERINFO},
97 {"USER_ADD", Server_Cmd_USERADD},
98 {"USER_FLAGS", Server_Cmd_USERFLAGS}
100 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
104 int giServer_Port = 11020;
105 int gbServer_RunInBackground = 0;
106 char *gsServer_LogFile = "/var/log/dispsrv.log";
107 char *gsServer_ErrorLog = "/var/log/dispsrv.err";
109 int giServer_Socket; // Server socket
110 int giServer_NextClientID = 1; // Debug client ID
115 * \brief Open listenting socket and serve connections
117 void Server_Start(void)
120 struct sockaddr_in server_addr, client_addr;
122 atexit(Server_Cleanup);
123 // Ignore SIGPIPE (stops crashes when the client exits early)
124 signal(SIGPIPE, SIG_IGN);
127 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
128 if( giServer_Socket < 0 ) {
129 fprintf(stderr, "ERROR: Unable to create server socket\n");
133 // Make listen address
134 memset(&server_addr, 0, sizeof(server_addr));
135 server_addr.sin_family = AF_INET; // Internet Socket
136 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
137 server_addr.sin_port = htons(giServer_Port); // Port
140 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
141 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
147 if( gbServer_RunInBackground )
151 fprintf(stderr, "ERROR: Unable to fork\n");
152 perror("fork background");
159 // In child, sort out stdin/stdout
160 reopen(0, "/dev/null", O_READ);
161 reopen(1, gsServer_LogFile, O_CREAT|O_APPEND);
162 reopen(2, gsServer_ErrorLog, O_CREAT|O_APPEND);
167 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
168 fprintf(stderr, "ERROR: Unable to listen to socket\n");
173 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
177 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
178 fprintf(fp, "%i", getpid());
184 uint len = sizeof(client_addr);
187 // Accept a connection
188 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
189 if(client_socket < 0) {
190 fprintf(stderr, "ERROR: Unable to accept client connection\n");
194 // Set a timeout on the user conneciton
197 tv.tv_sec = CLIENT_TIMEOUT;
199 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
201 perror("setsockopt");
206 // Debug: Print the connection string
207 if(giDebugLevel >= 2) {
208 char ipstr[INET_ADDRSTRLEN];
209 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
210 printf("Client connection from %s:%i\n",
211 ipstr, ntohs(client_addr.sin_port));
214 // Doesn't matter what, localhost is trusted
215 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
218 // Trusted Connections
219 if( ntohs(client_addr.sin_port) < 1024 )
221 // TODO: Make this runtime configurable
222 switch( ntohl( client_addr.sin_addr.s_addr ) )
224 case 0x7F000001: // 127.0.0.1 localhost
225 // case 0x825F0D00: // 130.95.13.0
226 case 0x825F0D07: // 130.95.13.7 motsugo
227 case 0x825F0D11: // 130.95.13.17 mermaid
228 case 0x825F0D12: // 130.95.13.18 mussel
229 case 0x825F0D17: // 130.95.13.23 martello
230 case 0x825F0D42: // 130.95.13.66 heathred
238 // TODO: Multithread this?
239 Server_HandleClient(client_socket, bTrusted);
241 close(client_socket);
245 void Server_Cleanup(void)
247 printf("\nClose(%i)\n", giServer_Socket);
248 close(giServer_Socket);
249 unlink("/var/run/dispsrv");
253 * \brief Reads from a client socket and parses the command strings
254 * \param Socket Client socket number/handle
255 * \param bTrusted Is the client trusted?
257 void Server_HandleClient(int Socket, int bTrusted)
259 char inbuf[INPUT_BUFFER_SIZE];
261 int remspace = INPUT_BUFFER_SIZE-1;
265 memset(&clientInfo, 0, sizeof(clientInfo));
267 // Initialise Client info
268 clientInfo.Socket = Socket;
269 clientInfo.ID = giServer_NextClientID ++;
270 clientInfo.bIsTrusted = bTrusted;
271 clientInfo.EffectiveUID = -1;
276 * - The `buf` and `remspace` variables allow a line to span several
277 * calls to recv(), if a line is not completed in one recv() call
278 * it is saved to the beginning of `inbuf` and `buf` is updated to
281 // TODO: Use select() instead (to give a timeout)
282 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
285 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
289 while( (eol = strchr(start, '\n')) )
293 Server_ParseClientCommand(&clientInfo, start);
298 // Check if there was an incomplete line
299 if( *start != '\0' ) {
300 int tailBytes = bytes - (start-buf);
301 // Roll back in buffer
302 memcpy(inbuf, start, tailBytes);
303 remspace -= tailBytes;
305 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
307 remspace = INPUT_BUFFER_SIZE - 1;
312 remspace = INPUT_BUFFER_SIZE - 1;
318 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
322 if(giDebugLevel >= 2) {
323 printf("Client %i: Disconnected\n", clientInfo.ID);
328 * \brief Parses a client command and calls the required helper function
329 * \param Client Pointer to client state structure
330 * \param CommandString Command from client (single line of the command)
331 * \return Heap String to return to the client
333 void Server_ParseClientCommand(tClient *Client, char *CommandString)
335 char *command, *args;
338 if( giDebugLevel >= 2 )
339 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
341 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
343 if( command == NULL ) return ;
344 // printf("command=%s, args=%s\n", command, args);
345 // Is this an error? (just ignore for now)
351 for( i = 0; i < NUM_COMMANDS; i++ )
353 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
354 if( giDebugLevel >= 2 )
355 Debug(Client, "CMD %s - \"%s\"", command, args);
356 gaServer_Commands[i].Function(Client, args);
361 sendf(Client->Socket, "400 Unknown Command\n");
368 * \brief Set client username
370 * Usage: USER <username>
372 void Server_Cmd_USER(tClient *Client, char *Args)
376 if( Server_int_ParseArgs(0, Args, &username, NULL) )
378 sendf(Client->Socket, "407 USER takes 1 argument\n");
384 Debug(Client, "Authenticating as '%s'", username);
388 free(Client->Username);
389 Client->Username = strdup(username);
392 // Create a salt (that changes if the username is changed)
393 // Yes, I know, I'm a little paranoid, but who isn't?
394 Client->Salt[0] = 0x21 + (rand()&0x3F);
395 Client->Salt[1] = 0x21 + (rand()&0x3F);
396 Client->Salt[2] = 0x21 + (rand()&0x3F);
397 Client->Salt[3] = 0x21 + (rand()&0x3F);
398 Client->Salt[4] = 0x21 + (rand()&0x3F);
399 Client->Salt[5] = 0x21 + (rand()&0x3F);
400 Client->Salt[6] = 0x21 + (rand()&0x3F);
401 Client->Salt[7] = 0x21 + (rand()&0x3F);
403 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
404 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
406 sendf(Client->Socket, "100 User Set\n");
411 * \brief Authenticate as a user
415 void Server_Cmd_PASS(tClient *Client, char *Args)
420 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
422 sendf(Client->Socket, "407 PASS takes 1 argument\n");
426 // Pass on to cokebank
427 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
429 if( Client->UID == -1 ) {
430 sendf(Client->Socket, "401 Auth Failure\n");
434 flags = Bank_GetFlags(Client->UID);
435 if( flags & USER_FLAG_DISABLED ) {
437 sendf(Client->Socket, "403 Account Disabled\n");
440 if( flags & USER_FLAG_INTERNAL ) {
442 sendf(Client->Socket, "403 Internal account\n");
446 Client->bIsAuthed = 1;
447 sendf(Client->Socket, "200 Auth OK\n");
451 * \brief Authenticate as a user without a password
453 * Usage: AUTOAUTH <user>
455 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
460 if( Server_int_ParseArgs(0, Args, &username, NULL) )
462 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
467 if( !Client->bIsTrusted ) {
469 Debug(Client, "Untrusted client attempting to AUTOAUTH");
470 sendf(Client->Socket, "401 Untrusted\n");
475 Client->UID = Bank_GetAcctByName( username );
476 if( Client->UID < 0 ) {
478 Debug(Client, "Unknown user '%s'", username);
479 sendf(Client->Socket, "403 Auth Failure\n");
483 userflags = Bank_GetFlags(Client->UID);
484 // You can't be an internal account
485 if( userflags & USER_FLAG_INTERNAL ) {
487 Debug(Client, "Autoauth as '%s', not allowed", username);
489 sendf(Client->Socket, "403 Account is internal\n");
494 if( userflags & USER_FLAG_DISABLED ) {
496 sendf(Client->Socket, "403 Account disabled\n");
500 Client->bIsAuthed = 1;
503 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
505 sendf(Client->Socket, "200 Auth OK\n");
509 * \brief Set effective user
511 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
514 int eUserFlags, userFlags;
516 if( Server_int_ParseArgs(0, Args, &username, NULL) )
518 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
522 if( !strlen(Args) ) {
523 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
527 // Check user permissions
528 userFlags = Bank_GetFlags(Client->UID);
529 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
530 sendf(Client->Socket, "403 Not in coke\n");
535 Client->EffectiveUID = Bank_GetAcctByName(username);
536 if( Client->EffectiveUID == -1 ) {
537 sendf(Client->Socket, "404 User not found\n");
541 // You can't be an internal account
542 if( !(userFlags & USER_FLAG_ADMIN) )
544 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
545 if( eUserFlags & USER_FLAG_INTERNAL ) {
546 Client->EffectiveUID = -1;
547 sendf(Client->Socket, "404 User not found\n");
550 // Disabled only avaliable to admins
551 if( eUserFlags & USER_FLAG_DISABLED ) {
552 Client->EffectiveUID = -1;
553 sendf(Client->Socket, "403 Account disabled\n");
558 sendf(Client->Socket, "200 User set\n");
562 * \brief Send an item status to the client
563 * \param Client Who to?
564 * \param Item Item to send
566 void Server_int_SendItem(tClient *Client, tItem *Item)
568 char *status = "avail";
570 if( Item->Handler->CanDispense )
572 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
574 case 0: status = "avail"; break;
575 case 1: status = "sold"; break;
577 case -1: status = "error"; break;
581 sendf(Client->Socket,
582 "202 Item %s:%i %s %i %s\n",
583 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
588 * \brief Enumerate the items that the server knows about
590 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
594 if( Args != NULL && strlen(Args) ) {
595 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
601 for( i = 0; i < giNumItems; i ++ ) {
602 if( gaItems[i].bHidden ) continue;
606 sendf(Client->Socket, "201 Items %i\n", count);
608 for( i = 0; i < giNumItems; i ++ ) {
609 if( gaItems[i].bHidden ) continue;
610 Server_int_SendItem( Client, &gaItems[i] );
613 sendf(Client->Socket, "200 List end\n");
616 tItem *_GetItemFromString(char *String)
620 char *colon = strchr(String, ':');
632 for( i = 0; i < giNumHandlers; i ++ )
634 if( strcmp(gaHandlers[i]->Name, type) == 0) {
635 handler = gaHandlers[i];
644 for( i = 0; i < giNumItems; i ++ )
646 if( gaItems[i].Handler != handler ) continue;
647 if( gaItems[i].ID != num ) continue;
654 * \brief Fetch information on a specific item
656 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
661 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
662 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
665 item = _GetItemFromString(Args);
668 sendf(Client->Socket, "406 Bad Item ID\n");
672 Server_int_SendItem( Client, item );
675 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
682 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
683 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
687 if( !Client->bIsAuthed ) {
688 sendf(Client->Socket, "401 Not Authenticated\n");
692 item = _GetItemFromString(itemname);
694 sendf(Client->Socket, "406 Bad Item ID\n");
698 if( Client->EffectiveUID != -1 ) {
699 uid = Client->EffectiveUID;
705 switch( ret = DispenseItem( Client->UID, uid, item ) )
707 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
708 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
709 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
711 sendf(Client->Socket, "500 Dispense Error\n");
716 void Server_Cmd_GIVE(tClient *Client, char *Args)
718 char *recipient, *ammount, *reason;
723 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
724 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
728 if( !Client->bIsAuthed ) {
729 sendf(Client->Socket, "401 Not Authenticated\n");
734 uid = Bank_GetAcctByName(recipient);
736 sendf(Client->Socket, "404 Invalid target user\n");
740 // You can't alter an internal account
741 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
742 // sendf(Client->Socket, "404 Invalid target user\n");
747 iAmmount = atoi(ammount);
748 if( iAmmount <= 0 ) {
749 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
753 if( Client->EffectiveUID != -1 ) {
754 thisUid = Client->EffectiveUID;
757 thisUid = Client->UID;
761 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
764 sendf(Client->Socket, "200 Give OK\n");
767 sendf(Client->Socket, "402 Poor You\n");
770 sendf(Client->Socket, "500 Unknown error\n");
775 void Server_Cmd_DONATE(tClient *Client, char *Args)
777 char *ammount, *reason;
782 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
783 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
787 if( !Client->bIsAuthed ) {
788 sendf(Client->Socket, "401 Not Authenticated\n");
793 iAmmount = atoi(ammount);
794 if( iAmmount <= 0 ) {
795 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
799 // Handle effective users
800 if( Client->EffectiveUID != -1 ) {
801 thisUid = Client->EffectiveUID;
804 thisUid = Client->UID;
808 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
811 sendf(Client->Socket, "200 Give OK\n");
814 sendf(Client->Socket, "402 Poor You\n");
817 sendf(Client->Socket, "500 Unknown error\n");
822 void Server_Cmd_ADD(tClient *Client, char *Args)
824 char *user, *ammount, *reason;
828 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
829 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
833 if( !Client->bIsAuthed ) {
834 sendf(Client->Socket, "401 Not Authenticated\n");
838 // Check user permissions
839 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
840 sendf(Client->Socket, "403 Not in coke\n");
845 uid = Bank_GetAcctByName(user);
847 sendf(Client->Socket, "404 Invalid user\n");
851 // You can't alter an internal account
852 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
854 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
855 sendf(Client->Socket, "404 Invalid user\n");
858 // TODO: Maybe disallow changes to disabled?
862 iAmmount = atoi(ammount);
863 if( iAmmount == 0 && ammount[0] != '0' ) {
864 sendf(Client->Socket, "407 Invalid Argument\n");
869 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
872 sendf(Client->Socket, "200 Add OK\n");
875 sendf(Client->Socket, "402 Poor Guy\n");
878 sendf(Client->Socket, "500 Unknown error\n");
883 void Server_Cmd_SET(tClient *Client, char *Args)
885 char *user, *ammount, *reason;
889 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
890 sendf(Client->Socket, "407 SET takes 3 arguments\n");
894 if( !Client->bIsAuthed ) {
895 sendf(Client->Socket, "401 Not Authenticated\n");
899 // Check user permissions
900 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
901 sendf(Client->Socket, "403 Not an admin\n");
906 uid = Bank_GetAcctByName(user);
908 sendf(Client->Socket, "404 Invalid user\n");
913 iAmmount = atoi(ammount);
914 if( iAmmount == 0 && ammount[0] != '0' ) {
915 sendf(Client->Socket, "407 Invalid Argument\n");
920 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
923 sendf(Client->Socket, "200 Add OK\n");
926 sendf(Client->Socket, "402 Poor Guy\n");
929 sendf(Client->Socket, "500 Unknown error\n");
934 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
938 int maxBal = INT_MAX, minBal = INT_MIN;
939 int flagMask = 0, flagVal = 0;
940 int sort = BANK_ITFLAG_SORT_NAME;
941 time_t lastSeenAfter=0, lastSeenBefore=0;
943 int flags; // Iterator flags
944 int balValue; // Balance value for iterator
945 time_t timeValue; // Time value for iterator
948 if( Args && strlen(Args) )
950 char *space = Args, *type, *val;
954 while(*type == ' ') type ++;
956 space = strchr(space, ' ');
957 if(space) *space = '\0';
960 val = strchr(type, ':');
967 if( strcmp(type, "min_balance") == 0 ) {
971 else if( strcmp(type, "max_balance") == 0 ) {
975 else if( strcmp(type, "flags") == 0 ) {
976 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
979 // - Last seen before timestamp
980 else if( strcmp(type, "last_seen_before") == 0 ) {
981 lastSeenAfter = atoll(val);
983 // - Last seen after timestamp
984 else if( strcmp(type, "last_seen_after") == 0 ) {
985 lastSeenAfter = atoll(val);
988 else if( strcmp(type, "sort") == 0 ) {
989 char *dash = strchr(val, '-');
994 if( strcmp(val, "name") == 0 ) {
995 sort = BANK_ITFLAG_SORT_NAME;
997 else if( strcmp(val, "balance") == 0 ) {
998 sort = BANK_ITFLAG_SORT_BAL;
1000 else if( strcmp(val, "lastseen") == 0 ) {
1001 sort = BANK_ITFLAG_SORT_LASTSEEN;
1004 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
1007 // Handle sort direction
1009 if( strcmp(dash, "desc") == 0 ) {
1010 sort |= BANK_ITFLAG_REVSORT;
1013 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
1020 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
1027 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1033 *space = ' '; // Repair (to be nice)
1035 while(*space == ' ') space ++;
1041 if( maxBal != INT_MAX ) {
1042 flags = sort|BANK_ITFLAG_MAXBALANCE;
1045 else if( minBal != INT_MIN ) {
1046 flags = sort|BANK_ITFLAG_MINBALANCE;
1053 if( lastSeenBefore ) {
1054 timeValue = lastSeenBefore;
1055 flags |= BANK_ITFLAG_SEENBEFORE;
1057 else if( lastSeenAfter ) {
1058 timeValue = lastSeenAfter;
1059 flags |= BANK_ITFLAG_SEENAFTER;
1064 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1066 // Get return number
1067 while( (i = Bank_IteratorNext(it)) != -1 )
1069 int bal = Bank_GetBalance(i);
1071 if( bal == INT_MIN ) continue;
1073 if( bal < minBal ) continue;
1074 if( bal > maxBal ) continue;
1079 Bank_DelIterator(it);
1082 sendf(Client->Socket, "201 Users %i\n", numRet);
1086 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1088 while( (i = Bank_IteratorNext(it)) != -1 )
1090 int bal = Bank_GetBalance(i);
1092 if( bal == INT_MIN ) continue;
1094 if( bal < minBal ) continue;
1095 if( bal > maxBal ) continue;
1097 _SendUserInfo(Client, i);
1100 Bank_DelIterator(it);
1102 sendf(Client->Socket, "200 List End\n");
1105 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1111 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1112 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1116 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1119 uid = Bank_GetAcctByName(user);
1121 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1123 sendf(Client->Socket, "404 Invalid user\n");
1127 _SendUserInfo(Client, uid);
1130 void _SendUserInfo(tClient *Client, int UserID)
1132 char *type, *disabled="", *door="";
1133 int flags = Bank_GetFlags(UserID);
1135 if( flags & USER_FLAG_INTERNAL ) {
1138 else if( flags & USER_FLAG_COKE ) {
1139 if( flags & USER_FLAG_ADMIN )
1140 type = "coke,admin";
1144 else if( flags & USER_FLAG_ADMIN ) {
1151 if( flags & USER_FLAG_DISABLED )
1152 disabled = ",disabled";
1153 if( flags & USER_FLAG_DOORGROUP )
1156 // TODO: User flags/type
1158 Client->Socket, "202 User %s %i %s%s%s\n",
1159 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1160 type, disabled, door
1164 void Server_Cmd_USERADD(tClient *Client, char *Args)
1169 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1170 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1174 // Check permissions
1175 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1176 sendf(Client->Socket, "403 Not a coke admin\n");
1180 // Try to create user
1181 if( Bank_CreateAcct(username) == -1 ) {
1182 sendf(Client->Socket, "404 User exists\n");
1187 char *thisName = Bank_GetAcctName(Client->UID);
1188 Log_Info("Account '%s' created by '%s'", username, thisName);
1192 sendf(Client->Socket, "200 User Added\n");
1195 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1197 char *username, *flags;
1198 int mask=0, value=0;
1202 if( Server_int_ParseArgs(0, Args, &username, &flags, NULL) ) {
1203 sendf(Client->Socket, "407 USER_FLAGS takes 2 arguments\n");
1207 // Check permissions
1208 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1209 sendf(Client->Socket, "403 Not a coke admin\n");
1214 uid = Bank_GetAcctByName(username);
1216 sendf(Client->Socket, "404 User '%s' not found\n", username);
1221 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1225 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1226 uid, username, mask, value);
1229 Bank_SetFlags(uid, mask, value);
1232 sendf(Client->Socket, "200 User Updated\n");
1235 // --- INTERNAL HELPERS ---
1236 void Debug(tClient *Client, const char *Format, ...)
1239 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1240 printf("[%i] ", Client->ID);
1241 va_start(args, Format);
1242 vprintf(Format, args);
1247 int sendf(int Socket, const char *Format, ...)
1252 va_start(args, Format);
1253 len = vsnprintf(NULL, 0, Format, args);
1258 va_start(args, Format);
1259 vsnprintf(buf, len+1, Format, args);
1262 #if DEBUG_TRACE_CLIENT
1263 printf("sendf: %s", buf);
1266 return send(Socket, buf, len, 0);
1270 // Takes a series of char *'s in
1272 * \brief Parse space-separated entries into
1274 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1279 va_start(args, ArgStr);
1284 while( (dest = va_arg(args, char **)) )
1290 savedChar = *ArgStr;
1292 while( (dest = va_arg(args, char **)) )
1294 // Trim leading spaces
1295 while( *ArgStr == ' ' || *ArgStr == '\t' )
1298 // ... oops, not enough arguments
1299 if( *ArgStr == '\0' )
1301 // NULL unset arguments
1304 } while( (dest = va_arg(args, char **)) );
1309 if( *ArgStr == '"' )
1314 while( *ArgStr && *ArgStr != '"' )
1321 // Read until a space
1322 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1325 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1331 // Oops, extra arguments, and greedy not set
1332 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1339 *ArgStr = savedChar;
1342 return 0; // Success!
1345 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1352 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1353 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1354 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1355 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1356 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1358 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1370 while( *Str == ' ' ) Str ++; // Eat whitespace
1371 space = strchr(Str, ','); // Find the end of the flag
1377 // Check for inversion/removal
1378 if( *Str == '!' || *Str == '-' ) {
1382 else if( *Str == '+' ) {
1386 // Check flag values
1387 for( i = 0; i < ciNumFlags; i ++ )
1389 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1390 *Mask |= cFLAGS[i].Mask;
1391 *Value &= ~cFLAGS[i].Mask;
1393 *Value |= cFLAGS[i].Value;
1399 if( i == ciNumFlags ) {
1401 strncpy(val, Str, len+1);
1402 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);