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("Close(%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 // printf("command=%s, args=%s\n", command, args);
314 // Is this an error? (just ignore for now)
320 for( i = 0; i < NUM_COMMANDS; i++ )
322 if(strcmp(command, gaServer_Commands[i].Name) == 0) {
323 if( giDebugLevel >= 2 )
324 Debug(Client, "CMD %s - \"%s\"", command, args);
325 gaServer_Commands[i].Function(Client, args);
330 sendf(Client->Socket, "400 Unknown Command\n");
337 * \brief Set client username
339 * Usage: USER <username>
341 void Server_Cmd_USER(tClient *Client, char *Args)
345 if( Server_int_ParseArgs(0, Args, &username, NULL) )
347 sendf(Client->Socket, "407 USER takes 1 argument\n");
353 Debug(Client, "Authenticating as '%s'", username);
357 free(Client->Username);
358 Client->Username = strdup(username);
361 // Create a salt (that changes if the username is changed)
362 // Yes, I know, I'm a little paranoid, but who isn't?
363 Client->Salt[0] = 0x21 + (rand()&0x3F);
364 Client->Salt[1] = 0x21 + (rand()&0x3F);
365 Client->Salt[2] = 0x21 + (rand()&0x3F);
366 Client->Salt[3] = 0x21 + (rand()&0x3F);
367 Client->Salt[4] = 0x21 + (rand()&0x3F);
368 Client->Salt[5] = 0x21 + (rand()&0x3F);
369 Client->Salt[6] = 0x21 + (rand()&0x3F);
370 Client->Salt[7] = 0x21 + (rand()&0x3F);
372 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
373 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
375 sendf(Client->Socket, "100 User Set\n");
380 * \brief Authenticate as a user
384 void Server_Cmd_PASS(tClient *Client, char *Args)
389 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
391 sendf(Client->Socket, "407 PASS takes 1 argument\n");
395 // Pass on to cokebank
396 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
398 if( Client->UID == -1 ) {
399 sendf(Client->Socket, "401 Auth Failure\n");
403 flags = Bank_GetFlags(Client->UID);
404 if( flags & USER_FLAG_DISABLED ) {
406 sendf(Client->Socket, "403 Account Disabled\n");
409 if( flags & USER_FLAG_INTERNAL ) {
411 sendf(Client->Socket, "403 Internal account\n");
415 Client->bIsAuthed = 1;
416 sendf(Client->Socket, "200 Auth OK\n");
420 * \brief Authenticate as a user without a password
422 * Usage: AUTOAUTH <user>
424 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
429 if( Server_int_ParseArgs(0, Args, &username, NULL) )
431 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
436 if( !Client->bIsTrusted ) {
438 Debug(Client, "Untrusted client attempting to AUTOAUTH");
439 sendf(Client->Socket, "401 Untrusted\n");
444 Client->UID = Bank_GetAcctByName( username );
445 if( Client->UID < 0 ) {
447 Debug(Client, "Unknown user '%s'", username);
448 sendf(Client->Socket, "403 Auth Failure\n");
452 userflags = Bank_GetFlags(Client->UID);
453 // You can't be an internal account
454 if( userflags & USER_FLAG_INTERNAL ) {
456 Debug(Client, "Autoauth as '%s', not allowed", username);
458 sendf(Client->Socket, "403 Account is internal\n");
463 if( userflags & USER_FLAG_DISABLED ) {
465 sendf(Client->Socket, "403 Account disabled\n");
469 Client->bIsAuthed = 1;
472 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
474 sendf(Client->Socket, "200 Auth OK\n");
478 * \brief Set effective user
480 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
483 int eUserFlags, userFlags;
485 if( Server_int_ParseArgs(0, Args, &username, NULL) )
487 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
491 if( !strlen(Args) ) {
492 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
496 // Check user permissions
497 userFlags = Bank_GetFlags(Client->UID);
498 if( !(userFlags & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
499 sendf(Client->Socket, "403 Not in coke\n");
504 Client->EffectiveUID = Bank_GetAcctByName(username);
505 if( Client->EffectiveUID == -1 ) {
506 sendf(Client->Socket, "404 User not found\n");
510 // You can't be an internal account
511 eUserFlags = Bank_GetFlags(Client->EffectiveUID);
512 if( eUserFlags & USER_FLAG_INTERNAL ) {
513 Client->EffectiveUID = -1;
514 sendf(Client->Socket, "404 User not found\n");
517 // Disabled only avaliable to admins
518 if( (eUserFlags & USER_FLAG_DISABLED) && !(userFlags & USER_FLAG_ADMIN) ) {
519 Client->EffectiveUID = -1;
520 sendf(Client->Socket, "403 Account disabled\n");
524 sendf(Client->Socket, "200 User set\n");
528 * \brief Send an item status to the client
529 * \param Client Who to?
530 * \param Item Item to send
532 void Server_int_SendItem(tClient *Client, tItem *Item)
534 char *status = "avail";
536 if( Item->Handler->CanDispense )
538 switch(Item->Handler->CanDispense(Client->UID, Item->ID))
540 case 0: status = "avail"; break;
541 case 1: status = "sold"; break;
543 case -1: status = "error"; break;
547 sendf(Client->Socket,
548 "202 Item %s:%i %s %i %s\n",
549 Item->Handler->Name, Item->ID, status, Item->Price, Item->Name
554 * \brief Enumerate the items that the server knows about
556 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
560 if( Args != NULL && strlen(Args) ) {
561 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
567 for( i = 0; i < giNumItems; i ++ ) {
568 if( gaItems[i].bHidden ) continue;
572 sendf(Client->Socket, "201 Items %i\n", count);
574 for( i = 0; i < giNumItems; i ++ ) {
575 if( gaItems[i].bHidden ) continue;
576 Server_int_SendItem( Client, &gaItems[i] );
579 sendf(Client->Socket, "200 List end\n");
582 tItem *_GetItemFromString(char *String)
586 char *colon = strchr(String, ':');
598 for( i = 0; i < giNumHandlers; i ++ )
600 if( strcmp(gaHandlers[i]->Name, type) == 0) {
601 handler = gaHandlers[i];
610 for( i = 0; i < giNumItems; i ++ )
612 if( gaItems[i].Handler != handler ) continue;
613 if( gaItems[i].ID != num ) continue;
620 * \brief Fetch information on a specific item
622 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
627 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
628 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
631 item = _GetItemFromString(Args);
634 sendf(Client->Socket, "406 Bad Item ID\n");
638 Server_int_SendItem( Client, item );
641 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
648 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
649 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
653 if( !Client->bIsAuthed ) {
654 sendf(Client->Socket, "401 Not Authenticated\n");
658 item = _GetItemFromString(itemname);
660 sendf(Client->Socket, "406 Bad Item ID\n");
664 if( Client->EffectiveUID != -1 ) {
665 uid = Client->EffectiveUID;
671 switch( ret = DispenseItem( Client->UID, uid, item ) )
673 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
674 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
675 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
677 sendf(Client->Socket, "500 Dispense Error\n");
682 void Server_Cmd_GIVE(tClient *Client, char *Args)
684 char *recipient, *ammount, *reason;
689 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
690 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
694 if( !Client->bIsAuthed ) {
695 sendf(Client->Socket, "401 Not Authenticated\n");
700 uid = Bank_GetAcctByName(recipient);
702 sendf(Client->Socket, "404 Invalid target user\n");
706 // You can't alter an internal account
707 // if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
708 // sendf(Client->Socket, "404 Invalid target user\n");
713 iAmmount = atoi(ammount);
714 if( iAmmount <= 0 ) {
715 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
719 if( Client->EffectiveUID != -1 ) {
720 thisUid = Client->EffectiveUID;
723 thisUid = Client->UID;
727 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
730 sendf(Client->Socket, "200 Give OK\n");
733 sendf(Client->Socket, "402 Poor You\n");
736 sendf(Client->Socket, "500 Unknown error\n");
741 void Server_Cmd_DONATE(tClient *Client, char *Args)
743 char *ammount, *reason;
748 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
749 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
753 if( !Client->bIsAuthed ) {
754 sendf(Client->Socket, "401 Not Authenticated\n");
759 iAmmount = atoi(ammount);
760 if( iAmmount <= 0 ) {
761 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
765 // Handle effective users
766 if( Client->EffectiveUID != -1 ) {
767 thisUid = Client->EffectiveUID;
770 thisUid = Client->UID;
774 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
777 sendf(Client->Socket, "200 Give OK\n");
780 sendf(Client->Socket, "402 Poor You\n");
783 sendf(Client->Socket, "500 Unknown error\n");
788 void Server_Cmd_ADD(tClient *Client, char *Args)
790 char *user, *ammount, *reason;
794 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
795 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
799 if( !Client->bIsAuthed ) {
800 sendf(Client->Socket, "401 Not Authenticated\n");
804 // Check user permissions
805 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
806 sendf(Client->Socket, "403 Not in coke\n");
811 uid = Bank_GetAcctByName(user);
813 sendf(Client->Socket, "404 Invalid user\n");
817 // You can't alter an internal account
818 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
819 sendf(Client->Socket, "404 Invalid user\n");
824 iAmmount = atoi(ammount);
825 if( iAmmount == 0 && ammount[0] != '0' ) {
826 sendf(Client->Socket, "407 Invalid Argument\n");
831 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
834 sendf(Client->Socket, "200 Add OK\n");
837 sendf(Client->Socket, "402 Poor Guy\n");
840 sendf(Client->Socket, "500 Unknown error\n");
845 void Server_Cmd_SET(tClient *Client, char *Args)
847 char *user, *ammount, *reason;
851 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
852 sendf(Client->Socket, "407 SET takes 3 arguments\n");
856 if( !Client->bIsAuthed ) {
857 sendf(Client->Socket, "401 Not Authenticated\n");
861 // Check user permissions
862 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
863 sendf(Client->Socket, "403 Not an admin\n");
868 uid = Bank_GetAcctByName(user);
870 sendf(Client->Socket, "404 Invalid user\n");
874 // You can't alter an internal account
875 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
876 sendf(Client->Socket, "404 Invalid user\n");
881 iAmmount = atoi(ammount);
882 if( iAmmount == 0 && ammount[0] != '0' ) {
883 sendf(Client->Socket, "407 Invalid Argument\n");
888 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
891 sendf(Client->Socket, "200 Add OK\n");
894 sendf(Client->Socket, "402 Poor Guy\n");
897 sendf(Client->Socket, "500 Unknown error\n");
902 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
906 int maxBal = INT_MAX, minBal = INT_MIN;
907 int flagMask = 0, flagVal = 0;
908 int sort = BANK_ITFLAG_SORT_NAME;
909 time_t lastSeenAfter=0, lastSeenBefore=0;
911 int flags; // Iterator flags
912 int balValue; // Balance value for iterator
913 time_t timeValue; // Time value for iterator
916 if( Args && strlen(Args) )
918 char *space = Args, *type, *val;
922 while(*type == ' ') type ++;
924 space = strchr(space, ' ');
925 if(space) *space = '\0';
928 val = strchr(type, ':');
935 if( strcmp(type, "min_balance") == 0 ) {
939 else if( strcmp(type, "max_balance") == 0 ) {
943 else if( strcmp(type, "flags") == 0 ) {
944 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
947 // - Last seen before timestamp
948 else if( strcmp(type, "last_seen_before") == 0 ) {
949 lastSeenAfter = atoll(val);
951 // - Last seen after timestamp
952 else if( strcmp(type, "last_seen_after") == 0 ) {
953 lastSeenAfter = atoll(val);
956 else if( strcmp(type, "sort") == 0 ) {
957 char *dash = strchr(val, '-');
962 if( strcmp(val, "name") == 0 ) {
963 sort = BANK_ITFLAG_SORT_NAME;
965 else if( strcmp(val, "balance") == 0 ) {
966 sort = BANK_ITFLAG_SORT_BAL;
968 else if( strcmp(val, "lastseen") == 0 ) {
969 sort = BANK_ITFLAG_SORT_LASTSEEN;
972 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
975 // Handle sort direction
977 if( strcmp(dash, "desc") == 0 ) {
978 sort |= BANK_ITFLAG_REVSORT;
981 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
988 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
995 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
1001 *space = ' '; // Repair (to be nice)
1003 while(*space == ' ') space ++;
1009 if( maxBal != INT_MAX ) {
1010 flags = sort|BANK_ITFLAG_MAXBALANCE;
1013 else if( minBal != INT_MIN ) {
1014 flags = sort|BANK_ITFLAG_MINBALANCE;
1021 if( lastSeenBefore ) {
1022 timeValue = lastSeenBefore;
1023 flags |= BANK_ITFLAG_SEENBEFORE;
1025 else if( lastSeenAfter ) {
1026 timeValue = lastSeenAfter;
1027 flags |= BANK_ITFLAG_SEENAFTER;
1032 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1034 // Get return number
1035 while( (i = Bank_IteratorNext(it)) != -1 )
1037 int bal = Bank_GetBalance(i);
1039 if( bal == INT_MIN ) continue;
1041 if( bal < minBal ) continue;
1042 if( bal > maxBal ) continue;
1047 Bank_DelIterator(it);
1050 sendf(Client->Socket, "201 Users %i\n", numRet);
1054 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1056 while( (i = Bank_IteratorNext(it)) != -1 )
1058 int bal = Bank_GetBalance(i);
1060 if( bal == INT_MIN ) continue;
1062 if( bal < minBal ) continue;
1063 if( bal > maxBal ) continue;
1065 _SendUserInfo(Client, i);
1068 Bank_DelIterator(it);
1070 sendf(Client->Socket, "200 List End\n");
1073 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1079 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1080 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1084 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1087 uid = Bank_GetAcctByName(user);
1089 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1091 sendf(Client->Socket, "404 Invalid user\n");
1095 _SendUserInfo(Client, uid);
1098 void _SendUserInfo(tClient *Client, int UserID)
1100 char *type, *disabled="", *door="";
1101 int flags = Bank_GetFlags(UserID);
1103 if( flags & USER_FLAG_INTERNAL ) {
1106 else if( flags & USER_FLAG_COKE ) {
1107 if( flags & USER_FLAG_ADMIN )
1108 type = "coke,admin";
1112 else if( flags & USER_FLAG_ADMIN ) {
1119 if( flags & USER_FLAG_DISABLED )
1120 disabled = ",disabled";
1121 if( flags & USER_FLAG_DOORGROUP )
1124 // TODO: User flags/type
1126 Client->Socket, "202 User %s %i %s%s%s\n",
1127 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1128 type, disabled, door
1132 void Server_Cmd_USERADD(tClient *Client, char *Args)
1137 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1138 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1142 // Check permissions
1143 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1144 sendf(Client->Socket, "403 Not a coke admin\n");
1148 // Try to create user
1149 if( Bank_CreateAcct(username) == -1 ) {
1150 sendf(Client->Socket, "404 User exists\n");
1155 char *thisName = Bank_GetAcctName(Client->UID);
1156 Log_Info("Account '%s' created by '%s'", username, thisName);
1160 sendf(Client->Socket, "200 User Added\n");
1163 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1165 char *username, *flags;
1166 int mask=0, value=0;
1170 if( Server_int_ParseArgs(0, Args, &username, &flags, NULL) ) {
1171 sendf(Client->Socket, "407 USER_FLAGS takes 2 arguments\n");
1175 // Check permissions
1176 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1177 sendf(Client->Socket, "403 Not a coke admin\n");
1182 uid = Bank_GetAcctByName(username);
1184 sendf(Client->Socket, "404 User '%s' not found\n", username);
1189 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1193 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1194 uid, username, mask, value);
1197 Bank_SetFlags(uid, mask, value);
1200 sendf(Client->Socket, "200 User Updated\n");
1203 // --- INTERNAL HELPERS ---
1204 void Debug(tClient *Client, const char *Format, ...)
1207 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1208 printf("[%i] ", Client->ID);
1209 va_start(args, Format);
1210 vprintf(Format, args);
1215 int sendf(int Socket, const char *Format, ...)
1220 va_start(args, Format);
1221 len = vsnprintf(NULL, 0, Format, args);
1226 va_start(args, Format);
1227 vsnprintf(buf, len+1, Format, args);
1230 #if DEBUG_TRACE_CLIENT
1231 printf("sendf: %s", buf);
1234 return send(Socket, buf, len, 0);
1238 // Takes a series of char *'s in
1240 * \brief Parse space-separated entries into
1242 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1247 va_start(args, ArgStr);
1252 while( (dest = va_arg(args, char **)) )
1258 savedChar = *ArgStr;
1260 while( (dest = va_arg(args, char **)) )
1262 // Trim leading spaces
1263 while( *ArgStr == ' ' || *ArgStr == '\t' )
1266 // ... oops, not enough arguments
1267 if( *ArgStr == '\0' )
1269 // NULL unset arguments
1272 } while( (dest = va_arg(args, char **)) );
1277 if( *ArgStr == '"' )
1282 while( *ArgStr && *ArgStr != '"' )
1289 // Read until a space
1290 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1293 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1299 // Oops, extra arguments, and greedy not set
1300 if( (savedChar == ' ' || savedChar == '\t') && !bUseLongLast ) {
1307 *ArgStr = savedChar;
1310 return 0; // Success!
1313 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1320 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1321 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1322 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1323 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1324 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1326 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1338 while( *Str == ' ' ) Str ++; // Eat whitespace
1339 space = strchr(Str, ','); // Find the end of the flag
1345 // Check for inversion/removal
1346 if( *Str == '!' || *Str == '-' ) {
1350 else if( *Str == '+' ) {
1354 // Check flag values
1355 for( i = 0; i < ciNumFlags; i ++ )
1357 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1358 *Mask |= cFLAGS[i].Mask;
1359 *Value &= ~cFLAGS[i].Mask;
1361 *Value |= cFLAGS[i].Value;
1367 if( i == ciNumFlags ) {
1369 strncpy(val, Str, len+1);
1370 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);