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);
55 int Dispense_AddUser(int Socket, const char *Username);
56 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
58 char *ReadLine(int Socket);
59 int sendf(int Socket, const char *Format, ...);
60 char *trim(char *string);
61 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
62 void CompileRegex(regex_t *regex, const char *pattern, int flags);
65 char *gsDispenseServer = "localhost";
66 int giDispensePort = 11020;
70 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex;
71 int gbIsAuthenticated = 0;
73 char *gsItemPattern; //!< Item pattern
74 char *gsOverrideUser; //!< '-u' Dispense as another user
75 int gbUseNCurses = 0; //!< '-G' Use the NCurses GUI?
76 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
77 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
80 int main(int argc, char *argv[])
86 // -- Create regular expressions
87 // > Code Type Count ...
88 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
89 // > Code Type Ident Price Desc
90 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z0-9:]+?)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
92 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
93 // > Code 'User' Username Balance Flags
94 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
97 for( i = 1; i < argc; i ++ )
110 case 'm': // Minimum balance
111 giMinimumBalance = atoi(argv[++i]);
113 case 'M': // Maximum balance
114 giMaximumBalance = atoi(argv[++i]);
117 case 'u': // Override User
118 gsOverrideUser = argv[++i];
129 if( strcmp(arg, "acct") == 0 )
132 sock = OpenConnection(gsDispenseServer, giDispensePort);
133 if( sock < 0 ) return -1;
136 if( i + 1 == argc ) {
137 Dispense_EnumUsers(sock);
141 // argv[i+1]: Username
146 if( i + 3 >= argc ) {
147 fprintf(stderr, "Error: `dispense acct' needs a reason\n");
151 // Authentication required
152 if( Authenticate(sock) )
155 // argv[i+1]: Username
156 // argv[i+2]: Ammount
159 if( argv[i+2][0] == '=' ) {
161 Dispense_SetBalance(sock, argv[i+1], atoi(argv[i+2] + 1), argv[i+3]);
165 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
169 Dispense_ShowUser(sock, argv[i+1]);
174 else if( strcmp(arg, "user") == 0 )
176 // Check argument count
177 if( i + 1 >= argc ) {
178 fprintf(stderr, "Error: `dispense user` requires arguments\n");
184 sock = OpenConnection(gsDispenseServer, giDispensePort);
185 if( sock < 0 ) return -1;
187 // Attempt authentication
188 if( Authenticate(sock) )
192 if( strcmp(argv[i+1], "add") == 0 )
194 if( i + 2 >= argc ) {
195 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
200 Dispense_AddUser(sock, argv[i+2]);
203 else if( strcmp(argv[i+1], "type") == 0 )
205 if( i + 3 >= argc ) {
206 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
211 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
215 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
222 // Item name / pattern
229 sock = OpenConnection(gsDispenseServer, giDispensePort);
230 if( sock < 0 ) return -1;
236 PopulateItemList(sock);
242 else if( gbUseNCurses )
248 for( i = 0; i < giNumItems; i ++ ) {
249 printf("%2i %s\t%3i %s\n", i, gaItems[i].Ident, gaItems[i].Price, gaItems[i].Desc);
258 fgets(buffer, BUFSIZ, stdin);
262 if( buf[0] == 'q' ) break;
266 if( i != 0 || buf[0] == '0' )
268 if( i < 0 || i >= giNumItems ) {
269 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
277 // Check for a valid item ID
279 DispenseItem(sock, i);
291 " Show interactive list\n"
293 " Dispense named item\n"
294 " dispense give <user> <ammount> \"<reason>\"\n"
295 " Give some of your money away\n"
296 " dispense acct [<user>]\n"
297 " Show user balances\n"
298 " dispense acct <user> [+-=]<ammount> \"<reason>\"\n"
299 " Alter a account value (Coke members only)\n"
300 " dispense user add <user>\n"
301 " Create new coke account (Wheel members only)\n"
302 " dispense user type <flags>\n"
303 " Alter a user's flags\n"
304 " <flags> is a comma-separated list of user,coke,wheel,disabled\n"
305 " Flags are removed by preceding the name with '-' or '!'\n"
309 " Set a different user (Coke members only)\n"
313 " Use alternate GUI\n"
314 " -m <min balance>\n"
315 " -M <max balance>\n"
316 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
320 // -------------------
321 // --- NCurses GUI ---
322 // -------------------
324 * \brief Render the NCurses UI
326 int ShowNCursesUI(void)
328 // TODO: ncurses interface (with separation between item classes)
329 // - Hmm... that would require standardising the item ID to be <class>:<index>
334 const int displayMinWidth = 40;
335 const int displayMinItems = 8;
336 char *titleString = "Dispense";
337 int itemCount = displayMinItems;
340 int ret = -2; // -2: Used for marking "no return yet"
349 // - 6: randomly chosen (Need at least 3)
350 itemCount = LINES - 6;
351 if( itemCount > giNumItems )
352 itemCount = giNumItems;
355 height = itemCount + 3;
356 width = displayMinWidth;
359 xBase = COLS/2 - width/2;
360 yBase = LINES/2 - height/2;
365 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
368 for( i = 0; i < itemCount; i ++ )
370 move( yBase + 1 + i, xBase );
372 if( currentItem == itemBase + i ) {
380 // - Oh god, magic numbers!
381 if( i == 0 && itemBase > 0 ) {
383 times = width-1 - 8 - 3;
384 while(times--) addch(' ');
386 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
388 times = width-1 - 8 - 3;
389 while(times--) addch(' ');
393 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
397 // Scrollbar (if needed)
398 if( giNumItems > itemCount ) {
402 else if( i == itemCount - 1 ) {
406 int percentage = itemBase * 100 / (giNumItems-itemCount);
407 if( i-1 == percentage*(itemCount-3)/100 ) {
421 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
434 //if( itemBase < giNumItems - (itemCount) )
436 if( currentItem < giNumItems - 1 )
438 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
444 if( currentItem > 0 )
446 if( itemBase + 1 > currentItem && itemBase > 0 )
462 ret = -1; // -1: Return with no dispense
466 // Check if the return value was changed
467 if( ret != -2 ) break;
479 * \brief Show item \a Index at (\a Col, \a Row)
480 * \note Part of the NCurses UI
482 void ShowItemAt(int Row, int Col, int Width, int Index)
490 if( Index < 0 || Index >= giNumItems ) {
495 name = gaItems[Index].Desc;
496 price = gaItems[Index].Price;
499 printw("%02i %s", Index, name);
501 getyx(stdscr, _y, _x);
502 // Assumes max 4 digit prices
503 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
504 while(times--) addch(' ');
505 printw("%4i", price);
509 * \brief Print a three-part string at the specified position (formatted)
510 * \note NCurses UI Helper
512 * Prints \a Left on the left of the area, \a Right on the righthand side
513 * and \a Mid in the middle of the area. These are padded with \a Pad1
514 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
516 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
517 * and the arguments to these are read in that order.
519 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
520 const char *Mid, char Pad2, const char *Right, ...)
522 int lLen, mLen, rLen;
527 // Get the length of the strings
528 va_start(args, Right);
529 lLen = vsnprintf(NULL, 0, Left, args);
530 mLen = vsnprintf(NULL, 0, Mid, args);
531 rLen = vsnprintf(NULL, 0, Right, args);
535 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
536 return ; // TODO: What to do?
542 va_start(args, Right);
546 vsnprintf(tmp, lLen+1, Left, args);
550 times = Width/2 - mLen/2 - lLen;
551 while(times--) addch(Pad1);
555 vsnprintf(tmp, mLen+1, Mid, args);
559 times = Width/2 - mLen/2 - rLen;
560 while(times--) addch(Pad2);
564 vsnprintf(tmp, rLen+1, Right, args);
569 // ---------------------
570 // --- Coke Protocol ---
571 // ---------------------
572 int OpenConnection(const char *Host, int Port)
574 struct hostent *host;
575 struct sockaddr_in serverAddr;
578 host = gethostbyname(Host);
580 fprintf(stderr, "Unable to look up '%s'\n", Host);
584 memset(&serverAddr, 0, sizeof(serverAddr));
586 serverAddr.sin_family = AF_INET; // IPv4
587 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
588 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
589 serverAddr.sin_port = htons(Port);
591 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
593 fprintf(stderr, "Failed to create socket\n");
599 struct sockaddr_in localAddr;
600 memset(&localAddr, 0, sizeof(localAddr));
601 localAddr.sin_family = AF_INET; // IPv4
602 localAddr.sin_port = 1023; // IPv4
603 // Attempt to bind to low port for autoauth
604 bind(sock, &localAddr, sizeof(localAddr));
608 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
609 fprintf(stderr, "Failed to connect to server\n");
617 * \brief Authenticate with the server
618 * \return Boolean Failure
620 int Authenticate(int Socket)
627 regmatch_t matches[4];
629 if( gbIsAuthenticated ) return 0;
632 pwd = getpwuid( getuid() );
634 // Attempt automatic authentication
635 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
637 // Check if it worked
638 buf = ReadLine(Socket);
640 responseCode = atoi(buf);
641 switch( responseCode )
644 case 200: // Authenticated, return :)
645 gbIsAuthenticated = 1;
649 case 401: // Untrusted, attempt password authentication
652 sendf(Socket, "USER %s\n", pwd->pw_name);
653 printf("Using username %s\n", pwd->pw_name);
655 buf = ReadLine(Socket);
658 // Expected format: 100 SALT <something> ...
660 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
661 responseCode = atoi(buf);
662 if( responseCode != 100 ) {
663 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
669 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
670 // Store it for later
671 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
672 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
676 // Give three attempts
677 for( i = 0; i < 3; i ++ )
679 int ofs = strlen(pwd->pw_name)+strlen(salt);
682 char *pass = getpass("Password: ");
685 // Create hash string
686 // <username><salt><hash>
687 strcpy(tmp, pwd->pw_name);
689 SHA1( (unsigned char*)pass, strlen(pass), h );
690 memcpy(tmp+ofs, h, 20);
693 SHA1( (unsigned char*)tmp, ofs+20, h );
694 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
695 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
696 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
700 sendf(Socket, "PASS %s\n", tmpBuf);
701 buf = ReadLine(Socket);
703 responseCode = atoi(buf);
705 if( responseCode == 200 ) break;
706 // Bad username/password
707 if( responseCode == 401 ) continue;
709 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
715 gbIsAuthenticated = 1;
719 return 2; // 2 = Bad Password
721 case 404: // Bad Username
722 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
727 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
736 * \brief Fill the item information structure
737 * \return Boolean Failure
739 void PopulateItemList(int Socket)
744 char *itemType, *itemStart;
746 regmatch_t matches[4];
748 // Ask server for stock list
749 send(Socket, "ENUM_ITEMS\n", 11, 0);
750 buf = ReadLine(Socket);
752 //printf("Output: %s\n", buf);
754 responseCode = atoi(buf);
755 if( responseCode != 201 ) {
756 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
765 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
767 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
768 count = atoi( &buf[ matches[3].rm_so ] );
771 if( strcmp(itemType, "Items") != 0 ) {
773 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
778 itemStart = &buf[ matches[3].rm_eo ];
783 gaItems = malloc( giNumItems * sizeof(tItem) );
785 // Fetch item information
786 for( i = 0; i < giNumItems; i ++ )
788 regmatch_t matches[6];
791 buf = ReadLine(Socket);
792 responseCode = atoi(buf);
794 if( responseCode != 202 ) {
795 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
799 RunRegex(&gItemRegex, buf, 6, matches, "Malformed server response");
801 buf[ matches[3].rm_eo ] = '\0';
803 gaItems[i].Ident = strdup( buf + matches[3].rm_so );
804 gaItems[i].Price = atoi( buf + matches[4].rm_so );
805 gaItems[i].Desc = strdup( buf + matches[5].rm_so );
811 buf = ReadLine(Socket);
812 responseCode = atoi(buf);
814 if( responseCode != 200 ) {
815 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
825 * \brief Dispense an item
826 * \return Boolean Failure
828 int DispenseItem(int Socket, int ItemID)
830 int ret, responseCode;
833 if( ItemID < 0 || ItemID > giNumItems ) return -1;
836 sendf(Socket, "DISPENSE %s\n", gaItems[ItemID].Ident);
837 buf = ReadLine(Socket);
839 responseCode = atoi(buf);
840 switch( responseCode )
843 printf("Dispense OK\n");
847 printf("Not authenticated\n");
851 printf("Insufficient balance\n");
855 printf("Bad item name, bug report\n");
859 printf("Item failed to dispense, is the slot empty?\n");
863 printf("Dispense not possible (slot empty/permissions)\n");
867 printf("Unknown response code %i ('%s')\n", responseCode, buf);
877 * \brief Alter a user's balance
879 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
884 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
885 buf = ReadLine(Socket);
887 responseCode = atoi(buf);
892 case 200: return 0; // OK
893 case 403: // Not in coke
894 fprintf(stderr, "You are not in coke (sucker)\n");
896 case 404: // Unknown user
897 fprintf(stderr, "Unknown user '%s'\n", Username);
900 fprintf(stderr, "Unknown response code %i\n", responseCode);
908 * \brief Alter a user's balance
910 int Dispense_SetBalance(int Socket, const char *Username, int Ammount, const char *Reason)
915 sendf(Socket, "SET %s %i %s\n", Username, Ammount, Reason);
916 buf = ReadLine(Socket);
918 responseCode = atoi(buf);
923 case 200: return 0; // OK
924 case 403: // Not in coke
925 fprintf(stderr, "You are not in coke (sucker)\n");
927 case 404: // Unknown user
928 fprintf(stderr, "Unknown user '%s'\n", Username);
931 fprintf(stderr, "Unknown response code %i\n", responseCode);
939 * \brief Enumerate users
941 int Dispense_EnumUsers(int Socket)
946 regmatch_t matches[4];
948 if( giMinimumBalance != INT_MIN ) {
949 if( giMaximumBalance != INT_MAX ) {
950 sendf(Socket, "ENUM_USERS %i %i\n", giMinimumBalance, giMaximumBalance);
953 sendf(Socket, "ENUM_USERS %i\n", giMinimumBalance);
957 if( giMaximumBalance != INT_MAX ) {
958 sendf(Socket, "ENUM_USERS - %i\n", giMaximumBalance);
961 sendf(Socket, "ENUM_USERS\n");
964 buf = ReadLine(Socket);
965 responseCode = atoi(buf);
969 case 201: break; // Ok, length follows
972 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
977 // Get count (not actually used)
978 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
979 nUsers = atoi( buf + matches[3].rm_so );
980 printf("%i users returned\n", nUsers);
985 // Read returned users
987 buf = ReadLine(Socket);
988 responseCode = atoi(buf);
990 if( responseCode != 202 ) break;
994 } while(responseCode == 202);
996 // Check final response
997 if( responseCode != 200 ) {
998 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1008 int Dispense_ShowUser(int Socket, const char *Username)
1011 int responseCode, ret;
1013 sendf(Socket, "USER_INFO %s\n", Username);
1014 buf = ReadLine(Socket);
1016 responseCode = atoi(buf);
1018 switch(responseCode)
1021 _PrintUserLine(buf);
1026 printf("Unknown user '%s'\n", Username);
1031 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1041 void _PrintUserLine(const char *Line)
1043 regmatch_t matches[6];
1046 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1051 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1052 char username[usernameLen + 1];
1053 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1054 char flags[flagsLen + 1];
1056 memcpy(username, Line + matches[3].rm_so, usernameLen);
1057 username[usernameLen] = '\0';
1058 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1059 flags[flagsLen] = '\0';
1061 bal = atoi(Line + matches[4].rm_so);
1062 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, bal%100, flags);
1066 int Dispense_AddUser(int Socket, const char *Username)
1069 int responseCode, ret;
1071 sendf(Socket, "USER_ADD %s\n", Username);
1073 buf = ReadLine(Socket);
1074 responseCode = atoi(buf);
1076 switch(responseCode)
1079 printf("User '%s' added\n", Username);
1084 printf("Only wheel can add users\n");
1089 printf("User '%s' already exists\n", Username);
1094 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1104 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1107 int responseCode, ret;
1109 // TODO: Pre-validate the string
1111 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1113 buf = ReadLine(Socket);
1114 responseCode = atoi(buf);
1116 switch(responseCode)
1119 printf("User '%s' updated\n", Username);
1124 printf("Only wheel can modify users\n");
1129 printf("User '%s' does not exist\n", Username);
1134 printf("Flag string is invalid\n");
1139 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1152 char *ReadLine(int Socket)
1154 static char buf[BUFSIZ];
1155 static int bufPos = 0;
1156 static int bufValid = 0;
1158 char *newline = NULL;
1160 char *ret = malloc(10);
1162 #if DEBUG_TRACE_SERVER
1163 printf("ReadLine: ");
1175 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1176 buf[bufPos+len] = '\0';
1179 newline = strchr( buf+bufPos, '\n' );
1184 retLen += strlen(buf+bufPos);
1185 ret = realloc(ret, retLen + 1);
1186 strcat( ret, buf+bufPos );
1189 int newLen = newline - (buf+bufPos) + 1;
1190 bufValid = len - newLen;
1193 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1196 #if DEBUG_TRACE_SERVER
1197 printf("%i '%s'\n", retLen, ret);
1203 int sendf(int Socket, const char *Format, ...)
1208 va_start(args, Format);
1209 len = vsnprintf(NULL, 0, Format, args);
1214 va_start(args, Format);
1215 vsnprintf(buf, len+1, Format, args);
1218 #if DEBUG_TRACE_SERVER
1219 printf("sendf: %s", buf);
1222 return send(Socket, buf, len, 0);
1226 char *trim(char *string)
1230 while( isspace(*string) )
1233 for( i = strlen(string); i--; )
1235 if( isspace(string[i]) )
1244 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1248 ret = regexec(regex, string, nMatches, matches, 0);
1250 size_t len = regerror(ret, regex, NULL, 0);
1252 regerror(ret, regex, errorStr, len);
1253 printf("string = '%s'\n", string);
1254 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1261 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1263 int ret = regcomp(regex, pattern, flags);
1265 size_t len = regerror(ret, regex, NULL, 0);
1267 regerror(ret, regex, errorStr, len);
1268 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);