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 Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value);
74 int sendf(int Socket, const char *Format, ...);
78 const struct sClientCommand {
80 void (*Function)(tClient *Client, char *Arguments);
81 } gaServer_Commands[] = {
82 {"USER", Server_Cmd_USER},
83 {"PASS", Server_Cmd_PASS},
84 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
85 {"SETEUSER", Server_Cmd_SETEUSER},
86 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
87 {"ITEM_INFO", Server_Cmd_ITEMINFO},
88 {"DISPENSE", Server_Cmd_DISPENSE},
89 {"GIVE", Server_Cmd_GIVE},
90 {"DONATE", Server_Cmd_DONATE},
91 {"ADD", Server_Cmd_ADD},
92 {"SET", Server_Cmd_SET},
93 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
94 {"USER_INFO", Server_Cmd_USERINFO},
95 {"USER_ADD", Server_Cmd_USERADD},
96 {"USER_FLAGS", Server_Cmd_USERFLAGS}
98 #define NUM_COMMANDS ((int)(sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0])))
101 int giServer_Port = 1020;
102 int giServer_NextClientID = 1;
107 * \brief Open listenting socket and serve connections
109 void Server_Start(void)
112 struct sockaddr_in server_addr, client_addr;
114 atexit(Server_Cleanup);
117 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
118 if( giServer_Socket < 0 ) {
119 fprintf(stderr, "ERROR: Unable to create server socket\n");
123 // Make listen address
124 memset(&server_addr, 0, sizeof(server_addr));
125 server_addr.sin_family = AF_INET; // Internet Socket
126 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
127 server_addr.sin_port = htons(giServer_Port); // Port
130 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
131 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
137 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
138 fprintf(stderr, "ERROR: Unable to listen to socket\n");
143 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
147 uint len = sizeof(client_addr);
150 // Accept a connection
151 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
152 if(client_socket < 0) {
153 fprintf(stderr, "ERROR: Unable to accept client connection\n");
157 // Set a timeout on the user conneciton
160 tv.tv_sec = CLIENT_TIMEOUT;
162 if( setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) )
164 perror("setsockopt");
169 // Debug: Print the connection string
170 if(giDebugLevel >= 2) {
171 char ipstr[INET_ADDRSTRLEN];
172 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
173 printf("Client connection from %s:%i\n",
174 ipstr, ntohs(client_addr.sin_port));
177 // Doesn't matter what, localhost is trusted
178 if( ntohl( client_addr.sin_addr.s_addr ) == 0x7F000001 )
181 // Trusted Connections
182 if( ntohs(client_addr.sin_port) < 1024 )
184 // TODO: Make this runtime configurable
185 switch( ntohl( client_addr.sin_addr.s_addr ) )
187 case 0x7F000001: // 127.0.0.1 localhost
188 //case 0x825E0D00: // 130.95.13.0
189 case 0x825E0D07: // 130.95.13.7 motsugo
190 case 0x825E0D12: // 130.95.13.18 mussel
191 case 0x825E0D17: // 130.95.13.23 martello
199 // TODO: Multithread this?
200 Server_HandleClient(client_socket, bTrusted);
202 close(client_socket);
206 void Server_Cleanup(void)
208 printf("Close(%i)\n", giServer_Socket);
209 close(giServer_Socket);
213 * \brief Reads from a client socket and parses the command strings
214 * \param Socket Client socket number/handle
215 * \param bTrusted Is the client trusted?
217 void Server_HandleClient(int Socket, int bTrusted)
219 char inbuf[INPUT_BUFFER_SIZE];
221 int remspace = INPUT_BUFFER_SIZE-1;
225 memset(&clientInfo, 0, sizeof(clientInfo));
227 // Initialise Client info
228 clientInfo.Socket = Socket;
229 clientInfo.ID = giServer_NextClientID ++;
230 clientInfo.bIsTrusted = bTrusted;
231 clientInfo.EffectiveUID = -1;
236 * - The `buf` and `remspace` variables allow a line to span several
237 * calls to recv(), if a line is not completed in one recv() call
238 * it is saved to the beginning of `inbuf` and `buf` is updated to
241 // TODO: Use select() instead (to give a timeout)
242 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
245 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
249 while( (eol = strchr(start, '\n')) )
253 Server_ParseClientCommand(&clientInfo, start);
258 // Check if there was an incomplete line
259 if( *start != '\0' ) {
260 int tailBytes = bytes - (start-buf);
261 // Roll back in buffer
262 memcpy(inbuf, start, tailBytes);
263 remspace -= tailBytes;
265 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
267 remspace = INPUT_BUFFER_SIZE - 1;
272 remspace = INPUT_BUFFER_SIZE - 1;
278 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
282 if(giDebugLevel >= 2) {
283 printf("Client %i: Disconnected\n", clientInfo.ID);
288 * \brief Parses a client command and calls the required helper function
289 * \param Client Pointer to client state structure
290 * \param CommandString Command from client (single line of the command)
291 * \return Heap String to return to the client
293 void Server_ParseClientCommand(tClient *Client, char *CommandString)
302 // Split at first space
303 space = strchr(CommandString, ' ');
310 while( *space == ' ' ) space ++;
315 for( i = 0; args[i]; )
317 while( CommandString[i] != ' ' ) {
318 if( CommandString[i] == '"' ) {
319 while( !(CommandString[i] != '\\' CommandString[i+1] == '"' ) )
326 while( CommandString[i] == ' ' ) i ++;
333 for( i = 0; i < NUM_COMMANDS; i++ )
335 if(strcmp(CommandString, gaServer_Commands[i].Name) == 0) {
336 gaServer_Commands[i].Function(Client, args);
341 sendf(Client->Socket, "400 Unknown Command\n");
348 * \brief Set client username
350 * Usage: USER <username>
352 void Server_Cmd_USER(tClient *Client, char *Args)
354 char *space = strchr(Args, ' ');
355 if(space) *space = '\0'; // Remove characters after the ' '
359 Debug(Client, "Authenticating as '%s'", Args);
363 free(Client->Username);
364 Client->Username = strdup(Args);
367 // Create a salt (that changes if the username is changed)
368 // Yes, I know, I'm a little paranoid, but who isn't?
369 Client->Salt[0] = 0x21 + (rand()&0x3F);
370 Client->Salt[1] = 0x21 + (rand()&0x3F);
371 Client->Salt[2] = 0x21 + (rand()&0x3F);
372 Client->Salt[3] = 0x21 + (rand()&0x3F);
373 Client->Salt[4] = 0x21 + (rand()&0x3F);
374 Client->Salt[5] = 0x21 + (rand()&0x3F);
375 Client->Salt[6] = 0x21 + (rand()&0x3F);
376 Client->Salt[7] = 0x21 + (rand()&0x3F);
378 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
379 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
381 sendf(Client->Socket, "100 User Set\n");
386 * \brief Authenticate as a user
390 void Server_Cmd_PASS(tClient *Client, char *Args)
392 char *space = strchr(Args, ' ');
393 if(space) *space = '\0'; // Remove characters after the ' '
395 // Pass on to cokebank
396 Client->UID = Bank_GetUserAuth(Client->Salt, Client->Username, Args);
398 if( Client->UID != -1 ) {
399 Client->bIsAuthed = 1;
400 sendf(Client->Socket, "200 Auth OK\n");
404 sendf(Client->Socket, "401 Auth Failure\n");
408 * \brief Authenticate as a user without a password
410 * Usage: AUTOAUTH <user>
412 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
414 char *space = strchr(Args, ' ');
415 if(space) *space = '\0'; // Remove characters after the ' '
418 if( !Client->bIsTrusted ) {
420 Debug(Client, "Untrusted client attempting to AUTOAUTH");
421 sendf(Client->Socket, "401 Untrusted\n");
426 Client->UID = Bank_GetAcctByName( Args );
427 if( Client->UID < 0 ) {
429 Debug(Client, "Unknown user '%s'", Args);
430 sendf(Client->Socket, "401 Auth Failure\n");
434 // You can't be an internal account
435 if( Bank_GetFlags(Client->UID) & USER_FLAG_INTERNAL ) {
437 sendf(Client->Socket, "401 Auth Failure\n");
441 Client->bIsAuthed = 1;
444 Debug(Client, "Auto authenticated as '%s' (%i)", Args, Client->UID);
446 sendf(Client->Socket, "200 Auth OK\n");
450 * \brief Set effective user
452 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
456 space = strchr(Args, ' ');
458 if(space) *space = '\0';
460 if( !strlen(Args) ) {
461 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
465 // Check user permissions
466 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
467 sendf(Client->Socket, "403 Not in coke\n");
472 Client->EffectiveUID = Bank_GetAcctByName(Args);
473 if( Client->EffectiveUID == -1 ) {
474 sendf(Client->Socket, "404 User not found\n");
478 // You can't be an internal account
479 if( Bank_GetFlags(Client->EffectiveUID) & USER_FLAG_INTERNAL ) {
480 Client->EffectiveUID = -1;
481 sendf(Client->Socket, "404 User not found\n");
485 sendf(Client->Socket, "200 User set\n");
489 * \brief Enumerate the items that the server knows about
491 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
495 if( Args != NULL && strlen(Args) ) {
496 sendf(Client->Socket, "407 ENUM_ITEMS takes no arguments\n");
500 sendf(Client->Socket, "201 Items %i\n", giNumItems);
502 for( i = 0; i < giNumItems; i ++ ) {
503 sendf(Client->Socket,
504 "202 Item %s:%i %i %s\n",
505 gaItems[i].Handler->Name, gaItems[i].ID, gaItems[i].Price, gaItems[i].Name
509 sendf(Client->Socket, "200 List end\n");
512 tItem *_GetItemFromString(char *String)
516 char *colon = strchr(String, ':');
528 for( i = 0; i < giNumHandlers; i ++ )
530 if( strcmp(gaHandlers[i]->Name, type) == 0) {
531 handler = gaHandlers[i];
540 for( i = 0; i < giNumItems; i ++ )
542 if( gaItems[i].Handler != handler ) continue;
543 if( gaItems[i].ID != num ) continue;
550 * \brief Fetch information on a specific item
552 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
554 tItem *item = _GetItemFromString(Args);
557 sendf(Client->Socket, "406 Bad Item ID\n");
561 sendf(Client->Socket,
562 "202 Item %s:%i %i %s\n",
563 item->Handler->Name, item->ID, item->Price, item->Name
567 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
573 if( !Client->bIsAuthed ) {
574 sendf(Client->Socket, "401 Not Authenticated\n");
578 item = _GetItemFromString(Args);
580 sendf(Client->Socket, "406 Bad Item ID\n");
584 if( Client->EffectiveUID != -1 ) {
585 uid = Client->EffectiveUID;
591 switch( ret = DispenseItem( Client->UID, uid, item ) )
593 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
594 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
595 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
597 sendf(Client->Socket, "500 Dispense Error\n");
602 void Server_Cmd_GIVE(tClient *Client, char *Args)
604 char *recipient, *ammount, *reason;
608 if( !Client->bIsAuthed ) {
609 sendf(Client->Socket, "401 Not Authenticated\n");
615 ammount = strchr(Args, ' ');
617 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
623 reason = strchr(ammount, ' ');
625 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
632 uid = Bank_GetAcctByName(recipient);
634 sendf(Client->Socket, "404 Invalid target user\n");
638 // You can't alter an internal account
639 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
640 sendf(Client->Socket, "404 Invalid target user\n");
645 iAmmount = atoi(ammount);
646 if( iAmmount <= 0 ) {
647 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
651 if( Client->EffectiveUID != -1 ) {
652 thisUid = Client->EffectiveUID;
655 thisUid = Client->UID;
659 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
662 sendf(Client->Socket, "200 Give OK\n");
665 sendf(Client->Socket, "402 Poor You\n");
668 sendf(Client->Socket, "500 Unknown error\n");
673 void Server_Cmd_DONATE(tClient *Client, char *Args)
675 char *ammount, *reason;
679 if( !Client->bIsAuthed ) {
680 sendf(Client->Socket, "401 Not Authenticated\n");
686 // Get the start of the reason
687 reason = strchr(Args, ' ');
689 sendf(Client->Socket, "407 Invalid Argument, expected 2 parameters, 1 encountered\n");
695 // Check the end of the reason
696 if( strchr(reason, ' ') ) {
697 sendf(Client->Socket, "407 Invalid Argument, expected 2 parameters, more encountered\n");
702 iAmmount = atoi(ammount);
703 if( iAmmount <= 0 ) {
704 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
708 // Handle effective users
709 if( Client->EffectiveUID != -1 ) {
710 thisUid = Client->EffectiveUID;
713 thisUid = Client->UID;
717 switch( DispenseDonate(Client->UID, thisUid, iAmmount, reason) )
720 sendf(Client->Socket, "200 Give OK\n");
723 sendf(Client->Socket, "402 Poor You\n");
726 sendf(Client->Socket, "500 Unknown error\n");
731 void Server_Cmd_ADD(tClient *Client, char *Args)
733 char *user, *ammount, *reason;
736 if( !Client->bIsAuthed ) {
737 sendf(Client->Socket, "401 Not Authenticated\n");
743 ammount = strchr(Args, ' ');
745 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
751 reason = strchr(ammount, ' ');
753 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
759 // Check user permissions
760 if( !(Bank_GetFlags(Client->UID) & (USER_FLAG_COKE|USER_FLAG_ADMIN)) ) {
761 sendf(Client->Socket, "403 Not in coke\n");
766 uid = Bank_GetAcctByName(user);
768 sendf(Client->Socket, "404 Invalid user\n");
772 // You can't alter an internal account
773 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
774 sendf(Client->Socket, "404 Invalid user\n");
779 iAmmount = atoi(ammount);
780 if( iAmmount == 0 && ammount[0] != '0' ) {
781 sendf(Client->Socket, "407 Invalid Argument\n");
786 switch( DispenseAdd(Client->UID, uid, iAmmount, reason) )
789 sendf(Client->Socket, "200 Add OK\n");
792 sendf(Client->Socket, "402 Poor Guy\n");
795 sendf(Client->Socket, "500 Unknown error\n");
800 void Server_Cmd_SET(tClient *Client, char *Args)
802 char *user, *ammount, *reason;
805 if( !Client->bIsAuthed ) {
806 sendf(Client->Socket, "401 Not Authenticated\n");
812 ammount = strchr(Args, ' ');
814 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
820 reason = strchr(ammount, ' ');
822 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
828 // Check user permissions
829 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
830 sendf(Client->Socket, "403 Not an admin\n");
835 uid = Bank_GetAcctByName(user);
837 sendf(Client->Socket, "404 Invalid user\n");
841 // You can't alter an internal account
842 if( Bank_GetFlags(uid) & USER_FLAG_INTERNAL ) {
843 sendf(Client->Socket, "404 Invalid user\n");
848 iAmmount = atoi(ammount);
849 if( iAmmount == 0 && ammount[0] != '0' ) {
850 sendf(Client->Socket, "407 Invalid Argument\n");
855 switch( DispenseSet(Client->UID, uid, iAmmount, reason) )
858 sendf(Client->Socket, "200 Add OK\n");
861 sendf(Client->Socket, "402 Poor Guy\n");
864 sendf(Client->Socket, "500 Unknown error\n");
869 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
873 int maxBal = INT_MAX, minBal = INT_MIN;
874 int flagMask = 0, flagVal = 0;
875 int sort = BANK_ITFLAG_SORT_NAME;
876 time_t lastSeenAfter=0, lastSeenBefore=0;
878 int flags; // Iterator flags
879 int balValue; // Balance value for iterator
880 time_t timeValue; // Time value for iterator
883 if( Args && strlen(Args) )
885 char *space = Args, *type, *val;
890 space = strchr(space, ' ');
891 if(space) *space = '\0';
894 val = strchr(type, ':');
901 if( strcmp(type, "min_balance") == 0 ) {
905 else if( strcmp(type, "max_balance") == 0 ) {
909 else if( strcmp(type, "flags") == 0 ) {
910 if( Server_int_ParseFlags(Client, val, &flagMask, &flagVal) )
913 // - Last seen before timestamp
914 else if( strcmp(type, "last_seen_before") == 0 ) {
915 lastSeenAfter = atoll(val);
917 // - Last seen after timestamp
918 else if( strcmp(type, "last_seen_after") == 0 ) {
919 lastSeenAfter = atoll(val);
922 else if( strcmp(type, "sort") == 0 ) {
923 char *dash = strchr(val, '-');
928 if( strcmp(val, "name") == 0 ) {
929 sort = BANK_ITFLAG_SORT_NAME;
931 else if( strcmp(val, "balance") == 0 ) {
932 sort = BANK_ITFLAG_SORT_BAL;
934 else if( strcmp(val, "lastseen") == 0 ) {
935 sort = BANK_ITFLAG_SORT_LASTSEEN;
938 sendf(Client->Socket, "407 Unknown sort field ('%s')\n", val);
941 // Handle sort direction
943 if( strcmp(dash, "desc") == 0 ) {
944 sort |= BANK_ITFLAG_REVSORT;
947 sendf(Client->Socket, "407 Unknown sort direction '%s'\n", dash);
954 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s:%s'\n", type, val);
961 sendf(Client->Socket, "407 Unknown argument to ENUM_USERS '%s'\n", type);
967 *space = ' '; // Repair (to be nice)
969 while(*space == ' ') space ++;
975 if( maxBal != INT_MAX ) {
976 flags = sort|BANK_ITFLAG_MAXBALANCE;
979 else if( minBal != INT_MIN ) {
980 flags = sort|BANK_ITFLAG_MINBALANCE;
987 if( lastSeenBefore ) {
988 timeValue = lastSeenBefore;
989 flags |= BANK_ITFLAG_SEENBEFORE;
991 else if( lastSeenAfter ) {
992 timeValue = lastSeenAfter;
993 flags |= BANK_ITFLAG_SEENAFTER;
998 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1000 // Get return number
1001 while( (i = Bank_IteratorNext(it)) != -1 )
1003 int bal = Bank_GetBalance(i);
1005 if( bal == INT_MIN ) continue;
1007 if( bal < minBal ) continue;
1008 if( bal > maxBal ) continue;
1013 Bank_DelIterator(it);
1016 sendf(Client->Socket, "201 Users %i\n", numRet);
1020 it = Bank_Iterator(flagMask, flagVal, flags, balValue, timeValue);
1022 while( (i = Bank_IteratorNext(it)) != -1 )
1024 int bal = Bank_GetBalance(i);
1026 if( bal == INT_MIN ) continue;
1028 if( bal < minBal ) continue;
1029 if( bal > maxBal ) continue;
1031 _SendUserInfo(Client, i);
1034 Bank_DelIterator(it);
1036 sendf(Client->Socket, "200 List End\n");
1039 void Server_Cmd_USERINFO(tClient *Client, char *Args)
1045 space = strchr(user, ' ');
1046 if(space) *space = '\0';
1048 if( giDebugLevel ) Debug(Client, "User Info '%s'", user);
1051 uid = Bank_GetAcctByName(user);
1053 if( giDebugLevel >= 2 ) Debug(Client, "uid = %i", uid);
1055 sendf(Client->Socket, "404 Invalid user\n");
1059 _SendUserInfo(Client, uid);
1062 void _SendUserInfo(tClient *Client, int UserID)
1064 char *type, *disabled="", *door="";
1065 int flags = Bank_GetFlags(UserID);
1067 if( flags & USER_FLAG_INTERNAL ) {
1070 else if( flags & USER_FLAG_COKE ) {
1071 if( flags & USER_FLAG_ADMIN )
1072 type = "coke,admin";
1076 else if( flags & USER_FLAG_ADMIN ) {
1083 if( flags & USER_FLAG_DISABLED )
1084 disabled = ",disabled";
1085 if( flags & USER_FLAG_DOORGROUP )
1088 // TODO: User flags/type
1090 Client->Socket, "202 User %s %i %s%s\n",
1091 Bank_GetAcctName(UserID), Bank_GetBalance(UserID),
1096 void Server_Cmd_USERADD(tClient *Client, char *Args)
1098 char *username, *space;
1100 // Check permissions
1101 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1102 sendf(Client->Socket, "403 Not a coke admin\n");
1108 while( *username == ' ' ) username ++;
1109 space = strchr(username, ' ');
1110 if(space) *space = '\0';
1112 // Try to create user
1113 if( Bank_CreateAcct(username) == -1 ) {
1114 sendf(Client->Socket, "404 User exists\n");
1119 char *thisName = Bank_GetAcctName(Client->UID);
1120 Log_Info("Account '%s' created by '%s'", username, thisName);
1124 sendf(Client->Socket, "200 User Added\n");
1127 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
1129 char *username, *flags;
1131 int mask=0, value=0;
1134 // Check permissions
1135 if( !(Bank_GetFlags(Client->UID) & USER_FLAG_ADMIN) ) {
1136 sendf(Client->Socket, "403 Not a coke admin\n");
1143 while( *username == ' ' ) username ++;
1144 space = strchr(username, ' ');
1146 sendf(Client->Socket, "407 USER_FLAGS requires 2 arguments, 1 given\n");
1152 while( *flags == ' ' ) flags ++;
1153 space = strchr(flags, ' ');
1154 if(space) *space = '\0';
1157 uid = Bank_GetAcctByName(username);
1159 sendf(Client->Socket, "404 User '%s' not found\n", username);
1164 if( Server_int_ParseFlags(Client, flags, &mask, &value) )
1168 Bank_SetFlags(uid, mask, value);
1171 sendf(Client->Socket, "200 User Updated\n");
1174 // --- INTERNAL HELPERS ---
1175 void Debug(tClient *Client, const char *Format, ...)
1178 //printf("%010i [%i] ", (int)time(NULL), Client->ID);
1179 printf("[%i] ", Client->ID);
1180 va_start(args, Format);
1181 vprintf(Format, args);
1186 int sendf(int Socket, const char *Format, ...)
1191 va_start(args, Format);
1192 len = vsnprintf(NULL, 0, Format, args);
1197 va_start(args, Format);
1198 vsnprintf(buf, len+1, Format, args);
1201 #if DEBUG_TRACE_CLIENT
1202 printf("sendf: %s", buf);
1205 return send(Socket, buf, len, 0);
1209 int Server_int_ParseFlags(tClient *Client, const char *Str, int *Mask, int *Value)
1216 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED}
1217 ,{"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP}
1218 ,{"coke", USER_FLAG_COKE, USER_FLAG_COKE}
1219 ,{"admin", USER_FLAG_ADMIN, USER_FLAG_ADMIN}
1220 ,{"internal", USER_FLAG_INTERNAL, USER_FLAG_INTERNAL}
1222 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
1234 while( *Str == ' ' ) Str ++; // Eat whitespace
1235 space = strchr(Str, ','); // Find the end of the flag
1241 // Check for inversion/removal
1242 if( *Str == '!' || *Str == '-' ) {
1246 else if( *Str == '+' ) {
1250 // Check flag values
1251 for( i = 0; i < ciNumFlags; i ++ )
1253 if( strncmp(Str, cFLAGS[i].Name, len) == 0 ) {
1254 *Mask |= cFLAGS[i].Mask;
1255 *Value &= ~cFLAGS[i].Mask;
1257 *Value |= cFLAGS[i].Value;
1263 if( i == ciNumFlags ) {
1265 strncpy(val, Str, len+1);
1266 sendf(Client->Socket, "407 Unknown flag value '%s'\n", val);