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 HACK_TPG_NOAUTH 1
23 #define HACK_ROOT_NOAUTH 1
25 #define DEBUG_TRACE_CLIENT 0
28 #define MAX_CONNECTION_QUEUE 5
29 #define INPUT_BUFFER_SIZE 256
31 #define HASH_TYPE SHA1
32 #define HASH_LENGTH 20
34 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
37 typedef struct sClient
39 int Socket; // Client socket ID
42 int bIsTrusted; // Is the connection from a trusted host/port
52 void Server_Start(void);
53 void Server_Cleanup(void);
54 void Server_HandleClient(int Socket, int bTrusted);
55 void Server_ParseClientCommand(tClient *Client, char *CommandString);
57 void Server_Cmd_USER(tClient *Client, char *Args);
58 void Server_Cmd_PASS(tClient *Client, char *Args);
59 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
60 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
61 void Server_Cmd_ITEMINFO(tClient *Client, char *Args);
62 void Server_Cmd_DISPENSE(tClient *Client, char *Args);
63 void Server_Cmd_GIVE(tClient *Client, char *Args);
64 void Server_Cmd_ADD(tClient *Client, char *Args);
65 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
66 void Server_Cmd_USERINFO(tClient *Client, char *Args);
67 void _SendUserInfo(tClient *Client, int UserID);
69 int sendf(int Socket, const char *Format, ...);
70 int GetUserAuth(const char *Salt, const char *Username, const uint8_t *Hash);
71 void HexBin(uint8_t *Dest, char *Src, int BufSize);
74 int giServer_Port = 1020;
75 int giServer_NextClientID = 1;
77 struct sClientCommand {
79 void (*Function)(tClient *Client, char *Arguments);
80 } gaServer_Commands[] = {
81 {"USER", Server_Cmd_USER},
82 {"PASS", Server_Cmd_PASS},
83 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
84 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
85 {"ITEM_INFO", Server_Cmd_ITEMINFO},
86 {"DISPENSE", Server_Cmd_DISPENSE},
87 {"GIVE", Server_Cmd_GIVE},
88 {"ADD", Server_Cmd_ADD},
89 {"ENUM_USERS", Server_Cmd_ENUMUSERS},
90 {"USER_INFO", Server_Cmd_USERINFO}
92 #define NUM_COMMANDS (sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0]))
97 * \brief Open listenting socket and serve connections
99 void Server_Start(void)
102 struct sockaddr_in server_addr, client_addr;
104 atexit(Server_Cleanup);
107 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
108 if( giServer_Socket < 0 ) {
109 fprintf(stderr, "ERROR: Unable to create server socket\n");
113 // Make listen address
114 memset(&server_addr, 0, sizeof(server_addr));
115 server_addr.sin_family = AF_INET; // Internet Socket
116 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
117 server_addr.sin_port = htons(giServer_Port); // Port
120 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
121 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
127 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
128 fprintf(stderr, "ERROR: Unable to listen to socket\n");
133 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
137 uint len = sizeof(client_addr);
140 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
141 if(client_socket < 0) {
142 fprintf(stderr, "ERROR: Unable to accept client connection\n");
146 if(giDebugLevel >= 2) {
147 char ipstr[INET_ADDRSTRLEN];
148 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
149 printf("Client connection from %s:%i\n",
150 ipstr, ntohs(client_addr.sin_port));
153 // Trusted Connections
154 if( ntohs(client_addr.sin_port) < 1024 )
156 // TODO: Make this runtime configurable
157 switch( ntohl( client_addr.sin_addr.s_addr ) )
159 case 0x7F000001: // 127.0.0.1 localhost
160 //case 0x825E0D00: // 130.95.13.0
161 case 0x825E0D12: // 130.95.13.18 mussel
162 case 0x825E0D17: // 130.95.13.23 martello
170 // TODO: Multithread this?
171 Server_HandleClient(client_socket, bTrusted);
173 close(client_socket);
177 void Server_Cleanup(void)
179 printf("Close(%i)\n", giServer_Socket);
180 close(giServer_Socket);
184 * \brief Reads from a client socket and parses the command strings
185 * \param Socket Client socket number/handle
186 * \param bTrusted Is the client trusted?
188 void Server_HandleClient(int Socket, int bTrusted)
190 char inbuf[INPUT_BUFFER_SIZE];
192 int remspace = INPUT_BUFFER_SIZE-1;
194 tClient clientInfo = {0};
196 // Initialise Client info
197 clientInfo.Socket = Socket;
198 clientInfo.ID = giServer_NextClientID ++;
199 clientInfo.bIsTrusted = bTrusted;
204 * - The `buf` and `remspace` variables allow a line to span several
205 * calls to recv(), if a line is not completed in one recv() call
206 * it is saved to the beginning of `inbuf` and `buf` is updated to
209 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
212 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
216 while( (eol = strchr(start, '\n')) )
220 Server_ParseClientCommand(&clientInfo, start);
225 // Check if there was an incomplete line
226 if( *start != '\0' ) {
227 int tailBytes = bytes - (start-buf);
228 // Roll back in buffer
229 memcpy(inbuf, start, tailBytes);
230 remspace -= tailBytes;
232 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
234 remspace = INPUT_BUFFER_SIZE - 1;
239 remspace = INPUT_BUFFER_SIZE - 1;
245 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
249 if(giDebugLevel >= 2) {
250 printf("Client %i: Disconnected\n", clientInfo.ID);
255 * \brief Parses a client command and calls the required helper function
256 * \param Client Pointer to client state structure
257 * \param CommandString Command from client (single line of the command)
258 * \return Heap String to return to the client
260 void Server_ParseClientCommand(tClient *Client, char *CommandString)
265 // Split at first space
266 space = strchr(CommandString, ' ');
276 for( i = 0; i < NUM_COMMANDS; i++ )
278 if(strcmp(CommandString, gaServer_Commands[i].Name) == 0) {
279 gaServer_Commands[i].Function(Client, args);
284 sendf(Client->Socket, "400 Unknown Command\n");
291 * \brief Set client username
293 * Usage: USER <username>
295 void Server_Cmd_USER(tClient *Client, char *Args)
299 printf("Client %i authenticating as '%s'\n", Client->ID, Args);
303 free(Client->Username);
304 Client->Username = strdup(Args);
307 // Create a salt (that changes if the username is changed)
308 // Yes, I know, I'm a little paranoid, but who isn't?
309 Client->Salt[0] = 0x21 + (rand()&0x3F);
310 Client->Salt[1] = 0x21 + (rand()&0x3F);
311 Client->Salt[2] = 0x21 + (rand()&0x3F);
312 Client->Salt[3] = 0x21 + (rand()&0x3F);
313 Client->Salt[4] = 0x21 + (rand()&0x3F);
314 Client->Salt[5] = 0x21 + (rand()&0x3F);
315 Client->Salt[6] = 0x21 + (rand()&0x3F);
316 Client->Salt[7] = 0x21 + (rand()&0x3F);
318 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
319 sendf(Client->Socket, "100 SALT %s\n", Client->Salt);
321 sendf(Client->Socket, "100 User Set\n");
326 * \brief Authenticate as a user
330 void Server_Cmd_PASS(tClient *Client, char *Args)
332 uint8_t clienthash[HASH_LENGTH] = {0};
335 HexBin(clienthash, Args, HASH_LENGTH);
337 // TODO: Decrypt password passed
339 Client->UID = GetUserAuth(Client->Salt, Client->Username, clienthash);
341 if( Client->UID != -1 ) {
342 Client->bIsAuthed = 1;
343 sendf(Client->Socket, "200 Auth OK\n");
349 printf("Client %i: Password hash ", Client->ID);
350 for(i=0;i<HASH_LENGTH;i++)
351 printf("%02x", clienthash[i]&0xFF);
355 sendf(Client->Socket, "401 Auth Failure\n");
359 * \brief Authenticate as a user without a password
361 * Usage: AUTOAUTH <user>
363 void Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
365 char *spos = strchr(Args, ' ');
366 if(spos) *spos = '\0'; // Remove characters after the ' '
369 if( !Client->bIsTrusted ) {
371 printf("Client %i: Untrusted client attempting to AUTOAUTH\n", Client->ID);
372 sendf(Client->Socket, "401 Untrusted\n");
377 Client->UID = GetUserID( Args );
378 if( Client->UID < 0 ) {
380 printf("Client %i: Unknown user '%s'\n", Client->ID, Args);
381 sendf(Client->Socket, "401 Auth Failure\n");
386 printf("Client %i: Authenticated as '%s' (%i)\n", Client->ID, Args, Client->UID);
388 sendf(Client->Socket, "200 Auth OK\n");
392 * \brief Enumerate the items that the server knows about
394 void Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
398 sendf(Client->Socket, "201 Items %i", giNumItems);
400 for( i = 0; i < giNumItems; i ++ ) {
401 sendf(Client->Socket, " %s:%i", gaItems[i].Handler->Name, gaItems[i].ID);
404 sendf(Client->Socket, "\n");
407 tItem *_GetItemFromString(char *String)
411 char *colon = strchr(String, ':');
423 for( i = 0; i < giNumHandlers; i ++ )
425 if( strcmp(gaHandlers[i]->Name, type) == 0) {
426 handler = gaHandlers[i];
435 for( i = 0; i < giNumItems; i ++ )
437 if( gaItems[i].Handler != handler ) continue;
438 if( gaItems[i].ID != num ) continue;
445 * \brief Fetch information on a specific item
447 void Server_Cmd_ITEMINFO(tClient *Client, char *Args)
449 tItem *item = _GetItemFromString(Args);
452 sendf(Client->Socket, "406 Bad Item ID\n");
456 sendf(Client->Socket,
457 "202 Item %s:%i %i %s\n",
458 item->Handler->Name, item->ID, item->Price, item->Name
462 void Server_Cmd_DISPENSE(tClient *Client, char *Args)
466 if( !Client->bIsAuthed ) {
467 sendf(Client->Socket, "401 Not Authenticated\n");
471 item = _GetItemFromString(Args);
473 sendf(Client->Socket, "406 Bad Item ID\n");
477 switch( ret = DispenseItem( Client->UID, item ) )
479 case 0: sendf(Client->Socket, "200 Dispense OK\n"); return ;
480 case 1: sendf(Client->Socket, "501 Unable to dispense\n"); return ;
481 case 2: sendf(Client->Socket, "402 Poor You\n"); return ;
483 sendf(Client->Socket, "500 Dispense Error\n");
488 void Server_Cmd_GIVE(tClient *Client, char *Args)
490 char *recipient, *ammount, *reason;
493 if( !Client->bIsAuthed ) {
494 sendf(Client->Socket, "401 Not Authenticated\n");
500 ammount = strchr(Args, ' ');
502 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
508 reason = strchr(ammount, ' ');
510 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
517 uid = GetUserID(recipient);
519 sendf(Client->Socket, "404 Invalid target user\n");
524 iAmmount = atoi(ammount);
525 if( iAmmount <= 0 ) {
526 sendf(Client->Socket, "407 Invalid Argument, ammount must be > zero\n");
531 switch( DispenseGive(Client->UID, uid, iAmmount, reason) )
534 sendf(Client->Socket, "200 Give OK\n");
537 sendf(Client->Socket, "402 Poor You\n");
540 sendf(Client->Socket, "500 Unknown error\n");
545 void Server_Cmd_ADD(tClient *Client, char *Args)
547 char *user, *ammount, *reason;
550 if( !Client->bIsAuthed ) {
551 sendf(Client->Socket, "401 Not Authenticated\n");
557 ammount = strchr(Args, ' ');
559 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 1 encountered\n");
565 reason = strchr(ammount, ' ');
567 sendf(Client->Socket, "407 Invalid Argument, expected 3 parameters, 2 encountered\n");
573 // TODO: Check if the current user is in coke/higher
574 if( (GetFlags(Client->UID) & USER_FLAG_TYPEMASK) < USER_TYPE_COKE ) {
575 sendf(Client->Socket, "403 Not in coke\n");
580 uid = GetUserID(user);
582 sendf(Client->Socket, "404 Invalid user\n");
587 iAmmount = atoi(ammount);
588 if( iAmmount == 0 && ammount[0] != '0' ) {
589 sendf(Client->Socket, "407 Invalid Argument\n");
594 switch( DispenseAdd(uid, Client->UID, iAmmount, reason) )
597 sendf(Client->Socket, "200 Add OK\n");
600 sendf(Client->Socket, "402 Poor Guy\n");
603 sendf(Client->Socket, "500 Unknown error\n");
608 void Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
611 int maxBal = INT_MAX, minBal = INT_MIN;
612 int numUsr = GetMaxID();
615 //minBal = atoi(Args);
618 for( i = 0; i < numUsr; i ++ )
620 int bal = GetBalance(i);
622 if( bal == INT_MIN ) continue;
624 if( bal < minBal ) continue;
625 if( bal > maxBal ) continue;
631 sendf(Client->Socket, "201 Users %i\n", numRet);
633 for( i = 0; i < numUsr; i ++ )
635 int bal = GetBalance(i);
637 if( bal == INT_MIN ) continue;
639 if( bal < minBal ) continue;
640 if( bal > maxBal ) continue;
643 _SendUserInfo(Client, i);
646 sendf(Client->Socket, "200 List End\n");
649 void Server_Cmd_USERINFO(tClient *Client, char *Args)
655 space = strchr(user, ' ');
656 if(space) *space = '\0';
659 uid = GetUserID(user);
661 sendf(Client->Socket, "404 Invalid user");
665 _SendUserInfo(Client, uid);
668 void _SendUserInfo(tClient *Client, int UserID)
670 char *type, *disabled="";
671 int flags = GetFlags(UserID);
673 switch( flags & USER_FLAG_TYPEMASK )
676 case USER_TYPE_NORMAL: type = "user"; break;
677 case USER_TYPE_COKE: type = "coke"; break;
678 case USER_TYPE_WHEEL: type = "wheel"; break;
679 case USER_TYPE_GOD: type = "meta"; break;
682 if( flags & USER_FLAG_DISABLED )
683 disabled = ",disabled";
685 // TODO: User flags/type
687 Client->Socket, "202 User %s %i %s%s\n",
688 GetUserName(UserID), GetBalance(UserID),
694 * \brief Authenticate a user
695 * \return User ID, or -1 if authentication failed
697 int GetUserAuth(const char *Salt, const char *Username, const uint8_t *ProvidedHash)
701 int ofs = strlen(Username) + strlen(Salt);
702 char input[ ofs + 40 + 1];
703 char tmp[4 + strlen(Username) + 1]; // uid=%s
707 if( strcmp(Username, "tpg") == 0 )
708 return GetUserID("tpg");
711 if( strcmp(Username, "root") == 0 )
712 return GetUserID("root");
717 strcpy(input, Username);
719 // TODO: Get user's SHA-1 hash
720 sprintf(tmp, "uid=%s", Username);
721 ldap_search_s(ld, "", LDAP_SCOPE_BASE, tmp, "userPassword", 0, res);
723 sprintf(input+ofs, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
724 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
725 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
727 // Then create the hash from the provided salt
728 // Compare that with the provided hash
734 // --- INTERNAL HELPERS ---
735 int sendf(int Socket, const char *Format, ...)
740 va_start(args, Format);
741 len = vsnprintf(NULL, 0, Format, args);
746 va_start(args, Format);
747 vsnprintf(buf, len+1, Format, args);
750 #if DEBUG_TRACE_CLIENT
751 printf("sendf: %s", buf);
754 return send(Socket, buf, len, 0);
758 // TODO: Move to another file
759 void HexBin(uint8_t *Dest, char *Src, int BufSize)
762 for( i = 0; i < BufSize; i ++ )
766 if('0' <= *Src && *Src <= '9')
767 val |= (*Src-'0') << 4;
768 else if('A' <= *Src && *Src <= 'F')
769 val |= (*Src-'A'+10) << 4;
770 else if('a' <= *Src && *Src <= 'f')
771 val |= (*Src-'a'+10) << 4;
776 if('0' <= *Src && *Src <= '9')
778 else if('A' <= *Src && *Src <= 'F')
779 val |= (*Src-'A'+10);
780 else if('a' <= *Src && *Src <= 'f')
781 val |= (*Src-'a'+10);
788 for( ; i < BufSize; i++ )
793 * \brief Decode a Base64 value
795 int UnBase64(uint8_t *Dest, char *Src, int BufSize)
799 char *start_src = Src;
801 for( i = 0; i+2 < BufSize; i += 3 )
804 for( j = 0; j < 4; j++, Src ++ ) {
805 if('A' <= *Src && *Src <= 'Z')
806 val |= (*Src - 'A') << ((3-j)*6);
807 else if('a' <= *Src && *Src <= 'z')
808 val |= (*Src - 'a' + 26) << ((3-j)*6);
809 else if('0' <= *Src && *Src <= '9')
810 val |= (*Src - '0' + 52) << ((3-j)*6);
812 val |= 62 << ((3-j)*6);
814 val |= 63 << ((3-j)*6);
818 j --; // Ignore invalid characters
820 Dest[i ] = (val >> 16) & 0xFF;
821 Dest[i+1] = (val >> 8) & 0xFF;
822 Dest[i+2] = val & 0xFF;
828 Dest[i] = (val >> 16) & 0xFF;
830 Dest[i+1] = (val >> 8) & 0xFF;
832 return Src - start_src;