3 * UCC (University [of WA] Computer Club) Electronic Accounting System
6 * main.c - Core and Initialisation
8 * This file is licenced under the 3-clause BSD Licence. See the file
9 * COPYING for full details.
14 #include <ctype.h> // isspace
19 #include <unistd.h> // close
20 #include <netdb.h> // gethostbyname
21 #include <pwd.h> // getpwuids
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <arpa/inet.h>
25 #include <openssl/sha.h> // SHA1
27 #define USE_NCURSES_INTERFACE 0
30 typedef struct sItem {
37 int ShowNCursesUI(void);
38 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
40 int sendf(int Socket, const char *Format, ...);
41 int OpenConnection(const char *Host, int Port);
42 void Authenticate(int Socket);
43 char *trim(char *string);
44 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
45 void CompileRegex(regex_t *regex, const char *pattern, int flags);
48 char *gsDispenseServer = "localhost";
49 int giDispensePort = 11020;
52 regex_t gArrayRegex, gItemRegex, gSaltRegex;
55 int main(int argc, char *argv[])
58 int i, responseCode, len;
61 // -- Create regular expressions
62 // > Code Type Count ...
63 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
64 // > Code Type Ident Price Desc
65 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+(.+?)\\s+(.+?)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
67 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+(.+)\\s+(.+)$", REG_EXTENDED);
70 sock = OpenConnection(gsDispenseServer, giDispensePort);
71 if( sock < 0 ) return -1;
73 // Determine what to do
76 if( strcmp(argv[1], "acct") == 0 )
84 // Ask server for stock list
85 send(sock, "ENUM_ITEMS\n", 11, 0);
86 len = recv(sock, buffer, BUFSIZ-1, 0);
91 printf("Output: %s\n", buffer);
93 responseCode = atoi(buffer);
94 if( responseCode != 201 )
96 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
102 char *itemType, *itemStart;
104 regmatch_t matches[4];
106 // Expected format: 201 Items <count> <item1> <item2> ...
107 RunRegex(&gArrayRegex, buffer, 4, matches, "Malformed server response");
109 itemType = &buffer[ matches[2].rm_so ]; buffer[ matches[2].rm_eo ] = '\0';
110 count = atoi( &buffer[ matches[3].rm_so ] );
113 if( strcmp(itemType, "Items") != 0 ) {
115 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
120 itemStart = &buffer[ matches[3].rm_eo ];
122 gaItems = malloc( count * sizeof(tItem) );
124 for( giNumItems = 0; giNumItems < count && itemStart; giNumItems ++ )
126 char *next = strchr( ++itemStart, ' ' );
127 if( next ) *next = '\0';
128 gaItems[giNumItems].Ident = strdup(itemStart);
133 // Get item information
134 for( i = 0; i < giNumItems; i ++ )
136 regmatch_t matches[6];
139 printf("%2i %s\t", i, gaItems[i].Ident);
142 sendf(sock, "ITEM_INFO %s\n", gaItems[i].Ident);
143 len = recv(sock, buffer, BUFSIZ-1, 0);
147 responseCode = atoi(buffer);
148 if( responseCode != 202 ) {
149 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
153 RunRegex(&gItemRegex, buffer, 6, matches, "Malformed server response");
155 buffer[ matches[3].rm_eo ] = '\0';
157 gaItems[i].Price = atoi( buffer + matches[4].rm_so );
158 gaItems[i].Desc = strdup( buffer + matches[5].rm_so );
160 printf("%3i %s\n", gaItems[i].Price, gaItems[i].Desc);
163 // and choose what to dispense
165 #if USE_NCURSES_INTERFACE
173 fgets(buffer, BUFSIZ, stdin);
177 if( buf[0] == 'q' ) break;
181 printf("buf = '%s', atoi(buf) = %i\n", buf, i);
183 if( i != 0 || buf[0] == '0' )
185 printf("i = %i\n", i);
187 if( i < 0 || i >= giNumItems ) {
188 printf("Bad item (should be between 0 and %i)\n", giNumItems);
201 sendf(sock, "DISPENSE %s\n", gaItems[i].Ident);
203 len = recv(sock, buffer, BUFSIZ-1, 0);
207 responseCode = atoi(buffer);
208 switch( responseCode )
211 printf("Dispense OK\n");
214 printf("Not authenticated\n");
217 printf("Insufficient balance\n");
220 printf("Bad item name, bug report\n");
223 printf("Item failed to dispense, is the slot empty?\n");
226 printf("Unknown response code %i ('%s')\n", responseCode, buffer);
236 void ShowItemAt(int Row, int Col, int Width, int Index)
242 if( Index < 0 || Index >= giNumItems ) {
243 printw("%02i OOR", Index);
246 printw("%02i %s", Index, gaItems[Index].Desc);
248 getyx(stdscr, _y, _x);
249 // Assumes max 4 digit prices
250 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
251 while(times--) addch(' ');
252 printw("%4i", gaItems[Index].Price);
257 int ShowNCursesUI(void)
259 // TODO: ncurses interface (with separation between item classes)
260 // - Hmm... that would require standardising the item ID to be <class>:<index>
265 const int displayMinWidth = 34;
266 const int displayMinItems = 8;
267 char *titleString = "Dispense";
268 int itemCount = displayMinItems;
271 int height = itemCount + 3;
272 int width = displayMinWidth;
278 xBase = COLS/2 - width/2;
279 yBase = LINES/2 - height/2;
284 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
287 for( i = 0; i < itemCount; i ++ )
289 move( yBase + 1 + i, xBase );
294 if( i == 0 && itemBase > 0 ) {
296 times = width - 1 - 8;
297 while(times--) addch(' ');
299 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
301 times = width - 1 - 8;
302 while(times--) addch(' ');
306 ShowItemAt( yBase + 1 + i, xBase + 2, width - 4, itemBase + i);
310 // Scrollbar (if needed)
311 if( giNumItems > itemCount ) {
315 else if( i == itemCount - 1 ) {
319 int percentage = itemBase * 100 / (giNumItems-itemCount);
320 if( i-1 == percentage*(itemCount-3)/100 ) {
334 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
347 if( itemBase < giNumItems - (itemCount) )
372 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...)
374 int lLen, mLen, rLen;
379 // Get the length of the strings
380 va_start(args, Right);
381 lLen = vsnprintf(NULL, 0, Left, args);
382 mLen = vsnprintf(NULL, 0, Mid, args);
383 rLen = vsnprintf(NULL, 0, Right, args);
387 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
388 return ; // TODO: What to do?
394 va_start(args, Right);
398 vsnprintf(tmp, lLen+1, Left, args);
402 times = Width/2 - mLen/2 - lLen;
403 while(times--) addch(Pad1);
407 vsnprintf(tmp, mLen+1, Mid, args);
411 times = Width/2 - mLen/2 - rLen;
412 while(times--) addch(Pad2);
416 vsnprintf(tmp, rLen+1, Right, args);
422 int sendf(int Socket, const char *Format, ...)
427 va_start(args, Format);
428 len = vsnprintf(NULL, 0, Format, args);
433 va_start(args, Format);
434 vsnprintf(buf, len+1, Format, args);
437 return send(Socket, buf, len, 0);
441 int OpenConnection(const char *Host, int Port)
443 struct hostent *host;
444 struct sockaddr_in serverAddr;
447 host = gethostbyname(Host);
449 fprintf(stderr, "Unable to look up '%s'\n", Host);
453 memset(&serverAddr, 0, sizeof(serverAddr));
455 serverAddr.sin_family = AF_INET; // IPv4
456 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
457 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
458 serverAddr.sin_port = htons(Port);
460 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
462 fprintf(stderr, "Failed to create socket\n");
468 struct sockaddr_in localAddr;
469 memset(&localAddr, 0, sizeof(localAddr));
470 localAddr.sin_family = AF_INET; // IPv4
471 localAddr.sin_port = 1023; // IPv4
472 // Attempt to bind to low port for autoauth
473 bind(sock, &localAddr, sizeof(localAddr));
477 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
478 fprintf(stderr, "Failed to connect to server\n");
485 void Authenticate(int Socket)
491 regmatch_t matches[4];
494 pwd = getpwuid( getuid() );
496 // Attempt automatic authentication
497 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
499 // Check if it worked
500 recv(Socket, buf, 511, 0);
503 responseCode = atoi(buf);
504 switch( responseCode )
506 case 200: // Authenticated, return :)
508 case 401: // Untrusted, attempt password authentication
509 sendf(Socket, "USER %s\n", pwd->pw_name);
510 printf("Using username %s\n", pwd->pw_name);
512 recv(Socket, buf, 511, 0);
515 // Expected format: 100 SALT <something> ...
517 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
518 if( atoi(buf) != 100 ) {
521 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
523 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
524 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
525 // printf("Salt: '%s'\n", salt);
530 int ofs = strlen(pwd->pw_name)+strlen(salt);
532 char *pass = getpass("Password: ");
535 strcpy(tmp, pwd->pw_name);
537 SHA1( (unsigned char*)pass, strlen(pass), h );
538 memcpy(tmp+ofs, h, 20);
541 SHA1( (unsigned char*)tmp, ofs+20, h );
542 sprintf(buf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
543 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
544 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
546 // printf("Final hash: '%s'\n", buf);
547 fflush(stdout); // Debug
550 sendf(Socket, "PASS %s\n", buf);
551 recv(Socket, buf, 511, 0);
553 case 404: // Bad Username
554 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
557 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
565 char *trim(char *string)
569 while( isspace(*string) )
572 for( i = strlen(string); i--; )
574 if( isspace(string[i]) )
583 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
587 ret = regexec(regex, string, nMatches, matches, 0);
589 size_t len = regerror(ret, regex, NULL, 0);
591 regerror(ret, regex, errorStr, len);
592 printf("string = '%s'\n", string);
593 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
600 void CompileRegex(regex_t *regex, const char *pattern, int flags)
602 int ret = regcomp(regex, pattern, flags);
604 size_t len = regerror(ret, regex, NULL, 0);
606 regerror(ret, regex, errorStr, len);
607 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);