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 1
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 char *Server_ParseClientCommand(tClient *Client, char *CommandString);
57 char *Server_Cmd_USER(tClient *Client, char *Args);
58 char *Server_Cmd_PASS(tClient *Client, char *Args);
59 char *Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
60 char *Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
61 char *Server_Cmd_ITEMINFO(tClient *Client, char *Args);
62 char *Server_Cmd_DISPENSE(tClient *Client, char *Args);
63 char *Server_Cmd_GIVE(tClient *Client, char *Args);
64 char *Server_Cmd_ADD(tClient *Client, char *Args);
65 char *Server_Cmd_ENUMUSERS(tClient *Client, char *Args);
66 char *Server_Cmd_USERINFO(tClient *Client, char *Args);
68 int sendf(int Socket, const char *Format, ...);
69 int GetUserAuth(const char *Salt, const char *Username, const uint8_t *Hash);
70 void HexBin(uint8_t *Dest, char *Src, int BufSize);
73 int giServer_Port = 1020;
74 int giServer_NextClientID = 1;
76 struct sClientCommand {
78 char *(*Function)(tClient *Client, char *Arguments);
79 } gaServer_Commands[] = {
80 {"USER", Server_Cmd_USER},
81 {"PASS", Server_Cmd_PASS},
82 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
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}
91 #define NUM_COMMANDS (sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0]))
96 * \brief Open listenting socket and serve connections
98 void Server_Start(void)
101 struct sockaddr_in server_addr, client_addr;
103 atexit(Server_Cleanup);
106 giServer_Socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
107 if( giServer_Socket < 0 ) {
108 fprintf(stderr, "ERROR: Unable to create server socket\n");
112 // Make listen address
113 memset(&server_addr, 0, sizeof(server_addr));
114 server_addr.sin_family = AF_INET; // Internet Socket
115 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
116 server_addr.sin_port = htons(giServer_Port); // Port
119 if( bind(giServer_Socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
120 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
126 if( listen(giServer_Socket, MAX_CONNECTION_QUEUE) < 0 ) {
127 fprintf(stderr, "ERROR: Unable to listen to socket\n");
132 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
136 uint len = sizeof(client_addr);
139 client_socket = accept(giServer_Socket, (struct sockaddr *) &client_addr, &len);
140 if(client_socket < 0) {
141 fprintf(stderr, "ERROR: Unable to accept client connection\n");
145 if(giDebugLevel >= 2) {
146 char ipstr[INET_ADDRSTRLEN];
147 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
148 printf("Client connection from %s:%i\n",
149 ipstr, ntohs(client_addr.sin_port));
152 // Trusted Connections
153 if( ntohs(client_addr.sin_port) < 1024 )
155 // TODO: Make this runtime configurable
156 switch( ntohl( client_addr.sin_addr.s_addr ) )
158 case 0x7F000001: // 127.0.0.1 localhost
159 //case 0x825E0D00: // 130.95.13.0
160 case 0x825E0D12: // 130.95.13.18 mussel
161 case 0x825E0D17: // 130.95.13.23 martello
169 // TODO: Multithread this?
170 Server_HandleClient(client_socket, bTrusted);
172 close(client_socket);
176 void Server_Cleanup(void)
178 printf("Close(%i)\n", giServer_Socket);
179 close(giServer_Socket);
183 * \brief Reads from a client socket and parses the command strings
184 * \param Socket Client socket number/handle
185 * \param bTrusted Is the client trusted?
187 void Server_HandleClient(int Socket, int bTrusted)
189 char inbuf[INPUT_BUFFER_SIZE];
191 int remspace = INPUT_BUFFER_SIZE-1;
193 tClient clientInfo = {0};
195 // Initialise Client info
196 clientInfo.Socket = Socket;
197 clientInfo.ID = giServer_NextClientID ++;
198 clientInfo.bIsTrusted = bTrusted;
203 * - The `buf` and `remspace` variables allow a line to span several
204 * calls to recv(), if a line is not completed in one recv() call
205 * it is saved to the beginning of `inbuf` and `buf` is updated to
208 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
211 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
215 while( (eol = strchr(start, '\n')) )
219 ret = Server_ParseClientCommand(&clientInfo, start);
221 #if DEBUG_TRACE_CLIENT
222 printf("send : %s", ret);
225 // `ret` is a string on the heap
226 send(Socket, ret, strlen(ret), 0);
231 // Check if there was an incomplete line
232 if( *start != '\0' ) {
233 int tailBytes = bytes - (start-buf);
234 // Roll back in buffer
235 memcpy(inbuf, start, tailBytes);
236 remspace -= tailBytes;
238 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
240 remspace = INPUT_BUFFER_SIZE - 1;
245 remspace = INPUT_BUFFER_SIZE - 1;
251 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
255 if(giDebugLevel >= 2) {
256 printf("Client %i: Disconnected\n", clientInfo.ID);
261 * \brief Parses a client command and calls the required helper function
262 * \param Client Pointer to client state structure
263 * \param CommandString Command from client (single line of the command)
264 * \return Heap String to return to the client
266 char *Server_ParseClientCommand(tClient *Client, char *CommandString)
271 // Split at first space
272 space = strchr(CommandString, ' ');
282 for( i = 0; i < NUM_COMMANDS; i++ )
284 if(strcmp(CommandString, gaServer_Commands[i].Name) == 0)
285 return gaServer_Commands[i].Function(Client, args);
288 return strdup("400 Unknown Command\n");
295 * \brief Set client username
297 * Usage: USER <username>
299 char *Server_Cmd_USER(tClient *Client, char *Args)
305 printf("Client %i authenticating as '%s'\n", Client->ID, Args);
309 free(Client->Username);
310 Client->Username = strdup(Args);
313 // Create a salt (that changes if the username is changed)
314 // Yes, I know, I'm a little paranoid, but who isn't?
315 Client->Salt[0] = 0x21 + (rand()&0x3F);
316 Client->Salt[1] = 0x21 + (rand()&0x3F);
317 Client->Salt[2] = 0x21 + (rand()&0x3F);
318 Client->Salt[3] = 0x21 + (rand()&0x3F);
319 Client->Salt[4] = 0x21 + (rand()&0x3F);
320 Client->Salt[5] = 0x21 + (rand()&0x3F);
321 Client->Salt[6] = 0x21 + (rand()&0x3F);
322 Client->Salt[7] = 0x21 + (rand()&0x3F);
324 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
325 ret = mkstr("100 SALT %s\n", Client->Salt);
327 ret = strdup("100 User Set\n");
333 * \brief Authenticate as a user
337 char *Server_Cmd_PASS(tClient *Client, char *Args)
339 uint8_t clienthash[HASH_LENGTH] = {0};
342 HexBin(clienthash, Args, HASH_LENGTH);
344 // TODO: Decrypt password passed
346 Client->UID = GetUserAuth(Client->Salt, Client->Username, clienthash);
348 if( Client->UID != -1 ) {
349 Client->bIsAuthed = 1;
350 return strdup("200 Auth OK\n");
355 printf("Client %i: Password hash ", Client->ID);
356 for(i=0;i<HASH_LENGTH;i++)
357 printf("%02x", clienthash[i]&0xFF);
361 return strdup("401 Auth Failure\n");
365 * \brief Authenticate as a user without a password
367 * Usage: AUTOAUTH <user>
369 char *Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
371 char *spos = strchr(Args, ' ');
372 if(spos) *spos = '\0'; // Remove characters after the ' '
375 if( !Client->bIsTrusted ) {
377 printf("Client %i: Untrusted client attempting to AUTOAUTH\n", Client->ID);
378 return strdup("401 Untrusted\n");
382 Client->UID = GetUserID( Args );
383 if( Client->UID < 0 ) {
385 printf("Client %i: Unknown user '%s'\n", Client->ID, Args);
386 return strdup("401 Auth Failure\n");
390 printf("Client %i: Authenticated as '%s' (%i)\n", Client->ID, Args, Client->UID);
392 return strdup("200 Auth OK\n");
396 * \brief Enumerate the items that the server knows about
398 char *Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
404 retLen = snprintf(NULL, 0, "201 Items %i", giNumItems);
406 for( i = 0; i < giNumItems; i ++ )
408 retLen += snprintf(NULL, 0, " %s:%i", gaItems[i].Handler->Name, gaItems[i].ID);
411 ret = malloc(retLen+1);
413 retLen += sprintf(ret+retLen, "201 Items %i", giNumItems);
415 for( i = 0; i < giNumItems; i ++ ) {
416 retLen += sprintf(ret+retLen, " %s:%i", gaItems[i].Handler->Name, gaItems[i].ID);
424 tItem *_GetItemFromString(char *String)
428 char *colon = strchr(String, ':');
440 for( i = 0; i < giNumHandlers; i ++ )
442 if( strcmp(gaHandlers[i]->Name, type) == 0) {
443 handler = gaHandlers[i];
452 for( i = 0; i < giNumItems; i ++ )
454 if( gaItems[i].Handler != handler ) continue;
455 if( gaItems[i].ID != num ) continue;
462 * \brief Fetch information on a specific item
464 char *Server_Cmd_ITEMINFO(tClient *Client, char *Args)
468 tItem *item = _GetItemFromString(Args);
471 return strdup("406 Bad Item ID\n");
475 retLen = snprintf(NULL, 0, "202 Item %s:%i %i %s\n",
476 item->Handler->Name, item->ID, item->Price, item->Name);
477 ret = malloc(retLen+1);
478 sprintf(ret, "202 Item %s:%i %i %s\n",
479 item->Handler->Name, item->ID, item->Price, item->Name);
484 char *Server_Cmd_DISPENSE(tClient *Client, char *Args)
488 if( !Client->bIsAuthed ) return strdup("401 Not Authenticated\n");
490 item = _GetItemFromString(Args);
492 return strdup("406 Bad Item ID\n");
495 switch( ret = DispenseItem( Client->UID, item ) )
497 case 0: return strdup("200 Dispense OK\n");
498 case 1: return strdup("501 Unable to dispense\n");
499 case 2: return strdup("402 Poor You\n");
501 return strdup("500 Dispense Error\n");
505 char *Server_Cmd_GIVE(tClient *Client, char *Args)
507 char *recipient, *ammount, *reason;
510 if( !Client->bIsAuthed ) return strdup("401 Not Authenticated\n");
514 ammount = strchr(Args, ' ');
515 if( !ammount ) return strdup("407 Invalid Argument, expected 3 parameters, 1 encountered\n");
519 reason = strchr(ammount, ' ');
520 if( !reason ) return strdup("407 Invalid Argument, expected 3 parameters, 2 encountered\n");
525 uid = GetUserID(recipient);
526 if( uid == -1 ) return strdup("404 Invalid target user");
529 iAmmount = atoi(ammount);
530 if( iAmmount <= 0 ) return strdup("407 Invalid Argument, ammount must be > zero\n");
533 switch( DispenseGive(Client->UID, uid, iAmmount, reason) )
536 return strdup("200 Give OK\n");
538 return strdup("402 Poor You\n");
540 return strdup("500 Unknown error\n");
544 char *Server_Cmd_ADD(tClient *Client, char *Args)
546 char *user, *ammount, *reason;
549 if( !Client->bIsAuthed ) return strdup("401 Not Authenticated\n");
553 ammount = strchr(Args, ' ');
554 if( !ammount ) return strdup("407 Invalid Argument, expected 3 parameters, 1 encountered\n");
558 reason = strchr(ammount, ' ');
559 if( !reason ) return strdup("407 Invalid Argument, expected 3 parameters, 2 encountered\n");
563 // TODO: Check if the current user is in coke/higher
566 uid = GetUserID(user);
567 if( uid == -1 ) return strdup("404 Invalid user");
570 iAmmount = atoi(ammount);
571 if( iAmmount == 0 && ammount[0] != '0' )
572 return strdup("407 Invalid Argument\n");
575 switch( DispenseAdd(uid, Client->UID, iAmmount, reason) )
578 return strdup("200 Add OK\n");
580 return strdup("402 Poor Guy\n");
582 return strdup("500 Unknown error\n");
586 char *Server_Cmd_ENUMUSERS(tClient *Client, char *Args)
589 int maxBal = INT_MAX, minBal = INT_MIN;
590 int numUsr = GetMaxID();
593 //minBal = atoi(Args);
596 for( i = 0; i < numUsr; i ++ )
598 int bal = GetBalance(i);
600 if( bal == INT_MIN ) continue;
602 if( bal < minBal ) continue;
603 if( bal > maxBal ) continue;
609 sendf(Client->Socket, "201 Users %i\n", numRet);
611 for( i = 0; i < numUsr; i ++ )
613 int bal = GetBalance(i);
615 if( bal == INT_MIN ) continue;
617 if( bal < minBal ) continue;
618 if( bal > maxBal ) continue;
621 sendf(Client->Socket, "202 User %s %i user\n", GetUserName(i), GetBalance(i));
624 return strdup("200 List End\n");
627 char *Server_Cmd_USERINFO(tClient *Client, char *Args)
633 space = strchr(user, ' ');
634 if(space) *space = '\0';
637 uid = GetUserID(user);
638 if( uid == -1 ) return strdup("404 Invalid user");
640 // TODO: User flags/type
641 return mkstr("202 User %s %i user\n", user, GetBalance(uid));
645 * \brief Authenticate a user
646 * \return User ID, or -1 if authentication failed
648 int GetUserAuth(const char *Salt, const char *Username, const uint8_t *ProvidedHash)
652 int ofs = strlen(Username) + strlen(Salt);
653 char input[ ofs + 40 + 1];
654 char tmp[4 + strlen(Username) + 1]; // uid=%s
658 if( strcmp(Username, "tpg") == 0 )
659 return GetUserID("tpg");
662 if( strcmp(Username, "root") == 0 )
663 return GetUserID("root");
668 strcpy(input, Username);
670 // TODO: Get user's SHA-1 hash
671 sprintf(tmp, "uid=%s", Username);
672 ldap_search_s(ld, "", LDAP_SCOPE_BASE, tmp, "userPassword", 0, res);
674 sprintf(input+ofs, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
675 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
676 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
678 // Then create the hash from the provided salt
679 // Compare that with the provided hash
685 // --- INTERNAL HELPERS ---
686 int sendf(int Socket, const char *Format, ...)
691 va_start(args, Format);
692 len = vsnprintf(NULL, 0, Format, args);
697 va_start(args, Format);
698 vsnprintf(buf, len+1, Format, args);
701 #if DEBUG_TRACE_CLIENT
702 printf("sendf: %s", buf);
705 return send(Socket, buf, len, 0);
709 // TODO: Move to another file
710 void HexBin(uint8_t *Dest, char *Src, int BufSize)
713 for( i = 0; i < BufSize; i ++ )
717 if('0' <= *Src && *Src <= '9')
718 val |= (*Src-'0') << 4;
719 else if('A' <= *Src && *Src <= 'F')
720 val |= (*Src-'A'+10) << 4;
721 else if('a' <= *Src && *Src <= 'f')
722 val |= (*Src-'a'+10) << 4;
727 if('0' <= *Src && *Src <= '9')
729 else if('A' <= *Src && *Src <= 'F')
730 val |= (*Src-'A'+10);
731 else if('a' <= *Src && *Src <= 'f')
732 val |= (*Src-'a'+10);
739 for( ; i < BufSize; i++ )
744 * \brief Decode a Base64 value
746 int UnBase64(uint8_t *Dest, char *Src, int BufSize)
750 char *start_src = Src;
752 for( i = 0; i+2 < BufSize; i += 3 )
755 for( j = 0; j < 4; j++, Src ++ ) {
756 if('A' <= *Src && *Src <= 'Z')
757 val |= (*Src - 'A') << ((3-j)*6);
758 else if('a' <= *Src && *Src <= 'z')
759 val |= (*Src - 'a' + 26) << ((3-j)*6);
760 else if('0' <= *Src && *Src <= '9')
761 val |= (*Src - '0' + 52) << ((3-j)*6);
763 val |= 62 << ((3-j)*6);
765 val |= 63 << ((3-j)*6);
769 j --; // Ignore invalid characters
771 Dest[i ] = (val >> 16) & 0xFF;
772 Dest[i+1] = (val >> 8) & 0xFF;
773 Dest[i+2] = val & 0xFF;
779 Dest[i] = (val >> 16) & 0xFF;
781 Dest[i+1] = (val >> 8) & 0xFF;
783 return Src - start_src;