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 {
40 int main(int argc, char *argv[]);
43 int ShowNCursesUI(void);
44 void ShowItemAt(int Row, int Col, int Width, int Index);
45 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
46 // --- Coke Server Communication ---
47 int OpenConnection(const char *Host, int Port);
48 int Authenticate(int Socket);
49 void PopulateItemList(int Socket);
50 int DispenseItem(int Socket, int ItemID);
51 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
52 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
53 int Dispense_EnumUsers(int Socket);
54 int Dispense_ShowUser(int Socket, const char *Username);
55 void _PrintUserLine(const char *Line);
56 int Dispense_AddUser(int Socket, const char *Username);
57 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
59 char *ReadLine(int Socket);
60 int sendf(int Socket, const char *Format, ...);
61 char *trim(char *string);
62 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
63 void CompileRegex(regex_t *regex, const char *pattern, int flags);
66 char *gsDispenseServer = "localhost";
67 int giDispensePort = 11020;
71 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex;
72 int gbIsAuthenticated = 0;
74 char *gsItemPattern; //!< Item pattern
75 char *gsEffectiveUser; //!< '-u' Dispense as another user
76 int gbUseNCurses = 0; //!< '-G' Use the NCurses GUI?
77 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
78 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
81 int main(int argc, char *argv[])
87 // -- Create regular expressions
88 // > Code Type Count ...
89 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
90 // > Code Type Ident Price Desc
91 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z]+):([0-9]+)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
93 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
94 // > Code 'User' Username Balance Flags
95 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
98 for( i = 1; i < argc; i ++ )
111 case 'm': // Minimum balance
112 giMinimumBalance = atoi(argv[++i]);
114 case 'M': // Maximum balance
115 giMaximumBalance = atoi(argv[++i]);
118 case 'u': // Override User
119 gsEffectiveUser = argv[++i];
130 if( strcmp(arg, "acct") == 0 )
133 sock = OpenConnection(gsDispenseServer, giDispensePort);
134 if( sock < 0 ) return -1;
137 if( i + 1 == argc ) {
138 Dispense_EnumUsers(sock);
142 // argv[i+1]: Username
147 if( i + 3 >= argc ) {
148 fprintf(stderr, "Error: `dispense acct' needs a reason\n");
152 // Authentication required
153 if( Authenticate(sock) )
156 // argv[i+1]: Username
157 // argv[i+2]: Ammount
161 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
164 // Show user information
165 Dispense_ShowUser(sock, argv[i+1]);
172 // - "Here, have some money."
173 else if( strcmp(arg, "give") == 0 )
175 if( i + 3 >= argc ) {
176 fprintf(stderr, "`dispense give` takes three arguments\n");
180 // TODO: `dispense give`
182 // argv[i+1]: Destination
183 // argv[i+2]: Ammount
187 sock = OpenConnection(gsDispenseServer, giDispensePort);
188 if( sock < 0 ) return -1;
191 if( Authenticate(sock) )
194 Dispense_Give(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
199 // - User administration (Wheel Only)
200 else if( strcmp(arg, "user") == 0 )
202 // Check argument count
203 if( i + 1 >= argc ) {
204 fprintf(stderr, "Error: `dispense user` requires arguments\n");
210 sock = OpenConnection(gsDispenseServer, giDispensePort);
211 if( sock < 0 ) return -1;
213 // Attempt authentication
214 if( Authenticate(sock) )
218 if( strcmp(argv[i+1], "add") == 0 )
220 if( i + 2 >= argc ) {
221 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
226 Dispense_AddUser(sock, argv[i+2]);
229 else if( strcmp(argv[i+1], "type") == 0 )
231 if( i + 3 >= argc ) {
232 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
237 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
241 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
248 // Item name / pattern
255 sock = OpenConnection(gsDispenseServer, giDispensePort);
256 if( sock < 0 ) return -1;
262 PopulateItemList(sock);
266 // TODO: Implement `dispense <name>`
267 printf("TODO: Implement `dispense <name>`\n");
270 else if( gbUseNCurses )
276 for( i = 0; i < giNumItems; i ++ ) {
277 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
278 gaItems[i].Price, gaItems[i].Desc);
287 fgets(buffer, BUFSIZ, stdin);
291 if( buf[0] == 'q' ) break;
295 if( i != 0 || buf[0] == '0' )
297 if( i < 0 || i >= giNumItems ) {
298 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
306 // Check for a valid item ID
308 DispenseItem(sock, i);
320 " Show interactive list\n"
322 " Dispense named item\n"
323 " dispense give <user> <ammount> \"<reason>\"\n"
324 " Give some of your money away\n"
325 " dispense acct [<user>]\n"
326 " Show user balances\n"
327 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
328 " Alter a account value (Coke members only)\n"
329 " dispense user add <user>\n"
330 " Create new coke account (Wheel members only)\n"
331 " dispense user type <flags>\n"
332 " Alter a user's flags\n"
333 " <flags> is a comma-separated list of user,coke,wheel,disabled\n"
334 " Flags are removed by preceding the name with '-' or '!'\n"
338 " Set a different user (Coke members only)\n"
342 " Use alternate GUI\n"
343 " -m <min balance>\n"
344 " -M <max balance>\n"
345 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
349 // -------------------
350 // --- NCurses GUI ---
351 // -------------------
353 * \brief Render the NCurses UI
355 int ShowNCursesUI(void)
357 // TODO: ncurses interface (with separation between item classes)
358 // - Hmm... that would require standardising the item ID to be <class>:<index>
363 const int displayMinWidth = 40;
364 const int displayMinItems = 8;
365 char *titleString = "Dispense";
366 int itemCount = displayMinItems;
369 int ret = -2; // -2: Used for marking "no return yet"
378 // - 6: randomly chosen (Need at least 3)
379 itemCount = LINES - 6;
380 if( itemCount > giNumItems )
381 itemCount = giNumItems;
384 height = itemCount + 3;
385 width = displayMinWidth;
388 xBase = COLS/2 - width/2;
389 yBase = LINES/2 - height/2;
394 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
397 for( i = 0; i < itemCount; i ++ )
399 move( yBase + 1 + i, xBase );
401 if( currentItem == itemBase + i ) {
409 // - Oh god, magic numbers!
410 if( i == 0 && itemBase > 0 ) {
412 times = width-1 - 8 - 3;
413 while(times--) addch(' ');
415 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
417 times = width-1 - 8 - 3;
418 while(times--) addch(' ');
422 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
426 // Scrollbar (if needed)
427 if( giNumItems > itemCount ) {
431 else if( i == itemCount - 1 ) {
435 int percentage = itemBase * 100 / (giNumItems-itemCount);
436 if( i-1 == percentage*(itemCount-3)/100 ) {
450 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
463 //if( itemBase < giNumItems - (itemCount) )
465 if( currentItem < giNumItems - 1 )
467 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
473 if( currentItem > 0 )
475 if( itemBase + 1 > currentItem && itemBase > 0 )
491 ret = -1; // -1: Return with no dispense
495 // Check if the return value was changed
496 if( ret != -2 ) break;
508 * \brief Show item \a Index at (\a Col, \a Row)
509 * \note Part of the NCurses UI
511 void ShowItemAt(int Row, int Col, int Width, int Index)
519 if( Index < 0 || Index >= giNumItems ) {
524 name = gaItems[Index].Desc;
525 price = gaItems[Index].Price;
528 printw("%02i %s", Index, name);
530 getyx(stdscr, _y, _x);
531 // Assumes max 4 digit prices
532 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
533 while(times--) addch(' ');
534 printw("%4i", price);
538 * \brief Print a three-part string at the specified position (formatted)
539 * \note NCurses UI Helper
541 * Prints \a Left on the left of the area, \a Right on the righthand side
542 * and \a Mid in the middle of the area. These are padded with \a Pad1
543 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
545 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
546 * and the arguments to these are read in that order.
548 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
549 const char *Mid, char Pad2, const char *Right, ...)
551 int lLen, mLen, rLen;
556 // Get the length of the strings
557 va_start(args, Right);
558 lLen = vsnprintf(NULL, 0, Left, args);
559 mLen = vsnprintf(NULL, 0, Mid, args);
560 rLen = vsnprintf(NULL, 0, Right, args);
564 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
565 return ; // TODO: What to do?
571 va_start(args, Right);
575 vsnprintf(tmp, lLen+1, Left, args);
579 times = Width/2 - mLen/2 - lLen;
580 while(times--) addch(Pad1);
584 vsnprintf(tmp, mLen+1, Mid, args);
588 times = Width/2 - mLen/2 - rLen;
589 while(times--) addch(Pad2);
593 vsnprintf(tmp, rLen+1, Right, args);
598 // ---------------------
599 // --- Coke Protocol ---
600 // ---------------------
601 int OpenConnection(const char *Host, int Port)
603 struct hostent *host;
604 struct sockaddr_in serverAddr;
607 host = gethostbyname(Host);
609 fprintf(stderr, "Unable to look up '%s'\n", Host);
613 memset(&serverAddr, 0, sizeof(serverAddr));
615 serverAddr.sin_family = AF_INET; // IPv4
616 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
617 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
618 serverAddr.sin_port = htons(Port);
620 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
622 fprintf(stderr, "Failed to create socket\n");
628 struct sockaddr_in localAddr;
629 memset(&localAddr, 0, sizeof(localAddr));
630 localAddr.sin_family = AF_INET; // IPv4
631 localAddr.sin_port = 1023; // IPv4
632 // Attempt to bind to low port for autoauth
633 bind(sock, &localAddr, sizeof(localAddr));
637 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
638 fprintf(stderr, "Failed to connect to server\n");
646 * \brief Authenticate with the server
647 * \return Boolean Failure
649 int Authenticate(int Socket)
656 regmatch_t matches[4];
658 if( gbIsAuthenticated ) return 0;
661 pwd = getpwuid( getuid() );
663 // Attempt automatic authentication
664 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
666 // Check if it worked
667 buf = ReadLine(Socket);
669 responseCode = atoi(buf);
670 switch( responseCode )
672 case 200: // Autoauth succeeded, return
676 case 401: // Untrusted, attempt password authentication
679 sendf(Socket, "USER %s\n", pwd->pw_name);
680 printf("Using username %s\n", pwd->pw_name);
682 buf = ReadLine(Socket);
685 // Expected format: 100 SALT <something> ...
687 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
688 responseCode = atoi(buf);
689 if( responseCode != 100 ) {
690 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
696 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
697 // Store it for later
698 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
699 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
703 // Give three attempts
704 for( i = 0; i < 3; i ++ )
706 int ofs = strlen(pwd->pw_name)+strlen(salt);
709 char *pass = getpass("Password: ");
712 // Create hash string
713 // <username><salt><hash>
714 strcpy(tmp, pwd->pw_name);
716 SHA1( (unsigned char*)pass, strlen(pass), h );
717 memcpy(tmp+ofs, h, 20);
720 SHA1( (unsigned char*)tmp, ofs+20, h );
721 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
722 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
723 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
727 sendf(Socket, "PASS %s\n", tmpBuf);
728 buf = ReadLine(Socket);
730 responseCode = atoi(buf);
732 if( responseCode == 200 ) break;
733 // Bad username/password
734 if( responseCode == 401 ) continue;
736 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
742 return 2; // 2 = Bad Password
745 case 404: // Bad Username
746 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
751 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
757 // Set effective user
758 if( gsEffectiveUser ) {
759 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
761 buf = ReadLine(Socket);
762 responseCode = atoi(buf);
767 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
771 printf("Only coke members can use `dispense -u`\n");
776 printf("Invalid user selected\n");
781 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
790 gbIsAuthenticated = 1;
797 * \brief Fill the item information structure
798 * \return Boolean Failure
800 void PopulateItemList(int Socket)
805 char *itemType, *itemStart;
807 regmatch_t matches[4];
809 // Ask server for stock list
810 send(Socket, "ENUM_ITEMS\n", 11, 0);
811 buf = ReadLine(Socket);
813 //printf("Output: %s\n", buf);
815 responseCode = atoi(buf);
816 if( responseCode != 201 ) {
817 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
826 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
828 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
829 count = atoi( &buf[ matches[3].rm_so ] );
832 if( strcmp(itemType, "Items") != 0 ) {
834 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
839 itemStart = &buf[ matches[3].rm_eo ];
844 gaItems = malloc( giNumItems * sizeof(tItem) );
846 // Fetch item information
847 for( i = 0; i < giNumItems; i ++ )
849 regmatch_t matches[7];
852 buf = ReadLine(Socket);
853 responseCode = atoi(buf);
855 if( responseCode != 202 ) {
856 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
860 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
862 buf[ matches[3].rm_eo ] = '\0';
864 gaItems[i].Type = strdup( buf + matches[3].rm_so );
865 gaItems[i].ID = atoi( buf + matches[4].rm_so );
866 gaItems[i].Price = atoi( buf + matches[5].rm_so );
867 gaItems[i].Desc = strdup( buf + matches[6].rm_so );
873 buf = ReadLine(Socket);
874 responseCode = atoi(buf);
876 if( responseCode != 200 ) {
877 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
887 * \brief Dispense an item
888 * \return Boolean Failure
890 int DispenseItem(int Socket, int ItemID)
892 int ret, responseCode;
895 if( ItemID < 0 || ItemID > giNumItems ) return -1;
898 sendf(Socket, "DISPENSE %s:%i\n", gaItems[ItemID].Type, gaItems[ItemID].ID);
899 buf = ReadLine(Socket);
901 responseCode = atoi(buf);
902 switch( responseCode )
905 printf("Dispense OK\n");
909 printf("Not authenticated\n");
913 printf("Insufficient balance\n");
917 printf("Bad item name, bug report\n");
921 printf("Item failed to dispense, is the slot empty?\n");
925 printf("Dispense not possible (slot empty/permissions)\n");
929 printf("Unknown response code %i ('%s')\n", responseCode, buf);
939 * \brief Alter a user's balance
941 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
946 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
947 buf = ReadLine(Socket);
949 responseCode = atoi(buf);
954 case 200: return 0; // OK
956 fprintf(stderr, "Insufficient balance\n");
958 case 403: // Not in coke
959 fprintf(stderr, "You are not in coke (sucker)\n");
961 case 404: // Unknown user
962 fprintf(stderr, "Unknown user '%s'\n", Username);
965 fprintf(stderr, "Unknown response code %i\n", responseCode);
973 * \brief Alter a user's balance
975 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
981 printf("Sorry, you can only give, you can't take.\n");
985 // Fast return on zero
987 printf("Are you actually going to give any?\n");
991 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
992 buf = ReadLine(Socket);
994 responseCode = atoi(buf);
999 case 200: return 0; // OK
1002 fprintf(stderr, "Insufficient balance\n");
1005 case 404: // Unknown user
1006 fprintf(stderr, "Unknown user '%s'\n", Username);
1010 fprintf(stderr, "Unknown response code %i\n", responseCode);
1018 * \brief Enumerate users
1020 int Dispense_EnumUsers(int Socket)
1025 regmatch_t matches[4];
1027 if( giMinimumBalance != INT_MIN ) {
1028 if( giMaximumBalance != INT_MAX ) {
1029 sendf(Socket, "ENUM_USERS %i %i\n", giMinimumBalance, giMaximumBalance);
1032 sendf(Socket, "ENUM_USERS %i\n", giMinimumBalance);
1036 if( giMaximumBalance != INT_MAX ) {
1037 sendf(Socket, "ENUM_USERS - %i\n", giMaximumBalance);
1040 sendf(Socket, "ENUM_USERS\n");
1043 buf = ReadLine(Socket);
1044 responseCode = atoi(buf);
1046 switch(responseCode)
1048 case 201: break; // Ok, length follows
1051 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1056 // Get count (not actually used)
1057 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1058 nUsers = atoi( buf + matches[3].rm_so );
1059 printf("%i users returned\n", nUsers);
1064 // Read returned users
1066 buf = ReadLine(Socket);
1067 responseCode = atoi(buf);
1069 if( responseCode != 202 ) break;
1071 _PrintUserLine(buf);
1073 } while(responseCode == 202);
1075 // Check final response
1076 if( responseCode != 200 ) {
1077 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1087 int Dispense_ShowUser(int Socket, const char *Username)
1090 int responseCode, ret;
1092 sendf(Socket, "USER_INFO %s\n", Username);
1093 buf = ReadLine(Socket);
1095 responseCode = atoi(buf);
1097 switch(responseCode)
1100 _PrintUserLine(buf);
1105 printf("Unknown user '%s'\n", Username);
1110 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1120 void _PrintUserLine(const char *Line)
1122 regmatch_t matches[6];
1125 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1130 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1131 char username[usernameLen + 1];
1132 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1133 char flags[flagsLen + 1];
1135 memcpy(username, Line + matches[3].rm_so, usernameLen);
1136 username[usernameLen] = '\0';
1137 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1138 flags[flagsLen] = '\0';
1140 bal = atoi(Line + matches[4].rm_so);
1141 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, bal%100, flags);
1145 int Dispense_AddUser(int Socket, const char *Username)
1148 int responseCode, ret;
1150 sendf(Socket, "USER_ADD %s\n", Username);
1152 buf = ReadLine(Socket);
1153 responseCode = atoi(buf);
1155 switch(responseCode)
1158 printf("User '%s' added\n", Username);
1163 printf("Only wheel can add users\n");
1168 printf("User '%s' already exists\n", Username);
1173 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1183 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1186 int responseCode, ret;
1188 // TODO: Pre-validate the string
1190 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1192 buf = ReadLine(Socket);
1193 responseCode = atoi(buf);
1195 switch(responseCode)
1198 printf("User '%s' updated\n", Username);
1203 printf("Only wheel can modify users\n");
1208 printf("User '%s' does not exist\n", Username);
1213 printf("Flag string is invalid\n");
1218 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1231 char *ReadLine(int Socket)
1233 static char buf[BUFSIZ];
1234 static int bufPos = 0;
1235 static int bufValid = 0;
1237 char *newline = NULL;
1239 char *ret = malloc(10);
1241 #if DEBUG_TRACE_SERVER
1242 printf("ReadLine: ");
1254 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1255 buf[bufPos+len] = '\0';
1258 newline = strchr( buf+bufPos, '\n' );
1263 retLen += strlen(buf+bufPos);
1264 ret = realloc(ret, retLen + 1);
1265 strcat( ret, buf+bufPos );
1268 int newLen = newline - (buf+bufPos) + 1;
1269 bufValid = len - newLen;
1272 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1275 #if DEBUG_TRACE_SERVER
1276 printf("%i '%s'\n", retLen, ret);
1282 int sendf(int Socket, const char *Format, ...)
1287 va_start(args, Format);
1288 len = vsnprintf(NULL, 0, Format, args);
1293 va_start(args, Format);
1294 vsnprintf(buf, len+1, Format, args);
1297 #if DEBUG_TRACE_SERVER
1298 printf("sendf: %s", buf);
1301 return send(Socket, buf, len, 0);
1305 char *trim(char *string)
1309 while( isspace(*string) )
1312 for( i = strlen(string); i--; )
1314 if( isspace(string[i]) )
1323 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1327 ret = regexec(regex, string, nMatches, matches, 0);
1329 size_t len = regerror(ret, regex, NULL, 0);
1331 regerror(ret, regex, errorStr, len);
1332 printf("string = '%s'\n", string);
1333 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1340 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1342 int ret = regcomp(regex, pattern, flags);
1344 size_t len = regerror(ret, regex, NULL, 0);
1346 regerror(ret, regex, errorStr, len);
1347 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);