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 {
38 int ShowNCursesUI(void);
39 void ShowItemAt(int Row, int Col, int Width, int Index);
40 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
41 // --- Coke Server Communication ---
42 int OpenConnection(const char *Host, int Port);
43 int Authenticate(int Socket);
44 void PopulateItemList(int Socket);
45 int DispenseItem(int Socket, int ItemID);
47 int sendf(int Socket, const char *Format, ...);
48 char *trim(char *string);
49 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
50 void CompileRegex(regex_t *regex, const char *pattern, int flags);
53 char *gsDispenseServer = "localhost";
54 int giDispensePort = 11020;
57 regex_t gArrayRegex, gItemRegex, gSaltRegex;
59 char *gsOverrideUser; //!< '-u' argument (dispense as another user)
60 int gbUseNCurses = 0; //!< '-G' Use the NCurses GUI?
63 int main(int argc, char *argv[])
69 // -- Create regular expressions
70 // > Code Type Count ...
71 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
72 // > Code Type Ident Price Desc
73 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z0-9:]+?)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
75 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+(.+)\\s+(.+)$", REG_EXTENDED);
78 sock = OpenConnection(gsDispenseServer, giDispensePort);
79 if( sock < 0 ) return -1;
85 for( i = 1; i < argc; i ++ )
93 case 'u': // Override User
94 gsOverrideUser = argv[++i];
105 if( strcmp(argv[1], "acct") == 0 ) {
111 // Item name / pattern
116 PopulateItemList(sock);
124 for( i = 0; i < giNumItems; i ++ ) {
125 printf("%2i %s\t%3i %s\n", i, gaItems[i].Ident, gaItems[i].Price, gaItems[i].Desc);
134 fgets(buffer, BUFSIZ, stdin);
138 if( buf[0] == 'q' ) break;
142 if( i != 0 || buf[0] == '0' )
144 if( i < 0 || i >= giNumItems ) {
145 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
153 // Check for a valid item ID
155 DispenseItem(sock, i);
162 // -------------------
163 // --- NCurses GUI ---
164 // -------------------
166 * \brief Render the NCurses UI
168 int ShowNCursesUI(void)
170 // TODO: ncurses interface (with separation between item classes)
171 // - Hmm... that would require standardising the item ID to be <class>:<index>
176 const int displayMinWidth = 40;
177 const int displayMinItems = 8;
178 char *titleString = "Dispense";
179 int itemCount = displayMinItems;
189 itemCount = LINES - 6;
190 if( itemCount > giNumItems )
191 itemCount = giNumItems;
194 height = itemCount + 3;
195 width = displayMinWidth;
198 xBase = COLS/2 - width/2;
199 yBase = LINES/2 - height/2;
204 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
207 for( i = 0; i < itemCount; i ++ )
209 move( yBase + 1 + i, xBase );
211 if( currentItem == itemBase + i ) {
219 // - Oh god, magic numbers!
220 if( i == 0 && itemBase > 0 ) {
222 times = width-1 - 8 - 3;
223 while(times--) addch(' ');
225 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
227 times = width-1 - 8 - 3;
228 while(times--) addch(' ');
232 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
236 // Scrollbar (if needed)
237 if( giNumItems > itemCount ) {
241 else if( i == itemCount - 1 ) {
245 int percentage = itemBase * 100 / (giNumItems-itemCount);
246 if( i-1 == percentage*(itemCount-3)/100 ) {
260 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
273 //if( itemBase < giNumItems - (itemCount) )
275 if( currentItem < giNumItems - 1 )
277 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
283 if( currentItem > 0 )
285 if( itemBase + 1 > currentItem && itemBase > 0 )
307 * \brief Show item \a Index at (\a Col, \a Row)
308 * \note Part of the NCurses UI
310 void ShowItemAt(int Row, int Col, int Width, int Index)
318 if( Index < 0 || Index >= giNumItems ) {
323 name = gaItems[Index].Desc;
324 price = gaItems[Index].Price;
327 printw("%02i %s", Index, name);
329 getyx(stdscr, _y, _x);
330 // Assumes max 4 digit prices
331 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
332 while(times--) addch(' ');
333 printw("%4i", price);
337 * \brief Print a three-part string at the specified position (formatted)
338 * \note NCurses UI Helper
340 * Prints \a Left on the left of the area, \a Right on the righthand side
341 * and \a Mid in the middle of the area. These are padded with \a Pad1
342 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
344 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
345 * and the arguments to these are read in that order.
347 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
348 const char *Mid, char Pad2, const char *Right, ...)
350 int lLen, mLen, rLen;
355 // Get the length of the strings
356 va_start(args, Right);
357 lLen = vsnprintf(NULL, 0, Left, args);
358 mLen = vsnprintf(NULL, 0, Mid, args);
359 rLen = vsnprintf(NULL, 0, Right, args);
363 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
364 return ; // TODO: What to do?
370 va_start(args, Right);
374 vsnprintf(tmp, lLen+1, Left, args);
378 times = Width/2 - mLen/2 - lLen;
379 while(times--) addch(Pad1);
383 vsnprintf(tmp, mLen+1, Mid, args);
387 times = Width/2 - mLen/2 - rLen;
388 while(times--) addch(Pad2);
392 vsnprintf(tmp, rLen+1, Right, args);
397 // ---------------------
398 // --- Coke Protocol ---
399 // ---------------------
400 int OpenConnection(const char *Host, int Port)
402 struct hostent *host;
403 struct sockaddr_in serverAddr;
406 host = gethostbyname(Host);
408 fprintf(stderr, "Unable to look up '%s'\n", Host);
412 memset(&serverAddr, 0, sizeof(serverAddr));
414 serverAddr.sin_family = AF_INET; // IPv4
415 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
416 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
417 serverAddr.sin_port = htons(Port);
419 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
421 fprintf(stderr, "Failed to create socket\n");
427 struct sockaddr_in localAddr;
428 memset(&localAddr, 0, sizeof(localAddr));
429 localAddr.sin_family = AF_INET; // IPv4
430 localAddr.sin_port = 1023; // IPv4
431 // Attempt to bind to low port for autoauth
432 bind(sock, &localAddr, sizeof(localAddr));
436 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
437 fprintf(stderr, "Failed to connect to server\n");
445 * \brief Authenticate with the server
446 * \return Boolean Failure
448 int Authenticate(int Socket)
455 regmatch_t matches[4];
458 pwd = getpwuid( getuid() );
460 // Attempt automatic authentication
461 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
463 // Check if it worked
464 recv(Socket, buf, 511, 0);
467 responseCode = atoi(buf);
468 switch( responseCode )
470 case 200: // Authenticated, return :)
472 case 401: // Untrusted, attempt password authentication
473 sendf(Socket, "USER %s\n", pwd->pw_name);
474 printf("Using username %s\n", pwd->pw_name);
476 recv(Socket, buf, 511, 0);
479 // Expected format: 100 SALT <something> ...
481 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
482 responseCode = atoi(buf);
483 if( responseCode != 100 ) {
484 fprintf(stderr, "Unknown repsonse code %i from server\n", responseCode);
489 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
490 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
491 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
497 // Give three attempts
498 for( i = 0; i < 3; i ++ )
500 int ofs = strlen(pwd->pw_name)+strlen(salt);
502 char *pass = getpass("Password: ");
505 // Create hash string
506 // <username><salt><hash>
507 strcpy(tmp, pwd->pw_name);
509 SHA1( (unsigned char*)pass, strlen(pass), h );
510 memcpy(tmp+ofs, h, 20);
513 SHA1( (unsigned char*)tmp, ofs+20, h );
514 sprintf(buf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
515 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
516 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
518 fflush(stdout); // Debug
521 sendf(Socket, "PASS %s\n", buf);
522 recv(Socket, buf, 511, 0);
524 responseCode = atoi(buf);
526 if( responseCode == 200 ) break;
527 // Bad username/password
528 if( responseCode == 401 ) continue;
530 fprintf(stderr, "Unknown repsonse code %i from server\n", responseCode);
533 return 2; // 2 = Bad Password
535 case 404: // Bad Username
536 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
540 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
546 return 0; // Seems OK
549 void PopulateItemList(int Socket)
555 char *itemType, *itemStart;
557 regmatch_t matches[4];
559 // Ask server for stock list
560 send(Socket, "ENUM_ITEMS\n", 11, 0);
561 len = recv(Socket, buffer, BUFSIZ-1, 0);
566 //printf("Output: %s\n", buffer);
568 responseCode = atoi(buffer);
569 if( responseCode != 201 ) {
570 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
576 // Expected format: 201 Items <count> <item1> <item2> ...
577 RunRegex(&gArrayRegex, buffer, 4, matches, "Malformed server response");
579 itemType = &buffer[ matches[2].rm_so ]; buffer[ matches[2].rm_eo ] = '\0';
580 count = atoi( &buffer[ matches[3].rm_so ] );
583 if( strcmp(itemType, "Items") != 0 ) {
585 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
590 itemStart = &buffer[ matches[3].rm_eo ];
592 gaItems = malloc( count * sizeof(tItem) );
594 for( giNumItems = 0; giNumItems < count && itemStart; giNumItems ++ )
596 char *next = strchr( ++itemStart, ' ' );
597 if( next ) *next = '\0';
598 gaItems[giNumItems].Ident = strdup(itemStart);
602 // Fetch item information
603 for( i = 0; i < giNumItems; i ++ )
605 regmatch_t matches[6];
608 sendf(Socket, "ITEM_INFO %s\n", gaItems[i].Ident);
609 len = recv(Socket, buffer, BUFSIZ-1, 0);
613 responseCode = atoi(buffer);
614 if( responseCode != 202 ) {
615 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
619 RunRegex(&gItemRegex, buffer, 6, matches, "Malformed server response");
621 buffer[ matches[3].rm_eo ] = '\0';
623 gaItems[i].Price = atoi( buffer + matches[4].rm_so );
624 gaItems[i].Desc = strdup( buffer + matches[5].rm_so );
628 int DispenseItem(int Socket, int ItemID)
630 int len, responseCode;
633 if( ItemID < 0 || ItemID > giNumItems ) return -1;
636 sendf(Socket, "DISPENSE %s\n", gaItems[ItemID].Ident);
637 len = recv(Socket, buffer, BUFSIZ-1, 0);
641 responseCode = atoi(buffer);
642 switch( responseCode )
645 printf("Dispense OK\n");
648 printf("Not authenticated\n");
651 printf("Insufficient balance\n");
654 printf("Bad item name, bug report\n");
657 printf("Item failed to dispense, is the slot empty?\n");
660 printf("Dispense not possible (slot empty/permissions)\n");
663 printf("Unknown response code %i ('%s')\n", responseCode, buffer);
671 int sendf(int Socket, const char *Format, ...)
676 va_start(args, Format);
677 len = vsnprintf(NULL, 0, Format, args);
682 va_start(args, Format);
683 vsnprintf(buf, len+1, Format, args);
686 return send(Socket, buf, len, 0);
690 char *trim(char *string)
694 while( isspace(*string) )
697 for( i = strlen(string); i--; )
699 if( isspace(string[i]) )
708 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
712 ret = regexec(regex, string, nMatches, matches, 0);
714 size_t len = regerror(ret, regex, NULL, 0);
716 regerror(ret, regex, errorStr, len);
717 printf("string = '%s'\n", string);
718 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
725 void CompileRegex(regex_t *regex, const char *pattern, int flags)
727 int ret = regcomp(regex, pattern, flags);
729 size_t len = regerror(ret, regex, NULL, 0);
731 regerror(ret, regex, errorStr, len);
732 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);