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 = 1020;
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 uint len = sizeof(client_addr);
151 // Accept a connection
152 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
153 if(client_socket < 0) {
154 fprintf(stderr, "ERROR: Unable to accept client connection\n");
158 // Set a timeout on the user conneciton
161 tv.tv_sec = CLIENT_TIMEOUT;
163 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
165 perror("setsockopt");
170 // Debug: Print the connection string
171 if(giDebugLevel >= 2) {
172 char ipstr[INET_ADDRSTRLEN];
173 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
174 printf("Client connection from %s:%i\n",
175 ipstr, ntohs(client_addr.sin_port));
178 // Doesn't matter what, localhost is trusted
179 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
182 // Trusted Connections
183 if( ntohs(client_addr.sin_port) < 1024 )
185 // TODO: Make this runtime configurable
186 switch( ntohl( client_addr.sin_addr.s_addr ) )
188 case 0x7F000001: // 127.0.0.1 localhost
189 // case 0x825F0D00: // 130.95.13.0
190 case 0x825F0D07: // 130.95.13.7 motsugo
191 case 0x825F0D11: // 130.95.13.17 mermaid
192 case 0x825F0D12: // 130.95.13.18 mussel
193 case 0x825F0D17: // 130.95.13.23 martello
194 case 0x825F0D42: // 130.95.13.66 heathred
202 // TODO: Multithread this?
203 Server_HandleClient(client_socket, bTrusted);
205 close(client_socket);
209 void Server_Cleanup(void)
211 printf("Close(%i)\n", giServer_Socket);
212 close(giServer_Socket);
216 * \brief Reads from a client socket and parses the command strings
217 * \param Socket Client socket number/handle
218 * \param bTrusted Is the client trusted?
220 void Server_HandleClient(int Socket, int bTrusted)
222 char inbuf[INPUT_BUFFER_SIZE];
224 int remspace = INPUT_BUFFER_SIZE-1;
228 memset(&clientInfo, 0, sizeof(clientInfo));
230 // Initialise Client info
231 clientInfo.Socket = Socket;
232 clientInfo.ID = giServer_NextClientID ++;
233 clientInfo.bIsTrusted = bTrusted;
234 clientInfo.EffectiveUID = -1;
239 * - The `buf` and `remspace` variables allow a line to span several
240 * calls to recv(), if a line is not completed in one recv() call
241 * it is saved to the beginning of `inbuf` and `buf` is updated to
244 // TODO: Use select() instead (to give a timeout)
245 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
248 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
252 while( (eol = strchr(start, '\n')) )
256 Server_ParseClientCommand(&clientInfo, start);
261 // Check if there was an incomplete line
262 if( *start != '\0' ) {
263 int tailBytes = bytes - (start-buf);
264 // Roll back in buffer
265 memcpy(inbuf, start, tailBytes);
266 remspace -= tailBytes;
268 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
270 remspace = INPUT_BUFFER_SIZE - 1;
275 remspace = INPUT_BUFFER_SIZE - 1;
281 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
285 if(giDebugLevel >= 2) {
286 printf("Client %i: Disconnected\n", clientInfo.ID);
291 * \brief Parses a client command and calls the required helper function
292 * \param Client Pointer to client state structure
293 * \param CommandString Command from client (single line of the command)
294 * \return Heap String to return to the client
296 void Server_ParseClientCommand(tClient *Client, char *CommandString)
298 char *command, *args;
305 if( Server_int_ParseArgs(1, CommandString, &command, &args, NULL) )
307 printf("command=%s, args=%s\n", command, args);
308 // Is this an error? (just ignore for now)
314 for( i = 0; i < NUM_COMMANDS; i++ )
316 if(strcmp(CommandString, gaServer_Commands[i].Name) == 0) {
317 gaServer_Commands[i].Function(Client, args);
322 sendf(Client->Socket, "400 Unknown Command\n");
329 * \brief Set client username
331 * Usage: USER <username>
333 void Server_Cmd_USER(tClient *Client, char *Args)
337 if( Server_int_ParseArgs(0, Args, &username, NULL) )
339 sendf(Client->Socket, "407 USER takes 1 argument\n");
345 Debug(Client, "Authenticating as '%s'", username);
349 free(Client->Username);
350 Client->Username = strdup(username);
353 // Create a salt (that changes if the username is changed)
354 // Yes, I know, I'm a little paranoid, but who isn't?
355 Client->Salt[0] = 0x21 + (rand()&0x3F);
356 Client->Salt[1] = 0x21 + (rand()&0x3F);
357 Client->Salt[2] = 0x21 + (rand()&0x3F);
358 Client->Salt[3] = 0x21 + (rand()&0x3F);
359 Client->Salt[4] = 0x21 + (rand()&0x3F);
360 Client->Salt[5] = 0x21 + (rand()&0x3F);
361 Client->Salt[6] = 0x21 + (rand()&0x3F);
362 Client->Salt[7] = 0x21 + (rand()&0x3F);
364 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
365 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
367 sendf(Client->Socket, "100 User Set\n");
372 * \brief Authenticate as a user
376 void Server_Cmd_PASS(tClient *Client, char *Args)
380 if( Server_int_ParseArgs(0, Args, &passhash, NULL) )
382 sendf(Client->Socket, "407 PASS takes 1 argument\n");
386 // Pass on to cokebank
387 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, passhash);
389 if( Client->UID != -1 ) {
390 Client->bIsAuthed = 1;
391 sendf(Client->Socket, "200 Auth OK\n");
395 sendf(Client->Socket, "401 Auth Failure\n");
399 * \brief Authenticate as a user without a password
401 * Usage: AUTOAUTH <user>
403 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
407 if( Server_int_ParseArgs(0, Args, &username, NULL) )
409 sendf(Client->Socket, "407 AUTOAUTH takes 1 argument\n");
414 if( !Client->bIsTrusted ) {
416 Debug(Client, "Untrusted client attempting to AUTOAUTH");
417 sendf(Client->Socket, "401 Untrusted\n");
422 Client->UID = Bank_GetAcctByName( username );
423 if( Client->UID < 0 ) {
425 Debug(Client, "Unknown user '%s'", username);
426 sendf(Client->Socket, "401 Auth Failure\n");
430 // You can't be an internal account
431 if( Bank_GetFlags(Client->UID) & USER_FLAG_INTERNAL ) {
433 sendf(Client->Socket, "401 Auth Failure\n");
437 Client->bIsAuthed = 1;
440 Debug(Client, "Auto authenticated as '%s' (%i)", username, Client->UID);
442 sendf(Client->Socket, "200 Auth OK\n");
446 * \brief Set effective user
448 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
452 if( Server_int_ParseArgs(0, Args, &username, NULL) )
454 sendf(Client->Socket, "407 SETEUSER takes 1 argument\n");
458 if( !strlen(Args) ) {
459 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
463 // Check user permissions
464 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
465 sendf(Client->Socket, "403 Not in coke\n");
470 Client->EffectiveUID = Bank_GetAcctByName(username);
471 if( Client->EffectiveUID == -1 ) {
472 sendf(Client->Socket, "404 User not found\n");
476 // You can't be an internal account
477 if( Bank_GetFlags(Client->EffectiveUID) & USER_FLAG_INTERNAL ) {
478 Client->EffectiveUID = -1;
479 sendf(Client->Socket, "404 User not found\n");
483 sendf(Client->Socket, "200 User set\n");
487 * \brief Enumerate the items that the server knows about
489 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
493 if( Args != NULL && strlen(Args) ) {
494 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
500 for( i = 0; i < giNumItems; i ++ ) {
501 if( gaItems[i].bHidden ) continue;
505 sendf(Client->Socket, "201 Items %i\n", count);
507 for( i = 0; i < giNumItems; i ++ ) {
508 if( gaItems[i].bHidden ) continue;
509 sendf(Client->Socket,
510 "202 Item %s:%i %i %s\n",
511 gaItems[i].Handler->Name, gaItems[i].ID, gaItems[i].Price, gaItems[i].Name
515 sendf(Client->Socket, "200 List end\n");
518 tItem *_GetItemFromString(char *String)
522 char *colon = strchr(String, ':');
534 for( i = 0; i < giNumHandlers; i ++ )
536 if( strcmp(gaHandlers[i]->Name, type) == 0) {
537 handler = gaHandlers[i];
546 for( i = 0; i < giNumItems; i ++ )
548 if( gaItems[i].Handler != handler ) continue;
549 if( gaItems[i].ID != num ) continue;
556 * \brief Fetch information on a specific item
558 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
563 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
564 sendf(Client->Socket, "407 ITEMINFO takes 1 argument\n");
567 item = _GetItemFromString(Args);
570 sendf(Client->Socket, "406 Bad Item ID\n");
574 sendf(Client->Socket,
575 "202 Item %s:%i %i %s\n",
576 item->Handler->Name, item->ID, item->Price, item->Name
580 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
587 if( Server_int_ParseArgs(0, Args, &itemname, NULL) ) {
588 sendf(Client->Socket, "407 DISPENSE takes only 1 argument\n");
592 if( !Client->bIsAuthed ) {
593 sendf(Client->Socket, "401 Not Authenticated\n");
597 item = _GetItemFromString(itemname);
599 sendf(Client->Socket, "406 Bad Item ID\n");
603 if( Client->EffectiveUID != -1 ) {
604 uid = Client->EffectiveUID;
610 switch( ret = DispenseItem( Client->UID, uid, item ) )
612 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
613 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
614 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
616 sendf(Client->Socket, "500 Dispense Error\n");
621 void Server_Cmd_GIVE(tClient *Client, char *Args)
623 char *recipient, *ammount, *reason;
628 if( Server_int_ParseArgs(1, Args, &recipient, &ammount, &reason, NULL) ) {
629 sendf(Client->Socket, "407 GIVE takes only 3 arguments\n");
633 if( !Client->bIsAuthed ) {
634 sendf(Client->Socket, "401 Not Authenticated\n");
639 uid = Bank_GetAcctByName(recipient);
641 sendf(Client->Socket, "404 Invalid target user\n");
645 // You can't alter an internal account
646 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
647 sendf(Client->Socket, "404 Invalid target user\n");
652 iAmmount = atoi(ammount);
653 if( iAmmount <= 0 ) {
654 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
658 if( Client->EffectiveUID != -1 ) {
659 thisUid = Client->EffectiveUID;
662 thisUid = Client->UID;
666 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
669 sendf(Client->Socket, "200 Give OK\n");
672 sendf(Client->Socket, "402 Poor You\n");
675 sendf(Client->Socket, "500 Unknown error\n");
680 void Server_Cmd_DONATE(tClient *Client, char *Args)
682 char *ammount, *reason;
687 if( Server_int_ParseArgs(1, Args, &ammount, &reason, NULL) ) {
688 sendf(Client->Socket, "407 DONATE takes 2 arguments\n");
692 if( !Client->bIsAuthed ) {
693 sendf(Client->Socket, "401 Not Authenticated\n");
698 iAmmount = atoi(ammount);
699 if( iAmmount <= 0 ) {
700 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
704 // Handle effective users
705 if( Client->EffectiveUID != -1 ) {
706 thisUid = Client->EffectiveUID;
709 thisUid = Client->UID;
713 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
716 sendf(Client->Socket, "200 Give OK\n");
719 sendf(Client->Socket, "402 Poor You\n");
722 sendf(Client->Socket, "500 Unknown error\n");
727 void Server_Cmd_ADD(tClient *Client, char *Args)
729 char *user, *ammount, *reason;
733 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
734 sendf(Client->Socket, "407 ADD takes 3 arguments\n");
738 if( !Client->bIsAuthed ) {
739 sendf(Client->Socket, "401 Not Authenticated\n");
743 // Check user permissions
744 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
745 sendf(Client->Socket, "403 Not in coke\n");
750 uid = Bank_GetAcctByName(user);
752 sendf(Client->Socket, "404 Invalid user\n");
756 // You can't alter an internal account
757 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
758 sendf(Client->Socket, "404 Invalid user\n");
763 iAmmount = atoi(ammount);
764 if( iAmmount == 0 && ammount[0] != '0' ) {
765 sendf(Client->Socket, "407 Invalid Argument\n");
770 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
773 sendf(Client->Socket, "200 Add OK\n");
776 sendf(Client->Socket, "402 Poor Guy\n");
779 sendf(Client->Socket, "500 Unknown error\n");
784 void Server_Cmd_SET(tClient *Client, char *Args)
786 char *user, *ammount, *reason;
790 if( Server_int_ParseArgs(1, Args, &user, &ammount, &reason, NULL) ) {
791 sendf(Client->Socket, "407 SET takes 3 arguments\n");
795 if( !Client->bIsAuthed ) {
796 sendf(Client->Socket, "401 Not Authenticated\n");
800 // Check user permissions
801 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
802 sendf(Client->Socket, "403 Not an admin\n");
807 uid = Bank_GetAcctByName(user);
809 sendf(Client->Socket, "404 Invalid user\n");
813 // You can't alter an internal account
814 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
815 sendf(Client->Socket, "404 Invalid user\n");
820 iAmmount = atoi(ammount);
821 if( iAmmount == 0 && ammount[0] != '0' ) {
822 sendf(Client->Socket, "407 Invalid Argument\n");
827 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
830 sendf(Client->Socket, "200 Add OK\n");
833 sendf(Client->Socket, "402 Poor Guy\n");
836 sendf(Client->Socket, "500 Unknown error\n");
841 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
845 int maxBal = INT_MAX, minBal = INT_MIN;
846 int flagMask = 0, flagVal = 0;
847 int sort = BANK_ITFLAG_SORT_NAME;
848 time_t lastSeenAfter=0, lastSeenBefore=0;
850 int flags; // Iterator flags
851 int balValue; // Balance value for iterator
852 time_t timeValue; // Time value for iterator
855 if( Args && strlen(Args) )
857 char *space = Args, *type, *val;
861 while(*type == ' ') type ++;
863 space = strchr(space, ' ');
864 if(space) *space = '\0';
867 val = strchr(type, ':');
874 if( strcmp(type, "min_balance") == 0 ) {
878 else if( strcmp(type, "max_balance") == 0 ) {
882 else if( strcmp(type, "flags") == 0 ) {
883 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
886 // - Last seen before timestamp
887 else if( strcmp(type, "last_seen_before") == 0 ) {
888 lastSeenAfter = atoll(val);
890 // - Last seen after timestamp
891 else if( strcmp(type, "last_seen_after") == 0 ) {
892 lastSeenAfter = atoll(val);
895 else if( strcmp(type, "sort") == 0 ) {
896 char *dash = strchr(val, '-');
901 if( strcmp(val, "name") == 0 ) {
902 sort = BANK_ITFLAG_SORT_NAME;
904 else if( strcmp(val, "balance") == 0 ) {
905 sort = BANK_ITFLAG_SORT_BAL;
907 else if( strcmp(val, "lastseen") == 0 ) {
908 sort = BANK_ITFLAG_SORT_LASTSEEN;
911 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
914 // Handle sort direction
916 if( strcmp(dash, "desc") == 0 ) {
917 sort |= BANK_ITFLAG_REVSORT;
920 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
927 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
934 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
940 *space = ' '; // Repair (to be nice)
942 while(*space == ' ') space ++;
948 if( maxBal != INT_MAX ) {
949 flags = sort|BANK_ITFLAG_MAXBALANCE;
952 else if( minBal != INT_MIN ) {
953 flags = sort|BANK_ITFLAG_MINBALANCE;
960 if( lastSeenBefore ) {
961 timeValue = lastSeenBefore;
962 flags |= BANK_ITFLAG_SEENBEFORE;
964 else if( lastSeenAfter ) {
965 timeValue = lastSeenAfter;
966 flags |= BANK_ITFLAG_SEENAFTER;
971 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
974 while( (i = Bank_IteratorNext(it)) != -1 )
976 int bal = Bank_GetBalance(i);
978 if( bal == INT_MIN ) continue;
980 if( bal < minBal ) continue;
981 if( bal > maxBal ) continue;
986 Bank_DelIterator(it);
989 sendf(Client->Socket, "201 Users %i\n", numRet);
993 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
995 while( (i = Bank_IteratorNext(it)) != -1 )
997 int bal = Bank_GetBalance(i);
999 if( bal == INT_MIN ) continue;
1001 if( bal < minBal ) continue;
1002 if( bal > maxBal ) continue;
1004 _SendUserInfo(Client, i);
1007 Bank_DelIterator(it);
1009 sendf(Client->Socket, "200 List End\n");
1012 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1018 if( Server_int_ParseArgs(0, Args, &user, NULL) ) {
1019 sendf(Client->Socket, "407 USER_INFO takes 1 argument\n");
1023 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1026 uid = Bank_GetAcctByName(user);
1028 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1030 sendf(Client->Socket, "404 Invalid user\n");
1034 _SendUserInfo(Client, uid);
1037 void _SendUserInfo(tClient *Client, int UserID)
1039 char *type, *disabled="", *door="";
1040 int flags = Bank_GetFlags(UserID);
1042 if( flags & USER_FLAG_INTERNAL ) {
1045 else if( flags & USER_FLAG_COKE ) {
1046 if( flags & USER_FLAG_ADMIN )
1047 type = "coke,admin";
1051 else if( flags & USER_FLAG_ADMIN ) {
1058 if( flags & USER_FLAG_DISABLED )
1059 disabled = ",disabled";
1060 if( flags & USER_FLAG_DOORGROUP )
1063 // TODO: User flags/type
1065 Client->Socket, "202 User %s %i %s%s%s\n",
1066 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1067 type, disabled, door
1071 void Server_Cmd_USERADD(tClient *Client, char *Args)
1076 if( Server_int_ParseArgs(0, Args, &username, NULL) ) {
1077 sendf(Client->Socket, "407 USER_ADD takes 1 argument\n");
1081 // Check permissions
1082 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1083 sendf(Client->Socket, "403 Not a coke admin\n");
1087 // Try to create user
1088 if( Bank_CreateAcct(username) == -1 ) {
1089 sendf(Client->Socket, "404 User exists\n");
1094 char *thisName = Bank_GetAcctName(Client->UID);
1095 Log_Info("Account '%s' created by '%s'", username, thisName);
1099 sendf(Client->Socket, "200 User Added\n");
1102 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1104 char *username, *flags;
1105 int mask=0, value=0;
1109 if( Server_int_ParseArgs(0, Args, &username, &flags, NULL) ) {
1110 sendf(Client->Socket, "407 USER_FLAGS takes 2 arguments\n");
1114 // Check permissions
1115 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1116 sendf(Client->Socket, "403 Not a coke admin\n");
1121 uid = Bank_GetAcctByName(username);
1123 sendf(Client->Socket, "404 User '%s' not found\n", username);
1128 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1132 Debug(Client, "Set %i(%s) flags to %x (masked %x)\n",
1133 uid, username, mask, value);
1136 Bank_SetFlags(uid, mask, value);
1139 sendf(Client->Socket, "200 User Updated\n");
1142 // --- INTERNAL HELPERS ---
1143 void Debug(tClient *Client, const char *Format, ...)
1146 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1147 printf("[%i] ", Client->ID);
1148 va_start(args, Format);
1149 vprintf(Format, args);
1154 int sendf(int Socket, const char *Format, ...)
1159 va_start(args, Format);
1160 len = vsnprintf(NULL, 0, Format, args);
1165 va_start(args, Format);
1166 vsnprintf(buf, len+1, Format, args);
1169 #if DEBUG_TRACE_CLIENT
1170 printf("sendf: %s", buf);
1173 return send(Socket, buf, len, 0);
1177 // Takes a series of char *'s in
1179 * \brief Parse space-separated entries into
1181 int Server_int_ParseArgs(int bUseLongLast, char *ArgStr, ...)
1184 char savedChar = *ArgStr;
1186 va_start(args, ArgStr);
1188 printf("Server_int_ParseArgs: ArgStr = '%s'\n", ArgStr);
1190 while( (dest = va_arg(args, char **)) )
1192 printf(" dest = %p\n", dest);
1193 // Trim leading spaces
1194 while( *ArgStr == ' ' || *ArgStr == '\t' )
1197 // ... oops, not enough arguments
1198 if( *ArgStr == '\0' )
1200 // NULL unset arguments
1203 } while( (dest = va_arg(args, char **)) );
1210 if( *ArgStr == '"' )
1213 while( *ArgStr && *ArgStr != '"' )
1218 // Read until a space
1219 while( *ArgStr && *ArgStr != ' ' && *ArgStr != '\t' )
1222 savedChar = *ArgStr; // savedChar is used to un-mangle the last string
1227 // Oops, extra arguments, and greedy not set
1228 if( savedChar == ' ' && bUseLongLast )
1234 *ArgStr = savedChar;
1239 return 0; // Success!
1242 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1249 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1250 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1251 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1252 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1253 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1255 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1267 while( *Str == ' ' ) Str ++; // Eat whitespace
1268 space = strchr(Str, ','); // Find the end of the flag
1274 // Check for inversion/removal
1275 if( *Str == '!' || *Str == '-' ) {
1279 else if( *Str == '+' ) {
1283 // Check flag values
1284 for( i = 0; i < ciNumFlags; i ++ )
1286 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1287 *Mask |= cFLAGS[i].Mask;
1288 *Value &= ~cFLAGS[i].Mask;
1290 *Value |= cFLAGS[i].Value;
1296 if( i == ciNumFlags ) {
1298 strncpy(val, Str, len+1);
1299 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);