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, ...);
70 void HexBin(uint8_t *Dest, char *Src, int BufSize);
74 const struct sClientCommand {
76 void (*Function)(tClient *Client, char *Arguments);
77 } gaServer_Commands[] = {
78 {"USER", Server_Cmd_USER},
79 {"PASS", Server_Cmd_PASS},
80 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
81 {"SETEUSER", Server_Cmd_SETEUSER},
82 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
83 {"ITEM_INFO", Server_Cmd_ITEMINFO},
84 {"DISPENSE", Server_Cmd_DISPENSE},
85 {"GIVE", Server_Cmd_GIVE},
86 {"ADD", Server_Cmd_ADD},
87 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
88 {"USER_INFO", Server_Cmd_USERINFO},
89 {"USER_ADD", Server_Cmd_USERADD},
90 {"USER_FLAGS", Server_Cmd_USERFLAGS}
92 #define NUM_COMMANDS (sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0]))
95 int giServer_Port = 1020;
96 int giServer_NextClientID = 1;
101 * \brief Open listenting socket and serve connections
103 void Server_Start(void)
106 struct sockaddr_in server_addr, client_addr;
108 atexit(Server_Cleanup);
111 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
112 if( giServer_Socket < 0 ) {
113 fprintf(stderr, "ERROR: Unable to create server socket\n");
117 // Make listen address
118 memset(&server_addr, 0, sizeof(server_addr));
119 server_addr.sin_family = AF_INET; // Internet Socket
120 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
121 server_addr.sin_port = htons(giServer_Port); // Port
124 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
125 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
131 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
132 fprintf(stderr, "ERROR: Unable to listen to socket\n");
137 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
141 uint len = sizeof(client_addr);
144 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
145 if(client_socket < 0) {
146 fprintf(stderr, "ERROR: Unable to accept client connection\n");
150 if(giDebugLevel >= 2) {
151 char ipstr[INET_ADDRSTRLEN];
152 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
153 printf("Client connection from %s:%i\n",
154 ipstr, ntohs(client_addr.sin_port));
157 // Trusted Connections
158 if( ntohs(client_addr.sin_port) < 1024 )
160 // TODO: Make this runtime configurable
161 switch( ntohl( client_addr.sin_addr.s_addr ) )
163 case 0x7F000001: // 127.0.0.1 localhost
164 //case 0x825E0D00: // 130.95.13.0
165 case 0x825E0D12: // 130.95.13.18 mussel
166 case 0x825E0D17: // 130.95.13.23 martello
174 // TODO: Multithread this?
175 Server_HandleClient(client_socket, bTrusted);
177 close(client_socket);
181 void Server_Cleanup(void)
183 printf("Close(%i)\n", giServer_Socket);
184 close(giServer_Socket);
188 * \brief Reads from a client socket and parses the command strings
189 * \param Socket Client socket number/handle
190 * \param bTrusted Is the client trusted?
192 void Server_HandleClient(int Socket, int bTrusted)
194 char inbuf[INPUT_BUFFER_SIZE];
196 int remspace = INPUT_BUFFER_SIZE-1;
198 tClient clientInfo = {0};
200 // Initialise Client info
201 clientInfo.Socket = Socket;
202 clientInfo.ID = giServer_NextClientID ++;
203 clientInfo.bIsTrusted = bTrusted;
208 * - The `buf` and `remspace` variables allow a line to span several
209 * calls to recv(), if a line is not completed in one recv() call
210 * it is saved to the beginning of `inbuf` and `buf` is updated to
213 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
216 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
220 while( (eol = strchr(start, '\n')) )
224 Server_ParseClientCommand(&clientInfo, start);
229 // Check if there was an incomplete line
230 if( *start != '\0' ) {
231 int tailBytes = bytes - (start-buf);
232 // Roll back in buffer
233 memcpy(inbuf, start, tailBytes);
234 remspace -= tailBytes;
236 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
238 remspace = INPUT_BUFFER_SIZE - 1;
243 remspace = INPUT_BUFFER_SIZE - 1;
249 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
253 if(giDebugLevel >= 2) {
254 printf("Client %i: Disconnected\n", clientInfo.ID);
259 * \brief Parses a client command and calls the required helper function
260 * \param Client Pointer to client state structure
261 * \param CommandString Command from client (single line of the command)
262 * \return Heap String to return to the client
264 void Server_ParseClientCommand(tClient *Client, char *CommandString)
273 // Split at first space
274 space = strchr(CommandString, ' ');
281 while( *space == ' ' ) space ++;
286 for( i = 0; args[i]; )
288 while( CommandString[i] != ' ' ) {
289 if( CommandString[i] == '"' ) {
290 while( !(CommandString[i] != '\\' CommandString[i+1] == '"' ) )
297 while( CommandString[i] == ' ' ) i ++;
304 for( i = 0; i < NUM_COMMANDS; i++ )
306 if(strcmp(CommandString, gaServer_Commands[i].Name) == 0) {
307 gaServer_Commands[i].Function(Client, args);
312 sendf(Client->Socket, "400 Unknown Command\n");
319 * \brief Set client username
321 * Usage: USER <username>
323 void Server_Cmd_USER(tClient *Client, char *Args)
325 char *space = strchr(Args, ' ');
326 if(space) *space = '\0'; // Remove characters after the ' '
330 printf("Client %i authenticating as '%s'\n", Client->ID, Args);
334 free(Client->Username);
335 Client->Username = strdup(Args);
338 // Create a salt (that changes if the username is changed)
339 // Yes, I know, I'm a little paranoid, but who isn't?
340 Client->Salt[0] = 0x21 + (rand()&0x3F);
341 Client->Salt[1] = 0x21 + (rand()&0x3F);
342 Client->Salt[2] = 0x21 + (rand()&0x3F);
343 Client->Salt[3] = 0x21 + (rand()&0x3F);
344 Client->Salt[4] = 0x21 + (rand()&0x3F);
345 Client->Salt[5] = 0x21 + (rand()&0x3F);
346 Client->Salt[6] = 0x21 + (rand()&0x3F);
347 Client->Salt[7] = 0x21 + (rand()&0x3F);
349 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
350 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
352 sendf(Client->Socket, "100 User Set\n");
357 * \brief Authenticate as a user
361 void Server_Cmd_PASS(tClient *Client, char *Args)
363 char *space = strchr(Args, ' ');
364 if(space) *space = '\0'; // Remove characters after the ' '
366 // Pass on to cokebank
367 Client->UID = GetUserAuth(Client->Salt, Client->Username, Args);
369 if( Client->UID != -1 ) {
370 Client->bIsAuthed = 1;
371 sendf(Client->Socket, "200 Auth OK\n");
375 sendf(Client->Socket, "401 Auth Failure\n");
379 * \brief Authenticate as a user without a password
381 * Usage: AUTOAUTH <user>
383 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
385 char *space = strchr(Args, ' ');
386 if(space) *space = '\0'; // Remove characters after the ' '
389 if( !Client->bIsTrusted ) {
391 printf("Client %i: Untrusted client attempting to AUTOAUTH\n", Client->ID);
392 sendf(Client->Socket, "401 Untrusted\n");
397 Client->UID = GetUserID( Args );
398 if( Client->UID < 0 ) {
400 printf("Client %i: Unknown user '%s'\n", Client->ID, Args);
401 sendf(Client->Socket, "401 Auth Failure\n");
406 printf("Client %i: Authenticated as '%s' (%i)\n", Client->ID, Args, Client->UID);
408 sendf(Client->Socket, "200 Auth OK\n");
412 * \brief Set effective user
414 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
418 space = strchr(Args, ' ');
420 if(space) *space = '\0';
422 if( !strlen(Args) ) {
423 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
427 // Check user permissions
428 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_COKE ) {
429 sendf(Client->Socket, "403 Not in coke\n");
434 Client->EffectiveUID = GetUserID(Args);
435 if( Client->EffectiveUID == -1 ) {
436 sendf(Client->Socket, "404 User not found\n");
440 sendf(Client->Socket, "200 User set\n");
444 * \brief Enumerate the items that the server knows about
446 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
450 sendf(Client->Socket, "201 Items %i\n", giNumItems);
452 for( i = 0; i < giNumItems; i ++ ) {
453 sendf(Client->Socket,
454 "202 Item %s:%i %i %s\n",
455 gaItems[i].Handler->Name, gaItems[i].ID, gaItems[i].Price, gaItems[i].Name
459 sendf(Client->Socket, "200 List end\n");
462 tItem *_GetItemFromString(char *String)
466 char *colon = strchr(String, ':');
478 for( i = 0; i < giNumHandlers; i ++ )
480 if( strcmp(gaHandlers[i]->Name, type) == 0) {
481 handler = gaHandlers[i];
490 for( i = 0; i < giNumItems; i ++ )
492 if( gaItems[i].Handler != handler ) continue;
493 if( gaItems[i].ID != num ) continue;
500 * \brief Fetch information on a specific item
502 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
504 tItem *item = _GetItemFromString(Args);
507 sendf(Client->Socket, "406 Bad Item ID\n");
511 sendf(Client->Socket,
512 "202 Item %s:%i %i %s\n",
513 item->Handler->Name, item->ID, item->Price, item->Name
517 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
523 if( !Client->bIsAuthed ) {
524 sendf(Client->Socket, "401 Not Authenticated\n");
528 item = _GetItemFromString(Args);
530 sendf(Client->Socket, "406 Bad Item ID\n");
534 if( Client->EffectiveUID != -1 ) {
535 uid = Client->EffectiveUID;
541 switch( ret = DispenseItem( Client->UID, uid, item ) )
543 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
544 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
545 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
547 sendf(Client->Socket, "500 Dispense Error\n");
552 void Server_Cmd_GIVE(tClient *Client, char *Args)
554 char *recipient, *ammount, *reason;
558 if( !Client->bIsAuthed ) {
559 sendf(Client->Socket, "401 Not Authenticated\n");
565 ammount = strchr(Args, ' ');
567 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
573 reason = strchr(ammount, ' ');
575 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
582 uid = GetUserID(recipient);
584 sendf(Client->Socket, "404 Invalid target user\n");
589 iAmmount = atoi(ammount);
590 if( iAmmount <= 0 ) {
591 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
595 if( Client->EffectiveUID != -1 ) {
596 thisUid = Client->EffectiveUID;
599 thisUid = Client->UID;
603 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
606 sendf(Client->Socket, "200 Give OK\n");
609 sendf(Client->Socket, "402 Poor You\n");
612 sendf(Client->Socket, "500 Unknown error\n");
617 void Server_Cmd_ADD(tClient *Client, char *Args)
619 char *user, *ammount, *reason;
622 if( !Client->bIsAuthed ) {
623 sendf(Client->Socket, "401 Not Authenticated\n");
629 ammount = strchr(Args, ' ');
631 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
637 reason = strchr(ammount, ' ');
639 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
645 // Check user permissions
646 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_COKE ) {
647 sendf(Client->Socket, "403 Not in coke\n");
652 uid = GetUserID(user);
654 // Check user permissions
655 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_COKE ) {
656 sendf(Client->Socket, "403 Not in coke\n");
660 sendf(Client->Socket, "404 Invalid user\n");
665 iAmmount = atoi(ammount);
666 if( iAmmount == 0 && ammount[0] != '0' ) {
667 sendf(Client->Socket, "407 Invalid Argument\n");
672 switch( DispenseAdd(uid, Client->UID, iAmmount, reason) )
675 sendf(Client->Socket, "200 Add OK\n");
678 sendf(Client->Socket, "402 Poor Guy\n");
681 sendf(Client->Socket, "500 Unknown error\n");
686 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
689 int maxBal = INT_MAX, minBal = INT_MIN;
690 int numUsr = GetMaxID();
693 if( Args && strlen(Args) )
695 char *min = Args, *max;
697 max = strchr(Args, ' ');
703 // If <minBal> != "-"
704 if( strcmp(min, "-") != 0 )
706 // If <maxBal> != "-"
707 if( max && strcmp(max, "-") != 0 )
712 for( i = 0; i < numUsr; i ++ )
714 int bal = GetBalance(i);
716 if( bal == INT_MIN ) continue;
718 if( bal < minBal ) continue;
719 if( bal > maxBal ) continue;
725 sendf(Client->Socket, "201 Users %i\n", numRet);
727 for( i = 0; i < numUsr; i ++ )
729 int bal = GetBalance(i);
731 if( bal == INT_MIN ) continue;
733 if( bal < minBal ) continue;
734 if( bal > maxBal ) continue;
736 _SendUserInfo(Client, i);
739 sendf(Client->Socket, "200 List End\n");
742 void Server_Cmd_USERINFO(tClient *Client, char *Args)
748 space = strchr(user, ' ');
749 if(space) *space = '\0';
752 uid = GetUserID(user);
754 sendf(Client->Socket, "404 Invalid user");
758 _SendUserInfo(Client, uid);
761 void _SendUserInfo(tClient *Client, int UserID)
763 char *type, *disabled="";
764 int flags = GetFlags(UserID);
766 switch( flags & USER_FLAG_TYPEMASK )
769 case USER_TYPE_NORMAL: type = "user"; break;
770 case USER_TYPE_COKE: type = "coke"; break;
771 case USER_TYPE_WHEEL: type = "wheel"; break;
772 case USER_TYPE_GOD: type = "meta"; break;
775 if( flags & USER_FLAG_DISABLED )
776 disabled = ",disabled";
777 if( flags & USER_FLAG_DOORGROUP )
780 // TODO: User flags/type
782 Client->Socket, "202 User %s %i %s%s\n",
783 GetUserName(UserID), GetBalance(UserID),
788 void Server_Cmd_USERADD(tClient *Client, char *Args)
790 char *username, *space;
793 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_WHEEL ) {
794 sendf(Client->Socket, "403 Not Wheel\n");
800 while( *username == ' ' ) username ++;
801 space = strchr(username, ' ');
802 if(space) *space = '\0';
804 // Try to create user
805 if( CreateUser(username) == -1 ) {
806 sendf(Client->Socket, "404 User exists\n");
810 sendf(Client->Socket, "200 User Added\n");
813 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
815 char *username, *flags;
821 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_WHEEL ) {
822 sendf(Client->Socket, "403 Not Wheel\n");
829 while( *username == ' ' ) username ++;
830 space = strchr(username, ' ');
832 sendf(Client->Socket, "407 USER_FLAGS requires 2 arguments, 1 given\n");
838 while( *flags == ' ' ) flags ++;
839 space = strchr(flags, ' ');
840 if(space) *space = '\0';
843 uid = GetUserID(username);
845 sendf(Client->Socket, "404 User '%s' not found\n", username);
858 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED},
859 {"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP},
860 {"user", USER_FLAG_TYPEMASK, USER_TYPE_NORMAL},
861 {"coke", USER_FLAG_TYPEMASK, USER_TYPE_COKE},
862 {"wheel", USER_FLAG_TYPEMASK, USER_TYPE_WHEEL},
863 {"meta", USER_FLAG_TYPEMASK, USER_TYPE_GOD}
865 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
867 while( *flags == ' ' ) flags ++; // Eat whitespace
868 space = strchr(flags, ','); // Find the end of the flag
869 if(space) *space = '\0';
871 // Check for inversion/removal
872 if( *flags == '!' || *flags == '-' ) {
876 else if( *flags == '+' ) {
881 for( i = 0; i < ciNumFlags; i ++ )
883 if( strcmp(flags, cFLAGS[i].Name) == 0 ) {
884 mask |= cFLAGS[i].Mask;
885 value &= ~cFLAGS[i].Mask;
887 value |= cFLAGS[i].Value;
893 if( i == ciNumFlags ) {
894 sendf(Client->Socket, "407 Unknown flag value '%s'\n", flags);
902 SetFlags(uid, mask, value);
905 sendf(Client->Socket, "200 User Updated\n");
908 // --- INTERNAL HELPERS ---
909 int sendf(int Socket, const char *Format, ...)
914 va_start(args, Format);
915 len = vsnprintf(NULL, 0, Format, args);
920 va_start(args, Format);
921 vsnprintf(buf, len+1, Format, args);
924 #if DEBUG_TRACE_CLIENT
925 printf("sendf: %s", buf);
928 return send(Socket, buf, len, 0);
933 * \brief Decode a Base64 value
935 int UnBase64(uint8_t *Dest, char *Src, int BufSize)
939 char *start_src = Src;
941 for( i = 0; i+2 < BufSize; i += 3 )
944 for( j = 0; j < 4; j++, Src ++ ) {
945 if('A' <= *Src && *Src <= 'Z')
946 val |= (*Src - 'A') << ((3-j)*6);
947 else if('a' <= *Src && *Src <= 'z')
948 val |= (*Src - 'a' + 26) << ((3-j)*6);
949 else if('0' <= *Src && *Src <= '9')
950 val |= (*Src - '0' + 52) << ((3-j)*6);
952 val |= 62 << ((3-j)*6);
954 val |= 63 << ((3-j)*6);
958 j --; // Ignore invalid characters
960 Dest[i ] = (val >> 16) & 0xFF;
961 Dest[i+1] = (val >> 8) & 0xFF;
962 Dest[i+2] = val & 0xFF;
968 Dest[i] = (val >> 16) & 0xFF;
970 Dest[i+1] = (val >> 8) & 0xFF;
972 return Src - start_src;