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
20 #include <unistd.h> // close
21 #include <netdb.h> // gethostbyname
22 #include <pwd.h> // getpwuids
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <openssl/sha.h> // SHA1
28 #define USE_NCURSES_INTERFACE 0
29 #define DEBUG_TRACE_SERVER 0
32 typedef struct sItem {
39 int main(int argc, char *argv[]);
42 int ShowNCursesUI(void);
43 void ShowItemAt(int Row, int Col, int Width, int Index);
44 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
45 // --- Coke Server Communication ---
46 int OpenConnection(const char *Host, int Port);
47 int Authenticate(int Socket);
48 void PopulateItemList(int Socket);
49 int DispenseItem(int Socket, int ItemID);
50 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
51 int Dispense_SetBalance(int Socket, const char *Username, int Ammount, const char *Reason);
52 int Dispense_EnumUsers(int Socket);
53 int Dispense_ShowUser(int Socket, const char *Username);
54 void _PrintUserLine(const char *Line);
56 char *ReadLine(int Socket);
57 int sendf(int Socket, const char *Format, ...);
58 char *trim(char *string);
59 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
60 void CompileRegex(regex_t *regex, const char *pattern, int flags);
63 char *gsDispenseServer = "localhost";
64 int giDispensePort = 11020;
68 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex;
69 int gbIsAuthenticated = 0;
71 char *gsOverrideUser; //!< '-u' Dispense as another user
72 int gbUseNCurses = 0; //!< '-G' Use the NCurses GUI?
73 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
74 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
77 int main(int argc, char *argv[])
83 // -- Create regular expressions
84 // > Code Type Count ...
85 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
86 // > Code Type Ident Price Desc
87 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z0-9:]+?)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
89 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
90 // > Code 'User' Username Balance Flags
91 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
94 for( i = 1; i < argc; i ++ )
107 case 'm': // Minimum balance
108 giMinimumBalance = atoi(argv[++i]);
110 case 'M': // Maximum balance
111 giMaximumBalance = atoi(argv[++i]);
114 case 'u': // Override User
115 gsOverrideUser = argv[++i];
126 if( strcmp(arg, "acct") == 0 )
130 sock = OpenConnection(gsDispenseServer, giDispensePort);
131 if( sock < 0 ) return -1;
134 if( i + 1 == argc ) {
135 Dispense_EnumUsers(sock);
139 // argv[i+1]: Username
144 if( i + 3 >= argc ) {
145 fprintf(stderr, "Error: `dispense acct' needs a reason\n");
149 // Authentication required
152 // argv[i+1]: Username
153 // argv[i+2]: Ammount
156 if( argv[i+2][0] == '=' ) {
158 Dispense_SetBalance(sock, argv[i+1], atoi(argv[i+2] + 1), argv[i+3]);
162 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
166 Dispense_ShowUser(sock, argv[i+1]);
172 // Item name / pattern
178 sock = OpenConnection(gsDispenseServer, giDispensePort);
179 if( sock < 0 ) return -1;
185 PopulateItemList(sock);
193 for( i = 0; i < giNumItems; i ++ ) {
194 printf("%2i %s\t%3i %s\n", i, gaItems[i].Ident, gaItems[i].Price, gaItems[i].Desc);
203 fgets(buffer, BUFSIZ, stdin);
207 if( buf[0] == 'q' ) break;
211 if( i != 0 || buf[0] == '0' )
213 if( i < 0 || i >= giNumItems ) {
214 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
222 // Check for a valid item ID
224 DispenseItem(sock, i);
236 "\t\tShow interactive list\n"
237 "\tdispense <item>\n"
238 "\t\tDispense named item\n"
239 "\tdispense give <user> <ammount> \"<reason>\"\n"
240 "\t\tGive some of your money away\n"
241 "\tdispense acct [<user>]\n"
242 "\t\tShow user balances\n"
243 "\tdispense acct <user> [+-=]<ammount> \"<reason>\"\n"
244 "\t\tAlter a account value (Coke members only)\n"
248 "\t\tSet a different user (Coke members only)\n"
250 "\t\tShow help text\n"
252 "\t\tUse alternate GUI\n"
253 "\t-m <min balance>\n"
254 "\t-M <max balance>\n"
255 "\t\tSet the Maximum/Minimum balances shown in `dispense acct`\n"
259 // -------------------
260 // --- NCurses GUI ---
261 // -------------------
263 * \brief Render the NCurses UI
265 int ShowNCursesUI(void)
267 // TODO: ncurses interface (with separation between item classes)
268 // - Hmm... that would require standardising the item ID to be <class>:<index>
273 const int displayMinWidth = 40;
274 const int displayMinItems = 8;
275 char *titleString = "Dispense";
276 int itemCount = displayMinItems;
279 int ret = -2; // -2: Used for marking "no return yet"
288 // - 6: randomly chosen (Need at least 3)
289 itemCount = LINES - 6;
290 if( itemCount > giNumItems )
291 itemCount = giNumItems;
294 height = itemCount + 3;
295 width = displayMinWidth;
298 xBase = COLS/2 - width/2;
299 yBase = LINES/2 - height/2;
304 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
307 for( i = 0; i < itemCount; i ++ )
309 move( yBase + 1 + i, xBase );
311 if( currentItem == itemBase + i ) {
319 // - Oh god, magic numbers!
320 if( i == 0 && itemBase > 0 ) {
322 times = width-1 - 8 - 3;
323 while(times--) addch(' ');
325 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
327 times = width-1 - 8 - 3;
328 while(times--) addch(' ');
332 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
336 // Scrollbar (if needed)
337 if( giNumItems > itemCount ) {
341 else if( i == itemCount - 1 ) {
345 int percentage = itemBase * 100 / (giNumItems-itemCount);
346 if( i-1 == percentage*(itemCount-3)/100 ) {
360 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
373 //if( itemBase < giNumItems - (itemCount) )
375 if( currentItem < giNumItems - 1 )
377 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
383 if( currentItem > 0 )
385 if( itemBase + 1 > currentItem && itemBase > 0 )
401 ret = -1; // -1: Return with no dispense
405 // Check if the return value was changed
406 if( ret != -2 ) break;
418 * \brief Show item \a Index at (\a Col, \a Row)
419 * \note Part of the NCurses UI
421 void ShowItemAt(int Row, int Col, int Width, int Index)
429 if( Index < 0 || Index >= giNumItems ) {
434 name = gaItems[Index].Desc;
435 price = gaItems[Index].Price;
438 printw("%02i %s", Index, name);
440 getyx(stdscr, _y, _x);
441 // Assumes max 4 digit prices
442 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
443 while(times--) addch(' ');
444 printw("%4i", price);
448 * \brief Print a three-part string at the specified position (formatted)
449 * \note NCurses UI Helper
451 * Prints \a Left on the left of the area, \a Right on the righthand side
452 * and \a Mid in the middle of the area. These are padded with \a Pad1
453 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
455 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
456 * and the arguments to these are read in that order.
458 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
459 const char *Mid, char Pad2, const char *Right, ...)
461 int lLen, mLen, rLen;
466 // Get the length of the strings
467 va_start(args, Right);
468 lLen = vsnprintf(NULL, 0, Left, args);
469 mLen = vsnprintf(NULL, 0, Mid, args);
470 rLen = vsnprintf(NULL, 0, Right, args);
474 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
475 return ; // TODO: What to do?
481 va_start(args, Right);
485 vsnprintf(tmp, lLen+1, Left, args);
489 times = Width/2 - mLen/2 - lLen;
490 while(times--) addch(Pad1);
494 vsnprintf(tmp, mLen+1, Mid, args);
498 times = Width/2 - mLen/2 - rLen;
499 while(times--) addch(Pad2);
503 vsnprintf(tmp, rLen+1, Right, args);
508 // ---------------------
509 // --- Coke Protocol ---
510 // ---------------------
511 int OpenConnection(const char *Host, int Port)
513 struct hostent *host;
514 struct sockaddr_in serverAddr;
517 host = gethostbyname(Host);
519 fprintf(stderr, "Unable to look up '%s'\n", Host);
523 memset(&serverAddr, 0, sizeof(serverAddr));
525 serverAddr.sin_family = AF_INET; // IPv4
526 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
527 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
528 serverAddr.sin_port = htons(Port);
530 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
532 fprintf(stderr, "Failed to create socket\n");
538 struct sockaddr_in localAddr;
539 memset(&localAddr, 0, sizeof(localAddr));
540 localAddr.sin_family = AF_INET; // IPv4
541 localAddr.sin_port = 1023; // IPv4
542 // Attempt to bind to low port for autoauth
543 bind(sock, &localAddr, sizeof(localAddr));
547 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
548 fprintf(stderr, "Failed to connect to server\n");
556 * \brief Authenticate with the server
557 * \return Boolean Failure
559 int Authenticate(int Socket)
566 regmatch_t matches[4];
568 if( gbIsAuthenticated ) return 0;
571 pwd = getpwuid( getuid() );
573 // Attempt automatic authentication
574 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
576 // Check if it worked
577 buf = ReadLine(Socket);
579 responseCode = atoi(buf);
580 switch( responseCode )
583 case 200: // Authenticated, return :)
584 gbIsAuthenticated = 1;
588 case 401: // Untrusted, attempt password authentication
591 sendf(Socket, "USER %s\n", pwd->pw_name);
592 printf("Using username %s\n", pwd->pw_name);
594 buf = ReadLine(Socket);
597 // Expected format: 100 SALT <something> ...
599 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
600 responseCode = atoi(buf);
601 if( responseCode != 100 ) {
602 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
608 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
609 // Store it for later
610 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
611 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
615 // Give three attempts
616 for( i = 0; i < 3; i ++ )
618 int ofs = strlen(pwd->pw_name)+strlen(salt);
621 char *pass = getpass("Password: ");
624 // Create hash string
625 // <username><salt><hash>
626 strcpy(tmp, pwd->pw_name);
628 SHA1( (unsigned char*)pass, strlen(pass), h );
629 memcpy(tmp+ofs, h, 20);
632 SHA1( (unsigned char*)tmp, ofs+20, h );
633 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
634 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
635 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
639 sendf(Socket, "PASS %s\n", tmpBuf);
640 buf = ReadLine(Socket);
642 responseCode = atoi(buf);
644 if( responseCode == 200 ) break;
645 // Bad username/password
646 if( responseCode == 401 ) continue;
648 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
654 gbIsAuthenticated = 1;
658 return 2; // 2 = Bad Password
660 case 404: // Bad Username
661 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
666 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
675 * \brief Fill the item information structure
676 * \return Boolean Failure
678 void PopulateItemList(int Socket)
683 char *itemType, *itemStart;
685 regmatch_t matches[4];
687 // Ask server for stock list
688 send(Socket, "ENUM_ITEMS\n", 11, 0);
689 buf = ReadLine(Socket);
691 //printf("Output: %s\n", buf);
693 responseCode = atoi(buf);
694 if( responseCode != 201 ) {
695 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
704 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
706 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
707 count = atoi( &buf[ matches[3].rm_so ] );
710 if( strcmp(itemType, "Items") != 0 ) {
712 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
717 itemStart = &buf[ matches[3].rm_eo ];
722 gaItems = malloc( giNumItems * sizeof(tItem) );
724 // Fetch item information
725 for( i = 0; i < giNumItems; i ++ )
727 regmatch_t matches[6];
730 buf = ReadLine(Socket);
731 responseCode = atoi(buf);
733 if( responseCode != 202 ) {
734 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
738 RunRegex(&gItemRegex, buf, 6, matches, "Malformed server response");
740 buf[ matches[3].rm_eo ] = '\0';
742 gaItems[i].Ident = strdup( buf + matches[3].rm_so );
743 gaItems[i].Price = atoi( buf + matches[4].rm_so );
744 gaItems[i].Desc = strdup( buf + matches[5].rm_so );
750 buf = ReadLine(Socket);
751 responseCode = atoi(buf);
753 if( responseCode != 200 ) {
754 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
764 * \brief Dispense an item
765 * \return Boolean Failure
767 int DispenseItem(int Socket, int ItemID)
769 int ret, responseCode;
772 if( ItemID < 0 || ItemID > giNumItems ) return -1;
775 sendf(Socket, "DISPENSE %s\n", gaItems[ItemID].Ident);
776 buf = ReadLine(Socket);
778 responseCode = atoi(buf);
779 switch( responseCode )
782 printf("Dispense OK\n");
786 printf("Not authenticated\n");
790 printf("Insufficient balance\n");
794 printf("Bad item name, bug report\n");
798 printf("Item failed to dispense, is the slot empty?\n");
802 printf("Dispense not possible (slot empty/permissions)\n");
806 printf("Unknown response code %i ('%s')\n", responseCode, buf);
816 * \brief Alter a user's balance
818 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
823 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
824 buf = ReadLine(Socket);
826 responseCode = atoi(buf);
831 case 200: return 0; // OK
832 case 403: // Not in coke
833 fprintf(stderr, "You are not in coke (sucker)\n");
835 case 404: // Unknown user
836 fprintf(stderr, "Unknown user '%s'\n", Username);
839 fprintf(stderr, "Unknown response code %i\n", responseCode);
847 * \brief Alter a user's balance
849 int Dispense_SetBalance(int Socket, const char *Username, int Ammount, const char *Reason)
854 sendf(Socket, "SET %s %i %s\n", Username, Ammount, Reason);
855 buf = ReadLine(Socket);
857 responseCode = atoi(buf);
862 case 200: return 0; // OK
863 case 403: // Not in coke
864 fprintf(stderr, "You are not in coke (sucker)\n");
866 case 404: // Unknown user
867 fprintf(stderr, "Unknown user '%s'\n", Username);
870 fprintf(stderr, "Unknown response code %i\n", responseCode);
877 int Dispense_EnumUsers(int Socket)
882 regmatch_t matches[4];
884 if( giMinimumBalance != INT_MIN ) {
885 if( giMaximumBalance != INT_MAX ) {
886 sendf(Socket, "ENUM_USERS %i %i\n", giMinimumBalance, giMaximumBalance);
889 sendf(Socket, "ENUM_USERS %i\n", giMinimumBalance);
893 if( giMaximumBalance != INT_MAX ) {
894 sendf(Socket, "ENUM_USERS - %i\n", giMaximumBalance);
897 sendf(Socket, "ENUM_USERS\n");
900 buf = ReadLine(Socket);
901 responseCode = atoi(buf);
905 case 201: break; // Ok, length follows
908 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
913 // Get count (not actually used)
914 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
915 nUsers = atoi( buf + matches[3].rm_so );
916 printf("%i users returned\n", nUsers);
921 // Read returned users
923 buf = ReadLine(Socket);
924 responseCode = atoi(buf);
926 if( responseCode != 202 ) break;
930 } while(responseCode == 202);
932 // Check final response
933 if( responseCode != 200 ) {
934 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
944 int Dispense_ShowUser(int Socket, const char *Username)
947 int responseCode, ret;
949 sendf(Socket, "USER_INFO %s\n", Username);
950 buf = ReadLine(Socket);
952 responseCode = atoi(buf);
962 printf("Unknown user '%s'\n", Username);
967 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
977 void _PrintUserLine(const char *Line)
979 regmatch_t matches[6];
982 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
987 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
988 char username[usernameLen + 1];
989 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
990 char flags[flagsLen + 1];
992 memcpy(username, Line + matches[3].rm_so, usernameLen);
993 username[usernameLen] = '\0';
994 memcpy(flags, Line + matches[5].rm_so, flagsLen);
995 flags[flagsLen] = '\0';
997 bal = atoi(Line + matches[4].rm_so);
998 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, bal%100, flags);
1005 char *ReadLine(int Socket)
1007 static char buf[BUFSIZ];
1008 static int bufPos = 0;
1009 static int bufValid = 0;
1011 char *newline = NULL;
1013 char *ret = malloc(10);
1015 #if DEBUG_TRACE_SERVER
1016 printf("ReadLine: ");
1028 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1029 buf[bufPos+len] = '\0';
1032 newline = strchr( buf+bufPos, '\n' );
1037 retLen += strlen(buf+bufPos);
1038 ret = realloc(ret, retLen + 1);
1039 strcat( ret, buf+bufPos );
1042 int newLen = newline - (buf+bufPos) + 1;
1043 bufValid = len - newLen;
1046 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1049 #if DEBUG_TRACE_SERVER
1050 printf("%i '%s'\n", retLen, ret);
1056 int sendf(int Socket, const char *Format, ...)
1061 va_start(args, Format);
1062 len = vsnprintf(NULL, 0, Format, args);
1067 va_start(args, Format);
1068 vsnprintf(buf, len+1, Format, args);
1071 #if DEBUG_TRACE_SERVER
1072 printf("sendf: %s", buf);
1075 return send(Socket, buf, len, 0);
1079 char *trim(char *string)
1083 while( isspace(*string) )
1086 for( i = strlen(string); i--; )
1088 if( isspace(string[i]) )
1097 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1101 ret = regexec(regex, string, nMatches, matches, 0);
1103 size_t len = regerror(ret, regex, NULL, 0);
1105 regerror(ret, regex, errorStr, len);
1106 printf("string = '%s'\n", string);
1107 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1114 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1116 int ret = regcomp(regex, pattern, flags);
1118 size_t len = regerror(ret, regex, NULL, 0);
1120 regerror(ret, regex, errorStr, len);
1121 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);