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, ...);
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 char *trim(char *string);
48 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
49 void CompileRegex(regex_t *regex, const char *pattern, int flags);
52 char *gsDispenseServer = "localhost";
53 int giDispensePort = 11020;
56 regex_t gArrayRegex, gItemRegex, gSaltRegex;
61 int main(int argc, char *argv[])
67 // -- Create regular expressions
68 // > Code Type Count ...
69 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
70 // > Code Type Ident Price Desc
71 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z0-9:]+?)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
73 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+(.+)\\s+(.+)$", REG_EXTENDED);
76 sock = OpenConnection(gsDispenseServer, giDispensePort);
77 if( sock < 0 ) return -1;
83 for( i = 1; i < argc; i ++ )
91 case 'u': // Override User
92 gsOverrideUser = argv[++i];
98 if( strcmp(argv[1], "acct") == 0 ) {
104 // Item name / pattern
109 PopulateItemList(sock);
111 #if USE_NCURSES_INTERFACE
114 for( i = 0; i < giNumItems; i ++ ) {
115 printf("%2i %s\t%3i %s\n", i, gaItems[i].Ident, gaItems[i].Price, gaItems[i].Desc);
124 fgets(buffer, BUFSIZ, stdin);
128 if( buf[0] == 'q' ) break;
132 if( i != 0 || buf[0] == '0' )
134 if( i < 0 || i >= giNumItems ) {
135 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
143 // Check for a valid item ID
145 DispenseItem(sock, i);
153 * \brief Show item \a Index at (\a Col, \a Row)
154 * \note Part of the NCurses UI
156 void ShowItemAt(int Row, int Col, int Width, int Index)
162 if( Index < 0 || Index >= giNumItems ) {
163 printw("%02i OOR", Index);
166 printw("%02i %s", Index, gaItems[Index].Desc);
168 getyx(stdscr, _y, _x);
169 // Assumes max 4 digit prices
170 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
171 while(times--) addch(' ');
172 printw("%4i", gaItems[Index].Price);
176 * \brief Render the NCurses UI
178 int ShowNCursesUI(void)
180 // TODO: ncurses interface (with separation between item classes)
181 // - Hmm... that would require standardising the item ID to be <class>:<index>
186 const int displayMinWidth = 40;
187 const int displayMinItems = 8;
188 char *titleString = "Dispense";
189 int itemCount = displayMinItems;
192 int height = itemCount + 3;
193 int width = displayMinWidth;
199 xBase = COLS/2 - width/2;
200 yBase = LINES/2 - height/2;
205 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
208 for( i = 0; i < itemCount; i ++ )
210 move( yBase + 1 + i, xBase );
215 if( i == 0 && itemBase > 0 ) {
217 times = width - 1 - 8;
218 while(times--) addch(' ');
220 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
222 times = width - 1 - 8;
223 while(times--) addch(' ');
227 ShowItemAt( yBase + 1 + i, xBase + 2, width - 4, itemBase + i);
231 // Scrollbar (if needed)
232 if( giNumItems > itemCount ) {
236 else if( i == itemCount - 1 ) {
240 int percentage = itemBase * 100 / (giNumItems-itemCount);
241 if( i-1 == percentage*(itemCount-3)/100 ) {
255 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
268 if( itemBase < giNumItems - (itemCount) )
294 * \brief Print a three-part string at the specified position (formatted)
295 * \note NCurses UI Helper
297 * Prints \a Left on the left of the area, \a Right on the righthand side
298 * and \a Mid in the middle of the area. These are padded with \a Pad1
299 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
301 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
302 * and the arguments to these are read in that order.
304 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
305 const char *Mid, char Pad2, const char *Right, ...)
307 int lLen, mLen, rLen;
312 // Get the length of the strings
313 va_start(args, Right);
314 lLen = vsnprintf(NULL, 0, Left, args);
315 mLen = vsnprintf(NULL, 0, Mid, args);
316 rLen = vsnprintf(NULL, 0, Right, args);
320 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
321 return ; // TODO: What to do?
327 va_start(args, Right);
331 vsnprintf(tmp, lLen+1, Left, args);
335 times = Width/2 - mLen/2 - lLen;
336 while(times--) addch(Pad1);
340 vsnprintf(tmp, mLen+1, Mid, args);
344 times = Width/2 - mLen/2 - rLen;
345 while(times--) addch(Pad2);
349 vsnprintf(tmp, rLen+1, Right, args);
355 int sendf(int Socket, const char *Format, ...)
360 va_start(args, Format);
361 len = vsnprintf(NULL, 0, Format, args);
366 va_start(args, Format);
367 vsnprintf(buf, len+1, Format, args);
370 return send(Socket, buf, len, 0);
374 int OpenConnection(const char *Host, int Port)
376 struct hostent *host;
377 struct sockaddr_in serverAddr;
380 host = gethostbyname(Host);
382 fprintf(stderr, "Unable to look up '%s'\n", Host);
386 memset(&serverAddr, 0, sizeof(serverAddr));
388 serverAddr.sin_family = AF_INET; // IPv4
389 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
390 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
391 serverAddr.sin_port = htons(Port);
393 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
395 fprintf(stderr, "Failed to create socket\n");
401 struct sockaddr_in localAddr;
402 memset(&localAddr, 0, sizeof(localAddr));
403 localAddr.sin_family = AF_INET; // IPv4
404 localAddr.sin_port = 1023; // IPv4
405 // Attempt to bind to low port for autoauth
406 bind(sock, &localAddr, sizeof(localAddr));
410 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
411 fprintf(stderr, "Failed to connect to server\n");
419 * \brief Authenticate with the server
420 * \return Boolean Failure
422 int Authenticate(int Socket)
429 regmatch_t matches[4];
432 pwd = getpwuid( getuid() );
434 // Attempt automatic authentication
435 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
437 // Check if it worked
438 recv(Socket, buf, 511, 0);
441 responseCode = atoi(buf);
442 switch( responseCode )
444 case 200: // Authenticated, return :)
446 case 401: // Untrusted, attempt password authentication
447 sendf(Socket, "USER %s\n", pwd->pw_name);
448 printf("Using username %s\n", pwd->pw_name);
450 recv(Socket, buf, 511, 0);
453 // Expected format: 100 SALT <something> ...
455 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
456 responseCode = atoi(buf);
457 if( responseCode != 100 ) {
458 fprintf(stderr, "Unknown repsonse code %i from server\n", responseCode);
463 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
464 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
465 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
471 // Give three attempts
472 for( i = 0; i < 3; i ++ )
474 int ofs = strlen(pwd->pw_name)+strlen(salt);
476 char *pass = getpass("Password: ");
479 // Create hash string
480 // <username><salt><hash>
481 strcpy(tmp, pwd->pw_name);
483 SHA1( (unsigned char*)pass, strlen(pass), h );
484 memcpy(tmp+ofs, h, 20);
487 SHA1( (unsigned char*)tmp, ofs+20, h );
488 sprintf(buf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
489 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
490 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
492 fflush(stdout); // Debug
495 sendf(Socket, "PASS %s\n", buf);
496 recv(Socket, buf, 511, 0);
498 responseCode = atoi(buf);
500 if( responseCode == 200 ) break;
501 // Bad username/password
502 if( responseCode == 401 ) continue;
504 fprintf(stderr, "Unknown repsonse code %i from server\n", responseCode);
507 return 2; // 2 = Bad Password
509 case 404: // Bad Username
510 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
514 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
520 return 0; // Seems OK
523 void PopulateItemList(int Socket)
529 char *itemType, *itemStart;
531 regmatch_t matches[4];
533 // Ask server for stock list
534 send(Socket, "ENUM_ITEMS\n", 11, 0);
535 len = recv(Socket, buffer, BUFSIZ-1, 0);
540 //printf("Output: %s\n", buffer);
542 responseCode = atoi(buffer);
543 if( responseCode != 201 ) {
544 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
550 // Expected format: 201 Items <count> <item1> <item2> ...
551 RunRegex(&gArrayRegex, buffer, 4, matches, "Malformed server response");
553 itemType = &buffer[ matches[2].rm_so ]; buffer[ matches[2].rm_eo ] = '\0';
554 count = atoi( &buffer[ matches[3].rm_so ] );
557 if( strcmp(itemType, "Items") != 0 ) {
559 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
564 itemStart = &buffer[ matches[3].rm_eo ];
566 gaItems = malloc( count * sizeof(tItem) );
568 for( giNumItems = 0; giNumItems < count && itemStart; giNumItems ++ )
570 char *next = strchr( ++itemStart, ' ' );
571 if( next ) *next = '\0';
572 gaItems[giNumItems].Ident = strdup(itemStart);
576 // Fetch item information
577 for( i = 0; i < giNumItems; i ++ )
579 regmatch_t matches[6];
582 sendf(Socket, "ITEM_INFO %s\n", gaItems[i].Ident);
583 len = recv(Socket, buffer, BUFSIZ-1, 0);
587 responseCode = atoi(buffer);
588 if( responseCode != 202 ) {
589 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
593 RunRegex(&gItemRegex, buffer, 6, matches, "Malformed server response");
595 buffer[ matches[3].rm_eo ] = '\0';
597 gaItems[i].Price = atoi( buffer + matches[4].rm_so );
598 gaItems[i].Desc = strdup( buffer + matches[5].rm_so );
602 int DispenseItem(int Socket, int ItemID)
604 int len, responseCode;
607 if( ItemID < 0 || ItemID > giNumItems ) return -1;
610 sendf(Socket, "DISPENSE %s\n", gaItems[ItemID].Ident);
611 len = recv(Socket, buffer, BUFSIZ-1, 0);
615 responseCode = atoi(buffer);
616 switch( responseCode )
619 printf("Dispense OK\n");
622 printf("Not authenticated\n");
625 printf("Insufficient balance\n");
628 printf("Bad item name, bug report\n");
631 printf("Item failed to dispense, is the slot empty?\n");
634 printf("Dispense not possible (slot empty/permissions)\n");
637 printf("Unknown response code %i ('%s')\n", responseCode, buffer);
642 char *trim(char *string)
646 while( isspace(*string) )
649 for( i = strlen(string); i--; )
651 if( isspace(string[i]) )
660 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
664 ret = regexec(regex, string, nMatches, matches, 0);
666 size_t len = regerror(ret, regex, NULL, 0);
668 regerror(ret, regex, errorStr, len);
669 printf("string = '%s'\n", string);
670 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
677 void CompileRegex(regex_t *regex, const char *pattern, int flags)
679 int ret = regcomp(regex, pattern, flags);
681 size_t len = regerror(ret, regex, NULL, 0);
683 regerror(ret, regex, errorStr, len);
684 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);