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 int 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);
196 // Check for a valid item ID and if so, authenticate
197 if( i >= 0 && Authenticate(sock) )
200 sendf(sock, "DISPENSE %s\n", gaItems[i].Ident);
202 len = recv(sock, buffer, BUFSIZ-1, 0);
206 responseCode = atoi(buffer);
207 switch( responseCode )
210 printf("Dispense OK\n");
213 printf("Not authenticated\n");
216 printf("Insufficient balance\n");
219 printf("Bad item name, bug report\n");
222 printf("Item failed to dispense, is the slot empty?\n");
225 printf("Dispense not possible (slot empty/permissions)\n");
228 printf("Unknown response code %i ('%s')\n", responseCode, buffer);
239 * \brief Show item \a Index at (\a Col, \a Row)
240 * \note Part of the NCurses UI
242 void ShowItemAt(int Row, int Col, int Width, int Index)
248 if( Index < 0 || Index >= giNumItems ) {
249 printw("%02i OOR", Index);
252 printw("%02i %s", Index, gaItems[Index].Desc);
254 getyx(stdscr, _y, _x);
255 // Assumes max 4 digit prices
256 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
257 while(times--) addch(' ');
258 printw("%4i", gaItems[Index].Price);
262 * \brief Render the NCurses UI
264 int ShowNCursesUI(void)
266 // TODO: ncurses interface (with separation between item classes)
267 // - Hmm... that would require standardising the item ID to be <class>:<index>
272 const int displayMinWidth = 34;
273 const int displayMinItems = 8;
274 char *titleString = "Dispense";
275 int itemCount = displayMinItems;
278 int height = itemCount + 3;
279 int width = displayMinWidth;
285 xBase = COLS/2 - width/2;
286 yBase = LINES/2 - height/2;
291 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
294 for( i = 0; i < itemCount; i ++ )
296 move( yBase + 1 + i, xBase );
301 if( i == 0 && itemBase > 0 ) {
303 times = width - 1 - 8;
304 while(times--) addch(' ');
306 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
308 times = width - 1 - 8;
309 while(times--) addch(' ');
313 ShowItemAt( yBase + 1 + i, xBase + 2, width - 4, itemBase + i);
317 // Scrollbar (if needed)
318 if( giNumItems > itemCount ) {
322 else if( i == itemCount - 1 ) {
326 int percentage = itemBase * 100 / (giNumItems-itemCount);
327 if( i-1 == percentage*(itemCount-3)/100 ) {
341 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
354 if( itemBase < giNumItems - (itemCount) )
380 * \brief Print a three-part string at the specified position (formatted)
381 * \note NCurses UI Helper
383 * Prints \a Left on the left of the area, \a Right on the righthand side
384 * and \a Mid in the middle of the area. These are padded with \a Pad1
385 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
387 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
388 * and the arguments to these are read in that order.
390 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
391 const char *Mid, char Pad2, const char *Right, ...)
393 int lLen, mLen, rLen;
398 // Get the length of the strings
399 va_start(args, Right);
400 lLen = vsnprintf(NULL, 0, Left, args);
401 mLen = vsnprintf(NULL, 0, Mid, args);
402 rLen = vsnprintf(NULL, 0, Right, args);
406 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
407 return ; // TODO: What to do?
413 va_start(args, Right);
417 vsnprintf(tmp, lLen+1, Left, args);
421 times = Width/2 - mLen/2 - lLen;
422 while(times--) addch(Pad1);
426 vsnprintf(tmp, mLen+1, Mid, args);
430 times = Width/2 - mLen/2 - rLen;
431 while(times--) addch(Pad2);
435 vsnprintf(tmp, rLen+1, Right, args);
441 int sendf(int Socket, const char *Format, ...)
446 va_start(args, Format);
447 len = vsnprintf(NULL, 0, Format, args);
452 va_start(args, Format);
453 vsnprintf(buf, len+1, Format, args);
456 return send(Socket, buf, len, 0);
460 int OpenConnection(const char *Host, int Port)
462 struct hostent *host;
463 struct sockaddr_in serverAddr;
466 host = gethostbyname(Host);
468 fprintf(stderr, "Unable to look up '%s'\n", Host);
472 memset(&serverAddr, 0, sizeof(serverAddr));
474 serverAddr.sin_family = AF_INET; // IPv4
475 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
476 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
477 serverAddr.sin_port = htons(Port);
479 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
481 fprintf(stderr, "Failed to create socket\n");
487 struct sockaddr_in localAddr;
488 memset(&localAddr, 0, sizeof(localAddr));
489 localAddr.sin_family = AF_INET; // IPv4
490 localAddr.sin_port = 1023; // IPv4
491 // Attempt to bind to low port for autoauth
492 bind(sock, &localAddr, sizeof(localAddr));
496 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
497 fprintf(stderr, "Failed to connect to server\n");
505 * \brief Authenticate with the server
506 * \return Boolean Failure
508 int Authenticate(int Socket)
515 regmatch_t matches[4];
518 pwd = getpwuid( getuid() );
520 // Attempt automatic authentication
521 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
523 // Check if it worked
524 recv(Socket, buf, 511, 0);
527 responseCode = atoi(buf);
528 switch( responseCode )
530 case 200: // Authenticated, return :)
532 case 401: // Untrusted, attempt password authentication
533 sendf(Socket, "USER %s\n", pwd->pw_name);
534 printf("Using username %s\n", pwd->pw_name);
536 recv(Socket, buf, 511, 0);
539 // Expected format: 100 SALT <something> ...
541 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
542 responseCode = atoi(buf);
543 if( responseCode != 100 ) {
544 fprintf(stderr, "Unknown repsonse code %i from server\n", responseCode);
549 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
550 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
551 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
557 // Give three attempts
558 for( i = 0; i < 3; i ++ )
560 int ofs = strlen(pwd->pw_name)+strlen(salt);
562 char *pass = getpass("Password: ");
565 // Create hash string
566 // <username><salt><hash>
567 strcpy(tmp, pwd->pw_name);
569 SHA1( (unsigned char*)pass, strlen(pass), h );
570 memcpy(tmp+ofs, h, 20);
573 SHA1( (unsigned char*)tmp, ofs+20, h );
574 sprintf(buf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
575 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
576 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
578 fflush(stdout); // Debug
581 sendf(Socket, "PASS %s\n", buf);
582 recv(Socket, buf, 511, 0);
584 responseCode = atoi(buf);
586 if( responseCode == 200 ) break;
587 // Bad username/password
588 if( responseCode == 401 ) continue;
590 fprintf(stderr, "Unknown repsonse code %i from server\n", responseCode);
593 return 2; // 2 = Bad Password
595 case 404: // Bad Username
596 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
600 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
606 return 0; // Seems OK
609 char *trim(char *string)
613 while( isspace(*string) )
616 for( i = strlen(string); i--; )
618 if( isspace(string[i]) )
627 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
631 ret = regexec(regex, string, nMatches, matches, 0);
633 size_t len = regerror(ret, regex, NULL, 0);
635 regerror(ret, regex, errorStr, len);
636 printf("string = '%s'\n", string);
637 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
644 void CompileRegex(regex_t *regex, const char *pattern, int flags)
646 int ret = regcomp(regex, pattern, flags);
648 size_t len = regerror(ret, regex, NULL, 0);
650 regerror(ret, regex, errorStr, len);
651 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);