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>
21 #define DEBUG_TRACE_CLIENT 0
24 #define MAX_CONNECTION_QUEUE 5
25 #define INPUT_BUFFER_SIZE 256
26 #define CLIENT_TIMEOUT 10 // Seconds
28 #define HASH_TYPE SHA1
29 #define HASH_LENGTH 20
31 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
34 typedef struct sClient
36 int Socket; // Client socket ID
39 int bIsTrusted; // Is the connection from a trusted host/port
50 void Server_Start(void);
51 void Server_Cleanup(void);
52 void Server_HandleClient(int Socket, int bTrusted);
53 void Server_ParseClientCommand(tClient *Client, char *CommandString);
55 void Server_Cmd_USER(tClient *Client, char *Args);
56 void Server_Cmd_PASS(tClient *Client, char *Args);
57 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
58 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
59 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
60 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
61 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
62 void Server_Cmd_GIVE(tClient *Client, char *Args);
63 void Server_Cmd_DONATE(tClient *Client, char *Args);
64 void Server_Cmd_ADD(tClient *Client, char *Args);
65 void Server_Cmd_SET(tClient *Client, char *Args);
66 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
67 void Server_Cmd_USERINFO(tClient *Client, char *Args);
68 void _SendUserInfo(tClient *Client, int UserID);
69 void Server_Cmd_USERADD(tClient *Client, char *Args);
70 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
72 void Debug(tClient *Client, const char *Format, ...);
73 int sendf(int Socket, const char *Format, ...);
74 int Server_int_ParseArgs(int bUseLongArg, char *ArgStr, ...);
75 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
79 const struct sClientCommand {
81 void (*Function)(tClient *Client, char *Arguments);
82 } gaServer_Commands[] = {
83 {"USER", Server_Cmd_USER},
84 {"PASS", Server_Cmd_PASS},
85 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
86 {"SETEUSER", Server_Cmd_SETEUSER},
87 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
88 {"ITEM_INFO", Server_Cmd_ITEMINFO},
89 {"DISPENSE", Server_Cmd_DISPENSE},
90 {"GIVE", Server_Cmd_GIVE},
91 {"DONATE", Server_Cmd_DONATE},
92 {"ADD", Server_Cmd_ADD},
93 {"SET", Server_Cmd_SET},
94 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
95 {"USER_INFO", Server_Cmd_USERINFO},
96 {"USER_ADD", Server_Cmd_USERADD},
97 {"USER_FLAGS", Server_Cmd_USERFLAGS}
99 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
102 int giServer_Port = 11020;
103 int giServer_NextClientID = 1;
108 * \brief Open listenting socket and serve connections
110 void Server_Start(void)
113 struct sockaddr_in server_addr, client_addr;
115 atexit(Server_Cleanup);
118 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
119 if( giServer_Socket < 0 ) {
120 fprintf(stderr, "ERROR: Unable to create server socket\n");
124 // Make listen address
125 memset(&server_addr, 0, sizeof(server_addr));
126 server_addr.sin_family = AF_INET; // Internet Socket
127 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
128 server_addr.sin_port = htons(giServer_Port); // Port
131 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
132 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
138 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
139 fprintf(stderr, "ERROR: Unable to listen to socket\n");
144 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
148 FILE *fp = fopen("/var/run/dispsrv.pid", "w");
149 fprintf(fp, "%i", getpid());
155 uint len = sizeof(client_addr);
158 // Accept a connection
159 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
160 if(client_socket < 0) {
161 fprintf(stderr, "ERROR: Unable to accept client connection\n");
165 // Set a timeout on the user conneciton
168 tv.tv_sec = CLIENT_TIMEOUT;
170 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
172 perror("setsockopt");
177 // Debug: Print the connection string
178 if(giDebugLevel >= 2) {
179 char ipstr[INET_ADDRSTRLEN];
180 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
181 printf("Client connection from %s:%i\n",
182 ipstr, ntohs(client_addr.sin_port));
185 // Doesn't matter what, localhost is trusted
186 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
189 // Trusted Connections
190 if( ntohs(client_addr.sin_port) < 1024 )
192 // TODO: Make this runtime configurable
193 switch( ntohl( client_addr.sin_addr.s_addr ) )
195 case 0x7F000001: // 127.0.0.1 localhost
196 // case 0x825F0D00: // 130.95.13.0
197 case 0x825F0D07: // 130.95.13.7 motsugo
198 case 0x825F0D11: // 130.95.13.17 mermaid
199 case 0x825F0D12: // 130.95.13.18 mussel
200 case 0x825F0D17: // 130.95.13.23 martello
201 case 0x825F0D42: // 130.95.13.66 heathred
209 // TODO: Multithread this?
210 Server_HandleClient(client_socket, bTrusted);
212 close(client_socket);
216 void Server_Cleanup(void)
218 printf("\nClose(%i)\n", giServer_Socket);
219 close(giServer_Socket);
223 * \brief Reads from a client socket and parses the command strings
224 * \param Socket Client socket number/handle
225 * \param bTrusted Is the client trusted?
227 void Server_HandleClient(int Socket, int bTrusted)
229 char inbuf[INPUT_BUFFER_SIZE];
231 int remspace = INPUT_BUFFER_SIZE-1;
235 memset(&clientInfo, 0, sizeof(clientInfo));
237 // Initialise Client info
238 clientInfo.Socket = Socket;
239 clientInfo.ID = giServer_NextClientID ++;
240 clientInfo.bIsTrusted = bTrusted;
241 clientInfo.EffectiveUID = -1;
246 * - The `buf` and `remspace` variables allow a line to span several
247 * calls to recv(), if a line is not completed in one recv() call
248 * it is saved to the beginning of `inbuf` and `buf` is updated to
251 // TODO: Use select() instead (to give a timeout)
252 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
255 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
259 while( (eol = strchr(start, '\n')) )
263 Server_ParseClientCommand(&clientInfo, start);
268 // Check if there was an incomplete line
269 if( *start != '\0' ) {
270 int tailBytes = bytes - (start-buf);
271 // Roll back in buffer
272 memcpy(inbuf, start, tailBytes);
273 remspace -= tailBytes;
275 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
277 remspace = INPUT_BUFFER_SIZE - 1;
282 remspace = INPUT_BUFFER_SIZE - 1;
288 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
292 if(giDebugLevel >= 2) {
293 printf("Client %i: Disconnected\n", clientInfo.ID);
298 * \brief Parses a client command and calls the required helper function
299 * \param Client Pointer to client state structure
300 * \param CommandString Command from client (single line of the command)
301 * \return Heap String to return to the client
303 void Server_ParseClientCommand(tClient *Client, char *CommandString)
305 char *command, *args;
308 if( giDebugLevel >= 2 )
309 Debug(Client, "Server_ParseClientCommand: (CommandString = '%s')", CommandString);
311 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
313 if( command == NULL ) return ;
314 // printf("command=%s, args=%s\n", command, args);
315 // Is this an error? (just ignore for now)
321 for( i = 0; i < NUM_COMMANDS; i++ )
323 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
324 if( giDebugLevel >= 2 )
325 Debug(Client, "CMD %s - \"%s\"", command, args);
326 gaServer_Commands[i].Function(Client, args);
331 sendf(Client->Socket, "400 Unknown Command\n");
338 * \brief Set client username
340 * Usage: USER <username>
342 void Server_Cmd_USER(tClient *Client, char *Args)
346 if( Server_int_ParseArgs(0, Args, &username, NULL) )
348 sendf(Client->Socket, "407 USER takes 1 argument\n");
354 Debug(Client, "Authenticating as '%s'", username);
358 free(Client->Username);
359 Client->Username = strdup(username);
362 // Create a salt (that changes if the username is changed)
363 // Yes, I know, I'm a little paranoid, but who isn't?
364 Client->Salt[0] = 0x21 + (rand()&0x3F);
365 Client->Salt[1] = 0x21 + (rand()&0x3F);
366 Client->Salt[2] = 0x21 + (rand()&0x3F);
367 Client->Salt[3] = 0x21 + (rand()&0x3F);
368 Client->Salt[4] = 0x21 + (rand()&0x3F);
369 Client->Salt[5] = 0x21 + (rand()&0x3F);
370 Client->Salt[6] = 0x21 + (rand()&0x3F);
371 Client->Salt[7] = 0x21 + (rand()&0x3F);
373 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
374 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
376 sendf(Client->Socket, "100 User Set\n");
381 * \brief Authenticate as a user
385 void Server_Cmd_PASS(tClient *Client, char *Args)
390 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
392 sendf(Client->Socket, "407 PASS takes 1 argument\n");
396 // Pass on to cokebank
397 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
399 if( Client->UID == -1 ) {
400 sendf(Client->Socket, "401 Auth Failure\n");
404 flags = Bank_GetFlags(Client->UID);
405 if( flags & USER_FLAG_DISABLED ) {
407 sendf(Client->Socket, "403 Account Disabled\n");
410 if( flags & USER_FLAG_INTERNAL ) {
412 sendf(Client->Socket, "403 Internal account\n");
416 Client->bIsAuthed = 1;
417 sendf(Client->Socket, "200 Auth OK\n");
421 * \brief Authenticate as a user without a password
423 * Usage: AUTOAUTH <user>
425 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
430 if( Server_int_ParseArgs(0, Args, &username, NULL) )
432 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
437 if( !Client->bIsTrusted ) {
439 Debug(Client, "Untrusted client attempting to AUTOAUTH");
440 sendf(Client->Socket, "401 Untrusted\n");
445 Client->UID = Bank_GetAcctByName( username );
446 if( Client->UID < 0 ) {
448 Debug(Client, "Unknown user '%s'", username);
449 sendf(Client->Socket, "403 Auth Failure\n");
453 userflags = Bank_GetFlags(Client->UID);
454 // You can't be an internal account
455 if( userflags & USER_FLAG_INTERNAL ) {
457 Debug(Client, "Autoauth as '%s', not allowed", username);
459 sendf(Client->Socket, "403 Account is internal\n");
464 if( userflags & USER_FLAG_DISABLED ) {
466 sendf(Client->Socket, "403 Account disabled\n");
470 Client->bIsAuthed = 1;
473 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
475 sendf(Client->Socket, "200 Auth OK\n");
479 * \brief Set effective user
481 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
484 int eUserFlags, userFlags;
486 if( Server_int_ParseArgs(0, Args, &username, NULL) )
488 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
492 if( !strlen(Args) ) {
493 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
497 // Check user permissions
498 userFlags = Bank_GetFlags(Client->UID);
499 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
500 sendf(Client->Socket, "403 Not in coke\n");
505 Client->EffectiveUID = Bank_GetAcctByName(username);
506 if( Client->EffectiveUID == -1 ) {
507 sendf(Client->Socket, "404 User not found\n");
511 // You can't be an internal account
512 if( !(userFlags & USER_FLAG_ADMIN) )
514 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
515 if( eUserFlags & USER_FLAG_INTERNAL ) {
516 Client->EffectiveUID = -1;
517 sendf(Client->Socket, "404 User not found\n");
520 // Disabled only avaliable to admins
521 if( eUserFlags & USER_FLAG_DISABLED ) {
522 Client->EffectiveUID = -1;
523 sendf(Client->Socket, "403 Account disabled\n");
528 sendf(Client->Socket, "200 User set\n");
532 * \brief Send an item status to the client
533 * \param Client Who to?
534 * \param Item Item to send
536 void Server_int_SendItem(tClient *Client, tItem *Item)
538 char *status = "avail";
540 if( Item->Handler->CanDispense )
542 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
544 case 0: status = "avail"; break;
545 case 1: status = "sold"; break;
547 case -1: status = "error"; break;
551 sendf(Client->Socket,
552 "202 Item %s:%i %s %i %s\n",
553 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
558 * \brief Enumerate the items that the server knows about
560 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
564 if( Args != NULL && strlen(Args) ) {
565 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
571 for( i = 0; i < giNumItems; i ++ ) {
572 if( gaItems[i].bHidden ) continue;
576 sendf(Client->Socket, "201 Items %i\n", count);
578 for( i = 0; i < giNumItems; i ++ ) {
579 if( gaItems[i].bHidden ) continue;
580 Server_int_SendItem( Client, &gaItems[i] );
583 sendf(Client->Socket, "200 List end\n");
586 tItem *_GetItemFromString(char *String)
590 char *colon = strchr(String, ':');
602 for( i = 0; i < giNumHandlers; i ++ )
604 if( strcmp(gaHandlers[i]->Name, type) == 0) {
605 handler = gaHandlers[i];
614 for( i = 0; i < giNumItems; i ++ )
616 if( gaItems[i].Handler != handler ) continue;
617 if( gaItems[i].ID != num ) continue;
624 * \brief Fetch information on a specific item
626 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
631 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
632 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
635 item = _GetItemFromString(Args);
638 sendf(Client->Socket, "406 Bad Item ID\n");
642 Server_int_SendItem( Client, item );
645 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
652 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
653 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
657 if( !Client->bIsAuthed ) {
658 sendf(Client->Socket, "401 Not Authenticated\n");
662 item = _GetItemFromString(itemname);
664 sendf(Client->Socket, "406 Bad Item ID\n");
668 if( Client->EffectiveUID != -1 ) {
669 uid = Client->EffectiveUID;
675 switch( ret = DispenseItem( Client->UID, uid, item ) )
677 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
678 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
679 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
681 sendf(Client->Socket, "500 Dispense Error\n");
686 void Server_Cmd_GIVE(tClient *Client, char *Args)
688 char *recipient, *ammount, *reason;
693 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
694 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
698 if( !Client->bIsAuthed ) {
699 sendf(Client->Socket, "401 Not Authenticated\n");
704 uid = Bank_GetAcctByName(recipient);
706 sendf(Client->Socket, "404 Invalid target user\n");
710 // You can't alter an internal account
711 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
712 // sendf(Client->Socket, "404 Invalid target user\n");
717 iAmmount = atoi(ammount);
718 if( iAmmount <= 0 ) {
719 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
723 if( Client->EffectiveUID != -1 ) {
724 thisUid = Client->EffectiveUID;
727 thisUid = Client->UID;
731 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
734 sendf(Client->Socket, "200 Give OK\n");
737 sendf(Client->Socket, "402 Poor You\n");
740 sendf(Client->Socket, "500 Unknown error\n");
745 void Server_Cmd_DONATE(tClient *Client, char *Args)
747 char *ammount, *reason;
752 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
753 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
757 if( !Client->bIsAuthed ) {
758 sendf(Client->Socket, "401 Not Authenticated\n");
763 iAmmount = atoi(ammount);
764 if( iAmmount <= 0 ) {
765 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
769 // Handle effective users
770 if( Client->EffectiveUID != -1 ) {
771 thisUid = Client->EffectiveUID;
774 thisUid = Client->UID;
778 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
781 sendf(Client->Socket, "200 Give OK\n");
784 sendf(Client->Socket, "402 Poor You\n");
787 sendf(Client->Socket, "500 Unknown error\n");
792 void Server_Cmd_ADD(tClient *Client, char *Args)
794 char *user, *ammount, *reason;
798 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
799 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
803 if( !Client->bIsAuthed ) {
804 sendf(Client->Socket, "401 Not Authenticated\n");
808 // Check user permissions
809 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
810 sendf(Client->Socket, "403 Not in coke\n");
815 uid = Bank_GetAcctByName(user);
817 sendf(Client->Socket, "404 Invalid user\n");
821 // You can't alter an internal account
822 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) )
824 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
825 sendf(Client->Socket, "404 Invalid user\n");
828 // TODO: Maybe disallow changes to disabled?
832 iAmmount = atoi(ammount);
833 if( iAmmount == 0 && ammount[0] != '0' ) {
834 sendf(Client->Socket, "407 Invalid Argument\n");
839 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
842 sendf(Client->Socket, "200 Add OK\n");
845 sendf(Client->Socket, "402 Poor Guy\n");
848 sendf(Client->Socket, "500 Unknown error\n");
853 void Server_Cmd_SET(tClient *Client, char *Args)
855 char *user, *ammount, *reason;
859 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
860 sendf(Client->Socket, "407 SET takes 3 arguments\n");
864 if( !Client->bIsAuthed ) {
865 sendf(Client->Socket, "401 Not Authenticated\n");
869 // Check user permissions
870 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
871 sendf(Client->Socket, "403 Not an admin\n");
876 uid = Bank_GetAcctByName(user);
878 sendf(Client->Socket, "404 Invalid user\n");
883 iAmmount = atoi(ammount);
884 if( iAmmount == 0 && ammount[0] != '0' ) {
885 sendf(Client->Socket, "407 Invalid Argument\n");
890 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
893 sendf(Client->Socket, "200 Add OK\n");
896 sendf(Client->Socket, "402 Poor Guy\n");
899 sendf(Client->Socket, "500 Unknown error\n");
904 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
908 int maxBal = INT_MAX, minBal = INT_MIN;
909 int flagMask = 0, flagVal = 0;
910 int sort = BANK_ITFLAG_SORT_NAME;
911 time_t lastSeenAfter=0, lastSeenBefore=0;
913 int flags; // Iterator flags
914 int balValue; // Balance value for iterator
915 time_t timeValue; // Time value for iterator
918 if( Args && strlen(Args) )
920 char *space = Args, *type, *val;
924 while(*type == ' ') type ++;
926 space = strchr(space, ' ');
927 if(space) *space = '\0';
930 val = strchr(type, ':');
937 if( strcmp(type, "min_balance") == 0 ) {
941 else if( strcmp(type, "max_balance") == 0 ) {
945 else if( strcmp(type, "flags") == 0 ) {
946 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
949 // - Last seen before timestamp
950 else if( strcmp(type, "last_seen_before") == 0 ) {
951 lastSeenAfter = atoll(val);
953 // - Last seen after timestamp
954 else if( strcmp(type, "last_seen_after") == 0 ) {
955 lastSeenAfter = atoll(val);
958 else if( strcmp(type, "sort") == 0 ) {
959 char *dash = strchr(val, '-');
964 if( strcmp(val, "name") == 0 ) {
965 sort = BANK_ITFLAG_SORT_NAME;
967 else if( strcmp(val, "balance") == 0 ) {
968 sort = BANK_ITFLAG_SORT_BAL;
970 else if( strcmp(val, "lastseen") == 0 ) {
971 sort = BANK_ITFLAG_SORT_LASTSEEN;
974 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
977 // Handle sort direction
979 if( strcmp(dash, "desc") == 0 ) {
980 sort |= BANK_ITFLAG_REVSORT;
983 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
990 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
997 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1003 *space = ' '; // Repair (to be nice)
1005 while(*space == ' ') space ++;
1011 if( maxBal != INT_MAX ) {
1012 flags = sort|BANK_ITFLAG_MAXBALANCE;
1015 else if( minBal != INT_MIN ) {
1016 flags = sort|BANK_ITFLAG_MINBALANCE;
1023 if( lastSeenBefore ) {
1024 timeValue = lastSeenBefore;
1025 flags |= BANK_ITFLAG_SEENBEFORE;
1027 else if( lastSeenAfter ) {
1028 timeValue = lastSeenAfter;
1029 flags |= BANK_ITFLAG_SEENAFTER;
1034 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1036 // Get return number
1037 while( (i = Bank_IteratorNext(it)) != -1 )
1039 int bal = Bank_GetBalance(i);
1041 if( bal == INT_MIN ) continue;
1043 if( bal < minBal ) continue;
1044 if( bal > maxBal ) continue;
1049 Bank_DelIterator(it);
1052 sendf(Client->Socket, "201 Users %i\n", numRet);
1056 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1058 while( (i = Bank_IteratorNext(it)) != -1 )
1060 int bal = Bank_GetBalance(i);
1062 if( bal == INT_MIN ) continue;
1064 if( bal < minBal ) continue;
1065 if( bal > maxBal ) continue;
1067 _SendUserInfo(Client, i);
1070 Bank_DelIterator(it);
1072 sendf(Client->Socket, "200 List End\n");
1075 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1081 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1082 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1086 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1089 uid = Bank_GetAcctByName(user);
1091 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1093 sendf(Client->Socket, "404 Invalid user\n");
1097 _SendUserInfo(Client, uid);
1100 void _SendUserInfo(tClient *Client, int UserID)
1102 char *type, *disabled="", *door="";
1103 int flags = Bank_GetFlags(UserID);
1105 if( flags & USER_FLAG_INTERNAL ) {
1108 else if( flags & USER_FLAG_COKE ) {
1109 if( flags & USER_FLAG_ADMIN )
1110 type = "coke,admin";
1114 else if( flags & USER_FLAG_ADMIN ) {
1121 if( flags & USER_FLAG_DISABLED )
1122 disabled = ",disabled";
1123 if( flags & USER_FLAG_DOORGROUP )
1126 // TODO: User flags/type
1128 Client->Socket, "202 User %s %i %s%s%s\n",
1129 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1130 type, disabled, door
1134 void Server_Cmd_USERADD(tClient *Client, char *Args)
1139 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1140 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1144 // Check permissions
1145 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1146 sendf(Client->Socket, "403 Not a coke admin\n");
1150 // Try to create user
1151 if( Bank_CreateAcct(username) == -1 ) {
1152 sendf(Client->Socket, "404 User exists\n");
1157 char *thisName = Bank_GetAcctName(Client->UID);
1158 Log_Info("Account '%s' created by '%s'", username, thisName);
1162 sendf(Client->Socket, "200 User Added\n");
1165 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1167 char *username, *flags;
1168 int mask=0, value=0;
1172 if( Server_int_ParseArgs(0, Args, &username, &flags, NULL) ) {
1173 sendf(Client->Socket, "407 USER_FLAGS takes 2 arguments\n");
1177 // Check permissions
1178 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1179 sendf(Client->Socket, "403 Not a coke admin\n");
1184 uid = Bank_GetAcctByName(username);
1186 sendf(Client->Socket, "404 User '%s' not found\n", username);
1191 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1195 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1196 uid, username, mask, value);
1199 Bank_SetFlags(uid, mask, value);
1202 sendf(Client->Socket, "200 User Updated\n");
1205 // --- INTERNAL HELPERS ---
1206 void Debug(tClient *Client, const char *Format, ...)
1209 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1210 printf("[%i] ", Client->ID);
1211 va_start(args, Format);
1212 vprintf(Format, args);
1217 int sendf(int Socket, const char *Format, ...)
1222 va_start(args, Format);
1223 len = vsnprintf(NULL, 0, Format, args);
1228 va_start(args, Format);
1229 vsnprintf(buf, len+1, Format, args);
1232 #if DEBUG_TRACE_CLIENT
1233 printf("sendf: %s", buf);
1236 return send(Socket, buf, len, 0);
1240 // Takes a series of char *'s in
1242 * \brief Parse space-separated entries into
1244 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1249 va_start(args, ArgStr);
1254 while( (dest = va_arg(args, char **)) )
1260 savedChar = *ArgStr;
1262 while( (dest = va_arg(args, char **)) )
1264 // Trim leading spaces
1265 while( *ArgStr == ' ' || *ArgStr == '\t' )
1268 // ... oops, not enough arguments
1269 if( *ArgStr == '\0' )
1271 // NULL unset arguments
1274 } while( (dest = va_arg(args, char **)) );
1279 if( *ArgStr == '"' )
1284 while( *ArgStr && *ArgStr != '"' )
1291 // Read until a space
1292 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1295 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1301 // Oops, extra arguments, and greedy not set
1302 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1309 *ArgStr = savedChar;
1312 return 0; // Success!
1315 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1322 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1323 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1324 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1325 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1326 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1328 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1340 while( *Str == ' ' ) Str ++; // Eat whitespace
1341 space = strchr(Str, ','); // Find the end of the flag
1347 // Check for inversion/removal
1348 if( *Str == '!' || *Str == '-' ) {
1352 else if( *Str == '+' ) {
1356 // Check flag values
1357 for( i = 0; i < ciNumFlags; i ++ )
1359 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1360 *Mask |= cFLAGS[i].Mask;
1361 *Value &= ~cFLAGS[i].Mask;
1363 *Value |= cFLAGS[i].Value;
1369 if( i == ciNumFlags ) {
1371 strncpy(val, Str, len+1);
1372 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);