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>
19 #define MAX_CONNECTION_QUEUE 5
20 #define INPUT_BUFFER_SIZE 256
22 #define HASH_TYPE SHA512
23 #define HASH_LENGTH 64
25 #define MSG_STR_TOO_LONG "499 Command too long (limit "EXPSTR(INPUT_BUFFER_SIZE)")\n"
28 typedef struct sClient
32 int bIsTrusted; // Is the connection from a trusted host/port
42 void Server_Start(void);
43 void Server_HandleClient(int Socket, int bTrusted);
44 char *Server_ParseClientCommand(tClient *Client, char *CommandString);
46 char *Server_Cmd_USER(tClient *Client, char *Args);
47 char *Server_Cmd_PASS(tClient *Client, char *Args);
48 char *Server_Cmd_AUTOAUTH(tClient *Client, char *Args);
49 char *Server_Cmd_ENUMITEMS(tClient *Client, char *Args);
50 char *Server_Cmd_ITEMINFO(tClient *Client, char *Args);
51 char *Server_Cmd_DISPENSE(tClient *Client, char *Args);
53 int GetUserAuth(const char *Salt, const char *Username, const uint8_t *Hash);
54 void HexBin(uint8_t *Dest, char *Src, int BufSize);
57 int giServer_Port = 1020;
58 int giServer_NextClientID = 1;
60 struct sClientCommand {
62 char *(*Function)(tClient *Client, char *Arguments);
63 } gaServer_Commands[] = {
64 {"USER", Server_Cmd_USER},
65 {"PASS", Server_Cmd_PASS},
66 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
67 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
68 {"ITEM_INFO", Server_Cmd_ITEMINFO},
69 {"DISPENSE", Server_Cmd_DISPENSE}
71 #define NUM_COMMANDS (sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0]))
75 * \brief Open listenting socket and serve connections
77 void Server_Start(void)
79 int server_socket, client_socket;
80 struct sockaddr_in server_addr, client_addr;
83 server_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
84 if( server_socket < 0 ) {
85 fprintf(stderr, "ERROR: Unable to create server socket\n");
89 // Make listen address
90 memset(&server_addr, 0, sizeof(server_addr));
91 server_addr.sin_family = AF_INET; // Internet Socket
92 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
93 server_addr.sin_port = htons(giServer_Port); // Port
96 if( bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
97 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
102 if( listen(server_socket, MAX_CONNECTION_QUEUE) < 0 ) {
103 fprintf(stderr, "ERROR: Unable to listen to socket\n");
107 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
111 uint len = sizeof(client_addr);
114 client_socket = accept(server_socket, (struct sockaddr *) &client_addr, &len);
115 if(client_socket < 0) {
116 fprintf(stderr, "ERROR: Unable to accept client connection\n");
120 if(giDebugLevel >= 2) {
121 char ipstr[INET_ADDRSTRLEN];
122 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
123 printf("Client connection from %s:%i\n",
124 ipstr, ntohs(client_addr.sin_port));
127 // Trusted Connections
128 if( ntohs(client_addr.sin_port) < 1024 )
130 // TODO: Make this runtime configurable
131 switch( ntohl( client_addr.sin_addr.s_addr ) )
133 case 0x7F000001: // 127.0.0.1 localhost
134 //case 0x825E0D00: // 130.95.13.0
135 case 0x825E0D12: // 130.95.13.18 mussel
136 case 0x825E0D17: // 130.95.13.23 martello
144 // TODO: Multithread this?
145 Server_HandleClient(client_socket, bTrusted);
147 close(client_socket);
152 * \brief Reads from a client socket and parses the command strings
153 * \param Socket Client socket number/handle
154 * \param bTrusted Is the client trusted?
156 void Server_HandleClient(int Socket, int bTrusted)
158 char inbuf[INPUT_BUFFER_SIZE];
160 int remspace = INPUT_BUFFER_SIZE-1;
162 tClient clientInfo = {0};
164 // Initialise Client info
165 clientInfo.ID = giServer_NextClientID ++;
166 clientInfo.bIsTrusted = bTrusted;
171 * - The `buf` and `remspace` variables allow a line to span several
172 * calls to recv(), if a line is not completed in one recv() call
173 * it is saved to the beginning of `inbuf` and `buf` is updated to
176 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
179 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
183 while( (eol = strchr(start, '\n')) )
187 ret = Server_ParseClientCommand(&clientInfo, start);
188 // `ret` is a string on the heap
189 send(Socket, ret, strlen(ret), 0);
194 // Check if there was an incomplete line
195 if( *start != '\0' ) {
196 int tailBytes = bytes - (start-buf);
197 // Roll back in buffer
198 memcpy(inbuf, start, tailBytes);
199 remspace -= tailBytes;
201 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
203 remspace = INPUT_BUFFER_SIZE - 1;
208 remspace = INPUT_BUFFER_SIZE - 1;
214 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
218 if(giDebugLevel >= 2) {
219 printf("Client %i: Disconnected\n", clientInfo.ID);
224 * \brief Parses a client command and calls the required helper function
225 * \param Client Pointer to client state structure
226 * \param CommandString Command from client (single line of the command)
227 * \return Heap String to return to the client
229 char *Server_ParseClientCommand(tClient *Client, char *CommandString)
234 // Split at first space
235 space = strchr(CommandString, ' ');
245 for( i = 0; i < NUM_COMMANDS; i++ )
247 if(strcmp(CommandString, gaServer_Commands[i].Name) == 0)
248 return gaServer_Commands[i].Function(Client, args);
251 return strdup("400 Unknown Command\n");
258 * \brief Set client username
260 * Usage: USER <username>
262 char *Server_Cmd_USER(tClient *Client, char *Args)
268 printf("Client %i authenticating as '%s'\n", Client->ID, Args);
272 free(Client->Username);
273 Client->Username = strdup(Args);
276 // Create a salt (that changes if the username is changed)
277 // Yes, I know, I'm a little paranoid, but who isn't?
278 Client->Salt[0] = 0x21 + (rand()&0x3F);
279 Client->Salt[1] = 0x21 + (rand()&0x3F);
280 Client->Salt[2] = 0x21 + (rand()&0x3F);
281 Client->Salt[3] = 0x21 + (rand()&0x3F);
282 Client->Salt[4] = 0x21 + (rand()&0x3F);
283 Client->Salt[5] = 0x21 + (rand()&0x3F);
284 Client->Salt[6] = 0x21 + (rand()&0x3F);
285 Client->Salt[7] = 0x21 + (rand()&0x3F);
287 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
288 // "100 Salt xxxxXXXX\n"
289 ret = strdup("100 SALT xxxxXXXX\n");
290 sprintf(ret, "100 SALT %s\n", Client->Salt);
292 ret = strdup("100 User Set\n");
298 * \brief Authenticate as a user
302 char *Server_Cmd_PASS(tClient *Client, char *Args)
304 uint8_t clienthash[HASH_LENGTH] = {0};
307 HexBin(clienthash, Args, HASH_LENGTH);
309 // TODO: Decrypt password passed
311 Client->UID = GetUserAuth(Client->Salt, Client->Username, clienthash);
313 if( Client->UID != -1 ) {
314 Client->bIsAuthed = 1;
315 return strdup("200 Auth OK\n");
320 printf("Client %i: Password hash ", Client->ID);
321 for(i=0;i<HASH_LENGTH;i++)
322 printf("%02x", clienthash[i]&0xFF);
326 return strdup("401 Auth Failure\n");
330 * \brief Authenticate as a user without a password
332 * Usage: AUTOAUTH <user>
334 char *Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
336 char *spos = strchr(Args, ' ');
337 if(spos) *spos = '\0'; // Remove characters after the ' '
340 if( !Client->bIsTrusted ) {
342 printf("Client %i: Untrusted client attempting to AUTOAUTH\n", Client->ID);
343 return strdup("401 Untrusted\n");
347 Client->UID = GetUserID( Args );
348 if( Client->UID < 0 ) {
350 printf("Client %i: Unknown user '%s'\n", Client->ID, Args);
351 return strdup("401 Auth Failure\n");
355 printf("Client %i: Authenticated as '%s' (%i)\n", Client->ID, Args, Client->UID);
357 return strdup("200 Auth OK\n");
361 * \brief Enumerate the items that the server knows about
363 char *Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
365 // int nItems = giNumItems;
370 retLen = snprintf(NULL, 0, "201 Items %i", giNumItems);
372 for( i = 0; i < giNumItems; i ++ )
374 retLen += snprintf(NULL, 0, " %s:%i", gaItems[i].Handler->Name, gaItems[i].ID);
377 ret = malloc(retLen+1);
379 retLen += sprintf(ret+retLen, "201 Items %i", giNumItems);
381 for( i = 0; i < giNumItems; i ++ ) {
382 retLen += sprintf(ret+retLen, " %s:%i", gaItems[i].Handler->Name, gaItems[i].ID);
390 tItem *_GetItemFromString(char *String)
394 char *colon = strchr(String, ':');
406 for( i = 0; i < giNumHandlers; i ++ )
408 if( strcmp(gaHandlers[i]->Name, type) == 0) {
409 handler = gaHandlers[i];
418 for( i = 0; i < giNumItems; i ++ )
420 if( gaItems[i].Handler != handler ) continue;
421 if( gaItems[i].ID != num ) continue;
428 * \brief Fetch information on a specific item
430 char *Server_Cmd_ITEMINFO(tClient *Client, char *Args)
434 tItem *item = _GetItemFromString(Args);
437 return strdup("406 Bad Item ID\n");
441 retLen = snprintf(NULL, 0, "202 Item %s:%i %i %s\n",
442 item->Handler->Name, item->ID, item->Price, item->Name);
443 ret = malloc(retLen+1);
444 sprintf(ret, "202 Item %s:%i %i %s\n",
445 item->Handler->Name, item->ID, item->Price, item->Name);
450 char *Server_Cmd_DISPENSE(tClient *Client, char *Args)
453 if( !Client->bIsAuthed ) return strdup("401 Not Authenticated\n");
455 item = _GetItemFromString(Args);
457 return strdup("406 Bad Item ID\n");
460 switch( DispenseItem( Client->UID, item ) )
462 case 0: return strdup("200 Dispense OK\n");
463 case 1: return strdup("501 Unable to dispense\n");
464 case 2: return strdup("402 Poor You\n");
466 return strdup("500 Dispense Error\n");
470 char *Server_Cmd_GIVE(tClient *Client, char *Args)
472 char *recipient, *ammount, *reason;
475 if( !Client->bIsAuthed ) return strdup("401 Not Authenticated\n");
479 ammount = strchr(Args, ' ');
480 if( !ammount ) return strdup("407 Invalid Argument, expected 3 parameters, 1 encountered\n");
484 reason = strchr(ammount, ' ');
485 if( !reason ) return strdup("407 Invalid Argument, expected 3 parameters, 2 encountered\n");
490 uid = GetUserID(recipient);
491 if( uid == -1 ) return strdup("404 Invalid target user");
494 iAmmount = atoi(ammount);
495 if( iAmmount <= 0 ) return strdup("407 Invalid Argument, ammount must be > zero\n");
498 switch( Transfer(Client->UID, uid, iAmmount, reason) )
501 return strdup("200 Give OK\n");
503 return strdup("402 Poor You\n");
508 * \brief Authenticate a user
509 * \return User ID, or -1 if authentication failed
511 int GetUserAuth(const char *Salt, const char *Username, const uint8_t *ProvidedHash)
515 int ofs = strlen(Username) + strlen(Salt);
516 char input[ ofs + 40 + 1];
517 char tmp[4 + strlen(Username) + 1]; // uid=%s
521 if( strcmp(Username, "tpg") == 0 )
522 return GetUserID("tpg");
527 strcpy(input, Username);
529 // TODO: Get user's SHA-1 hash
530 sprintf(tmp, "uid=%s", Username);
531 ldap_search_s(ld, "", LDAP_SCOPE_BASE, tmp, "userPassword", 0, res);
533 sprintf(input+ofs, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
534 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
535 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
537 // Then create the hash from the provided salt
538 // Compare that with the provided hash
544 // --- INTERNAL HELPERS ---
545 // TODO: Move to another file
546 void HexBin(uint8_t *Dest, char *Src, int BufSize)
549 for( i = 0; i < BufSize; i ++ )
553 if('0' <= *Src && *Src <= '9')
554 val |= (*Src-'0') << 4;
555 else if('A' <= *Src && *Src <= 'F')
556 val |= (*Src-'A'+10) << 4;
557 else if('a' <= *Src && *Src <= 'f')
558 val |= (*Src-'a'+10) << 4;
563 if('0' <= *Src && *Src <= '9')
565 else if('A' <= *Src && *Src <= 'F')
566 val |= (*Src-'A'+10);
567 else if('a' <= *Src && *Src <= 'f')
568 val |= (*Src-'a'+10);
575 for( ; i < BufSize; i++ )
580 * \brief Decode a Base64 value
582 int UnBase64(uint8_t *Dest, char *Src, int BufSize)
586 char *start_src = Src;
588 for( i = 0; i+2 < BufSize; i += 3 )
591 for( j = 0; j < 4; j++, Src ++ ) {
592 if('A' <= *Src && *Src <= 'Z')
593 val |= (*Src - 'A') << ((3-j)*6);
594 else if('a' <= *Src && *Src <= 'z')
595 val |= (*Src - 'a' + 26) << ((3-j)*6);
596 else if('0' <= *Src && *Src <= '9')
597 val |= (*Src - '0' + 52) << ((3-j)*6);
599 val |= 62 << ((3-j)*6);
601 val |= 63 << ((3-j)*6);
605 j --; // Ignore invalid characters
607 Dest[i ] = (val >> 16) & 0xFF;
608 Dest[i+1] = (val >> 8) & 0xFF;
609 Dest[i+2] = val & 0xFF;
615 Dest[i] = (val >> 16) & 0xFF;
617 Dest[i+1] = (val >> 8) & 0xFF;
619 return Src - start_src;