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
30 #define USE_AUTOAUTH 1
32 #define MAX_TXT_ARGS 5 // Maximum number of textual arguments (including command)
33 #define DISPENSE_MULTIPLE_MAX 20 // Maximum argument to -c
37 UI_MODE_BASIC, // Non-NCurses
52 RV_SERVER_ERROR, // Generic for 5xx codes
53 RV_UNKNOWN_ERROR = -1,
55 RV_UNKNOWN_RESPONSE = -3,
59 typedef struct sItem {
62 int Status; // 0: Availiable, 1: Sold out, -1: Error
69 int main(int argc, char *argv[]);
71 int ShowNCursesUI(void);
72 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted);
73 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
74 // --- Coke Server Communication ---
75 int OpenConnection(const char *Host, int Port);
76 int Authenticate(int Socket);
77 int GetUserBalance(int Socket);
78 void PopulateItemList(int Socket);
79 int Dispense_ItemInfo(int Socket, const char *Type, int ID);
80 int DispenseItem(int Socket, const char *Type, int ID);
81 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
82 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
83 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
84 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride);
85 int Dispense_Donate(int Socket, int Ammount, const char *Reason);
86 int Dispense_EnumUsers(int Socket);
87 int Dispense_ShowUser(int Socket, const char *Username);
88 void _PrintUserLine(const char *Line);
89 int Dispense_AddUser(int Socket, const char *Username);
90 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
91 int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName);
93 char *ReadLine(int Socket);
94 int sendf(int Socket, const char *Format, ...);
95 char *trim(char *string);
96 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
97 void CompileRegex(regex_t *regex, const char *pattern, int flags);
100 char *gsDispenseServer = "heathred";
101 int giDispensePort = 11020;
105 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
106 int gbIsAuthenticated = 0;
108 char *gsItemPattern; //!< Item pattern
109 char *gsEffectiveUser; //!< '-u' Dispense as another user
110 int giUIMode = UI_MODE_STANDARD;
111 int gbDryRun = 0; //!< '-n' Read-only
112 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
113 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
114 char *gsUserName; //!< User that dispense will happen as
115 char *gsUserFlags; //!< User's flag set
116 int giUserBalance=-1; //!< User balance (set by Authenticate)
117 int giDispenseCount = 1; //!< Number of dispenses to do
126 " Show interactive list\n"
127 " dispense <name>|<index>|<itemid>\n"
128 " Dispense named item (<name> matches if it is a unique prefix)\n"
129 " dispense give <user> <ammount> \"<reason>\"\n"
130 " Give money to another user\n"
131 " dispense donate <ammount> \"<reason>\"\n"
132 " Donate to the club\n"
133 " dispense iteminfo <itemid>\n"
134 " Get the name and price for an item\n"
135 " == Coke members == \n"
136 " dispense acct [<user>]\n"
137 " Show user balances\n"
138 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
139 " Alter a account value\n"
140 " dispense refund <user> <itemid> [<price>]\n"
141 " Refund an item to a user (with optional price override)\n"
142 " dispense slot <itemid> <price> <name>\n"
143 " Rename/Re-price a slot\n"
144 " == Dispense administrators ==\n"
145 " dispense acct <user> =<ammount> \"<reason>\"\n"
146 " Set an account balance\n"
147 " dispense user add <user>\n"
148 " Create new account\n"
149 " dispense user type <user> <flags>\n"
150 " Alter a user's flags\n"
151 " <flags> is a comma-separated list of user, coke, admin, internal or disabled\n"
152 " Flags are removed by preceding the name with '-' or '!'\n"
156 " Dispense multiple times\n"
158 " Set a different user (Coke members only)\n"
162 " Use alternate GUI\n"
164 " Dry run - Do not actually do dispenses\n"
165 " -m <min balance>\n"
166 " -M <max balance>\n"
167 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
170 " Item ID of the form <type>:<num> where <type> is a non-empty string of alpha-numeric characters, and <num> is a non-negative integer\n"
176 int main(int argc, char *argv[])
181 char *text_args[MAX_TXT_ARGS]; // Non-flag arguments
186 // -- Create regular expressions
187 // > Code Type Count ...
188 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
189 // > Code Type Ident Status Price Desc
190 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z]+):([0-9]+)\\s+(avail|sold|error)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
191 // > Code 'SALT' salt
192 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
193 // > Code 'User' Username Balance Flags
194 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
196 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
199 for( i = 1; i < argc; i ++ )
213 if( i + 1 >= argc ) {
214 fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
218 giDispenseCount = atoi(argv[++i]);
219 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
220 fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
226 case 'm': // Minimum balance
227 if( i + 1 >= argc ) {
228 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
232 giMinimumBalance = atoi(argv[++i]);
234 case 'M': // Maximum balance
235 if( i + 1 >= argc ) {
236 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
240 giMaximumBalance = atoi(argv[++i]);
243 case 'u': // Override User
244 if( i + 1 >= argc ) {
245 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
249 gsEffectiveUser = argv[++i];
252 case 'H': // Override remote host
253 if( i + 1 >= argc ) {
254 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
258 gsDispenseServer = argv[++i];
260 case 'P': // Override remote port
261 if( i + 1 >= argc ) {
262 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
266 giDispensePort = atoi(argv[++i]);
269 // Set slot name/price
271 if( text_argc != 0 ) {
272 fprintf(stderr, "%s: -s must appear before other arguments\n", argv[0]);
276 text_args[0] = "slot"; // HACK!!
280 case 'G': // Don't use GUI
281 giUIMode = UI_MODE_BASIC;
283 case 'D': // Drinks only
284 giUIMode = UI_MODE_DRINKSONLY;
286 case 'n': // Dry Run / read-only
290 // if( !isdigit(argv[i][0]) ) {
291 // fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
293 // return RV_ARGUMENTS;
295 if( text_argc + 1 == MAX_TXT_ARGS )
297 fprintf(stderr, "ERROR: Too many arguments\n");
300 text_args[text_argc++] = argv[i];
307 if( text_argc + 1 == MAX_TXT_ARGS )
309 fprintf(stderr, "ERROR: Too many arguments\n");
313 text_args[text_argc++] = argv[i];
320 if( strcmp(text_args[0], "acct") == 0 )
323 sock = OpenConnection(gsDispenseServer, giDispensePort);
324 if( sock < 0 ) return RV_SOCKET_ERROR;
326 if( text_argc == 1 ) {
327 ret = Dispense_EnumUsers(sock);
332 // text_args[1]: Username
337 if( text_argc != 4 ) {
338 fprintf(stderr, "`dispense acct` requires a reason\n");
343 // Authentication required
344 ret = Authenticate(sock);
347 // text_args[1]: Username
348 // text_args[2]: Ammount
349 // text_args[3]: Reason
351 if( text_args[2][0] == '=' ) {
353 if( text_args[2][1] != '0' && atoi(text_args[2]+1) == 0 ) {
354 fprintf(stderr, "Error: Invalid balance to be set\n");
358 ret = Dispense_SetBalance(sock, text_args[1], atoi(text_args[2]+1), text_args[3]);
362 ret = Dispense_AlterBalance(sock, text_args[1], atoi(text_args[2]), text_args[3]);
365 // TODO: Preserve ret if non-zero
367 // Show user information
368 ret = Dispense_ShowUser(sock, text_args[1]);
375 // - "Here, have some money."
376 else if( strcmp(text_args[0], "give") == 0 )
378 if( text_argc != 4 ) {
379 fprintf(stderr, "`dispense give` takes three arguments\n");
384 // text_args[1]: Destination
385 // text_args[2]: Ammount
386 // text_args[3]: Reason
389 sock = OpenConnection(gsDispenseServer, giDispensePort);
390 if( sock < 0 ) return RV_SOCKET_ERROR;
393 ret = Authenticate(sock);
396 ret = Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
404 // - User administration (Admin Only)
405 if( strcmp(text_args[0], "user") == 0 )
407 // Check argument count
408 if( text_argc == 1 ) {
409 fprintf(stderr, "Error: `dispense user` requires arguments\n");
415 sock = OpenConnection(gsDispenseServer, giDispensePort);
416 if( sock < 0 ) return RV_SOCKET_ERROR;
418 // Attempt authentication
419 ret = Authenticate(sock);
423 if( strcmp(text_args[1], "add") == 0 )
425 if( text_argc != 3 ) {
426 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
431 ret = Dispense_AddUser(sock, text_args[2]);
434 else if( strcmp(text_args[1], "type") == 0 || strcmp(text_args[1], "flags") == 0 )
436 if( text_argc != 4 ) {
437 fprintf(stderr, "Error: `dispense user flags` requires two arguments\n");
442 ret = Dispense_SetUserType(sock, text_args[2], text_args[3]);
446 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
454 else if( strcmp(text_args[0], "donate") == 0 )
456 // Check argument count
457 if( text_argc != 3 ) {
458 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
464 sock = OpenConnection(gsDispenseServer, giDispensePort);
465 if( sock < 0 ) return RV_SOCKET_ERROR;
467 // Attempt authentication
468 ret = Authenticate(sock);
472 ret = Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
479 else if( strcmp(text_args[0], "refund") == 0 )
482 // Check argument count
483 if( text_argc != 3 && text_argc != 4 ) {
484 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
490 sock = OpenConnection(gsDispenseServer, giDispensePort);
491 if(sock < 0) return RV_SOCKET_ERROR;
493 // Attempt authentication
494 ret = Authenticate(sock);
497 if( text_argc == 4 ) {
498 price = atoi(text_args[3]);
500 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
505 // Username, Item, cost
506 ret = Dispense_Refund(sock, text_args[1], text_args[2], price);
510 return RV_UNKNOWN_ERROR;
512 // Query an item price
513 else if( strcmp(text_args[0], "iteminfo") == 0 )
515 regmatch_t matches[3];
518 // Check argument count
519 if( text_argc != 2 ) {
520 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
525 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
526 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
529 type = text_args[1] + matches[1].rm_so;
530 text_args[1][ matches[1].rm_eo ] = '\0';
531 id = atoi( text_args[1] + matches[2].rm_so );
533 sock = OpenConnection(gsDispenseServer, giDispensePort);
534 if( sock < 0 ) return RV_SOCKET_ERROR;
536 ret = Dispense_ItemInfo(sock, type, id);
541 else if( strcmp(text_args[0], "slot") == 0 )
543 regmatch_t matches[3];
544 char *item_type, *newname;
548 if( text_argc != 4 ) {
549 fprintf(stderr, "Error: `dispense slot` takes three arguments\n");
555 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
556 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
559 item_type = text_args[1] + matches[1].rm_so;
560 text_args[1][ matches[1].rm_eo ] = '\0';
561 item_id = atoi( text_args[1] + matches[2].rm_so );
564 price = atoi( text_args[2] );
565 if( price <= 0 && text_args[2][0] != '0' ) {
566 fprintf(stderr, "Error: Invalid price passed (must be >= 0)\n");
571 newname = text_args[3];
575 for( pos = newname; *pos; pos ++ )
577 if( !isalnum(*pos) && *pos != ' ' ) {
578 fprintf(stderr, "Error: You should only have letters, numbers and spaces in an item name\n");
584 // Connect & Authenticate
585 sock = OpenConnection(gsDispenseServer, giDispensePort);
586 if( sock < 0 ) return RV_SOCKET_ERROR;
587 ret = Authenticate(sock);
590 ret = Dispense_SetItem(sock, item_type, item_id, price, newname);
595 // Item name / pattern
598 gsItemPattern = text_args[0];
602 sock = OpenConnection(gsDispenseServer, giDispensePort);
603 if( sock < 0 ) return RV_SOCKET_ERROR;
605 // Get the user's balance
606 ret = GetUserBalance(sock);
610 PopulateItemList(sock);
612 // Disconnect from server
615 if( gsItemPattern && gsItemPattern[0] )
617 regmatch_t matches[3];
619 if( strcmp(gsItemPattern, "door") == 0 )
621 // Connect, Authenticate, dispense and close
622 sock = OpenConnection(gsDispenseServer, giDispensePort);
623 if( sock < 0 ) return RV_SOCKET_ERROR;
624 ret = Authenticate(sock);
626 ret = DispenseItem(sock, "door", 0);
630 // Item id (<type>:<num>)
631 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
636 // Get and finish ident
637 ident = gsItemPattern + matches[1].rm_so;
638 gsItemPattern[matches[1].rm_eo] = '\0';
640 id = atoi( gsItemPattern + matches[2].rm_so );
642 // Connect, Authenticate, dispense and close
643 sock = OpenConnection(gsDispenseServer, giDispensePort);
644 if( sock < 0 ) return RV_SOCKET_ERROR;
646 Dispense_ItemInfo(sock, ident, id);
648 ret = Authenticate(sock);
650 ret = DispenseItem(sock, ident, id);
654 // Item number (6 = coke)
655 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
657 i = atoi(gsItemPattern);
664 for( i = 0; i < giNumItems; i ++ )
666 // Prefix match (with case-insensitive match)
667 for( j = 0; gsItemPattern[j]; j ++ )
669 if( gaItems[i].Desc[j] == gsItemPattern[j] )
671 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
675 // Check if the prefix matched
676 if( gsItemPattern[j] != '\0' )
680 if( gaItems[i].Desc[j] == '\0' ) {
685 // Only one match allowed
690 // TODO: Allow ambiguous matches?
691 // or just print a wanrning
692 printf("Warning - Ambiguous pattern, stopping\n");
697 // Was a match found?
700 fprintf(stderr, "No item matches the passed string\n");
707 else if( giUIMode != UI_MODE_BASIC )
713 // Very basic dispense interface
714 for( i = 0; i < giNumItems; i ++ ) {
716 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
719 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
720 gaItems[i].Price, gaItems[i].Desc);
729 fgets(buffer, BUFSIZ, stdin);
733 if( buf[0] == 'q' ) break;
737 if( i != 0 || buf[0] == '0' )
739 if( i < 0 || i >= giNumItems ) {
740 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
749 // Check for a valid item ID
753 // Connect, Authenticate, dispense and close
754 sock = OpenConnection(gsDispenseServer, giDispensePort);
755 if( sock < 0 ) return RV_SOCKET_ERROR;
757 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
760 ret = Authenticate(sock);
763 for( j = 0; j < giDispenseCount; j ++ ) {
764 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
768 printf("%i items dispensed\n", j);
776 // -------------------
777 // --- NCurses GUI ---
778 // -------------------
780 * \brief Render the NCurses UI
782 int ShowNCursesUI(void)
787 const int displayMinWidth = 40;
788 char *titleString = "Dispense";
793 int ret = -2; // -2: Used for marking "no return yet"
795 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
802 if( gsEffectiveUser )
803 username = gsEffectiveUser;
805 pwd = getpwuid( getuid() );
806 username = pwd->pw_name;
809 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
816 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
817 // Get item count per screen
818 // - 6: randomly chosen (Need at least 3)
819 itemCount = LINES - 6;
820 if( itemCount > maxItemIndex )
821 itemCount = maxItemIndex;
824 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
829 height = itemCount + 3;
830 width = displayMinWidth;
833 xBase = COLS/2 - width/2;
834 yBase = LINES/2 - height/2;
839 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
842 for( i = 0; i < itemCount; i ++ )
846 move( yBase + 1 + i, xBase );
851 // Check for the '...' row
852 // - Oh god, magic numbers!
853 if( (i == 0 && itemBase > 0)
854 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
856 printw(" ..."); pos += 8;
857 times = (width - pos) - 1;
858 while(times--) addch(' ');
863 yBase + 1 + i, xBase + pos, // Position
864 (width - pos) - 3, // Width
865 itemBase + i, // Index
866 !!(currentItem == itemBase + i) // Hilighted
871 // Scrollbar (if needed)
872 if( maxItemIndex > itemCount ) {
876 else if( i == itemCount - 1 ) {
880 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
881 if( i-1 == percentage*(itemCount-3)/100 ) {
895 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
898 // - Username, balance, flags
899 PrintAlign(yBase+height-1, xBase+1, width-2,
900 username, ' ', balance_str, ' ', gsUserFlags);
916 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
919 if( currentItem >= maxItemIndex ) {
922 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
929 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
932 if( currentItem < 0 ) {
933 currentItem = maxItemIndex - 1;
935 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
945 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
946 itemBase = currentItem - 2;
947 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
948 itemBase = currentItem - itemCount + 2;
954 ret = ShowItemAt(0, 0, 0, currentItem, 0);
958 ret = -1; // -1: Return with no dispense
962 // Check if the return value was changed
963 if( ret != -2 ) break;
975 * \brief Show item \a Index at (\a Col, \a Row)
976 * \return Dispense index of item
977 * \note Part of the NCurses UI
979 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
989 // - This assumes that
990 case UI_MODE_STANDARD:
992 // Index = -1, request limit
993 if( Index < 0 || Index >= giNumItems+2 )
999 name = "Coke Machine";
1000 Index = -1; // -1 indicates a label
1007 name = gaItems[Index].Desc;
1008 price = gaItems[Index].Price;
1009 status = gaItems[Index].Status;
1017 name = "Electronic Payment System";
1018 Index = -1; // -1 indicates a label
1023 name = gaItems[Index].Desc;
1024 price = gaItems[Index].Price;
1025 status = gaItems[Index].Status;
1031 // Width = 0, don't print
1034 // 4 preceding, 5 price
1035 int nameWidth = Width - 4 - 5;
1040 // Show hilight and status
1059 printw("%-*.*s", nameWidth, nameWidth, name);
1061 // getyx(stdscr, _y, _x);
1062 // Assumes max 4 digit prices
1063 // times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
1064 // while(times--) addch(' ');
1066 printw(" %4i", price);
1070 printw("-- %s", name);
1071 getyx(stdscr, _y, _x);
1072 times = Width - 4 - (_x - Col);
1073 while(times--) addch(' ');
1078 // If the item isn't availiable for sale, return -1 (so it's skipped)
1086 * \brief Print a three-part string at the specified position (formatted)
1087 * \note NCurses UI Helper
1089 * Prints \a Left on the left of the area, \a Right on the righthand side
1090 * and \a Mid in the middle of the area. These are padded with \a Pad1
1091 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1093 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1094 * and the arguments to these are read in that order.
1096 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1097 const char *Mid, char Pad2, const char *Right, ...)
1099 int lLen, mLen, rLen;
1104 // Get the length of the strings
1105 va_start(args, Right);
1106 lLen = vsnprintf(NULL, 0, Left, args);
1107 mLen = vsnprintf(NULL, 0, Mid, args);
1108 rLen = vsnprintf(NULL, 0, Right, args);
1112 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1113 return ; // TODO: What to do?
1119 va_start(args, Right);
1123 vsnprintf(tmp, lLen+1, Left, args);
1127 times = (Width - mLen)/2 - lLen;
1128 while(times--) addch(Pad1);
1132 vsnprintf(tmp, mLen+1, Mid, args);
1136 times = (Width - mLen)/2 - rLen;
1137 if( (Width - mLen) % 2 ) times ++;
1138 while(times--) addch(Pad2);
1142 vsnprintf(tmp, rLen+1, Right, args);
1147 // ---------------------
1148 // --- Coke Protocol ---
1149 // ---------------------
1150 int OpenConnection(const char *Host, int Port)
1152 struct hostent *host;
1153 struct sockaddr_in serverAddr;
1156 host = gethostbyname(Host);
1158 fprintf(stderr, "Unable to look up '%s'\n", Host);
1162 memset(&serverAddr, 0, sizeof(serverAddr));
1164 serverAddr.sin_family = AF_INET; // IPv4
1165 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1166 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1167 serverAddr.sin_port = htons(Port);
1169 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1171 fprintf(stderr, "Failed to create socket\n");
1175 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1177 if( geteuid() == 0 || getuid() == 0 )
1180 struct sockaddr_in localAddr;
1181 memset(&localAddr, 0, sizeof(localAddr));
1182 localAddr.sin_family = AF_INET; // IPv4
1184 // Loop through all the top ports until one is avaliable
1185 for( i = 512; i < 1024; i ++)
1187 localAddr.sin_port = htons(i); // IPv4
1188 // Attempt to bind to low port for autoauth
1189 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1193 printf("Warning: AUTOAUTH unavaliable\n");
1195 // printf("Bound to 0.0.0.0:%i\n", i);
1198 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1199 fprintf(stderr, "Failed to connect to server\n");
1203 // We're not authenticated if the connection has just opened
1204 gbIsAuthenticated = 0;
1210 * \brief Authenticate with the server
1211 * \return Boolean Failure
1213 int Authenticate(int Socket)
1218 #if ATTEMPT_PASSWORD_AUTH
1221 regmatch_t matches[4];
1224 if( gbIsAuthenticated ) return 0;
1227 pwd = getpwuid( getuid() );
1229 // Attempt automatic authentication
1230 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1232 // Check if it worked
1233 buf = ReadLine(Socket);
1235 responseCode = atoi(buf);
1236 switch( responseCode )
1238 case 200: // Autoauth succeeded, return
1242 case 401: // Untrusted, attempt password authentication
1245 #if ATTEMPT_PASSWORD_AUTH
1246 sendf(Socket, "USER %s\n", pwd->pw_name);
1247 printf("Using username %s\n", pwd->pw_name);
1249 buf = ReadLine(Socket);
1252 // Expected format: 100 SALT <something> ...
1253 // OR : 100 User Set
1254 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1255 responseCode = atoi(buf);
1256 if( responseCode != 100 ) {
1257 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1259 return RV_UNKNOWN_ERROR; // ERROR
1263 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1264 // Store it for later
1265 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1266 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1270 // Give three attempts
1271 for( i = 0; i < 3; i ++ )
1273 int ofs = strlen(pwd->pw_name)+strlen(salt);
1276 char *pass = getpass("Password: ");
1279 // Create hash string
1280 // <username><salt><hash>
1281 strcpy(tmp, pwd->pw_name);
1283 SHA1( (unsigned char*)pass, strlen(pass), h );
1284 memcpy(tmp+ofs, h, 20);
1287 SHA1( (unsigned char*)tmp, ofs+20, h );
1288 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1289 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1290 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1294 sendf(Socket, "PASS %s\n", tmpBuf);
1295 buf = ReadLine(Socket);
1297 responseCode = atoi(buf);
1299 if( responseCode == 200 ) break;
1300 // Bad username/password
1301 if( responseCode == 401 ) continue;
1303 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1305 return RV_UNKNOWN_ERROR;
1309 return RV_INVALID_USER; // 2 = Bad Password
1312 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1313 return RV_INVALID_USER;
1317 case 404: // Bad Username
1318 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1320 return RV_INVALID_USER;
1323 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1324 printf("%s\n", buf);
1326 return RV_UNKNOWN_ERROR;
1329 // Set effective user
1330 if( gsEffectiveUser ) {
1331 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1333 buf = ReadLine(Socket);
1334 responseCode = atoi(buf);
1336 switch(responseCode)
1339 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1343 printf("Only coke members can use `dispense -u`\n");
1345 return RV_PERMISSIONS;
1348 printf("Invalid user selected\n");
1350 return RV_INVALID_USER;
1353 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1354 printf("%s\n", buf);
1356 return RV_UNKNOWN_ERROR;
1362 gbIsAuthenticated = 1;
1367 int GetUserBalance(int Socket)
1369 regmatch_t matches[6];
1376 if( gsEffectiveUser ) {
1377 gsUserName = gsEffectiveUser;
1380 pwd = getpwuid( getuid() );
1381 gsUserName = strdup(pwd->pw_name);
1385 sendf(Socket, "USER_INFO %s\n", gsUserName);
1386 buf = ReadLine(Socket);
1387 responseCode = atoi(buf);
1388 switch(responseCode)
1390 case 202: break; // Ok
1393 printf("Invalid user? (USER_INFO failed)\n");
1395 return RV_INVALID_USER;
1398 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1399 printf("%s\n", buf);
1401 return RV_UNKNOWN_ERROR;
1404 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1406 giUserBalance = atoi( buf + matches[4].rm_so );
1407 gsUserFlags = strdup( buf + matches[5].rm_so );
1415 * \brief Read an item info response from the server
1416 * \param Dest Destination for the read item (strings will be on the heap)
1418 int ReadItemInfo(int Socket, tItem *Dest)
1423 regmatch_t matches[8];
1427 buf = ReadLine(Socket);
1428 responseCode = atoi(buf);
1430 switch(responseCode)
1435 printf("Bad item name\n");
1440 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1442 return RV_UNKNOWN_ERROR;
1445 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1447 buf[ matches[3].rm_eo ] = '\0';
1448 buf[ matches[5].rm_eo ] = '\0';
1449 buf[ matches[7].rm_eo ] = '\0';
1451 statusStr = &buf[ matches[5].rm_so ];
1453 Dest->ID = atoi( buf + matches[4].rm_so );
1455 if( strcmp(statusStr, "avail") == 0 )
1457 else if( strcmp(statusStr, "sold") == 0 )
1459 else if( strcmp(statusStr, "error") == 0 )
1462 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1464 return RV_UNKNOWN_ERROR;
1466 Dest->Price = atoi( buf + matches[6].rm_so );
1468 // Hack a little to reduce heap fragmentation
1470 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1471 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1472 strcpy(tmpType, buf + matches[3].rm_so);
1473 strcpy(tmpDesc, buf + matches[7].rm_so);
1475 Dest->Type = strdup( tmpType );
1476 Dest->Desc = strdup( tmpDesc );
1483 * \brief Fill the item information structure
1484 * \return Boolean Failure
1486 void PopulateItemList(int Socket)
1491 char *itemType, *itemStart;
1493 regmatch_t matches[4];
1495 // Ask server for stock list
1496 send(Socket, "ENUM_ITEMS\n", 11, 0);
1497 buf = ReadLine(Socket);
1499 //printf("Output: %s\n", buf);
1501 responseCode = atoi(buf);
1502 if( responseCode != 201 ) {
1503 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1504 exit(RV_UNKNOWN_ERROR);
1507 // - Get item list -
1510 // 201 Items <count>
1512 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1514 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1515 count = atoi( &buf[ matches[3].rm_so ] );
1518 if( strcmp(itemType, "Items") != 0 ) {
1520 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1522 exit(RV_UNKNOWN_ERROR);
1525 itemStart = &buf[ matches[3].rm_eo ];
1530 gaItems = malloc( giNumItems * sizeof(tItem) );
1532 // Fetch item information
1533 for( i = 0; i < giNumItems; i ++ )
1535 ReadItemInfo( Socket, &gaItems[i] );
1539 buf = ReadLine(Socket);
1540 responseCode = atoi(buf);
1542 if( responseCode != 200 ) {
1543 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1554 * \brief Get information on an item
1555 * \return Boolean Failure
1557 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1563 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1565 ret = ReadItemInfo(Socket, &item);
1568 printf("%8s:%-2i %2i.%02i %s\n",
1570 item.Price/100, item.Price%100,
1580 * \brief Dispense an item
1581 * \return Boolean Failure
1583 int DispenseItem(int Socket, const char *Type, int ID)
1585 int ret, responseCode;
1588 // Check for a dry run
1590 printf("Dry Run - No action\n");
1595 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1596 buf = ReadLine(Socket);
1598 responseCode = atoi(buf);
1599 switch( responseCode )
1602 printf("Dispense OK\n");
1606 printf("Not authenticated\n");
1607 ret = RV_PERMISSIONS;
1610 printf("Insufficient balance\n");
1614 printf("Bad item name\n");
1618 printf("Item failed to dispense, is the slot empty?\n");
1619 ret = RV_SERVER_ERROR;
1622 printf("Dispense not possible (slot empty/permissions)\n");
1623 ret = RV_SERVER_ERROR;
1626 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1627 ret = RV_UNKNOWN_ERROR;
1636 * \brief Alter a user's balance
1638 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1643 // Check for a dry run
1645 printf("Dry Run - No action\n");
1650 if( Ammount == 0 ) {
1651 printf("An ammount would be nice\n");
1652 return RV_ARGUMENTS;
1655 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1656 buf = ReadLine(Socket);
1658 responseCode = atoi(buf);
1661 switch(responseCode)
1663 case 200: return 0; // OK
1665 fprintf(stderr, "Insufficient balance\n");
1667 case 403: // Not in coke
1668 fprintf(stderr, "You are not in coke (sucker)\n");
1669 return RV_PERMISSIONS;
1670 case 404: // Unknown user
1671 fprintf(stderr, "Unknown user '%s'\n", Username);
1672 return RV_INVALID_USER;
1674 fprintf(stderr, "Unknown response code %i\n", responseCode);
1675 return RV_UNKNOWN_RESPONSE;
1682 * \brief Set a user's balance
1683 * \note Only avaliable to dispense admins
1685 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1690 // Check for a dry run
1692 printf("Dry Run - No action\n");
1696 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1697 buf = ReadLine(Socket);
1699 responseCode = atoi(buf);
1702 switch(responseCode)
1704 case 200: return 0; // OK
1705 case 403: // Not in coke
1706 fprintf(stderr, "You are not an admin\n");
1707 return RV_PERMISSIONS;
1708 case 404: // Unknown user
1709 fprintf(stderr, "Unknown user '%s'\n", Username);
1710 return RV_INVALID_USER;
1712 fprintf(stderr, "Unknown response code %i\n", responseCode);
1713 return RV_UNKNOWN_RESPONSE;
1720 * \brief Give money to another user
1722 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1728 printf("Sorry, you can only give, you can't take.\n");
1729 return RV_ARGUMENTS;
1732 // Fast return on zero
1733 if( Ammount == 0 ) {
1734 printf("Are you actually going to give any?\n");
1735 return RV_ARGUMENTS;
1738 // Check for a dry run
1740 printf("Dry Run - No action\n");
1744 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1746 buf = ReadLine(Socket);
1747 responseCode = atoi(buf);
1749 switch(responseCode)
1752 printf("Give succeeded\n");
1753 return RV_SUCCESS; // OK
1756 fprintf(stderr, "Insufficient balance\n");
1759 case 404: // Unknown user
1760 fprintf(stderr, "Unknown user '%s'\n", Username);
1761 return RV_INVALID_USER;
1764 fprintf(stderr, "Unknown response code %i\n", responseCode);
1765 return RV_UNKNOWN_RESPONSE;
1771 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1774 int responseCode, ret = -1;
1777 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1779 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1780 return RV_ARGUMENTS;
1783 // Check username (quick)
1784 if( strchr(Username, ' ') || strchr(Username, '\n') )
1786 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1787 return RV_ARGUMENTS;
1791 sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1793 buf = ReadLine(Socket);
1794 responseCode = atoi(buf);
1795 switch(responseCode)
1798 Dispense_ShowUser(Socket, Username); // Show destination account
1802 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1803 ret = RV_PERMISSIONS;
1806 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1807 ret = RV_INVALID_USER;
1810 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1814 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1823 * \brief Donate money to the club
1825 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1831 printf("Sorry, you can only give, you can't take.\n");
1835 // Fast return on zero
1836 if( Ammount == 0 ) {
1837 printf("Are you actually going to give any?\n");
1841 // Check for a dry run
1843 printf("Dry Run - No action\n");
1847 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1848 buf = ReadLine(Socket);
1850 responseCode = atoi(buf);
1853 switch(responseCode)
1855 case 200: return 0; // OK
1858 fprintf(stderr, "Insufficient balance\n");
1862 fprintf(stderr, "Unknown response code %i\n", responseCode);
1870 * \brief Enumerate users
1872 int Dispense_EnumUsers(int Socket)
1877 regmatch_t matches[4];
1879 if( giMinimumBalance != INT_MIN ) {
1880 if( giMaximumBalance != INT_MAX ) {
1881 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1884 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1888 if( giMaximumBalance != INT_MAX ) {
1889 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1892 sendf(Socket, "ENUM_USERS\n");
1895 buf = ReadLine(Socket);
1896 responseCode = atoi(buf);
1898 switch(responseCode)
1900 case 201: break; // Ok, length follows
1903 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1908 // Get count (not actually used)
1909 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1910 nUsers = atoi( buf + matches[3].rm_so );
1911 printf("%i users returned\n", nUsers);
1916 // Read returned users
1918 buf = ReadLine(Socket);
1919 responseCode = atoi(buf);
1921 if( responseCode != 202 ) break;
1923 _PrintUserLine(buf);
1925 } while(responseCode == 202);
1927 // Check final response
1928 if( responseCode != 200 ) {
1929 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1939 int Dispense_ShowUser(int Socket, const char *Username)
1942 int responseCode, ret;
1944 sendf(Socket, "USER_INFO %s\n", Username);
1945 buf = ReadLine(Socket);
1947 responseCode = atoi(buf);
1949 switch(responseCode)
1952 _PrintUserLine(buf);
1957 printf("Unknown user '%s'\n", Username);
1962 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1972 void _PrintUserLine(const char *Line)
1974 regmatch_t matches[6];
1977 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1982 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1983 char username[usernameLen + 1];
1984 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1985 char flags[flagsLen + 1];
1987 memcpy(username, Line + matches[3].rm_so, usernameLen);
1988 username[usernameLen] = '\0';
1989 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1990 flags[flagsLen] = '\0';
1992 bal = atoi(Line + matches[4].rm_so);
1993 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1997 int Dispense_AddUser(int Socket, const char *Username)
2000 int responseCode, ret;
2002 // Check for a dry run
2004 printf("Dry Run - No action\n");
2008 sendf(Socket, "USER_ADD %s\n", Username);
2010 buf = ReadLine(Socket);
2011 responseCode = atoi(buf);
2013 switch(responseCode)
2016 printf("User '%s' added\n", Username);
2021 printf("Only wheel can add users\n");
2026 printf("User '%s' already exists\n", Username);
2031 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2041 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
2044 int responseCode, ret;
2046 // Check for a dry run
2048 printf("Dry Run - No action\n");
2052 // TODO: Pre-validate the string
2054 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
2056 buf = ReadLine(Socket);
2057 responseCode = atoi(buf);
2059 switch(responseCode)
2062 printf("User '%s' updated\n", Username);
2067 printf("Only wheel can modify users\n");
2068 ret = RV_PERMISSIONS;
2072 printf("User '%s' does not exist\n", Username);
2073 ret = RV_INVALID_USER;
2077 printf("Flag string is invalid\n");
2082 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2083 ret = RV_UNKNOWN_RESPONSE;
2092 int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName)
2095 int responseCode, ret;
2097 // Check for a dry run
2099 printf("Dry Run - No action\n");
2103 sendf(Socket, "UPDATE_ITEM %s:%i %i %s\n", Type, ID, NewPrice, NewName);
2105 buf = ReadLine(Socket);
2106 responseCode = atoi(buf);
2108 switch(responseCode)
2111 printf("Item %s:%i updated\n", Type, ID);
2116 printf("Only coke members can modify the slots\n");
2117 ret = RV_PERMISSIONS;
2121 printf("Invalid item passed\n");
2126 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2139 char *ReadLine(int Socket)
2141 static char buf[BUFSIZ];
2142 static int bufPos = 0;
2143 static int bufValid = 0;
2145 char *newline = NULL;
2147 char *ret = malloc(10);
2149 #if DEBUG_TRACE_SERVER
2150 printf("ReadLine: ");
2162 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2165 return strdup("499 Client Connection Error\n");
2167 buf[bufPos+len] = '\0';
2170 newline = strchr( buf+bufPos, '\n' );
2175 retLen += strlen(buf+bufPos);
2176 ret = realloc(ret, retLen + 1);
2177 strcat( ret, buf+bufPos );
2180 int newLen = newline - (buf+bufPos) + 1;
2181 bufValid = len - newLen;
2184 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2187 #if DEBUG_TRACE_SERVER
2188 printf("%i '%s'\n", retLen, ret);
2194 int sendf(int Socket, const char *Format, ...)
2199 va_start(args, Format);
2200 len = vsnprintf(NULL, 0, Format, args);
2205 va_start(args, Format);
2206 vsnprintf(buf, len+1, Format, args);
2209 #if DEBUG_TRACE_SERVER
2210 printf("sendf: %s", buf);
2213 return send(Socket, buf, len, 0);
2217 char *trim(char *string)
2221 while( isspace(*string) )
2224 for( i = strlen(string); i--; )
2226 if( isspace(string[i]) )
2235 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2239 ret = regexec(regex, string, nMatches, matches, 0);
2240 if( ret && errorMessage ) {
2241 size_t len = regerror(ret, regex, NULL, 0);
2243 regerror(ret, regex, errorStr, len);
2244 printf("string = '%s'\n", string);
2245 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2252 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2254 int ret = regcomp(regex, pattern, flags);
2256 size_t len = regerror(ret, regex, NULL, 0);
2258 regerror(ret, regex, errorStr, len);
2259 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);