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>
22 #define DEBUG_TRACE_CLIENT 0
25 #define MAX_CONNECTION_QUEUE 5
26 #define INPUT_BUFFER_SIZE 256
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_ADD(tClient *Client, char *Args);
64 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
65 void Server_Cmd_USERINFO(tClient *Client, char *Args);
66 void _SendUserInfo(tClient *Client, int UserID);
67 void Server_Cmd_USERADD(tClient *Client, char *Args);
68 void Server_Cmd_USERFLAGS(tClient *Client, char *Args);
70 int sendf(int Socket, const char *Format, ...);
71 void HexBin(uint8_t *Dest, char *Src, int BufSize);
75 const struct sClientCommand {
77 void (*Function)(tClient *Client, char *Arguments);
78 } gaServer_Commands[] = {
79 {"USER", Server_Cmd_USER},
80 {"PASS", Server_Cmd_PASS},
81 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
82 {"SETEUSER", Server_Cmd_SETEUSER},
83 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
84 {"ITEM_INFO", Server_Cmd_ITEMINFO},
85 {"DISPENSE", Server_Cmd_DISPENSE},
86 {"GIVE", Server_Cmd_GIVE},
87 {"ADD", Server_Cmd_ADD},
88 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
89 {"USER_INFO", Server_Cmd_USERINFO},
90 {"USER_ADD", Server_Cmd_USERADD},
91 {"USER_FLAGS", Server_Cmd_USERFLAGS}
93 #define NUM_COMMANDS (sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0]))
96 int giServer_Port = 1020;
97 int giServer_NextClientID = 1;
102 * \brief Open listenting socket and serve connections
104 void Server_Start(void)
107 struct sockaddr_in server_addr, client_addr;
109 atexit(Server_Cleanup);
112 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
113 if( giServer_Socket < 0 ) {
114 fprintf(stderr, "ERROR: Unable to create server socket\n");
118 // Make listen address
119 memset(&server_addr, 0, sizeof(server_addr));
120 server_addr.sin_family = AF_INET; // Internet Socket
121 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
122 server_addr.sin_port = htons(giServer_Port); // Port
125 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
126 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
132 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
133 fprintf(stderr, "ERROR: Unable to listen to socket\n");
138 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
142 uint len = sizeof(client_addr);
145 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
146 if(client_socket < 0) {
147 fprintf(stderr, "ERROR: Unable to accept client connection\n");
151 if(giDebugLevel >= 2) {
152 char ipstr[INET_ADDRSTRLEN];
153 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
154 printf("Client connection from %s:%i\n",
155 ipstr, ntohs(client_addr.sin_port));
158 // Trusted Connections
159 if( ntohs(client_addr.sin_port) < 1024 )
161 // TODO: Make this runtime configurable
162 switch( ntohl( client_addr.sin_addr.s_addr ) )
164 case 0x7F000001: // 127.0.0.1 localhost
165 //case 0x825E0D00: // 130.95.13.0
166 case 0x825E0D12: // 130.95.13.18 mussel
167 case 0x825E0D17: // 130.95.13.23 martello
175 // TODO: Multithread this?
176 Server_HandleClient(client_socket, bTrusted);
178 close(client_socket);
182 void Server_Cleanup(void)
184 printf("Close(%i)\n", giServer_Socket);
185 close(giServer_Socket);
189 * \brief Reads from a client socket and parses the command strings
190 * \param Socket Client socket number/handle
191 * \param bTrusted Is the client trusted?
193 void Server_HandleClient(int Socket, int bTrusted)
195 char inbuf[INPUT_BUFFER_SIZE];
197 int remspace = INPUT_BUFFER_SIZE-1;
199 tClient clientInfo = {0};
201 // Initialise Client info
202 clientInfo.Socket = Socket;
203 clientInfo.ID = giServer_NextClientID ++;
204 clientInfo.bIsTrusted = bTrusted;
209 * - The `buf` and `remspace` variables allow a line to span several
210 * calls to recv(), if a line is not completed in one recv() call
211 * it is saved to the beginning of `inbuf` and `buf` is updated to
214 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
217 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
221 while( (eol = strchr(start, '\n')) )
225 Server_ParseClientCommand(&clientInfo, start);
230 // Check if there was an incomplete line
231 if( *start != '\0' ) {
232 int tailBytes = bytes - (start-buf);
233 // Roll back in buffer
234 memcpy(inbuf, start, tailBytes);
235 remspace -= tailBytes;
237 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
239 remspace = INPUT_BUFFER_SIZE - 1;
244 remspace = INPUT_BUFFER_SIZE - 1;
250 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
254 if(giDebugLevel >= 2) {
255 printf("Client %i: Disconnected\n", clientInfo.ID);
260 * \brief Parses a client command and calls the required helper function
261 * \param Client Pointer to client state structure
262 * \param CommandString Command from client (single line of the command)
263 * \return Heap String to return to the client
265 void Server_ParseClientCommand(tClient *Client, char *CommandString)
274 // Split at first space
275 space = strchr(CommandString, ' ');
282 while( *space == ' ' ) space ++;
287 for( i = 0; args[i]; )
289 while( CommandString[i] != ' ' ) {
290 if( CommandString[i] == '"' ) {
291 while( !(CommandString[i] != '\\' CommandString[i+1] == '"' ) )
298 while( CommandString[i] == ' ' ) i ++;
305 for( i = 0; i < NUM_COMMANDS; i++ )
307 if(strcmp(CommandString, gaServer_Commands[i].Name) == 0) {
308 gaServer_Commands[i].Function(Client, args);
313 sendf(Client->Socket, "400 Unknown Command\n");
320 * \brief Set client username
322 * Usage: USER <username>
324 void Server_Cmd_USER(tClient *Client, char *Args)
328 printf("Client %i authenticating as '%s'\n", Client->ID, Args);
332 free(Client->Username);
333 Client->Username = strdup(Args);
336 // Create a salt (that changes if the username is changed)
337 // Yes, I know, I'm a little paranoid, but who isn't?
338 Client->Salt[0] = 0x21 + (rand()&0x3F);
339 Client->Salt[1] = 0x21 + (rand()&0x3F);
340 Client->Salt[2] = 0x21 + (rand()&0x3F);
341 Client->Salt[3] = 0x21 + (rand()&0x3F);
342 Client->Salt[4] = 0x21 + (rand()&0x3F);
343 Client->Salt[5] = 0x21 + (rand()&0x3F);
344 Client->Salt[6] = 0x21 + (rand()&0x3F);
345 Client->Salt[7] = 0x21 + (rand()&0x3F);
347 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
348 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
350 sendf(Client->Socket, "100 User Set\n");
355 * \brief Authenticate as a user
359 void Server_Cmd_PASS(tClient *Client, char *Args)
361 // TODO: Decrypt password passed
363 Client->UID = GetUserAuth(Client->Salt, Client->Username, Args);
365 if( Client->UID != -1 ) {
366 Client->bIsAuthed = 1;
367 sendf(Client->Socket, "200 Auth OK\n");
371 sendf(Client->Socket, "401 Auth Failure\n");
375 * \brief Authenticate as a user without a password
377 * Usage: AUTOAUTH <user>
379 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
381 char *spos = strchr(Args, ' ');
382 if(spos) *spos = '\0'; // Remove characters after the ' '
385 if( !Client->bIsTrusted ) {
387 printf("Client %i: Untrusted client attempting to AUTOAUTH\n", Client->ID);
388 sendf(Client->Socket, "401 Untrusted\n");
393 Client->UID = GetUserID( Args );
394 if( Client->UID < 0 ) {
396 printf("Client %i: Unknown user '%s'\n", Client->ID, Args);
397 sendf(Client->Socket, "401 Auth Failure\n");
402 printf("Client %i: Authenticated as '%s' (%i)\n", Client->ID, Args, Client->UID);
404 sendf(Client->Socket, "200 Auth OK\n");
408 * \brief Set effective user
410 void Server_Cmd_SETEUSER(tClient *Client, char *Args)
414 space = strchr(Args, ' ');
416 if(space) *space = '\0';
418 if( !strlen(Args) ) {
419 sendf(Client->Socket, "407 SETEUSER expects an argument\n");
423 // Check user permissions
424 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_COKE ) {
425 sendf(Client->Socket, "403 Not in coke\n");
430 Client->EffectiveUID = GetUserID(Args);
431 if( Client->EffectiveUID == -1 ) {
432 sendf(Client->Socket, "404 User not found\n");
436 sendf(Client->Socket, "200 User set\n");
440 * \brief Enumerate the items that the server knows about
442 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
446 sendf(Client->Socket, "201 Items %i\n", giNumItems);
448 for( i = 0; i < giNumItems; i ++ ) {
449 sendf(Client->Socket,
450 "202 Item %s:%i %i %s\n",
451 gaItems[i].Handler->Name, gaItems[i].ID, gaItems[i].Price, gaItems[i].Name
455 sendf(Client->Socket, "200 List end\n");
458 tItem *_GetItemFromString(char *String)
462 char *colon = strchr(String, ':');
474 for( i = 0; i < giNumHandlers; i ++ )
476 if( strcmp(gaHandlers[i]->Name, type) == 0) {
477 handler = gaHandlers[i];
486 for( i = 0; i < giNumItems; i ++ )
488 if( gaItems[i].Handler != handler ) continue;
489 if( gaItems[i].ID != num ) continue;
496 * \brief Fetch information on a specific item
498 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
500 tItem *item = _GetItemFromString(Args);
503 sendf(Client->Socket, "406 Bad Item ID\n");
507 sendf(Client->Socket,
508 "202 Item %s:%i %i %s\n",
509 item->Handler->Name, item->ID, item->Price, item->Name
513 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
519 if( !Client->bIsAuthed ) {
520 sendf(Client->Socket, "401 Not Authenticated\n");
524 item = _GetItemFromString(Args);
526 sendf(Client->Socket, "406 Bad Item ID\n");
530 if( Client->EffectiveUID != -1 ) {
531 uid = Client->EffectiveUID;
537 switch( ret = DispenseItem( Client->UID, uid, item ) )
539 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
540 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
541 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
543 sendf(Client->Socket, "500 Dispense Error\n");
548 void Server_Cmd_GIVE(tClient *Client, char *Args)
550 char *recipient, *ammount, *reason;
554 if( !Client->bIsAuthed ) {
555 sendf(Client->Socket, "401 Not Authenticated\n");
561 ammount = strchr(Args, ' ');
563 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
569 reason = strchr(ammount, ' ');
571 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
578 uid = GetUserID(recipient);
580 sendf(Client->Socket, "404 Invalid target user\n");
585 iAmmount = atoi(ammount);
586 if( iAmmount <= 0 ) {
587 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
591 if( Client->EffectiveUID != -1 ) {
592 thisUid = Client->EffectiveUID;
595 thisUid = Client->UID;
599 switch( DispenseGive(Client->UID, thisUid, uid, iAmmount, reason) )
602 sendf(Client->Socket, "200 Give OK\n");
605 sendf(Client->Socket, "402 Poor You\n");
608 sendf(Client->Socket, "500 Unknown error\n");
613 void Server_Cmd_ADD(tClient *Client, char *Args)
615 char *user, *ammount, *reason;
618 if( !Client->bIsAuthed ) {
619 sendf(Client->Socket, "401 Not Authenticated\n");
625 ammount = strchr(Args, ' ');
627 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
633 reason = strchr(ammount, ' ');
635 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
641 // Check user permissions
642 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_COKE ) {
643 sendf(Client->Socket, "403 Not in coke\n");
648 uid = GetUserID(user);
650 // Check user permissions
651 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_COKE ) {
652 sendf(Client->Socket, "403 Not in coke\n");
656 sendf(Client->Socket, "404 Invalid user\n");
661 iAmmount = atoi(ammount);
662 if( iAmmount == 0 && ammount[0] != '0' ) {
663 sendf(Client->Socket, "407 Invalid Argument\n");
668 switch( DispenseAdd(uid, Client->UID, iAmmount, reason) )
671 sendf(Client->Socket, "200 Add OK\n");
674 sendf(Client->Socket, "402 Poor Guy\n");
677 sendf(Client->Socket, "500 Unknown error\n");
682 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
685 int maxBal = INT_MAX, minBal = INT_MIN;
686 int numUsr = GetMaxID();
689 if( Args && strlen(Args) )
691 char *min = Args, *max;
693 max = strchr(Args, ' ');
699 // If <minBal> != "-"
700 if( strcmp(min, "-") != 0 )
702 // If <maxBal> != "-"
703 if( max && strcmp(max, "-") != 0 )
708 for( i = 0; i < numUsr; i ++ )
710 int bal = GetBalance(i);
712 if( bal == INT_MIN ) continue;
714 if( bal < minBal ) continue;
715 if( bal > maxBal ) continue;
721 sendf(Client->Socket, "201 Users %i\n", numRet);
723 for( i = 0; i < numUsr; i ++ )
725 int bal = GetBalance(i);
727 if( bal == INT_MIN ) continue;
729 if( bal < minBal ) continue;
730 if( bal > maxBal ) continue;
732 _SendUserInfo(Client, i);
735 sendf(Client->Socket, "200 List End\n");
738 void Server_Cmd_USERINFO(tClient *Client, char *Args)
744 space = strchr(user, ' ');
745 if(space) *space = '\0';
748 uid = GetUserID(user);
750 sendf(Client->Socket, "404 Invalid user");
754 _SendUserInfo(Client, uid);
757 void _SendUserInfo(tClient *Client, int UserID)
759 char *type, *disabled="";
760 int flags = GetFlags(UserID);
762 switch( flags & USER_FLAG_TYPEMASK )
765 case USER_TYPE_NORMAL: type = "user"; break;
766 case USER_TYPE_COKE: type = "coke"; break;
767 case USER_TYPE_WHEEL: type = "wheel"; break;
768 case USER_TYPE_GOD: type = "meta"; break;
771 if( flags & USER_FLAG_DISABLED )
772 disabled = ",disabled";
773 if( flags & USER_FLAG_DOORGROUP )
776 // TODO: User flags/type
778 Client->Socket, "202 User %s %i %s%s\n",
779 GetUserName(UserID), GetBalance(UserID),
784 void Server_Cmd_USERADD(tClient *Client, char *Args)
786 char *username, *space;
789 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_WHEEL ) {
790 sendf(Client->Socket, "403 Not Wheel\n");
796 while( *username == ' ' ) username ++;
797 space = strchr(username, ' ');
798 if(space) *space = '\0';
800 // Try to create user
801 if( CreateUser(username) == -1 ) {
802 sendf(Client->Socket, "404 User exists\n");
806 sendf(Client->Socket, "200 User Added\n");
809 void Server_Cmd_USERFLAGS(tClient *Client, char *Args)
811 char *username, *flags;
817 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_WHEEL ) {
818 sendf(Client->Socket, "403 Not Wheel\n");
825 while( *username == ' ' ) username ++;
826 space = strchr(username, ' ');
828 sendf(Client->Socket, "407 USER_FLAGS requires 2 arguments, 1 given\n");
834 while( *flags == ' ' ) flags ++;
835 space = strchr(flags, ' ');
836 if(space) *space = '\0';
839 uid = GetUserID(username);
841 sendf(Client->Socket, "404 User '%s' not found\n", username);
854 {"disabled", USER_FLAG_DISABLED, USER_FLAG_DISABLED},
855 {"door", USER_FLAG_DOORGROUP, USER_FLAG_DOORGROUP},
856 {"user", USER_FLAG_TYPEMASK, USER_TYPE_NORMAL},
857 {"coke", USER_FLAG_TYPEMASK, USER_TYPE_COKE},
858 {"wheel", USER_FLAG_TYPEMASK, USER_TYPE_WHEEL},
859 {"meta", USER_FLAG_TYPEMASK, USER_TYPE_GOD}
861 const int ciNumFlags = sizeof(cFLAGS)/sizeof(cFLAGS[0]);
863 while( *flags == ' ' ) flags ++; // Eat whitespace
864 space = strchr(flags, ','); // Find the end of the flag
865 if(space) *space = '\0';
867 // Check for inversion/removal
868 if( *flags == '!' || *flags == '-' ) {
872 else if( *flags == '+' ) {
877 for( i = 0; i < ciNumFlags; i ++ )
879 if( strcmp(flags, cFLAGS[i].Name) == 0 ) {
880 mask |= cFLAGS[i].Mask;
881 value &= ~cFLAGS[i].Mask;
883 value |= cFLAGS[i].Value;
889 if( i == ciNumFlags ) {
890 sendf(Client->Socket, "407 Unknown flag value '%s'\n", flags);
898 SetFlags(uid, mask, value);
901 sendf(Client->Socket, "200 User Updated\n");
904 // --- INTERNAL HELPERS ---
905 int sendf(int Socket, const char *Format, ...)
910 va_start(args, Format);
911 len = vsnprintf(NULL, 0, Format, args);
916 va_start(args, Format);
917 vsnprintf(buf, len+1, Format, args);
920 #if DEBUG_TRACE_CLIENT
921 printf("sendf: %s", buf);
924 return send(Socket, buf, len, 0);
929 * \brief Decode a Base64 value
931 int UnBase64(uint8_t *Dest, char *Src, int BufSize)
935 char *start_src = Src;
937 for( i = 0; i+2 < BufSize; i += 3 )
940 for( j = 0; j < 4; j++, Src ++ ) {
941 if('A' <= *Src && *Src <= 'Z')
942 val |= (*Src - 'A') << ((3-j)*6);
943 else if('a' <= *Src && *Src <= 'z')
944 val |= (*Src - 'a' + 26) << ((3-j)*6);
945 else if('0' <= *Src && *Src <= '9')
946 val |= (*Src - '0' + 52) << ((3-j)*6);
948 val |= 62 << ((3-j)*6);
950 val |= 63 << ((3-j)*6);
954 j --; // Ignore invalid characters
956 Dest[i ] = (val >> 16) & 0xFF;
957 Dest[i+1] = (val >> 8) & 0xFF;
958 Dest[i+2] = val & 0xFF;
964 Dest[i] = (val >> 16) & 0xFF;
966 Dest[i+1] = (val >> 8) & 0xFF;
968 return Src - start_src;