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 main(int argc, char *argv[]);
40 int ShowNCursesUI(void);
41 void ShowItemAt(int Row, int Col, int Width, int Index);
42 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
43 // --- Coke Server Communication ---
44 int OpenConnection(const char *Host, int Port);
45 int Authenticate(int Socket);
46 void PopulateItemList(int Socket);
47 int DispenseItem(int Socket, int ItemID);
48 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
49 int Dispense_SetBalance(int Socket, const char *Username, int Ammount, const char *Reason);
50 int Dispense_EnumUsers(int Socket);
51 int Dispense_ShowUser(int Socket, const char *Username);
52 void _PrintUserLine(const char *Line);
54 char *ReadLine(int Socket);
55 int sendf(int Socket, const char *Format, ...);
56 char *trim(char *string);
57 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
58 void CompileRegex(regex_t *regex, const char *pattern, int flags);
61 char *gsDispenseServer = "localhost";
62 int giDispensePort = 11020;
66 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex;
67 int gbIsAuthenticated = 0;
69 char *gsOverrideUser; //!< '-u' argument (dispense as another user)
70 int gbUseNCurses = 0; //!< '-G' Use the NCurses GUI?
74 int main(int argc, char *argv[])
80 // -- Create regular expressions
81 // > Code Type Count ...
82 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
83 // > Code Type Ident Price Desc
84 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z0-9:]+?)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
86 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
87 // > Code 'User' Username Balance Flags
88 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
91 for( i = 1; i < argc; i ++ )
104 case 'u': // Override User
105 gsOverrideUser = argv[++i];
116 if( strcmp(arg, "acct") == 0 )
120 sock = OpenConnection(gsDispenseServer, giDispensePort);
121 if( sock < 0 ) return -1;
124 if( i + 1 == argc ) {
125 Dispense_EnumUsers(sock);
129 // argv[i+1]: Username
134 if( i + 3 >= argc ) {
135 fprintf(stderr, "Error: `dispense acct' needs a reason\n");
139 // Authentication required
142 // argv[i+1]: Username
143 // argv[i+2]: Ammount
146 if( argv[i+2][0] == '=' ) {
148 Dispense_SetBalance(sock, argv[i+1], atoi(argv[i+2] + 1), argv[i+3]);
152 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
156 Dispense_ShowUser(sock, argv[i+1]);
162 // Item name / pattern
168 sock = OpenConnection(gsDispenseServer, giDispensePort);
169 if( sock < 0 ) return -1;
175 PopulateItemList(sock);
183 for( i = 0; i < giNumItems; i ++ ) {
184 printf("%2i %s\t%3i %s\n", i, gaItems[i].Ident, gaItems[i].Price, gaItems[i].Desc);
193 fgets(buffer, BUFSIZ, stdin);
197 if( buf[0] == 'q' ) break;
201 if( i != 0 || buf[0] == '0' )
203 if( i < 0 || i >= giNumItems ) {
204 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
212 // Check for a valid item ID
214 DispenseItem(sock, i);
226 "\t\tShow interactive list\n"
227 "\tdispense <item>\n"
228 "\t\tDispense named item\n"
229 "\tdispense give <user> <ammount> \"<reason>\"\n"
230 "\t\tGive some of your money away\n"
231 "\tdispense acct [<user>]\n"
232 "\t\tShow user balances\n"
233 "\tdispense acct <user> [+-=]<ammount> \"<reason>\"\n"
234 "\t\tAlter a account value (Coke members only)\n"
238 "\t\tSet a different user (Coke members only)\n"
240 "\t\tShow help text\n"
242 "\t\tUse alternate GUI\n"
246 // -------------------
247 // --- NCurses GUI ---
248 // -------------------
250 * \brief Render the NCurses UI
252 int ShowNCursesUI(void)
254 // TODO: ncurses interface (with separation between item classes)
255 // - Hmm... that would require standardising the item ID to be <class>:<index>
260 const int displayMinWidth = 40;
261 const int displayMinItems = 8;
262 char *titleString = "Dispense";
263 int itemCount = displayMinItems;
266 int ret = -2; // -2: Used for marking "no return yet"
275 // - 6: randomly chosen (Need at least 3)
276 itemCount = LINES - 6;
277 if( itemCount > giNumItems )
278 itemCount = giNumItems;
281 height = itemCount + 3;
282 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 );
298 if( currentItem == itemBase + i ) {
306 // - Oh god, magic numbers!
307 if( i == 0 && itemBase > 0 ) {
309 times = width-1 - 8 - 3;
310 while(times--) addch(' ');
312 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
314 times = width-1 - 8 - 3;
315 while(times--) addch(' ');
319 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
323 // Scrollbar (if needed)
324 if( giNumItems > itemCount ) {
328 else if( i == itemCount - 1 ) {
332 int percentage = itemBase * 100 / (giNumItems-itemCount);
333 if( i-1 == percentage*(itemCount-3)/100 ) {
347 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
360 //if( itemBase < giNumItems - (itemCount) )
362 if( currentItem < giNumItems - 1 )
364 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
370 if( currentItem > 0 )
372 if( itemBase + 1 > currentItem && itemBase > 0 )
388 ret = -1; // -1: Return with no dispense
392 // Check if the return value was changed
393 if( ret != -2 ) break;
405 * \brief Show item \a Index at (\a Col, \a Row)
406 * \note Part of the NCurses UI
408 void ShowItemAt(int Row, int Col, int Width, int Index)
416 if( Index < 0 || Index >= giNumItems ) {
421 name = gaItems[Index].Desc;
422 price = gaItems[Index].Price;
425 printw("%02i %s", Index, name);
427 getyx(stdscr, _y, _x);
428 // Assumes max 4 digit prices
429 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
430 while(times--) addch(' ');
431 printw("%4i", price);
435 * \brief Print a three-part string at the specified position (formatted)
436 * \note NCurses UI Helper
438 * Prints \a Left on the left of the area, \a Right on the righthand side
439 * and \a Mid in the middle of the area. These are padded with \a Pad1
440 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
442 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
443 * and the arguments to these are read in that order.
445 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
446 const char *Mid, char Pad2, const char *Right, ...)
448 int lLen, mLen, rLen;
453 // Get the length of the strings
454 va_start(args, Right);
455 lLen = vsnprintf(NULL, 0, Left, args);
456 mLen = vsnprintf(NULL, 0, Mid, args);
457 rLen = vsnprintf(NULL, 0, Right, args);
461 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
462 return ; // TODO: What to do?
468 va_start(args, Right);
472 vsnprintf(tmp, lLen+1, Left, args);
476 times = Width/2 - mLen/2 - lLen;
477 while(times--) addch(Pad1);
481 vsnprintf(tmp, mLen+1, Mid, args);
485 times = Width/2 - mLen/2 - rLen;
486 while(times--) addch(Pad2);
490 vsnprintf(tmp, rLen+1, Right, args);
495 // ---------------------
496 // --- Coke Protocol ---
497 // ---------------------
498 int OpenConnection(const char *Host, int Port)
500 struct hostent *host;
501 struct sockaddr_in serverAddr;
504 host = gethostbyname(Host);
506 fprintf(stderr, "Unable to look up '%s'\n", Host);
510 memset(&serverAddr, 0, sizeof(serverAddr));
512 serverAddr.sin_family = AF_INET; // IPv4
513 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
514 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
515 serverAddr.sin_port = htons(Port);
517 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
519 fprintf(stderr, "Failed to create socket\n");
525 struct sockaddr_in localAddr;
526 memset(&localAddr, 0, sizeof(localAddr));
527 localAddr.sin_family = AF_INET; // IPv4
528 localAddr.sin_port = 1023; // IPv4
529 // Attempt to bind to low port for autoauth
530 bind(sock, &localAddr, sizeof(localAddr));
534 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
535 fprintf(stderr, "Failed to connect to server\n");
543 * \brief Authenticate with the server
544 * \return Boolean Failure
546 int Authenticate(int Socket)
553 regmatch_t matches[4];
555 if( gbIsAuthenticated ) return 0;
558 pwd = getpwuid( getuid() );
560 // Attempt automatic authentication
561 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
563 // Check if it worked
564 buf = ReadLine(Socket);
566 responseCode = atoi(buf);
567 switch( responseCode )
570 case 200: // Authenticated, return :)
571 gbIsAuthenticated = 1;
575 case 401: // Untrusted, attempt password authentication
578 sendf(Socket, "USER %s\n", pwd->pw_name);
579 printf("Using username %s\n", pwd->pw_name);
581 buf = ReadLine(Socket);
584 // Expected format: 100 SALT <something> ...
586 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
587 responseCode = atoi(buf);
588 if( responseCode != 100 ) {
589 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
595 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
596 // Store it for later
597 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
598 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
602 // Give three attempts
603 for( i = 0; i < 3; i ++ )
605 int ofs = strlen(pwd->pw_name)+strlen(salt);
608 char *pass = getpass("Password: ");
611 // Create hash string
612 // <username><salt><hash>
613 strcpy(tmp, pwd->pw_name);
615 SHA1( (unsigned char*)pass, strlen(pass), h );
616 memcpy(tmp+ofs, h, 20);
619 SHA1( (unsigned char*)tmp, ofs+20, h );
620 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
621 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
622 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
626 sendf(Socket, "PASS %s\n", tmpBuf);
627 buf = ReadLine(Socket);
629 responseCode = atoi(buf);
631 if( responseCode == 200 ) break;
632 // Bad username/password
633 if( responseCode == 401 ) continue;
635 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
641 gbIsAuthenticated = 1;
645 return 2; // 2 = Bad Password
647 case 404: // Bad Username
648 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
653 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
662 * \brief Fill the item information structure
663 * \return Boolean Failure
665 void PopulateItemList(int Socket)
670 char *itemType, *itemStart;
672 regmatch_t matches[4];
674 // Ask server for stock list
675 send(Socket, "ENUM_ITEMS\n", 11, 0);
676 buf = ReadLine(Socket);
678 //printf("Output: %s\n", buf);
680 responseCode = atoi(buf);
681 if( responseCode != 201 ) {
682 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
688 // Expected format: 201 Items <count> <item1> <item2> ...
689 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
691 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
692 count = atoi( &buf[ matches[3].rm_so ] );
695 if( strcmp(itemType, "Items") != 0 ) {
697 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
702 itemStart = &buf[ matches[3].rm_eo ];
704 gaItems = malloc( count * sizeof(tItem) );
706 for( giNumItems = 0; giNumItems < count && itemStart; giNumItems ++ )
708 char *next = strchr( ++itemStart, ' ' );
709 if( next ) *next = '\0';
710 gaItems[giNumItems].Ident = strdup(itemStart);
716 // Fetch item information
717 for( i = 0; i < giNumItems; i ++ )
719 regmatch_t matches[6];
722 sendf(Socket, "ITEM_INFO %s\n", gaItems[i].Ident);
723 buf = ReadLine(Socket);
725 responseCode = atoi(buf);
726 if( responseCode != 202 ) {
727 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
731 RunRegex(&gItemRegex, buf, 6, matches, "Malformed server response");
733 buf[ matches[3].rm_eo ] = '\0';
735 gaItems[i].Price = atoi( buf + matches[4].rm_so );
736 gaItems[i].Desc = strdup( buf + matches[5].rm_so );
743 * \brief Dispense an item
744 * \return Boolean Failure
746 int DispenseItem(int Socket, int ItemID)
748 int ret, responseCode;
751 if( ItemID < 0 || ItemID > giNumItems ) return -1;
754 sendf(Socket, "DISPENSE %s\n", gaItems[ItemID].Ident);
755 buf = ReadLine(Socket);
757 responseCode = atoi(buf);
758 switch( responseCode )
761 printf("Dispense OK\n");
765 printf("Not authenticated\n");
769 printf("Insufficient balance\n");
773 printf("Bad item name, bug report\n");
777 printf("Item failed to dispense, is the slot empty?\n");
781 printf("Dispense not possible (slot empty/permissions)\n");
785 printf("Unknown response code %i ('%s')\n", responseCode, buf);
795 * \brief Alter a user's balance
797 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
802 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
803 buf = ReadLine(Socket);
805 responseCode = atoi(buf);
810 case 200: return 0; // OK
811 case 403: // Not in coke
812 fprintf(stderr, "You are not in coke (sucker)\n");
814 case 404: // Unknown user
815 fprintf(stderr, "Unknown user '%s'\n", Username);
818 fprintf(stderr, "Unknown response code %i\n", responseCode);
826 * \brief Alter a user's balance
828 int Dispense_SetBalance(int Socket, const char *Username, int Ammount, const char *Reason)
833 sendf(Socket, "SET %s %i %s\n", Username, Ammount, Reason);
834 buf = ReadLine(Socket);
836 responseCode = atoi(buf);
841 case 200: return 0; // OK
842 case 403: // Not in coke
843 fprintf(stderr, "You are not in coke (sucker)\n");
845 case 404: // Unknown user
846 fprintf(stderr, "Unknown user '%s'\n", Username);
849 fprintf(stderr, "Unknown response code %i\n", responseCode);
856 int Dispense_EnumUsers(int Socket)
858 printf("TODO: Dispense_EnumUsers\n");
862 int Dispense_ShowUser(int Socket, const char *Username)
865 int responseCode, ret;
867 sendf(Socket, "USER_INFO %s\n", Username);
868 buf = ReadLine(Socket);
870 responseCode = atoi(buf);
880 printf("Unknown user '%s'\n", Username);
885 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
895 void _PrintUserLine(const char *Line)
897 regmatch_t matches[6];
900 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
905 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
906 char username[usernameLen + 1];
907 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
908 char flags[flagsLen + 1];
910 memcpy(username, Line + matches[3].rm_so, usernameLen);
911 username[usernameLen] = '\0';
912 memcpy(flags, Line + matches[5].rm_so, flagsLen);
913 flags[flagsLen] = '\0';
915 bal = atoi(Line + matches[4].rm_so);
916 printf("%-15s: $%i.%02i (%s)\n", username, bal/100, bal%100, flags);
923 char *ReadLine(int Socket)
925 static char buf[BUFSIZ];
926 static int bufPos = 0;
928 char *newline = NULL;
930 char *ret = malloc(10);
933 printf("ReadLine: ");
941 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
942 buf[bufPos+len] = '\0';
944 newline = strchr( buf+bufPos, '\n' );
949 retLen += strlen(buf+bufPos);
950 ret = realloc(ret, retLen + 1);
951 strcat( ret, buf+bufPos );
954 bufPos += newline - (buf+bufPos) + 1;
956 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
960 printf("%i '%s'\n", retLen, ret);
966 int sendf(int Socket, const char *Format, ...)
971 va_start(args, Format);
972 len = vsnprintf(NULL, 0, Format, args);
977 va_start(args, Format);
978 vsnprintf(buf, len+1, Format, args);
982 printf("sendf: %s", buf);
985 return send(Socket, buf, len, 0);
989 char *trim(char *string)
993 while( isspace(*string) )
996 for( i = strlen(string); i--; )
998 if( isspace(string[i]) )
1007 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1011 ret = regexec(regex, string, nMatches, matches, 0);
1013 size_t len = regerror(ret, regex, NULL, 0);
1015 regerror(ret, regex, errorStr, len);
1016 printf("string = '%s'\n", string);
1017 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1024 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1026 int ret = regcomp(regex, pattern, flags);
1028 size_t len = regerror(ret, regex, NULL, 0);
1030 regerror(ret, regex, errorStr, len);
1031 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);