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 *gsEffectiveUser; //!< '-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 gsEffectiveUser = 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 // Show user information
170 Dispense_ShowUser(sock, argv[i+1]);
175 else if( strcmp(arg, "give") == 0 )
177 // TODO: `dispense give`
178 printf("TODO: Implement `dispense give`\n");
181 else if( strcmp(arg, "user") == 0 )
183 // Check argument count
184 if( i + 1 >= argc ) {
185 fprintf(stderr, "Error: `dispense user` requires arguments\n");
191 sock = OpenConnection(gsDispenseServer, giDispensePort);
192 if( sock < 0 ) return -1;
194 // Attempt authentication
195 if( Authenticate(sock) )
199 if( strcmp(argv[i+1], "add") == 0 )
201 if( i + 2 >= argc ) {
202 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
207 Dispense_AddUser(sock, argv[i+2]);
210 else if( strcmp(argv[i+1], "type") == 0 )
212 if( i + 3 >= argc ) {
213 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
218 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
222 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
229 // Item name / pattern
236 sock = OpenConnection(gsDispenseServer, giDispensePort);
237 if( sock < 0 ) return -1;
243 PopulateItemList(sock);
247 // TODO: Implement `dispense <name>`
248 printf("TODO: Implement `dispense <name>`\n");
251 else if( gbUseNCurses )
257 for( i = 0; i < giNumItems; i ++ ) {
258 printf("%2i %s\t%3i %s\n", i, gaItems[i].Ident, gaItems[i].Price, gaItems[i].Desc);
267 fgets(buffer, BUFSIZ, stdin);
271 if( buf[0] == 'q' ) break;
275 if( i != 0 || buf[0] == '0' )
277 if( i < 0 || i >= giNumItems ) {
278 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
286 // Check for a valid item ID
288 DispenseItem(sock, i);
300 " Show interactive list\n"
302 " Dispense named item\n"
303 " dispense give <user> <ammount> \"<reason>\"\n"
304 " Give some of your money away\n"
305 " dispense acct [<user>]\n"
306 " Show user balances\n"
307 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
308 " Alter a account value (Coke members only)\n"
309 " dispense user add <user>\n"
310 " Create new coke account (Wheel members only)\n"
311 " dispense user type <flags>\n"
312 " Alter a user's flags\n"
313 " <flags> is a comma-separated list of user,coke,wheel,disabled\n"
314 " Flags are removed by preceding the name with '-' or '!'\n"
318 " Set a different user (Coke members only)\n"
322 " Use alternate GUI\n"
323 " -m <min balance>\n"
324 " -M <max balance>\n"
325 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
329 // -------------------
330 // --- NCurses GUI ---
331 // -------------------
333 * \brief Render the NCurses UI
335 int ShowNCursesUI(void)
337 // TODO: ncurses interface (with separation between item classes)
338 // - Hmm... that would require standardising the item ID to be <class>:<index>
343 const int displayMinWidth = 40;
344 const int displayMinItems = 8;
345 char *titleString = "Dispense";
346 int itemCount = displayMinItems;
349 int ret = -2; // -2: Used for marking "no return yet"
358 // - 6: randomly chosen (Need at least 3)
359 itemCount = LINES - 6;
360 if( itemCount > giNumItems )
361 itemCount = giNumItems;
364 height = itemCount + 3;
365 width = displayMinWidth;
368 xBase = COLS/2 - width/2;
369 yBase = LINES/2 - height/2;
374 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
377 for( i = 0; i < itemCount; i ++ )
379 move( yBase + 1 + i, xBase );
381 if( currentItem == itemBase + i ) {
389 // - Oh god, magic numbers!
390 if( i == 0 && itemBase > 0 ) {
392 times = width-1 - 8 - 3;
393 while(times--) addch(' ');
395 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
397 times = width-1 - 8 - 3;
398 while(times--) addch(' ');
402 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
406 // Scrollbar (if needed)
407 if( giNumItems > itemCount ) {
411 else if( i == itemCount - 1 ) {
415 int percentage = itemBase * 100 / (giNumItems-itemCount);
416 if( i-1 == percentage*(itemCount-3)/100 ) {
430 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
443 //if( itemBase < giNumItems - (itemCount) )
445 if( currentItem < giNumItems - 1 )
447 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
453 if( currentItem > 0 )
455 if( itemBase + 1 > currentItem && itemBase > 0 )
471 ret = -1; // -1: Return with no dispense
475 // Check if the return value was changed
476 if( ret != -2 ) break;
488 * \brief Show item \a Index at (\a Col, \a Row)
489 * \note Part of the NCurses UI
491 void ShowItemAt(int Row, int Col, int Width, int Index)
499 if( Index < 0 || Index >= giNumItems ) {
504 name = gaItems[Index].Desc;
505 price = gaItems[Index].Price;
508 printw("%02i %s", Index, name);
510 getyx(stdscr, _y, _x);
511 // Assumes max 4 digit prices
512 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
513 while(times--) addch(' ');
514 printw("%4i", price);
518 * \brief Print a three-part string at the specified position (formatted)
519 * \note NCurses UI Helper
521 * Prints \a Left on the left of the area, \a Right on the righthand side
522 * and \a Mid in the middle of the area. These are padded with \a Pad1
523 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
525 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
526 * and the arguments to these are read in that order.
528 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
529 const char *Mid, char Pad2, const char *Right, ...)
531 int lLen, mLen, rLen;
536 // Get the length of the strings
537 va_start(args, Right);
538 lLen = vsnprintf(NULL, 0, Left, args);
539 mLen = vsnprintf(NULL, 0, Mid, args);
540 rLen = vsnprintf(NULL, 0, Right, args);
544 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
545 return ; // TODO: What to do?
551 va_start(args, Right);
555 vsnprintf(tmp, lLen+1, Left, args);
559 times = Width/2 - mLen/2 - lLen;
560 while(times--) addch(Pad1);
564 vsnprintf(tmp, mLen+1, Mid, args);
568 times = Width/2 - mLen/2 - rLen;
569 while(times--) addch(Pad2);
573 vsnprintf(tmp, rLen+1, Right, args);
578 // ---------------------
579 // --- Coke Protocol ---
580 // ---------------------
581 int OpenConnection(const char *Host, int Port)
583 struct hostent *host;
584 struct sockaddr_in serverAddr;
587 host = gethostbyname(Host);
589 fprintf(stderr, "Unable to look up '%s'\n", Host);
593 memset(&serverAddr, 0, sizeof(serverAddr));
595 serverAddr.sin_family = AF_INET; // IPv4
596 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
597 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
598 serverAddr.sin_port = htons(Port);
600 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
602 fprintf(stderr, "Failed to create socket\n");
608 struct sockaddr_in localAddr;
609 memset(&localAddr, 0, sizeof(localAddr));
610 localAddr.sin_family = AF_INET; // IPv4
611 localAddr.sin_port = 1023; // IPv4
612 // Attempt to bind to low port for autoauth
613 bind(sock, &localAddr, sizeof(localAddr));
617 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
618 fprintf(stderr, "Failed to connect to server\n");
626 * \brief Authenticate with the server
627 * \return Boolean Failure
629 int Authenticate(int Socket)
636 regmatch_t matches[4];
638 if( gbIsAuthenticated ) return 0;
641 pwd = getpwuid( getuid() );
643 // Attempt automatic authentication
644 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
646 // Check if it worked
647 buf = ReadLine(Socket);
649 responseCode = atoi(buf);
650 switch( responseCode )
653 case 200: // Authenticated, return :)
657 case 401: // Untrusted, attempt password authentication
660 sendf(Socket, "USER %s\n", pwd->pw_name);
661 printf("Using username %s\n", pwd->pw_name);
663 buf = ReadLine(Socket);
666 // Expected format: 100 SALT <something> ...
668 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
669 responseCode = atoi(buf);
670 if( responseCode != 100 ) {
671 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
677 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
678 // Store it for later
679 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
680 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
684 // Give three attempts
685 for( i = 0; i < 3; i ++ )
687 int ofs = strlen(pwd->pw_name)+strlen(salt);
690 char *pass = getpass("Password: ");
693 // Create hash string
694 // <username><salt><hash>
695 strcpy(tmp, pwd->pw_name);
697 SHA1( (unsigned char*)pass, strlen(pass), h );
698 memcpy(tmp+ofs, h, 20);
701 SHA1( (unsigned char*)tmp, ofs+20, h );
702 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
703 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
704 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
708 sendf(Socket, "PASS %s\n", tmpBuf);
709 buf = ReadLine(Socket);
711 responseCode = atoi(buf);
713 if( responseCode == 200 ) break;
714 // Bad username/password
715 if( responseCode == 401 ) continue;
717 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
723 return 2; // 2 = Bad Password
726 case 404: // Bad Username
727 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
732 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
738 // Set effective user
739 if( gsEffectiveUser ) {
740 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
742 buf = ReadLine(Socket);
743 responseCode = atoi(buf);
748 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
752 printf("Only coke members can use `dispense -u`\n");
757 printf("Invalid user selected\n");
762 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
771 gbIsAuthenticated = 1;
778 * \brief Fill the item information structure
779 * \return Boolean Failure
781 void PopulateItemList(int Socket)
786 char *itemType, *itemStart;
788 regmatch_t matches[4];
790 // Ask server for stock list
791 send(Socket, "ENUM_ITEMS\n", 11, 0);
792 buf = ReadLine(Socket);
794 //printf("Output: %s\n", buf);
796 responseCode = atoi(buf);
797 if( responseCode != 201 ) {
798 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
807 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
809 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
810 count = atoi( &buf[ matches[3].rm_so ] );
813 if( strcmp(itemType, "Items") != 0 ) {
815 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
820 itemStart = &buf[ matches[3].rm_eo ];
825 gaItems = malloc( giNumItems * sizeof(tItem) );
827 // Fetch item information
828 for( i = 0; i < giNumItems; i ++ )
830 regmatch_t matches[6];
833 buf = ReadLine(Socket);
834 responseCode = atoi(buf);
836 if( responseCode != 202 ) {
837 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
841 RunRegex(&gItemRegex, buf, 6, matches, "Malformed server response");
843 buf[ matches[3].rm_eo ] = '\0';
845 gaItems[i].Ident = strdup( buf + matches[3].rm_so );
846 gaItems[i].Price = atoi( buf + matches[4].rm_so );
847 gaItems[i].Desc = strdup( buf + matches[5].rm_so );
853 buf = ReadLine(Socket);
854 responseCode = atoi(buf);
856 if( responseCode != 200 ) {
857 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
867 * \brief Dispense an item
868 * \return Boolean Failure
870 int DispenseItem(int Socket, int ItemID)
872 int ret, responseCode;
875 if( ItemID < 0 || ItemID > giNumItems ) return -1;
878 sendf(Socket, "DISPENSE %s\n", gaItems[ItemID].Ident);
879 buf = ReadLine(Socket);
881 responseCode = atoi(buf);
882 switch( responseCode )
885 printf("Dispense OK\n");
889 printf("Not authenticated\n");
893 printf("Insufficient balance\n");
897 printf("Bad item name, bug report\n");
901 printf("Item failed to dispense, is the slot empty?\n");
905 printf("Dispense not possible (slot empty/permissions)\n");
909 printf("Unknown response code %i ('%s')\n", responseCode, buf);
919 * \brief Alter a user's balance
921 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
926 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
927 buf = ReadLine(Socket);
929 responseCode = atoi(buf);
934 case 200: return 0; // OK
935 case 403: // Not in coke
936 fprintf(stderr, "You are not in coke (sucker)\n");
938 case 404: // Unknown user
939 fprintf(stderr, "Unknown user '%s'\n", Username);
942 fprintf(stderr, "Unknown response code %i\n", responseCode);
950 * \brief Alter a user's balance
952 int Dispense_SetBalance(int Socket, const char *Username, int Ammount, const char *Reason)
957 sendf(Socket, "SET %s %i %s\n", Username, Ammount, Reason);
958 buf = ReadLine(Socket);
960 responseCode = atoi(buf);
965 case 200: return 0; // OK
966 case 403: // Not in coke
967 fprintf(stderr, "You are not in coke (sucker)\n");
969 case 404: // Unknown user
970 fprintf(stderr, "Unknown user '%s'\n", Username);
973 fprintf(stderr, "Unknown response code %i\n", responseCode);
981 * \brief Enumerate users
983 int Dispense_EnumUsers(int Socket)
988 regmatch_t matches[4];
990 if( giMinimumBalance != INT_MIN ) {
991 if( giMaximumBalance != INT_MAX ) {
992 sendf(Socket, "ENUM_USERS %i %i\n", giMinimumBalance, giMaximumBalance);
995 sendf(Socket, "ENUM_USERS %i\n", giMinimumBalance);
999 if( giMaximumBalance != INT_MAX ) {
1000 sendf(Socket, "ENUM_USERS - %i\n", giMaximumBalance);
1003 sendf(Socket, "ENUM_USERS\n");
1006 buf = ReadLine(Socket);
1007 responseCode = atoi(buf);
1009 switch(responseCode)
1011 case 201: break; // Ok, length follows
1014 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1019 // Get count (not actually used)
1020 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1021 nUsers = atoi( buf + matches[3].rm_so );
1022 printf("%i users returned\n", nUsers);
1027 // Read returned users
1029 buf = ReadLine(Socket);
1030 responseCode = atoi(buf);
1032 if( responseCode != 202 ) break;
1034 _PrintUserLine(buf);
1036 } while(responseCode == 202);
1038 // Check final response
1039 if( responseCode != 200 ) {
1040 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1050 int Dispense_ShowUser(int Socket, const char *Username)
1053 int responseCode, ret;
1055 sendf(Socket, "USER_INFO %s\n", Username);
1056 buf = ReadLine(Socket);
1058 responseCode = atoi(buf);
1060 switch(responseCode)
1063 _PrintUserLine(buf);
1068 printf("Unknown user '%s'\n", Username);
1073 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1083 void _PrintUserLine(const char *Line)
1085 regmatch_t matches[6];
1088 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1093 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1094 char username[usernameLen + 1];
1095 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1096 char flags[flagsLen + 1];
1098 memcpy(username, Line + matches[3].rm_so, usernameLen);
1099 username[usernameLen] = '\0';
1100 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1101 flags[flagsLen] = '\0';
1103 bal = atoi(Line + matches[4].rm_so);
1104 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, bal%100, flags);
1108 int Dispense_AddUser(int Socket, const char *Username)
1111 int responseCode, ret;
1113 sendf(Socket, "USER_ADD %s\n", Username);
1115 buf = ReadLine(Socket);
1116 responseCode = atoi(buf);
1118 switch(responseCode)
1121 printf("User '%s' added\n", Username);
1126 printf("Only wheel can add users\n");
1131 printf("User '%s' already exists\n", Username);
1136 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1146 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1149 int responseCode, ret;
1151 // TODO: Pre-validate the string
1153 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1155 buf = ReadLine(Socket);
1156 responseCode = atoi(buf);
1158 switch(responseCode)
1161 printf("User '%s' updated\n", Username);
1166 printf("Only wheel can modify users\n");
1171 printf("User '%s' does not exist\n", Username);
1176 printf("Flag string is invalid\n");
1181 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1194 char *ReadLine(int Socket)
1196 static char buf[BUFSIZ];
1197 static int bufPos = 0;
1198 static int bufValid = 0;
1200 char *newline = NULL;
1202 char *ret = malloc(10);
1204 #if DEBUG_TRACE_SERVER
1205 printf("ReadLine: ");
1217 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1218 buf[bufPos+len] = '\0';
1221 newline = strchr( buf+bufPos, '\n' );
1226 retLen += strlen(buf+bufPos);
1227 ret = realloc(ret, retLen + 1);
1228 strcat( ret, buf+bufPos );
1231 int newLen = newline - (buf+bufPos) + 1;
1232 bufValid = len - newLen;
1235 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1238 #if DEBUG_TRACE_SERVER
1239 printf("%i '%s'\n", retLen, ret);
1245 int sendf(int Socket, const char *Format, ...)
1250 va_start(args, Format);
1251 len = vsnprintf(NULL, 0, Format, args);
1256 va_start(args, Format);
1257 vsnprintf(buf, len+1, Format, args);
1260 #if DEBUG_TRACE_SERVER
1261 printf("sendf: %s", buf);
1264 return send(Socket, buf, len, 0);
1268 char *trim(char *string)
1272 while( isspace(*string) )
1275 for( i = strlen(string); i--; )
1277 if( isspace(string[i]) )
1286 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1290 ret = regexec(regex, string, nMatches, matches, 0);
1292 size_t len = regerror(ret, regex, NULL, 0);
1294 regerror(ret, regex, errorStr, len);
1295 printf("string = '%s'\n", string);
1296 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1303 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1305 int ret = regcomp(regex, pattern, flags);
1307 size_t len = regerror(ret, regex, NULL, 0);
1309 regerror(ret, regex, errorStr, len);
1310 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);