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_Give(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
160 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
163 // Show user information
164 Dispense_ShowUser(sock, argv[i+1]);
171 // - "Here, have some money."
172 else if( strcmp(arg, "give") == 0 )
174 if( i + 3 >= argc ) {
175 fprintf(stderr, "`dispense give` takes three arguments\n");
179 // TODO: `dispense give`
181 // argv[i+1]: Destination
182 // argv[i+2]: Ammount
186 sock = OpenConnection(gsDispenseServer, giDispensePort);
187 if( sock < 0 ) return -1;
190 if( Authenticate(sock) )
193 Dispense_Give(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
198 // - User administration (Wheel Only)
199 else if( strcmp(arg, "user") == 0 )
201 // Check argument count
202 if( i + 1 >= argc ) {
203 fprintf(stderr, "Error: `dispense user` requires arguments\n");
209 sock = OpenConnection(gsDispenseServer, giDispensePort);
210 if( sock < 0 ) return -1;
212 // Attempt authentication
213 if( Authenticate(sock) )
217 if( strcmp(argv[i+1], "add") == 0 )
219 if( i + 2 >= argc ) {
220 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
225 Dispense_AddUser(sock, argv[i+2]);
228 else if( strcmp(argv[i+1], "type") == 0 )
230 if( i + 3 >= argc ) {
231 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
236 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
240 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
247 // Item name / pattern
254 sock = OpenConnection(gsDispenseServer, giDispensePort);
255 if( sock < 0 ) return -1;
261 PopulateItemList(sock);
265 // TODO: Implement `dispense <name>`
266 printf("TODO: Implement `dispense <name>`\n");
269 else if( gbUseNCurses )
275 for( i = 0; i < giNumItems; i ++ ) {
276 printf("%2i %s\t%3i %s\n", i, gaItems[i].Ident, gaItems[i].Price, gaItems[i].Desc);
285 fgets(buffer, BUFSIZ, stdin);
289 if( buf[0] == 'q' ) break;
293 if( i != 0 || buf[0] == '0' )
295 if( i < 0 || i >= giNumItems ) {
296 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
304 // Check for a valid item ID
306 DispenseItem(sock, i);
318 " Show interactive list\n"
320 " Dispense named item\n"
321 " dispense give <user> <ammount> \"<reason>\"\n"
322 " Give some of your money away\n"
323 " dispense acct [<user>]\n"
324 " Show user balances\n"
325 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
326 " Alter a account value (Coke members only)\n"
327 " dispense user add <user>\n"
328 " Create new coke account (Wheel members only)\n"
329 " dispense user type <flags>\n"
330 " Alter a user's flags\n"
331 " <flags> is a comma-separated list of user,coke,wheel,disabled\n"
332 " Flags are removed by preceding the name with '-' or '!'\n"
336 " Set a different user (Coke members only)\n"
340 " Use alternate GUI\n"
341 " -m <min balance>\n"
342 " -M <max balance>\n"
343 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
347 // -------------------
348 // --- NCurses GUI ---
349 // -------------------
351 * \brief Render the NCurses UI
353 int ShowNCursesUI(void)
355 // TODO: ncurses interface (with separation between item classes)
356 // - Hmm... that would require standardising the item ID to be <class>:<index>
361 const int displayMinWidth = 40;
362 const int displayMinItems = 8;
363 char *titleString = "Dispense";
364 int itemCount = displayMinItems;
367 int ret = -2; // -2: Used for marking "no return yet"
376 // - 6: randomly chosen (Need at least 3)
377 itemCount = LINES - 6;
378 if( itemCount > giNumItems )
379 itemCount = giNumItems;
382 height = itemCount + 3;
383 width = displayMinWidth;
386 xBase = COLS/2 - width/2;
387 yBase = LINES/2 - height/2;
392 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
395 for( i = 0; i < itemCount; i ++ )
397 move( yBase + 1 + i, xBase );
399 if( currentItem == itemBase + i ) {
407 // - Oh god, magic numbers!
408 if( i == 0 && itemBase > 0 ) {
410 times = width-1 - 8 - 3;
411 while(times--) addch(' ');
413 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
415 times = width-1 - 8 - 3;
416 while(times--) addch(' ');
420 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
424 // Scrollbar (if needed)
425 if( giNumItems > itemCount ) {
429 else if( i == itemCount - 1 ) {
433 int percentage = itemBase * 100 / (giNumItems-itemCount);
434 if( i-1 == percentage*(itemCount-3)/100 ) {
448 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
461 //if( itemBase < giNumItems - (itemCount) )
463 if( currentItem < giNumItems - 1 )
465 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
471 if( currentItem > 0 )
473 if( itemBase + 1 > currentItem && itemBase > 0 )
489 ret = -1; // -1: Return with no dispense
493 // Check if the return value was changed
494 if( ret != -2 ) break;
506 * \brief Show item \a Index at (\a Col, \a Row)
507 * \note Part of the NCurses UI
509 void ShowItemAt(int Row, int Col, int Width, int Index)
517 if( Index < 0 || Index >= giNumItems ) {
522 name = gaItems[Index].Desc;
523 price = gaItems[Index].Price;
526 printw("%02i %s", Index, name);
528 getyx(stdscr, _y, _x);
529 // Assumes max 4 digit prices
530 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
531 while(times--) addch(' ');
532 printw("%4i", price);
536 * \brief Print a three-part string at the specified position (formatted)
537 * \note NCurses UI Helper
539 * Prints \a Left on the left of the area, \a Right on the righthand side
540 * and \a Mid in the middle of the area. These are padded with \a Pad1
541 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
543 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
544 * and the arguments to these are read in that order.
546 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
547 const char *Mid, char Pad2, const char *Right, ...)
549 int lLen, mLen, rLen;
554 // Get the length of the strings
555 va_start(args, Right);
556 lLen = vsnprintf(NULL, 0, Left, args);
557 mLen = vsnprintf(NULL, 0, Mid, args);
558 rLen = vsnprintf(NULL, 0, Right, args);
562 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
563 return ; // TODO: What to do?
569 va_start(args, Right);
573 vsnprintf(tmp, lLen+1, Left, args);
577 times = Width/2 - mLen/2 - lLen;
578 while(times--) addch(Pad1);
582 vsnprintf(tmp, mLen+1, Mid, args);
586 times = Width/2 - mLen/2 - rLen;
587 while(times--) addch(Pad2);
591 vsnprintf(tmp, rLen+1, Right, args);
596 // ---------------------
597 // --- Coke Protocol ---
598 // ---------------------
599 int OpenConnection(const char *Host, int Port)
601 struct hostent *host;
602 struct sockaddr_in serverAddr;
605 host = gethostbyname(Host);
607 fprintf(stderr, "Unable to look up '%s'\n", Host);
611 memset(&serverAddr, 0, sizeof(serverAddr));
613 serverAddr.sin_family = AF_INET; // IPv4
614 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
615 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
616 serverAddr.sin_port = htons(Port);
618 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
620 fprintf(stderr, "Failed to create socket\n");
626 struct sockaddr_in localAddr;
627 memset(&localAddr, 0, sizeof(localAddr));
628 localAddr.sin_family = AF_INET; // IPv4
629 localAddr.sin_port = 1023; // IPv4
630 // Attempt to bind to low port for autoauth
631 bind(sock, &localAddr, sizeof(localAddr));
635 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
636 fprintf(stderr, "Failed to connect to server\n");
644 * \brief Authenticate with the server
645 * \return Boolean Failure
647 int Authenticate(int Socket)
654 regmatch_t matches[4];
656 if( gbIsAuthenticated ) return 0;
659 pwd = getpwuid( getuid() );
661 // Attempt automatic authentication
662 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
664 // Check if it worked
665 buf = ReadLine(Socket);
667 responseCode = atoi(buf);
668 switch( responseCode )
671 case 200: // Authenticated, return :)
675 case 401: // Untrusted, attempt password authentication
678 sendf(Socket, "USER %s\n", pwd->pw_name);
679 printf("Using username %s\n", pwd->pw_name);
681 buf = ReadLine(Socket);
684 // Expected format: 100 SALT <something> ...
686 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
687 responseCode = atoi(buf);
688 if( responseCode != 100 ) {
689 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
695 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
696 // Store it for later
697 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
698 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
702 // Give three attempts
703 for( i = 0; i < 3; i ++ )
705 int ofs = strlen(pwd->pw_name)+strlen(salt);
708 char *pass = getpass("Password: ");
711 // Create hash string
712 // <username><salt><hash>
713 strcpy(tmp, pwd->pw_name);
715 SHA1( (unsigned char*)pass, strlen(pass), h );
716 memcpy(tmp+ofs, h, 20);
719 SHA1( (unsigned char*)tmp, ofs+20, h );
720 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
721 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
722 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
726 sendf(Socket, "PASS %s\n", tmpBuf);
727 buf = ReadLine(Socket);
729 responseCode = atoi(buf);
731 if( responseCode == 200 ) break;
732 // Bad username/password
733 if( responseCode == 401 ) continue;
735 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
741 return 2; // 2 = Bad Password
744 case 404: // Bad Username
745 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
750 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
756 // Set effective user
757 if( gsEffectiveUser ) {
758 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
760 buf = ReadLine(Socket);
761 responseCode = atoi(buf);
766 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
770 printf("Only coke members can use `dispense -u`\n");
775 printf("Invalid user selected\n");
780 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
789 gbIsAuthenticated = 1;
796 * \brief Fill the item information structure
797 * \return Boolean Failure
799 void PopulateItemList(int Socket)
804 char *itemType, *itemStart;
806 regmatch_t matches[4];
808 // Ask server for stock list
809 send(Socket, "ENUM_ITEMS\n", 11, 0);
810 buf = ReadLine(Socket);
812 //printf("Output: %s\n", buf);
814 responseCode = atoi(buf);
815 if( responseCode != 201 ) {
816 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
825 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
827 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
828 count = atoi( &buf[ matches[3].rm_so ] );
831 if( strcmp(itemType, "Items") != 0 ) {
833 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
838 itemStart = &buf[ matches[3].rm_eo ];
843 gaItems = malloc( giNumItems * sizeof(tItem) );
845 // Fetch item information
846 for( i = 0; i < giNumItems; i ++ )
848 regmatch_t matches[6];
851 buf = ReadLine(Socket);
852 responseCode = atoi(buf);
854 if( responseCode != 202 ) {
855 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
859 RunRegex(&gItemRegex, buf, 6, matches, "Malformed server response");
861 buf[ matches[3].rm_eo ] = '\0';
863 gaItems[i].Ident = strdup( buf + matches[3].rm_so );
864 gaItems[i].Price = atoi( buf + matches[4].rm_so );
865 gaItems[i].Desc = strdup( buf + matches[5].rm_so );
871 buf = ReadLine(Socket);
872 responseCode = atoi(buf);
874 if( responseCode != 200 ) {
875 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
885 * \brief Dispense an item
886 * \return Boolean Failure
888 int DispenseItem(int Socket, int ItemID)
890 int ret, responseCode;
893 if( ItemID < 0 || ItemID > giNumItems ) return -1;
896 sendf(Socket, "DISPENSE %s\n", gaItems[ItemID].Ident);
897 buf = ReadLine(Socket);
899 responseCode = atoi(buf);
900 switch( responseCode )
903 printf("Dispense OK\n");
907 printf("Not authenticated\n");
911 printf("Insufficient balance\n");
915 printf("Bad item name, bug report\n");
919 printf("Item failed to dispense, is the slot empty?\n");
923 printf("Dispense not possible (slot empty/permissions)\n");
927 printf("Unknown response code %i ('%s')\n", responseCode, buf);
937 * \brief Alter a user's balance
939 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
944 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
945 buf = ReadLine(Socket);
947 responseCode = atoi(buf);
952 case 200: return 0; // OK
954 fprintf(stderr, "Insufficient balance\n");
956 case 403: // Not in coke
957 fprintf(stderr, "You are not in coke (sucker)\n");
959 case 404: // Unknown user
960 fprintf(stderr, "Unknown user '%s'\n", Username);
963 fprintf(stderr, "Unknown response code %i\n", responseCode);
971 * \brief Alter a user's balance
973 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
979 printf("Sorry, you can only give, you can't take.\n");
983 // Fast return on zero
985 printf("Are you actually going to give any?\n");
989 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
990 buf = ReadLine(Socket);
992 responseCode = atoi(buf);
997 case 200: return 0; // OK
1000 fprintf(stderr, "Insufficient balance\n");
1003 case 404: // Unknown user
1004 fprintf(stderr, "Unknown user '%s'\n", Username);
1008 fprintf(stderr, "Unknown response code %i\n", responseCode);
1016 * \brief Enumerate users
1018 int Dispense_EnumUsers(int Socket)
1023 regmatch_t matches[4];
1025 if( giMinimumBalance != INT_MIN ) {
1026 if( giMaximumBalance != INT_MAX ) {
1027 sendf(Socket, "ENUM_USERS %i %i\n", giMinimumBalance, giMaximumBalance);
1030 sendf(Socket, "ENUM_USERS %i\n", giMinimumBalance);
1034 if( giMaximumBalance != INT_MAX ) {
1035 sendf(Socket, "ENUM_USERS - %i\n", giMaximumBalance);
1038 sendf(Socket, "ENUM_USERS\n");
1041 buf = ReadLine(Socket);
1042 responseCode = atoi(buf);
1044 switch(responseCode)
1046 case 201: break; // Ok, length follows
1049 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1054 // Get count (not actually used)
1055 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1056 nUsers = atoi( buf + matches[3].rm_so );
1057 printf("%i users returned\n", nUsers);
1062 // Read returned users
1064 buf = ReadLine(Socket);
1065 responseCode = atoi(buf);
1067 if( responseCode != 202 ) break;
1069 _PrintUserLine(buf);
1071 } while(responseCode == 202);
1073 // Check final response
1074 if( responseCode != 200 ) {
1075 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1085 int Dispense_ShowUser(int Socket, const char *Username)
1088 int responseCode, ret;
1090 sendf(Socket, "USER_INFO %s\n", Username);
1091 buf = ReadLine(Socket);
1093 responseCode = atoi(buf);
1095 switch(responseCode)
1098 _PrintUserLine(buf);
1103 printf("Unknown user '%s'\n", Username);
1108 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1118 void _PrintUserLine(const char *Line)
1120 regmatch_t matches[6];
1123 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1128 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1129 char username[usernameLen + 1];
1130 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1131 char flags[flagsLen + 1];
1133 memcpy(username, Line + matches[3].rm_so, usernameLen);
1134 username[usernameLen] = '\0';
1135 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1136 flags[flagsLen] = '\0';
1138 bal = atoi(Line + matches[4].rm_so);
1139 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, bal%100, flags);
1143 int Dispense_AddUser(int Socket, const char *Username)
1146 int responseCode, ret;
1148 sendf(Socket, "USER_ADD %s\n", Username);
1150 buf = ReadLine(Socket);
1151 responseCode = atoi(buf);
1153 switch(responseCode)
1156 printf("User '%s' added\n", Username);
1161 printf("Only wheel can add users\n");
1166 printf("User '%s' already exists\n", Username);
1171 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1181 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1184 int responseCode, ret;
1186 // TODO: Pre-validate the string
1188 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1190 buf = ReadLine(Socket);
1191 responseCode = atoi(buf);
1193 switch(responseCode)
1196 printf("User '%s' updated\n", Username);
1201 printf("Only wheel can modify users\n");
1206 printf("User '%s' does not exist\n", Username);
1211 printf("Flag string is invalid\n");
1216 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1229 char *ReadLine(int Socket)
1231 static char buf[BUFSIZ];
1232 static int bufPos = 0;
1233 static int bufValid = 0;
1235 char *newline = NULL;
1237 char *ret = malloc(10);
1239 #if DEBUG_TRACE_SERVER
1240 printf("ReadLine: ");
1252 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1253 buf[bufPos+len] = '\0';
1256 newline = strchr( buf+bufPos, '\n' );
1261 retLen += strlen(buf+bufPos);
1262 ret = realloc(ret, retLen + 1);
1263 strcat( ret, buf+bufPos );
1266 int newLen = newline - (buf+bufPos) + 1;
1267 bufValid = len - newLen;
1270 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1273 #if DEBUG_TRACE_SERVER
1274 printf("%i '%s'\n", retLen, ret);
1280 int sendf(int Socket, const char *Format, ...)
1285 va_start(args, Format);
1286 len = vsnprintf(NULL, 0, Format, args);
1291 va_start(args, Format);
1292 vsnprintf(buf, len+1, Format, args);
1295 #if DEBUG_TRACE_SERVER
1296 printf("sendf: %s", buf);
1299 return send(Socket, buf, len, 0);
1303 char *trim(char *string)
1307 while( isspace(*string) )
1310 for( i = strlen(string); i--; )
1312 if( isspace(string[i]) )
1321 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1325 ret = regexec(regex, string, nMatches, matches, 0);
1327 size_t len = regerror(ret, regex, NULL, 0);
1329 regerror(ret, regex, errorStr, len);
1330 printf("string = '%s'\n", string);
1331 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1338 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1340 int ret = regcomp(regex, pattern, flags);
1342 size_t len = regerror(ret, regex, NULL, 0);
1344 regerror(ret, regex, errorStr, len);
1345 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);