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( strcmp(argv[i], "--help") == 0 ) {
295 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
301 // The first argument is not allowed to begin with 'i'
302 // (catches most bad flags)
303 if( text_argc == 0 ) {
304 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
308 if( text_argc + 1 == MAX_TXT_ARGS )
310 fprintf(stderr, "ERROR: Too many arguments\n");
313 text_args[text_argc++] = argv[i];
320 if( text_argc + 1 == MAX_TXT_ARGS )
322 fprintf(stderr, "ERROR: Too many arguments\n");
326 text_args[text_argc++] = argv[i];
333 if( strcmp(text_args[0], "acct") == 0 )
336 sock = OpenConnection(gsDispenseServer, giDispensePort);
337 if( sock < 0 ) return RV_SOCKET_ERROR;
339 if( text_argc == 1 ) {
340 ret = Dispense_EnumUsers(sock);
345 // text_args[1]: Username
350 if( text_argc != 4 ) {
351 fprintf(stderr, "`dispense acct` requires a reason\n");
356 // Authentication required
357 ret = Authenticate(sock);
360 // text_args[1]: Username
361 // text_args[2]: Ammount
362 // text_args[3]: Reason
364 if( text_args[2][0] == '=' ) {
366 if( text_args[2][1] != '0' && atoi(text_args[2]+1) == 0 ) {
367 fprintf(stderr, "Error: Invalid balance to be set\n");
371 ret = Dispense_SetBalance(sock, text_args[1], atoi(text_args[2]+1), text_args[3]);
375 ret = Dispense_AlterBalance(sock, text_args[1], atoi(text_args[2]), text_args[3]);
378 // TODO: Preserve ret if non-zero
380 // Show user information
381 ret = Dispense_ShowUser(sock, text_args[1]);
388 // - "Here, have some money."
389 else if( strcmp(text_args[0], "give") == 0 )
391 if( text_argc != 4 ) {
392 fprintf(stderr, "`dispense give` takes three arguments\n");
397 // text_args[1]: Destination
398 // text_args[2]: Ammount
399 // text_args[3]: Reason
402 sock = OpenConnection(gsDispenseServer, giDispensePort);
403 if( sock < 0 ) return RV_SOCKET_ERROR;
406 ret = Authenticate(sock);
409 ret = Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
417 // - User administration (Admin Only)
418 if( strcmp(text_args[0], "user") == 0 )
420 // Check argument count
421 if( text_argc == 1 ) {
422 fprintf(stderr, "Error: `dispense user` requires arguments\n");
428 sock = OpenConnection(gsDispenseServer, giDispensePort);
429 if( sock < 0 ) return RV_SOCKET_ERROR;
431 // Attempt authentication
432 ret = Authenticate(sock);
436 if( strcmp(text_args[1], "add") == 0 )
438 if( text_argc != 3 ) {
439 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
444 ret = Dispense_AddUser(sock, text_args[2]);
447 else if( strcmp(text_args[1], "type") == 0 || strcmp(text_args[1], "flags") == 0 )
449 if( text_argc != 4 ) {
450 fprintf(stderr, "Error: `dispense user flags` requires two arguments\n");
455 ret = Dispense_SetUserType(sock, text_args[2], text_args[3]);
459 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
467 else if( strcmp(text_args[0], "donate") == 0 )
469 // Check argument count
470 if( text_argc != 3 ) {
471 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
477 sock = OpenConnection(gsDispenseServer, giDispensePort);
478 if( sock < 0 ) return RV_SOCKET_ERROR;
480 // Attempt authentication
481 ret = Authenticate(sock);
485 ret = Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
492 else if( strcmp(text_args[0], "refund") == 0 )
495 // Check argument count
496 if( text_argc != 3 && text_argc != 4 ) {
497 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
503 sock = OpenConnection(gsDispenseServer, giDispensePort);
504 if(sock < 0) return RV_SOCKET_ERROR;
506 // Attempt authentication
507 ret = Authenticate(sock);
510 if( text_argc == 4 ) {
511 price = atoi(text_args[3]);
513 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
518 // Username, Item, cost
519 ret = Dispense_Refund(sock, text_args[1], text_args[2], price);
523 return RV_UNKNOWN_ERROR;
525 // Query an item price
526 else if( strcmp(text_args[0], "iteminfo") == 0 )
528 regmatch_t matches[3];
531 // Check argument count
532 if( text_argc != 2 ) {
533 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
538 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
539 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
542 type = text_args[1] + matches[1].rm_so;
543 text_args[1][ matches[1].rm_eo ] = '\0';
544 id = atoi( text_args[1] + matches[2].rm_so );
546 sock = OpenConnection(gsDispenseServer, giDispensePort);
547 if( sock < 0 ) return RV_SOCKET_ERROR;
549 ret = Dispense_ItemInfo(sock, type, id);
554 else if( strcmp(text_args[0], "slot") == 0 )
556 regmatch_t matches[3];
557 char *item_type, *newname;
561 if( text_argc != 4 ) {
562 fprintf(stderr, "Error: `dispense slot` takes three arguments\n");
568 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
569 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
572 item_type = text_args[1] + matches[1].rm_so;
573 text_args[1][ matches[1].rm_eo ] = '\0';
574 item_id = atoi( text_args[1] + matches[2].rm_so );
577 price = atoi( text_args[2] );
578 if( price <= 0 && text_args[2][0] != '0' ) {
579 fprintf(stderr, "Error: Invalid price passed (must be >= 0)\n");
584 newname = text_args[3];
588 for( pos = newname; *pos; pos ++ )
590 if( !isalnum(*pos) && *pos != ' ' ) {
591 fprintf(stderr, "Error: You should only have letters, numbers and spaces in an item name\n");
597 // Connect & Authenticate
598 sock = OpenConnection(gsDispenseServer, giDispensePort);
599 if( sock < 0 ) return RV_SOCKET_ERROR;
600 ret = Authenticate(sock);
603 ret = Dispense_SetItem(sock, item_type, item_id, price, newname);
608 // Item name / pattern
611 gsItemPattern = text_args[0];
615 sock = OpenConnection(gsDispenseServer, giDispensePort);
616 if( sock < 0 ) return RV_SOCKET_ERROR;
618 // Get the user's balance
619 ret = GetUserBalance(sock);
623 PopulateItemList(sock);
625 // Disconnect from server
628 if( gsItemPattern && gsItemPattern[0] )
630 regmatch_t matches[3];
632 if( strcmp(gsItemPattern, "door") == 0 )
634 // Connect, Authenticate, dispense and close
635 sock = OpenConnection(gsDispenseServer, giDispensePort);
636 if( sock < 0 ) return RV_SOCKET_ERROR;
637 ret = Authenticate(sock);
639 ret = DispenseItem(sock, "door", 0);
643 // Item id (<type>:<num>)
644 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
649 // Get and finish ident
650 ident = gsItemPattern + matches[1].rm_so;
651 gsItemPattern[matches[1].rm_eo] = '\0';
653 id = atoi( gsItemPattern + matches[2].rm_so );
655 // Connect, Authenticate, dispense and close
656 sock = OpenConnection(gsDispenseServer, giDispensePort);
657 if( sock < 0 ) return RV_SOCKET_ERROR;
659 Dispense_ItemInfo(sock, ident, id);
661 ret = Authenticate(sock);
663 ret = DispenseItem(sock, ident, id);
667 // Item number (6 = coke)
668 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
670 i = atoi(gsItemPattern);
677 for( i = 0; i < giNumItems; i ++ )
679 // Prefix match (with case-insensitive match)
680 for( j = 0; gsItemPattern[j]; j ++ )
682 if( gaItems[i].Desc[j] == gsItemPattern[j] )
684 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
688 // Check if the prefix matched
689 if( gsItemPattern[j] != '\0' )
693 if( gaItems[i].Desc[j] == '\0' ) {
698 // Only one match allowed
703 // TODO: Allow ambiguous matches?
704 // or just print a wanrning
705 printf("Warning - Ambiguous pattern, stopping\n");
710 // Was a match found?
713 fprintf(stderr, "No item matches the passed string\n");
720 else if( giUIMode != UI_MODE_BASIC )
726 // Very basic dispense interface
727 for( i = 0; i < giNumItems; i ++ ) {
729 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
732 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
733 gaItems[i].Price, gaItems[i].Desc);
742 fgets(buffer, BUFSIZ, stdin);
746 if( buf[0] == 'q' ) break;
750 if( i != 0 || buf[0] == '0' )
752 if( i < 0 || i >= giNumItems ) {
753 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
762 // Check for a valid item ID
766 // Connect, Authenticate, dispense and close
767 sock = OpenConnection(gsDispenseServer, giDispensePort);
768 if( sock < 0 ) return RV_SOCKET_ERROR;
770 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
773 ret = Authenticate(sock);
776 for( j = 0; j < giDispenseCount; j ++ ) {
777 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
781 printf("%i items dispensed\n", j);
789 // -------------------
790 // --- NCurses GUI ---
791 // -------------------
793 * \brief Render the NCurses UI
795 int ShowNCursesUI(void)
800 const int displayMinWidth = 40;
801 char *titleString = "Dispense";
806 int ret = -2; // -2: Used for marking "no return yet"
808 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
815 if( gsEffectiveUser )
816 username = gsEffectiveUser;
818 pwd = getpwuid( getuid() );
819 username = pwd->pw_name;
822 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
829 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
830 // Get item count per screen
831 // - 6: randomly chosen (Need at least 3)
832 itemCount = LINES - 6;
833 if( itemCount > maxItemIndex )
834 itemCount = maxItemIndex;
837 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
842 height = itemCount + 3;
843 width = displayMinWidth;
846 xBase = COLS/2 - width/2;
847 yBase = LINES/2 - height/2;
852 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
855 for( i = 0; i < itemCount; i ++ )
859 move( yBase + 1 + i, xBase );
864 // Check for the '...' row
865 // - Oh god, magic numbers!
866 if( (i == 0 && itemBase > 0)
867 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
869 printw(" ..."); pos += 8;
870 times = (width - pos) - 1;
871 while(times--) addch(' ');
876 yBase + 1 + i, xBase + pos, // Position
877 (width - pos) - 3, // Width
878 itemBase + i, // Index
879 !!(currentItem == itemBase + i) // Hilighted
884 // Scrollbar (if needed)
885 if( maxItemIndex > itemCount ) {
889 else if( i == itemCount - 1 ) {
893 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
894 if( i-1 == percentage*(itemCount-3)/100 ) {
908 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
911 // - Username, balance, flags
912 PrintAlign(yBase+height-1, xBase+1, width-2,
913 username, ' ', balance_str, ' ', gsUserFlags);
929 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
932 if( currentItem >= maxItemIndex ) {
935 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
942 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
945 if( currentItem < 0 ) {
946 currentItem = maxItemIndex - 1;
948 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
958 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
959 itemBase = currentItem - 2;
960 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
961 itemBase = currentItem - itemCount + 2;
967 ret = ShowItemAt(0, 0, 0, currentItem, 0);
971 ret = -1; // -1: Return with no dispense
975 // Check if the return value was changed
976 if( ret != -2 ) break;
988 * \brief Show item \a Index at (\a Col, \a Row)
989 * \return Dispense index of item
990 * \note Part of the NCurses UI
992 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
1002 // - This assumes that
1003 case UI_MODE_STANDARD:
1005 // Index = -1, request limit
1006 if( Index < 0 || Index >= giNumItems+2 )
1007 return giNumItems+2;
1012 name = "Coke Machine";
1013 Index = -1; // -1 indicates a label
1020 name = gaItems[Index].Desc;
1021 price = gaItems[Index].Price;
1022 status = gaItems[Index].Status;
1030 name = "Electronic Payment System";
1031 Index = -1; // -1 indicates a label
1036 name = gaItems[Index].Desc;
1037 price = gaItems[Index].Price;
1038 status = gaItems[Index].Status;
1044 // Width = 0, don't print
1047 // 4 preceding, 5 price
1048 int nameWidth = Width - 4 - 5;
1053 // Show hilight and status
1072 printw("%-*.*s", nameWidth, nameWidth, name);
1074 // getyx(stdscr, _y, _x);
1075 // Assumes max 4 digit prices
1076 // times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
1077 // while(times--) addch(' ');
1079 printw(" %4i", price);
1083 printw("-- %s", name);
1084 getyx(stdscr, _y, _x);
1085 times = Width - 4 - (_x - Col);
1086 while(times--) addch(' ');
1091 // If the item isn't availiable for sale, return -1 (so it's skipped)
1092 if( status || price >= giUserBalance )
1099 * \brief Print a three-part string at the specified position (formatted)
1100 * \note NCurses UI Helper
1102 * Prints \a Left on the left of the area, \a Right on the righthand side
1103 * and \a Mid in the middle of the area. These are padded with \a Pad1
1104 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1106 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1107 * and the arguments to these are read in that order.
1109 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1110 const char *Mid, char Pad2, const char *Right, ...)
1112 int lLen, mLen, rLen;
1117 // Get the length of the strings
1118 va_start(args, Right);
1119 lLen = vsnprintf(NULL, 0, Left, args);
1120 mLen = vsnprintf(NULL, 0, Mid, args);
1121 rLen = vsnprintf(NULL, 0, Right, args);
1125 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1126 return ; // TODO: What to do?
1132 va_start(args, Right);
1136 vsnprintf(tmp, lLen+1, Left, args);
1140 times = (Width - mLen)/2 - lLen;
1141 while(times--) addch(Pad1);
1145 vsnprintf(tmp, mLen+1, Mid, args);
1149 times = (Width - mLen)/2 - rLen;
1150 if( (Width - mLen) % 2 ) times ++;
1151 while(times--) addch(Pad2);
1155 vsnprintf(tmp, rLen+1, Right, args);
1160 // ---------------------
1161 // --- Coke Protocol ---
1162 // ---------------------
1163 int OpenConnection(const char *Host, int Port)
1165 struct hostent *host;
1166 struct sockaddr_in serverAddr;
1169 host = gethostbyname(Host);
1171 fprintf(stderr, "Unable to look up '%s'\n", Host);
1175 memset(&serverAddr, 0, sizeof(serverAddr));
1177 serverAddr.sin_family = AF_INET; // IPv4
1178 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1179 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1180 serverAddr.sin_port = htons(Port);
1182 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1184 fprintf(stderr, "Failed to create socket\n");
1188 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1190 if( geteuid() == 0 || getuid() == 0 )
1193 struct sockaddr_in localAddr;
1194 memset(&localAddr, 0, sizeof(localAddr));
1195 localAddr.sin_family = AF_INET; // IPv4
1197 // Loop through all the top ports until one is avaliable
1198 for( i = 512; i < 1024; i ++)
1200 localAddr.sin_port = htons(i); // IPv4
1201 // Attempt to bind to low port for autoauth
1202 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1206 printf("Warning: AUTOAUTH unavaliable\n");
1208 // printf("Bound to 0.0.0.0:%i\n", i);
1211 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1212 fprintf(stderr, "Failed to connect to server\n");
1216 // We're not authenticated if the connection has just opened
1217 gbIsAuthenticated = 0;
1223 * \brief Authenticate with the server
1224 * \return Boolean Failure
1226 int Authenticate(int Socket)
1231 #if ATTEMPT_PASSWORD_AUTH
1234 regmatch_t matches[4];
1237 if( gbIsAuthenticated ) return 0;
1240 pwd = getpwuid( getuid() );
1242 // Attempt automatic authentication
1243 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1245 // Check if it worked
1246 buf = ReadLine(Socket);
1248 responseCode = atoi(buf);
1249 switch( responseCode )
1251 case 200: // Autoauth succeeded, return
1255 case 401: // Untrusted, attempt password authentication
1258 #if ATTEMPT_PASSWORD_AUTH
1259 sendf(Socket, "USER %s\n", pwd->pw_name);
1260 printf("Using username %s\n", pwd->pw_name);
1262 buf = ReadLine(Socket);
1265 // Expected format: 100 SALT <something> ...
1266 // OR : 100 User Set
1267 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1268 responseCode = atoi(buf);
1269 if( responseCode != 100 ) {
1270 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1272 return RV_UNKNOWN_ERROR; // ERROR
1276 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1277 // Store it for later
1278 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1279 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1283 // Give three attempts
1284 for( i = 0; i < 3; i ++ )
1286 int ofs = strlen(pwd->pw_name)+strlen(salt);
1289 char *pass = getpass("Password: ");
1292 // Create hash string
1293 // <username><salt><hash>
1294 strcpy(tmp, pwd->pw_name);
1296 SHA1( (unsigned char*)pass, strlen(pass), h );
1297 memcpy(tmp+ofs, h, 20);
1300 SHA1( (unsigned char*)tmp, ofs+20, h );
1301 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1302 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1303 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1307 sendf(Socket, "PASS %s\n", tmpBuf);
1308 buf = ReadLine(Socket);
1310 responseCode = atoi(buf);
1312 if( responseCode == 200 ) break;
1313 // Bad username/password
1314 if( responseCode == 401 ) continue;
1316 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1318 return RV_UNKNOWN_ERROR;
1322 return RV_INVALID_USER; // 2 = Bad Password
1325 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1326 return RV_INVALID_USER;
1330 case 404: // Bad Username
1331 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1333 return RV_INVALID_USER;
1336 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1337 printf("%s\n", buf);
1339 return RV_UNKNOWN_ERROR;
1342 // Set effective user
1343 if( gsEffectiveUser ) {
1344 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1346 buf = ReadLine(Socket);
1347 responseCode = atoi(buf);
1349 switch(responseCode)
1352 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1356 printf("Only coke members can use `dispense -u`\n");
1358 return RV_PERMISSIONS;
1361 printf("Invalid user selected\n");
1363 return RV_INVALID_USER;
1366 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1367 printf("%s\n", buf);
1369 return RV_UNKNOWN_ERROR;
1375 gbIsAuthenticated = 1;
1380 int GetUserBalance(int Socket)
1382 regmatch_t matches[6];
1389 if( gsEffectiveUser ) {
1390 gsUserName = gsEffectiveUser;
1393 pwd = getpwuid( getuid() );
1394 gsUserName = strdup(pwd->pw_name);
1398 sendf(Socket, "USER_INFO %s\n", gsUserName);
1399 buf = ReadLine(Socket);
1400 responseCode = atoi(buf);
1401 switch(responseCode)
1403 case 202: break; // Ok
1406 printf("Invalid user? (USER_INFO failed)\n");
1408 return RV_INVALID_USER;
1411 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1412 printf("%s\n", buf);
1414 return RV_UNKNOWN_ERROR;
1417 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1419 giUserBalance = atoi( buf + matches[4].rm_so );
1420 gsUserFlags = strdup( buf + matches[5].rm_so );
1428 * \brief Read an item info response from the server
1429 * \param Dest Destination for the read item (strings will be on the heap)
1431 int ReadItemInfo(int Socket, tItem *Dest)
1436 regmatch_t matches[8];
1440 buf = ReadLine(Socket);
1441 responseCode = atoi(buf);
1443 switch(responseCode)
1448 printf("Bad item name\n");
1453 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1455 return RV_UNKNOWN_ERROR;
1458 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1460 buf[ matches[3].rm_eo ] = '\0';
1461 buf[ matches[5].rm_eo ] = '\0';
1462 buf[ matches[7].rm_eo ] = '\0';
1464 statusStr = &buf[ matches[5].rm_so ];
1466 Dest->ID = atoi( buf + matches[4].rm_so );
1468 if( strcmp(statusStr, "avail") == 0 )
1470 else if( strcmp(statusStr, "sold") == 0 )
1472 else if( strcmp(statusStr, "error") == 0 )
1475 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1477 return RV_UNKNOWN_ERROR;
1479 Dest->Price = atoi( buf + matches[6].rm_so );
1481 // Hack a little to reduce heap fragmentation
1483 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1484 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1485 strcpy(tmpType, buf + matches[3].rm_so);
1486 strcpy(tmpDesc, buf + matches[7].rm_so);
1488 Dest->Type = strdup( tmpType );
1489 Dest->Desc = strdup( tmpDesc );
1496 * \brief Fill the item information structure
1497 * \return Boolean Failure
1499 void PopulateItemList(int Socket)
1504 char *itemType, *itemStart;
1506 regmatch_t matches[4];
1508 // Ask server for stock list
1509 send(Socket, "ENUM_ITEMS\n", 11, 0);
1510 buf = ReadLine(Socket);
1512 //printf("Output: %s\n", buf);
1514 responseCode = atoi(buf);
1515 if( responseCode != 201 ) {
1516 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1517 exit(RV_UNKNOWN_ERROR);
1520 // - Get item list -
1523 // 201 Items <count>
1525 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1527 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1528 count = atoi( &buf[ matches[3].rm_so ] );
1531 if( strcmp(itemType, "Items") != 0 ) {
1533 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1535 exit(RV_UNKNOWN_ERROR);
1538 itemStart = &buf[ matches[3].rm_eo ];
1543 gaItems = malloc( giNumItems * sizeof(tItem) );
1545 // Fetch item information
1546 for( i = 0; i < giNumItems; i ++ )
1548 ReadItemInfo( Socket, &gaItems[i] );
1552 buf = ReadLine(Socket);
1553 responseCode = atoi(buf);
1555 if( responseCode != 200 ) {
1556 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1567 * \brief Get information on an item
1568 * \return Boolean Failure
1570 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1576 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1578 ret = ReadItemInfo(Socket, &item);
1581 printf("%8s:%-2i %2i.%02i %s\n",
1583 item.Price/100, item.Price%100,
1593 * \brief Dispense an item
1594 * \return Boolean Failure
1596 int DispenseItem(int Socket, const char *Type, int ID)
1598 int ret, responseCode;
1601 // Check for a dry run
1603 printf("Dry Run - No action\n");
1608 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1609 buf = ReadLine(Socket);
1611 responseCode = atoi(buf);
1612 switch( responseCode )
1615 printf("Dispense OK\n");
1619 printf("Not authenticated\n");
1620 ret = RV_PERMISSIONS;
1623 printf("Insufficient balance\n");
1627 printf("Bad item name\n");
1631 printf("Item failed to dispense, is the slot empty?\n");
1632 ret = RV_SERVER_ERROR;
1635 printf("Dispense not possible (slot empty/permissions)\n");
1636 ret = RV_SERVER_ERROR;
1639 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1640 ret = RV_UNKNOWN_ERROR;
1649 * \brief Alter a user's balance
1651 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1656 // Check for a dry run
1658 printf("Dry Run - No action\n");
1663 if( Ammount == 0 ) {
1664 printf("An ammount would be nice\n");
1665 return RV_ARGUMENTS;
1668 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1669 buf = ReadLine(Socket);
1671 responseCode = atoi(buf);
1674 switch(responseCode)
1676 case 200: return 0; // OK
1678 fprintf(stderr, "Insufficient balance\n");
1680 case 403: // Not in coke
1681 fprintf(stderr, "You are not in coke (sucker)\n");
1682 return RV_PERMISSIONS;
1683 case 404: // Unknown user
1684 fprintf(stderr, "Unknown user '%s'\n", Username);
1685 return RV_INVALID_USER;
1687 fprintf(stderr, "Unknown response code %i\n", responseCode);
1688 return RV_UNKNOWN_RESPONSE;
1695 * \brief Set a user's balance
1696 * \note Only avaliable to dispense admins
1698 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1703 // Check for a dry run
1705 printf("Dry Run - No action\n");
1709 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1710 buf = ReadLine(Socket);
1712 responseCode = atoi(buf);
1715 switch(responseCode)
1717 case 200: return 0; // OK
1718 case 403: // Not in coke
1719 fprintf(stderr, "You are not an admin\n");
1720 return RV_PERMISSIONS;
1721 case 404: // Unknown user
1722 fprintf(stderr, "Unknown user '%s'\n", Username);
1723 return RV_INVALID_USER;
1725 fprintf(stderr, "Unknown response code %i\n", responseCode);
1726 return RV_UNKNOWN_RESPONSE;
1733 * \brief Give money to another user
1735 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1741 printf("Sorry, you can only give, you can't take.\n");
1742 return RV_ARGUMENTS;
1745 // Fast return on zero
1746 if( Ammount == 0 ) {
1747 printf("Are you actually going to give any?\n");
1748 return RV_ARGUMENTS;
1751 // Check for a dry run
1753 printf("Dry Run - No action\n");
1757 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1759 buf = ReadLine(Socket);
1760 responseCode = atoi(buf);
1762 switch(responseCode)
1765 printf("Give succeeded\n");
1766 return RV_SUCCESS; // OK
1769 fprintf(stderr, "Insufficient balance\n");
1772 case 404: // Unknown user
1773 fprintf(stderr, "Unknown user '%s'\n", Username);
1774 return RV_INVALID_USER;
1777 fprintf(stderr, "Unknown response code %i\n", responseCode);
1778 return RV_UNKNOWN_RESPONSE;
1784 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1787 int responseCode, ret = -1;
1790 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1792 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1793 return RV_ARGUMENTS;
1796 // Check username (quick)
1797 if( strchr(Username, ' ') || strchr(Username, '\n') )
1799 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1800 return RV_ARGUMENTS;
1804 sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1806 buf = ReadLine(Socket);
1807 responseCode = atoi(buf);
1808 switch(responseCode)
1811 Dispense_ShowUser(Socket, Username); // Show destination account
1815 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1816 ret = RV_PERMISSIONS;
1819 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1820 ret = RV_INVALID_USER;
1823 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1827 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1836 * \brief Donate money to the club
1838 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1844 printf("Sorry, you can only give, you can't take.\n");
1848 // Fast return on zero
1849 if( Ammount == 0 ) {
1850 printf("Are you actually going to give any?\n");
1854 // Check for a dry run
1856 printf("Dry Run - No action\n");
1860 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1861 buf = ReadLine(Socket);
1863 responseCode = atoi(buf);
1866 switch(responseCode)
1868 case 200: return 0; // OK
1871 fprintf(stderr, "Insufficient balance\n");
1875 fprintf(stderr, "Unknown response code %i\n", responseCode);
1883 * \brief Enumerate users
1885 int Dispense_EnumUsers(int Socket)
1890 regmatch_t matches[4];
1892 if( giMinimumBalance != INT_MIN ) {
1893 if( giMaximumBalance != INT_MAX ) {
1894 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1897 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1901 if( giMaximumBalance != INT_MAX ) {
1902 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1905 sendf(Socket, "ENUM_USERS\n");
1908 buf = ReadLine(Socket);
1909 responseCode = atoi(buf);
1911 switch(responseCode)
1913 case 201: break; // Ok, length follows
1916 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1921 // Get count (not actually used)
1922 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1923 nUsers = atoi( buf + matches[3].rm_so );
1924 printf("%i users returned\n", nUsers);
1929 // Read returned users
1931 buf = ReadLine(Socket);
1932 responseCode = atoi(buf);
1934 if( responseCode != 202 ) break;
1936 _PrintUserLine(buf);
1938 } while(responseCode == 202);
1940 // Check final response
1941 if( responseCode != 200 ) {
1942 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1952 int Dispense_ShowUser(int Socket, const char *Username)
1955 int responseCode, ret;
1957 sendf(Socket, "USER_INFO %s\n", Username);
1958 buf = ReadLine(Socket);
1960 responseCode = atoi(buf);
1962 switch(responseCode)
1965 _PrintUserLine(buf);
1970 printf("Unknown user '%s'\n", Username);
1975 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1985 void _PrintUserLine(const char *Line)
1987 regmatch_t matches[6];
1990 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1995 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1996 char username[usernameLen + 1];
1997 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1998 char flags[flagsLen + 1];
2000 memcpy(username, Line + matches[3].rm_so, usernameLen);
2001 username[usernameLen] = '\0';
2002 memcpy(flags, Line + matches[5].rm_so, flagsLen);
2003 flags[flagsLen] = '\0';
2005 bal = atoi(Line + matches[4].rm_so);
2006 printf("%-15s: $%8.02f (%s)\n", username, ((float)bal)/100, flags);
2010 int Dispense_AddUser(int Socket, const char *Username)
2013 int responseCode, ret;
2015 // Check for a dry run
2017 printf("Dry Run - No action\n");
2021 sendf(Socket, "USER_ADD %s\n", Username);
2023 buf = ReadLine(Socket);
2024 responseCode = atoi(buf);
2026 switch(responseCode)
2029 printf("User '%s' added\n", Username);
2034 printf("Only wheel can add users\n");
2039 printf("User '%s' already exists\n", Username);
2044 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2054 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
2057 int responseCode, ret;
2059 // Check for a dry run
2061 printf("Dry Run - No action\n");
2065 // TODO: Pre-validate the string
2067 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
2069 buf = ReadLine(Socket);
2070 responseCode = atoi(buf);
2072 switch(responseCode)
2075 printf("User '%s' updated\n", Username);
2080 printf("Only wheel can modify users\n");
2081 ret = RV_PERMISSIONS;
2085 printf("User '%s' does not exist\n", Username);
2086 ret = RV_INVALID_USER;
2090 printf("Flag string is invalid\n");
2095 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2096 ret = RV_UNKNOWN_RESPONSE;
2105 int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName)
2108 int responseCode, ret;
2110 // Check for a dry run
2112 printf("Dry Run - No action\n");
2116 sendf(Socket, "UPDATE_ITEM %s:%i %i %s\n", Type, ID, NewPrice, NewName);
2118 buf = ReadLine(Socket);
2119 responseCode = atoi(buf);
2121 switch(responseCode)
2124 printf("Item %s:%i updated\n", Type, ID);
2129 printf("Only coke members can modify the slots\n");
2130 ret = RV_PERMISSIONS;
2134 printf("Invalid item passed\n");
2139 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2152 char *ReadLine(int Socket)
2154 static char buf[BUFSIZ];
2155 static int bufPos = 0;
2156 static int bufValid = 0;
2158 char *newline = NULL;
2160 char *ret = malloc(10);
2162 #if DEBUG_TRACE_SERVER
2163 printf("ReadLine: ");
2175 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2178 return strdup("499 Client Connection Error\n");
2180 buf[bufPos+len] = '\0';
2183 newline = strchr( buf+bufPos, '\n' );
2188 retLen += strlen(buf+bufPos);
2189 ret = realloc(ret, retLen + 1);
2190 strcat( ret, buf+bufPos );
2193 int newLen = newline - (buf+bufPos) + 1;
2194 bufValid = len - newLen;
2197 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2200 #if DEBUG_TRACE_SERVER
2201 printf("%i '%s'\n", retLen, ret);
2207 int sendf(int Socket, const char *Format, ...)
2212 va_start(args, Format);
2213 len = vsnprintf(NULL, 0, Format, args);
2218 va_start(args, Format);
2219 vsnprintf(buf, len+1, Format, args);
2222 #if DEBUG_TRACE_SERVER
2223 printf("sendf: %s", buf);
2226 return send(Socket, buf, len, 0);
2230 char *trim(char *string)
2234 while( isspace(*string) )
2237 for( i = strlen(string); i--; )
2239 if( isspace(string[i]) )
2248 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2252 ret = regexec(regex, string, nMatches, matches, 0);
2253 if( ret && errorMessage ) {
2254 size_t len = regerror(ret, regex, NULL, 0);
2256 regerror(ret, regex, errorStr, len);
2257 printf("string = '%s'\n", string);
2258 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2265 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2267 int ret = regcomp(regex, pattern, flags);
2269 size_t len = regerror(ret, regex, NULL, 0);
2271 regerror(ret, regex, errorStr, len);
2272 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);