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 void HexBin(uint8_t *Dest, char *Src, int BufSize);
56 int giServer_Port = 1020;
57 int giServer_NextClientID = 1;
59 struct sClientCommand {
61 char *(*Function)(tClient *Client, char *Arguments);
62 } gaServer_Commands[] = {
63 {"USER", Server_Cmd_USER},
64 {"PASS", Server_Cmd_PASS},
65 {"AUTOAUTH", Server_Cmd_AUTOAUTH},
66 {"ENUM_ITEMS", Server_Cmd_ENUMITEMS},
67 {"ITEM_INFO", Server_Cmd_ITEMINFO},
68 {"DISPENSE", Server_Cmd_DISPENSE}
70 #define NUM_COMMANDS (sizeof(gaServer_Commands)/sizeof(gaServer_Commands[0]))
74 * \brief Open listenting socket and serve connections
76 void Server_Start(void)
78 int server_socket, client_socket;
79 struct sockaddr_in server_addr, client_addr;
82 server_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
83 if( server_socket < 0 ) {
84 fprintf(stderr, "ERROR: Unable to create server socket\n");
88 // Make listen address
89 memset(&server_addr, 0, sizeof(server_addr));
90 server_addr.sin_family = AF_INET; // Internet Socket
91 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
92 server_addr.sin_port = htons(giServer_Port); // Port
95 if( bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0 ) {
96 fprintf(stderr, "ERROR: Unable to bind to 0.0.0.0:%i\n", giServer_Port);
101 if( listen(server_socket, MAX_CONNECTION_QUEUE) < 0 ) {
102 fprintf(stderr, "ERROR: Unable to listen to socket\n");
106 printf("Listening on 0.0.0.0:%i\n", giServer_Port);
110 uint len = sizeof(client_addr);
113 client_socket = accept(server_socket, (struct sockaddr *) &client_addr, &len);
114 if(client_socket < 0) {
115 fprintf(stderr, "ERROR: Unable to accept client connection\n");
119 if(giDebugLevel >= 2) {
120 char ipstr[INET_ADDRSTRLEN];
121 inet_ntop(AF_INET, &client_addr.sin_addr, ipstr, INET_ADDRSTRLEN);
122 printf("Client connection from %s:%i\n",
123 ipstr, ntohs(client_addr.sin_port));
126 // Trusted Connections
127 if( ntohs(client_addr.sin_port) < 1024 )
129 // TODO: Make this runtime configurable
130 switch( ntohl( client_addr.sin_addr.s_addr ) )
132 case 0x7F000001: // 127.0.0.1 localhost
133 //case 0x825E0D00: // 130.95.13.0
134 case 0x825E0D12: // 130.95.13.18 mussel
135 case 0x825E0D17: // 130.95.13.23 martello
143 // TODO: Multithread this?
144 Server_HandleClient(client_socket, bTrusted);
146 close(client_socket);
151 * \brief Reads from a client socket and parses the command strings
152 * \param Socket Client socket number/handle
153 * \param bTrusted Is the client trusted?
155 void Server_HandleClient(int Socket, int bTrusted)
157 char inbuf[INPUT_BUFFER_SIZE];
159 int remspace = INPUT_BUFFER_SIZE-1;
161 tClient clientInfo = {0};
163 // Initialise Client info
164 clientInfo.ID = giServer_NextClientID ++;
165 clientInfo.bIsTrusted = bTrusted;
170 * - The `buf` and `remspace` variables allow a line to span several
171 * calls to recv(), if a line is not completed in one recv() call
172 * it is saved to the beginning of `inbuf` and `buf` is updated to
175 while( (bytes = recv(Socket, buf, remspace, 0)) > 0 )
178 buf[bytes] = '\0'; // Allow us to use stdlib string functions on it
182 while( (eol = strchr(start, '\n')) )
186 ret = Server_ParseClientCommand(&clientInfo, start);
187 // `ret` is a string on the heap
188 send(Socket, ret, strlen(ret), 0);
193 // Check if there was an incomplete line
194 if( *start != '\0' ) {
195 int tailBytes = bytes - (start-buf);
196 // Roll back in buffer
197 memcpy(inbuf, start, tailBytes);
198 remspace -= tailBytes;
200 send(Socket, MSG_STR_TOO_LONG, sizeof(MSG_STR_TOO_LONG), 0);
202 remspace = INPUT_BUFFER_SIZE - 1;
207 remspace = INPUT_BUFFER_SIZE - 1;
213 fprintf(stderr, "ERROR: Unable to recieve from client on socket %i\n", Socket);
217 if(giDebugLevel >= 2) {
218 printf("Client %i: Disconnected\n", clientInfo.ID);
223 * \brief Parses a client command and calls the required helper function
224 * \param Client Pointer to client state structure
225 * \param CommandString Command from client (single line of the command)
226 * \return Heap String to return to the client
228 char *Server_ParseClientCommand(tClient *Client, char *CommandString)
233 // Split at first space
234 space = strchr(CommandString, ' ');
244 for( i = 0; i < NUM_COMMANDS; i++ )
246 if(strcmp(CommandString, gaServer_Commands[i].Name) == 0)
247 return gaServer_Commands[i].Function(Client, args);
250 return strdup("400 Unknown Command\n");
257 * \brief Set client username
259 * Usage: USER <username>
261 char *Server_Cmd_USER(tClient *Client, char *Args)
267 printf("Client %i authenticating as '%s'\n", Client->ID, Args);
271 free(Client->Username);
272 Client->Username = strdup(Args);
275 // Create a salt (that changes if the username is changed)
276 // Yes, I know, I'm a little paranoid, but who isn't?
277 Client->Salt[0] = 0x21 + (rand()&0x3F);
278 Client->Salt[1] = 0x21 + (rand()&0x3F);
279 Client->Salt[2] = 0x21 + (rand()&0x3F);
280 Client->Salt[3] = 0x21 + (rand()&0x3F);
281 Client->Salt[4] = 0x21 + (rand()&0x3F);
282 Client->Salt[5] = 0x21 + (rand()&0x3F);
283 Client->Salt[6] = 0x21 + (rand()&0x3F);
284 Client->Salt[7] = 0x21 + (rand()&0x3F);
286 // TODO: Also send hash type to use, (SHA1 or crypt according to [DAA])
287 // "100 Salt xxxxXXXX\n"
288 ret = strdup("100 SALT xxxxXXXX\n");
289 sprintf(ret, "100 SALT %s\n", Client->Salt);
291 ret = strdup("100 User Set\n");
297 * \brief Authenticate as a user
301 char *Server_Cmd_PASS(tClient *Client, char *Args)
303 uint8_t clienthash[HASH_LENGTH] = {0};
306 HexBin(clienthash, Args, HASH_LENGTH);
308 // TODO: Decrypt password passed
310 Client->UID = GetUserAuth(Client->Username, "");
312 if( Client->UID != -1 ) {
313 Client->bIsAuthed = 1;
314 return strdup("200 Auth OK\n");
319 printf("Client %i: Password hash ", Client->ID);
320 for(i=0;i<HASH_LENGTH;i++)
321 printf("%02x", clienthash[i]&0xFF);
325 return strdup("401 Auth Failure\n");
329 * \brief Authenticate as a user without a password
331 * Usage: AUTOAUTH <user>
333 char *Server_Cmd_AUTOAUTH(tClient *Client, char *Args)
335 char *spos = strchr(Args, ' ');
336 if(spos) *spos = '\0'; // Remove characters after the ' '
339 if( !Client->bIsTrusted ) {
341 printf("Client %i: Untrusted client attempting to AUTOAUTH\n", Client->ID);
342 return strdup("401 Untrusted\n");
346 Client->UID = GetUserID( Args );
347 if( Client->UID < 0 ) {
349 printf("Client %i: Unknown user '%s'\n", Client->ID, Args);
350 return strdup("401 Auth Failure\n");
354 printf("Client %i: Authenticated as '%s' (%i)\n", Client->ID, Args, Client->UID);
356 return strdup("200 Auth OK\n");
360 * \brief Enumerate the items that the server knows about
362 char *Server_Cmd_ENUMITEMS(tClient *Client, char *Args)
364 // int nItems = giNumItems;
369 retLen = snprintf(NULL, 0, "201 Items %i", giNumItems);
371 for( i = 0; i < giNumItems; i ++ )
373 retLen += snprintf(NULL, 0, " %s:%i", gaItems[i].Handler->Name, gaItems[i].ID);
376 ret = malloc(retLen+1);
378 retLen += sprintf(ret+retLen, "201 Items %i", giNumItems);
380 for( i = 0; i < giNumItems; i ++ ) {
381 retLen += sprintf(ret+retLen, " %s:%i", gaItems[i].Handler->Name, gaItems[i].ID);
389 tItem *_GetItemFromString(char *String)
393 char *colon = strchr(String, ':');
405 for( i = 0; i < giNumHandlers; i ++ )
407 if( strcmp(gaHandlers[i]->Name, type) == 0) {
408 handler = gaHandlers[i];
417 for( i = 0; i < giNumItems; i ++ )
419 if( gaItems[i].Handler != handler ) continue;
420 if( gaItems[i].ID != num ) continue;
427 * \brief Fetch information on a specific item
429 char *Server_Cmd_ITEMINFO(tClient *Client, char *Args)
433 tItem *item = _GetItemFromString(Args);
436 return strdup("406 Bad Item ID\n");
440 retLen = snprintf(NULL, 0, "202 Item %s:%i %i %s\n",
441 item->Handler->Name, item->ID, item->Price, item->Name);
442 ret = malloc(retLen+1);
443 sprintf(ret, "202 Item %s:%i %i %s\n",
444 item->Handler->Name, item->ID, item->Price, item->Name);
449 char *Server_Cmd_DISPENSE(tClient *Client, char *Args)
452 if( !Client->bIsAuthed ) return strdup("401 Not Authenticated\n");
454 item = _GetItemFromString(Args);
456 return strdup("406 Bad Item ID\n");
459 switch( DispenseItem( Client->UID, item ) )
461 case 0: return strdup("200 Dispense OK\n");
462 case 1: return strdup("501 Unable to dispense\n");
463 case 2: return strdup("402 Poor You\n");
465 return strdup("500 Dispense Error\n");
469 char *Server_Cmd_GIVE(tClient *Client, char *Args)
471 char *recipient, *ammount, *reason;
474 if( !Client->bIsAuthed ) return strdup("401 Not Authenticated\n");
478 ammount = strchr(Args, ' ');
479 if( !ammount ) return strdup("407 Invalid Argument, expected 3 parameters, 1 encountered\n");
483 reason = strchr(ammount, ' ');
484 if( !reason ) return strdup("407 Invalid Argument, expected 3 parameters, 2 encountered\n");
489 uid = GetUserID(recipient);
490 if( uid == -1 ) return strdup("404 Invalid target user");
493 iAmmount = atoi(ammount);
494 if( iAmmount <= 0 ) return strdup("407 Invalid Argument, ammount must be > zero\n");
497 switch( Transfer(Client->UID, uid, iAmmount, reason) )
500 return strdup("200 Give OK\n");
502 return strdup("402 Poor You\n");
506 // --- INTERNAL HELPERS ---
507 // TODO: Move to another file
508 void HexBin(uint8_t *Dest, char *Src, int BufSize)
511 for( i = 0; i < BufSize; i ++ )
515 if('0' <= *Src && *Src <= '9')
516 val |= (*Src-'0') << 4;
517 else if('A' <= *Src && *Src <= 'F')
518 val |= (*Src-'A'+10) << 4;
519 else if('a' <= *Src && *Src <= 'f')
520 val |= (*Src-'a'+10) << 4;
525 if('0' <= *Src && *Src <= '9')
527 else if('A' <= *Src && *Src <= 'F')
528 val |= (*Src-'A'+10);
529 else if('a' <= *Src && *Src <= 'f')
530 val |= (*Src-'a'+10);
537 for( ; i < BufSize; i++ )
542 * \brief Decode a Base64 value
544 int UnBase64(uint8_t *Dest, char *Src, int BufSize)
548 char *start_src = Src;
550 for( i = 0; i+2 < BufSize; i += 3 )
553 for( j = 0; j < 4; j++, Src ++ ) {
554 if('A' <= *Src && *Src <= 'Z')
555 val |= (*Src - 'A') << ((3-j)*6);
556 else if('a' <= *Src && *Src <= 'z')
557 val |= (*Src - 'a' + 26) << ((3-j)*6);
558 else if('0' <= *Src && *Src <= '9')
559 val |= (*Src - '0' + 52) << ((3-j)*6);
561 val |= 62 << ((3-j)*6);
563 val |= 63 << ((3-j)*6);
567 j --; // Ignore invalid characters
569 Dest[i ] = (val >> 16) & 0xFF;
570 Dest[i+1] = (val >> 8) & 0xFF;
571 Dest[i+2] = val & 0xFF;
577 Dest[i] = (val >> 16) & 0xFF;
579 Dest[i+1] = (val >> 8) & 0xFF;
581 return Src - start_src;