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
27 #define HASH_TYPE SHA1
28 #define HASH_LENGTH 20
30 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
33 typedef struct sClient
35 int Socket; // Client socket ID
38 int bIsTrusted; // Is the connection from a trusted host/port
49 void Server_Start(void);
50 void Server_Cleanup(void);
51 void Server_HandleClient(int Socket, int bTrusted);
52 void Server_ParseClientCommand(tClient *Client, char *CommandString);
54 void Server_Cmd_USER(tClient *Client, char *Args);
55 void Server_Cmd_PASS(tClient *Client, char *Args);
56 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
57 void Server_Cmd_SETEUSER(tClient *Client, char *Args);
58 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
59 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
60 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
61 void Server_Cmd_GIVE(tClient *Client, char *Args);
62 void Server_Cmd_ADD(tClient *Client, char *Args);
63 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
64 void Server_Cmd_USERINFO(tClient *Client, char *Args);
65 void _SendUserInfo(tClient *Client, int UserID);
66 void Server_Cmd_USERADD(tClient *Client, char *Args);
67 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
69 int sendf(int Socket, const char *Format, ...);
73 const struct sClientCommand {
75 void (*Function)(tClient *Client, char *Arguments);
76 } gaServer_Commands[] = {
77 {"USER", Server_Cmd_USER},
78 {"PASS", Server_Cmd_PASS},
79 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
80 {"SETEUSER", Server_Cmd_SETEUSER},
81 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
82 {"ITEM_INFO", Server_Cmd_ITEMINFO},
83 {"DISPENSE", Server_Cmd_DISPENSE},
84 {"GIVE", Server_Cmd_GIVE},
85 {"ADD", Server_Cmd_ADD},
86 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
87 {"USER_INFO", Server_Cmd_USERINFO},
88 {"USER_ADD", Server_Cmd_USERADD},
89 {"USER_FLAGS", Server_Cmd_USERFLAGS}
91 #define NUM_COMMANDS (sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0]))
94 int giServer_Port = 1020;
95 int giServer_NextClientID = 1;
100 * \brief Open listenting socket and serve connections
102 void Server_Start(void)
105 struct sockaddr_in server_addr, client_addr;
107 atexit(Server_Cleanup);
110 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
111 if( giServer_Socket < 0 ) {
112 fprintf(stderr, "ERROR: Unable to create server socket\n");
116 // Make listen address
117 memset(&server_addr, 0, sizeof(server_addr));
118 server_addr.sin_family = AF_INET; // Internet Socket
119 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
120 server_addr.sin_port = htons(giServer_Port); // Port
123 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
124 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
130 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
131 fprintf(stderr, "ERROR: Unable to listen to socket\n");
136 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
140 uint len = sizeof(client_addr);
143 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
144 if(client_socket < 0) {
145 fprintf(stderr, "ERROR: Unable to accept client connection\n");
149 if(giDebugLevel >= 2) {
150 char ipstr[INET_ADDRSTRLEN];
151 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
152 printf("Client connection from %s:%i\n",
153 ipstr, ntohs(client_addr.sin_port));
156 // Trusted Connections
157 if( ntohs(client_addr.sin_port) < 1024 )
159 // TODO: Make this runtime configurable
160 switch( ntohl( client_addr.sin_addr.s_addr ) )
162 case 0x7F000001: // 127.0.0.1 localhost
163 //case 0x825E0D00: // 130.95.13.0
164 case 0x825E0D12: // 130.95.13.18 mussel
165 case 0x825E0D17: // 130.95.13.23 martello
173 // TODO: Multithread this?
174 Server_HandleClient(client_socket, bTrusted);
176 close(client_socket);
180 void Server_Cleanup(void)
182 printf("Close(%i)\n", giServer_Socket);
183 close(giServer_Socket);
187 * \brief Reads from a client socket and parses the command strings
188 * \param Socket Client socket number/handle
189 * \param bTrusted Is the client trusted?
191 void Server_HandleClient(int Socket, int bTrusted)
193 char inbuf[INPUT_BUFFER_SIZE];
195 int remspace = INPUT_BUFFER_SIZE-1;
197 tClient clientInfo = {0};
199 // Initialise Client info
200 clientInfo.Socket = Socket;
201 clientInfo.ID = giServer_NextClientID ++;
202 clientInfo.bIsTrusted = bTrusted;
207 * - The `buf` and `remspace` variables allow a line to span several
208 * calls to recv(), if a line is not completed in one recv() call
209 * it is saved to the beginning of `inbuf` and `buf` is updated to
212 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
215 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
219 while( (eol = strchr(start, '\n')) )
223 Server_ParseClientCommand(&clientInfo, start);
228 // Check if there was an incomplete line
229 if( *start != '\0' ) {
230 int tailBytes = bytes - (start-buf);
231 // Roll back in buffer
232 memcpy(inbuf, start, tailBytes);
233 remspace -= tailBytes;
235 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
237 remspace = INPUT_BUFFER_SIZE - 1;
242 remspace = INPUT_BUFFER_SIZE - 1;
248 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
252 if(giDebugLevel >= 2) {
253 printf("Client %i: Disconnected\n", clientInfo.ID);
258 * \brief Parses a client command and calls the required helper function
259 * \param Client Pointer to client state structure
260 * \param CommandString Command from client (single line of the command)
261 * \return Heap String to return to the client
263 void Server_ParseClientCommand(tClient *Client, char *CommandString)
272 // Split at first space
273 space = strchr(CommandString, ' ');
280 while( *space == ' ' ) space ++;
285 for( i = 0; args[i]; )
287 while( CommandString[i] != ' ' ) {
288 if( CommandString[i] == '"' ) {
289 while( !(CommandString[i] != '\\' CommandString[i+1] == '"' ) )
296 while( CommandString[i] == ' ' ) i ++;
303 for( i = 0; i < NUM_COMMANDS; i++ )
305 if(strcmp(CommandString, gaServer_Commands[i].Name) == 0) {
306 gaServer_Commands[i].Function(Client, args);
311 sendf(Client->Socket, "400 Unknown Command\n");
318 * \brief Set client username
320 * Usage: USER <username>
322 void Server_Cmd_USER(tClient *Client, char *Args)
324 char *space = strchr(Args, ' ');
325 if(space) *space = '\0'; // Remove characters after the ' '
329 printf("Client %i authenticating as '%s'\n", Client->ID, Args);
333 free(Client->Username);
334 Client->Username = strdup(Args);
337 // Create a salt (that changes if the username is changed)
338 // Yes, I know, I'm a little paranoid, but who isn't?
339 Client->Salt[0] = 0x21 + (rand()&0x3F);
340 Client->Salt[1] = 0x21 + (rand()&0x3F);
341 Client->Salt[2] = 0x21 + (rand()&0x3F);
342 Client->Salt[3] = 0x21 + (rand()&0x3F);
343 Client->Salt[4] = 0x21 + (rand()&0x3F);
344 Client->Salt[5] = 0x21 + (rand()&0x3F);
345 Client->Salt[6] = 0x21 + (rand()&0x3F);
346 Client->Salt[7] = 0x21 + (rand()&0x3F);
348 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
349 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
351 sendf(Client->Socket, "100 User Set\n");
356 * \brief Authenticate as a user
360 void Server_Cmd_PASS(tClient *Client, char *Args)
362 char *space = strchr(Args, ' ');
363 if(space) *space = '\0'; // Remove characters after the ' '
365 // Pass on to cokebank
366 Client->UID = GetUserAuth(Client->Salt, Client->Username, Args);
368 if( Client->UID != -1 ) {
369 Client->bIsAuthed = 1;
370 sendf(Client->Socket, "200 Auth OK\n");
374 sendf(Client->Socket, "401 Auth Failure\n");
378 * \brief Authenticate as a user without a password
380 * Usage: AUTOAUTH <user>
382 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
384 char *space = strchr(Args, ' ');
385 if(space) *space = '\0'; // Remove characters after the ' '
388 if( !Client->bIsTrusted ) {
390 printf("Client %i: Untrusted client attempting to AUTOAUTH\n", Client->ID);
391 sendf(Client->Socket, "401 Untrusted\n");
396 Client->UID = GetUserID( Args );
397 if( Client->UID < 0 ) {
399 printf("Client %i: Unknown user '%s'\n", Client->ID, Args);
400 sendf(Client->Socket, "401 Auth Failure\n");
405 printf("Client %i: Authenticated as '%s' (%i)\n", Client->ID, Args, Client->UID);
407 sendf(Client->Socket, "200 Auth OK\n");
411 * \brief Set effective user
413 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
417 space = strchr(Args, ' ');
419 if(space) *space = '\0';
421 if( !strlen(Args) ) {
422 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
426 // Check user permissions
427 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_COKE ) {
428 sendf(Client->Socket, "403 Not in coke\n");
433 Client->EffectiveUID = GetUserID(Args);
434 if( Client->EffectiveUID == -1 ) {
435 sendf(Client->Socket, "404 User not found\n");
439 sendf(Client->Socket, "200 User set\n");
443 * \brief Enumerate the items that the server knows about
445 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
449 sendf(Client->Socket, "201 Items %i\n", giNumItems);
451 for( i = 0; i < giNumItems; i ++ ) {
452 sendf(Client->Socket,
453 "202 Item %s:%i %i %s\n",
454 gaItems[i].Handler->Name, gaItems[i].ID, gaItems[i].Price, gaItems[i].Name
458 sendf(Client->Socket, "200 List end\n");
461 tItem *_GetItemFromString(char *String)
465 char *colon = strchr(String, ':');
477 for( i = 0; i < giNumHandlers; i ++ )
479 if( strcmp(gaHandlers[i]->Name, type) == 0) {
480 handler = gaHandlers[i];
489 for( i = 0; i < giNumItems; i ++ )
491 if( gaItems[i].Handler != handler ) continue;
492 if( gaItems[i].ID != num ) continue;
499 * \brief Fetch information on a specific item
501 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
503 tItem *item = _GetItemFromString(Args);
506 sendf(Client->Socket, "406 Bad Item ID\n");
510 sendf(Client->Socket,
511 "202 Item %s:%i %i %s\n",
512 item->Handler->Name, item->ID, item->Price, item->Name
516 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
522 if( !Client->bIsAuthed ) {
523 sendf(Client->Socket, "401 Not Authenticated\n");
527 item = _GetItemFromString(Args);
529 sendf(Client->Socket, "406 Bad Item ID\n");
533 if( Client->EffectiveUID != -1 ) {
534 uid = Client->EffectiveUID;
540 switch( ret = DispenseItem( Client->UID, uid, item ) )
542 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
543 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
544 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
546 sendf(Client->Socket, "500 Dispense Error\n");
551 void Server_Cmd_GIVE(tClient *Client, char *Args)
553 char *recipient, *ammount, *reason;
557 if( !Client->bIsAuthed ) {
558 sendf(Client->Socket, "401 Not Authenticated\n");
564 ammount = strchr(Args, ' ');
566 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
572 reason = strchr(ammount, ' ');
574 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
581 uid = GetUserID(recipient);
583 sendf(Client->Socket, "404 Invalid target user\n");
588 iAmmount = atoi(ammount);
589 if( iAmmount <= 0 ) {
590 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
594 if( Client->EffectiveUID != -1 ) {
595 thisUid = Client->EffectiveUID;
598 thisUid = Client->UID;
602 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
605 sendf(Client->Socket, "200 Give OK\n");
608 sendf(Client->Socket, "402 Poor You\n");
611 sendf(Client->Socket, "500 Unknown error\n");
616 void Server_Cmd_ADD(tClient *Client, char *Args)
618 char *user, *ammount, *reason;
621 if( !Client->bIsAuthed ) {
622 sendf(Client->Socket, "401 Not Authenticated\n");
628 ammount = strchr(Args, ' ');
630 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
636 reason = strchr(ammount, ' ');
638 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
644 // Check user permissions
645 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_COKE ) {
646 sendf(Client->Socket, "403 Not in coke\n");
651 uid = GetUserID(user);
653 // Check user permissions
654 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_COKE ) {
655 sendf(Client->Socket, "403 Not in coke\n");
659 sendf(Client->Socket, "404 Invalid user\n");
664 iAmmount = atoi(ammount);
665 if( iAmmount == 0 && ammount[0] != '0' ) {
666 sendf(Client->Socket, "407 Invalid Argument\n");
671 switch( DispenseAdd(uid, Client->UID, iAmmount, reason) )
674 sendf(Client->Socket, "200 Add OK\n");
677 sendf(Client->Socket, "402 Poor Guy\n");
680 sendf(Client->Socket, "500 Unknown error\n");
685 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
688 int maxBal = INT_MAX, minBal = INT_MIN;
689 int numUsr = GetMaxID();
692 if( Args && strlen(Args) )
694 char *min = Args, *max;
696 max = strchr(Args, ' ');
702 // If <minBal> != "-"
703 if( strcmp(min, "-") != 0 )
705 // If <maxBal> != "-"
706 if( max && strcmp(max, "-") != 0 )
711 for( i = 0; i < numUsr; i ++ )
713 int bal = GetBalance(i);
715 if( bal == INT_MIN ) continue;
717 if( bal < minBal ) continue;
718 if( bal > maxBal ) continue;
724 sendf(Client->Socket, "201 Users %i\n", numRet);
726 for( i = 0; i < numUsr; i ++ )
728 int bal = GetBalance(i);
730 if( bal == INT_MIN ) continue;
732 if( bal < minBal ) continue;
733 if( bal > maxBal ) continue;
735 _SendUserInfo(Client, i);
738 sendf(Client->Socket, "200 List End\n");
741 void Server_Cmd_USERINFO(tClient *Client, char *Args)
747 space = strchr(user, ' ');
748 if(space) *space = '\0';
751 uid = GetUserID(user);
753 sendf(Client->Socket, "404 Invalid user");
757 _SendUserInfo(Client, uid);
760 void _SendUserInfo(tClient *Client, int UserID)
762 char *type, *disabled="";
763 int flags = GetFlags(UserID);
765 switch( flags & USER_FLAG_TYPEMASK )
768 case USER_TYPE_NORMAL: type = "user"; break;
769 case USER_TYPE_COKE: type = "coke"; break;
770 case USER_TYPE_WHEEL: type = "wheel"; break;
771 case USER_TYPE_GOD: type = "meta"; break;
774 if( flags & USER_FLAG_DISABLED )
775 disabled = ",disabled";
776 if( flags & USER_FLAG_DOORGROUP )
779 // TODO: User flags/type
781 Client->Socket, "202 User %s %i %s%s\n",
782 GetUserName(UserID), GetBalance(UserID),
787 void Server_Cmd_USERADD(tClient *Client, char *Args)
789 char *username, *space;
792 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_WHEEL ) {
793 sendf(Client->Socket, "403 Not Wheel\n");
799 while( *username == ' ' ) username ++;
800 space = strchr(username, ' ');
801 if(space) *space = '\0';
803 // Try to create user
804 if( CreateUser(username) == -1 ) {
805 sendf(Client->Socket, "404 User exists\n");
809 sendf(Client->Socket, "200 User Added\n");
812 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
814 char *username, *flags;
820 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_WHEEL ) {
821 sendf(Client->Socket, "403 Not Wheel\n");
828 while( *username == ' ' ) username ++;
829 space = strchr(username, ' ');
831 sendf(Client->Socket, "407 USER_FLAGS requires 2 arguments, 1 given\n");
837 while( *flags == ' ' ) flags ++;
838 space = strchr(flags, ' ');
839 if(space) *space = '\0';
842 uid = GetUserID(username);
844 sendf(Client->Socket, "404 User '%s' not found\n", username);
857 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED},
858 {"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP},
859 {"user", USER_FLAG_TYPEMASK, USER_TYPE_NORMAL},
860 {"coke", USER_FLAG_TYPEMASK, USER_TYPE_COKE},
861 {"wheel", USER_FLAG_TYPEMASK, USER_TYPE_WHEEL},
862 {"meta", USER_FLAG_TYPEMASK, USER_TYPE_GOD}
864 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
866 while( *flags == ' ' ) flags ++; // Eat whitespace
867 space = strchr(flags, ','); // Find the end of the flag
868 if(space) *space = '\0';
870 // Check for inversion/removal
871 if( *flags == '!' || *flags == '-' ) {
875 else if( *flags == '+' ) {
880 for( i = 0; i < ciNumFlags; i ++ )
882 if( strcmp(flags, cFLAGS[i].Name) == 0 ) {
883 mask |= cFLAGS[i].Mask;
884 value &= ~cFLAGS[i].Mask;
886 value |= cFLAGS[i].Value;
892 if( i == ciNumFlags ) {
893 sendf(Client->Socket, "407 Unknown flag value '%s'\n", flags);
901 SetFlags(uid, mask, value);
904 sendf(Client->Socket, "200 User Updated\n");
907 // --- INTERNAL HELPERS ---
908 int sendf(int Socket, const char *Format, ...)
913 va_start(args, Format);
914 len = vsnprintf(NULL, 0, Format, args);
919 va_start(args, Format);
920 vsnprintf(buf, len+1, Format, args);
923 #if DEBUG_TRACE_CLIENT
924 printf("sendf: %s", buf);
927 return send(Socket, buf, len, 0);