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
28 typedef struct sItem {
35 int ShowNCursesUI(void);
36 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
38 int sendf(int Socket, const char *Format, ...);
39 int OpenConnection(const char *Host, int Port);
40 void Authenticate(int Socket);
41 char *trim(char *string);
42 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
43 void CompileRegex(regex_t *regex, const char *pattern, int flags);
46 char *gsDispenseServer = "localhost";
47 int giDispensePort = 11020;
50 regex_t gArrayRegex, gItemRegex, gSaltRegex;
53 int main(int argc, char *argv[])
56 int i, responseCode, len;
59 // -- Create regular expressions
60 // > Code Type Count ...
61 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
62 // > Code Type Ident Price Desc
63 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+(.+?)\\s+(.+?)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
65 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+(.+)\\s+(.+)$", REG_EXTENDED);
68 sock = OpenConnection(gsDispenseServer, giDispensePort);
69 if( sock < 0 ) return -1;
71 // Determine what to do
74 if( strcmp(argv[1], "acct") == 0 )
82 // Ask server for stock list
83 send(sock, "ENUM_ITEMS\n", 11, 0);
84 len = recv(sock, buffer, BUFSIZ-1, 0);
89 printf("Output: %s\n", buffer);
91 responseCode = atoi(buffer);
92 if( responseCode != 201 )
94 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
100 char *itemType, *itemStart;
102 regmatch_t matches[4];
104 // Expected format: 201 Items <count> <item1> <item2> ...
105 RunRegex(&gArrayRegex, buffer, 4, matches, "Malformed server response");
107 itemType = &buffer[ matches[2].rm_so ]; buffer[ matches[2].rm_eo ] = '\0';
108 count = atoi( &buffer[ matches[3].rm_so ] );
111 if( strcmp(itemType, "Items") != 0 ) {
113 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
118 itemStart = &buffer[ matches[3].rm_eo ];
120 gaItems = malloc( count * sizeof(tItem) );
122 for( giNumItems = 0; giNumItems < count && itemStart; giNumItems ++ )
124 char *next = strchr( ++itemStart, ' ' );
125 if( next ) *next = '\0';
126 gaItems[giNumItems].Ident = strdup(itemStart);
131 // Get item information
132 for( i = 0; i < giNumItems; i ++ )
134 regmatch_t matches[6];
137 printf("%2i %s\t", i, gaItems[i].Ident);
140 sendf(sock, "ITEM_INFO %s\n", gaItems[i].Ident);
141 len = recv(sock, buffer, BUFSIZ-1, 0);
145 responseCode = atoi(buffer);
146 if( responseCode != 202 ) {
147 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
151 RunRegex(&gItemRegex, buffer, 6, matches, "Malformed server response");
153 buffer[ matches[3].rm_eo ] = '\0';
155 gaItems[i].Price = atoi( buffer + matches[4].rm_so );
156 gaItems[i].Desc = strdup( buffer + matches[5].rm_so );
158 printf("%3i %s\n", gaItems[i].Price, gaItems[i].Desc);
161 // and choose what to dispense
162 // TODO: ncurses interface (with separation between item classes)
163 // - Hmm... that would require standardising the item ID to be <class>:<index>
174 fgets(buffer, BUFSIZ, stdin);
178 if( buf[0] == 'q' ) break;
182 printf("buf = '%s', atoi(buf) = %i\n", buf, i);
184 if( i != 0 || buf[0] == '0' )
186 printf("i = %i\n", i);
188 if( i < 0 || i >= giNumItems ) {
189 printf("Bad item (should be between 0 and %i)\n", giNumItems);
202 sendf(sock, "DISPENSE %s\n", gaItems[i].Ident);
204 len = recv(sock, buffer, BUFSIZ-1, 0);
208 responseCode = atoi(buffer);
209 switch( responseCode )
212 printf("Dispense OK\n");
215 printf("Not authenticated\n");
218 printf("Insufficient balance\n");
221 printf("Bad item name, bug report\n");
224 printf("Item failed to dispense, is the slot empty?\n");
227 printf("Unknown response code %i\n", responseCode);
237 void ShowItemAt(int Row, int Col, int Width, int Index)
243 if( Index < 0 || Index >= giNumItems ) {
244 printw("%02i OOR", Index);
247 printw("%02i %s", Index, gaItems[Index].Desc);
249 getyx(stdscr, _y, _x);
250 // Assumes max 4 digit prices
251 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
252 while(times--) addch(' ');
253 printw("%4i", gaItems[Index].Price);
258 int ShowNCursesUI(void)
263 const int displayMinWidth = 34;
264 const int displayMinItems = 8;
265 char *titleString = "Dispense";
266 int itemCount = displayMinItems;
269 int height = itemCount + 3;
270 int width = displayMinWidth;
276 xBase = COLS/2 - width/2;
277 yBase = LINES/2 - height/2;
282 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
285 for( i = 0; i < itemCount; i ++ )
287 move( yBase + 1 + i, xBase );
292 if( i == 0 && itemBase > 0 ) {
294 times = width - 1 - 8;
295 while(times--) addch(' ');
297 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
299 times = width - 1 - 8;
300 while(times--) addch(' ');
304 ShowItemAt( yBase + 1 + i, xBase + 2, width - 4, itemBase + i);
308 // Scrollbar (if needed)
309 if( giNumItems > itemCount ) {
313 else if( i == itemCount - 1 ) {
317 int percentage = itemBase * 100 / (giNumItems-itemCount);
318 if( i-1 == percentage*(itemCount-3)/100 ) {
332 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
345 if( itemBase < giNumItems - (itemCount) )
370 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...)
372 int lLen, mLen, rLen;
377 // Get the length of the strings
378 va_start(args, Right);
379 lLen = vsnprintf(NULL, 0, Left, args);
380 mLen = vsnprintf(NULL, 0, Mid, args);
381 rLen = vsnprintf(NULL, 0, Right, args);
385 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
386 return ; // TODO: What to do?
392 va_start(args, Right);
396 vsnprintf(tmp, lLen+1, Left, args);
400 times = Width/2 - mLen/2 - lLen;
401 while(times--) addch(Pad1);
405 vsnprintf(tmp, mLen+1, Mid, args);
409 times = Width/2 - mLen/2 - rLen;
410 while(times--) addch(Pad2);
414 vsnprintf(tmp, rLen+1, Right, args);
420 int sendf(int Socket, const char *Format, ...)
425 va_start(args, Format);
426 len = vsnprintf(NULL, 0, Format, args);
431 va_start(args, Format);
432 vsnprintf(buf, len+1, Format, args);
435 return send(Socket, buf, len, 0);
439 int OpenConnection(const char *Host, int Port)
441 struct hostent *host;
442 struct sockaddr_in serverAddr;
445 host = gethostbyname(Host);
447 fprintf(stderr, "Unable to look up '%s'\n", Host);
451 memset(&serverAddr, 0, sizeof(serverAddr));
453 serverAddr.sin_family = AF_INET; // IPv4
454 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
455 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
456 serverAddr.sin_port = htons(Port);
458 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
460 fprintf(stderr, "Failed to create socket\n");
466 struct sockaddr_in localAddr;
467 memset(&localAddr, 0, sizeof(localAddr));
468 localAddr.sin_family = AF_INET; // IPv4
469 localAddr.sin_port = 1023; // IPv4
470 // Attempt to bind to low port for autoauth
471 bind(sock, &localAddr, sizeof(localAddr));
475 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
476 fprintf(stderr, "Failed to connect to server\n");
483 void Authenticate(int Socket)
489 regmatch_t matches[4];
492 pwd = getpwuid( getuid() );
494 // Attempt automatic authentication
495 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
497 // Check if it worked
498 recv(Socket, buf, 511, 0);
501 responseCode = atoi(buf);
502 switch( responseCode )
504 case 200: // Authenticated, return :)
506 case 401: // Untrusted, attempt password authentication
507 sendf(Socket, "USER %s\n", pwd->pw_name);
508 printf("Using username %s\n", pwd->pw_name);
510 recv(Socket, buf, 511, 0);
513 // Expected format: 100 SALT <something> ...
515 printf("string = '%s'\n", buf);
516 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
517 if( atoi(buf) != 100 ) {
520 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
522 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
523 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
524 printf("Salt: '%s'\n", salt);
529 int ofs = strlen(pwd->pw_name)+strlen(salt);
531 char *pass = getpass("Password: ");
534 strcpy(tmp, pwd->pw_name);
536 SHA1( (unsigned char*)pass, strlen(pass), h );
537 memcpy(tmp+ofs, h, 20);
540 SHA1( (unsigned char*)tmp, ofs+20, h );
541 sprintf(buf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
542 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
543 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
545 printf("Final hash: '%s'\n", buf);
546 fflush(stdout); // Debug
549 sendf(Socket, "PASS %s\n", buf);
550 recv(Socket, buf, 511, 0);
552 case 404: // Bad Username
553 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
556 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
564 char *trim(char *string)
568 while( isspace(*string) )
571 for( i = strlen(string); i--; )
573 if( isspace(string[i]) )
582 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
586 ret = regexec(regex, string, nMatches, matches, 0);
588 size_t len = regerror(ret, regex, NULL, 0);
590 regerror(ret, regex, errorStr, len);
591 printf("string = '%s'\n", string);
592 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
599 void CompileRegex(regex_t *regex, const char *pattern, int flags)
601 int ret = regcomp(regex, pattern, flags);
603 size_t len = regerror(ret, regex, NULL, 0);
605 regerror(ret, regex, errorStr, len);
606 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);