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, const char *Reason);
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
118 char *gsTextArgs[MAX_TXT_ARGS];
124 printf( "Usage:\n" );
125 if( giTextArgc == 0 )
129 " Show interactive list\n"
130 " dispense <name>|<index>|<itemid>\n"
131 " Dispense named item (<name> matches if it is a unique prefix)\n"
133 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "give") == 0 )
135 " dispense give <user> <ammount> \"<reason>\"\n"
136 " Give money to another user\n"
139 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "donate") == 0 )
141 " dispense donate <ammount> \"<reason>\"\n"
142 " Donate to the club\n"
144 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "iteminfo") == 0 )
146 " dispense iteminfo <itemid>\n"
147 " Get the name and price for an item\n"
149 if( giTextArgc == 0 )
150 printf(" == Coke members == \n");
151 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "acct") == 0 )
153 " dispense acct [<user>]\n"
154 " Show user balances\n"
155 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
156 " Alter a account value\n"
157 " dispense acct <user> =<ammount> \"<reason>\"\n"
158 " Set an account balance\n"
160 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "refund") == 0 )
162 " dispense refund <user> <itemid> [<price>]\n"
163 " Refund an item to a user (with optional price override)\n"
165 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "slot") == 0 )
167 " dispense slot <itemid> <price> <name>\n"
168 " Rename/Re-price a slot\n"
170 if( giTextArgc == 0 )
171 printf(" == Dispense administrators ==\n");
172 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "user") == 0 )
174 " dispense user add <user>\n"
175 " Create new account\n"
176 " dispense user type <user> <flags> <reason>\n"
177 " Alter a user's flags\n"
178 " <flags> is a comma-separated list of user, coke, admin, internal or disabled\n"
179 " Flags are removed by preceding the name with '-' or '!'\n"
181 if( giTextArgc == 0 )
185 " Dispense multiple times\n"
187 " Set a different user (Coke members only)\n"
191 " Use simple textual interface (instead of ncurses)\n"
193 " Dry run - Do not actually do dispenses\n"
194 " -m <min balance>\n"
195 " -M <max balance>\n"
196 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
199 " 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"
205 int main(int argc, char *argv[])
213 // -- Create regular expressions
214 // > Code Type Count ...
215 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
216 // > Code Type Ident Status Price Desc
217 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);
218 // > Code 'SALT' salt
219 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
220 // > Code 'User' Username Balance Flags
221 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
223 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
226 for( i = 1; i < argc; i ++ )
240 if( i + 1 >= argc ) {
241 fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
245 giDispenseCount = atoi(argv[++i]);
246 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
247 fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
253 case 'm': // Minimum balance
254 if( i + 1 >= argc ) {
255 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
259 giMinimumBalance = atoi(argv[++i]);
261 case 'M': // Maximum balance
262 if( i + 1 >= argc ) {
263 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
267 giMaximumBalance = atoi(argv[++i]);
270 case 'u': // Override User
271 if( i + 1 >= argc ) {
272 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
276 gsEffectiveUser = argv[++i];
279 case 'H': // Override remote host
280 if( i + 1 >= argc ) {
281 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
285 gsDispenseServer = argv[++i];
287 case 'P': // Override remote port
288 if( i + 1 >= argc ) {
289 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
293 giDispensePort = atoi(argv[++i]);
296 // Set slot name/price
298 if( giTextArgc != 0 ) {
299 fprintf(stderr, "%s: -s must appear before other arguments\n", argv[0]);
303 gsTextArgs[0] = "slot"; // HACK!!
307 case 'G': // Don't use GUI
308 giUIMode = UI_MODE_BASIC;
310 case 'D': // Drinks only
311 giUIMode = UI_MODE_DRINKSONLY;
313 case 'n': // Dry Run / read-only
317 if( strcmp(argv[i], "--help") == 0 ) {
322 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
328 // The first argument is not allowed to begin with 'i'
329 // (catches most bad flags)
330 if( giTextArgc == 0 ) {
331 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
335 if( giTextArgc == MAX_TXT_ARGS )
337 fprintf(stderr, "ERROR: Too many arguments\n");
340 gsTextArgs[giTextArgc++] = argv[i];
347 if( giTextArgc == MAX_TXT_ARGS )
349 fprintf(stderr, "ERROR: Too many arguments\n");
353 gsTextArgs[giTextArgc++] = argv[i];
360 if( strcmp(gsTextArgs[0], "acct") == 0 )
363 sock = OpenConnection(gsDispenseServer, giDispensePort);
364 if( sock < 0 ) return RV_SOCKET_ERROR;
366 if( giTextArgc == 1 ) {
367 ret = Dispense_EnumUsers(sock);
372 // gsTextArgs[1]: Username
375 if( giTextArgc != 2 )
377 if( giTextArgc != 4 ) {
378 fprintf(stderr, "`dispense acct` requires a reason\n");
383 // Authentication required
384 ret = Authenticate(sock);
387 // gsTextArgs[1]: Username
388 // gsTextArgs[2]: Ammount
389 // gsTextArgs[3]: Reason
391 if( gsTextArgs[2][0] == '=' ) {
393 if( gsTextArgs[2][1] != '0' && atoi(gsTextArgs[2]+1) == 0 ) {
394 fprintf(stderr, "Error: Invalid balance to be set\n");
398 ret = Dispense_SetBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]+1), gsTextArgs[3]);
402 ret = Dispense_AlterBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
411 // Show user information
412 ret = Dispense_ShowUser(sock, gsTextArgs[1]);
419 // - "Here, have some money."
420 else if( strcmp(gsTextArgs[0], "give") == 0 )
422 if( giTextArgc != 4 ) {
423 fprintf(stderr, "`dispense give` takes three arguments\n");
428 // gsTextArgs[1]: Destination
429 // gsTextArgs[2]: Ammount
430 // gsTextArgs[3]: Reason
433 sock = OpenConnection(gsDispenseServer, giDispensePort);
434 if( sock < 0 ) return RV_SOCKET_ERROR;
437 ret = Authenticate(sock);
440 ret = Dispense_Give(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
448 // - User administration (Admin Only)
449 if( strcmp(gsTextArgs[0], "user") == 0 )
451 // Check argument count
452 if( giTextArgc == 1 ) {
453 fprintf(stderr, "Error: `dispense user` requires arguments\n");
459 sock = OpenConnection(gsDispenseServer, giDispensePort);
460 if( sock < 0 ) return RV_SOCKET_ERROR;
462 // Attempt authentication
463 ret = Authenticate(sock);
467 if( strcmp(gsTextArgs[1], "add") == 0 )
469 if( giTextArgc != 3 ) {
470 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
475 ret = Dispense_AddUser(sock, gsTextArgs[2]);
478 else if( strcmp(gsTextArgs[1], "type") == 0 || strcmp(gsTextArgs[1], "flags") == 0 )
480 if( giTextArgc < 4 || giTextArgc > 5 ) {
481 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
486 if( giTextArgc == 4 )
487 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], "");
489 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], gsTextArgs[4]);
493 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
501 else if( strcmp(gsTextArgs[0], "donate") == 0 )
503 // Check argument count
504 if( giTextArgc != 3 ) {
505 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
511 sock = OpenConnection(gsDispenseServer, giDispensePort);
512 if( sock < 0 ) return RV_SOCKET_ERROR;
514 // Attempt authentication
515 ret = Authenticate(sock);
519 ret = Dispense_Donate(sock, atoi(gsTextArgs[1]), gsTextArgs[2]);
526 else if( strcmp(gsTextArgs[0], "refund") == 0 )
529 // Check argument count
530 if( giTextArgc != 3 && giTextArgc != 4 ) {
531 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
537 sock = OpenConnection(gsDispenseServer, giDispensePort);
538 if(sock < 0) return RV_SOCKET_ERROR;
540 // Attempt authentication
541 ret = Authenticate(sock);
544 if( giTextArgc == 4 ) {
545 price = atoi(gsTextArgs[3]);
547 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
552 // Username, Item, cost
553 ret = Dispense_Refund(sock, gsTextArgs[1], gsTextArgs[2], price);
559 // Query an item price
560 else if( strcmp(gsTextArgs[0], "iteminfo") == 0 )
562 regmatch_t matches[3];
565 // Check argument count
566 if( giTextArgc != 2 ) {
567 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
572 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
573 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
576 type = gsTextArgs[1] + matches[1].rm_so;
577 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
578 id = atoi( gsTextArgs[1] + matches[2].rm_so );
580 sock = OpenConnection(gsDispenseServer, giDispensePort);
581 if( sock < 0 ) return RV_SOCKET_ERROR;
583 ret = Dispense_ItemInfo(sock, type, id);
588 else if( strcmp(gsTextArgs[0], "slot") == 0 )
590 regmatch_t matches[3];
591 char *item_type, *newname;
595 if( giTextArgc != 4 ) {
596 fprintf(stderr, "Error: `dispense slot` takes three arguments\n");
602 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
603 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
606 item_type = gsTextArgs[1] + matches[1].rm_so;
607 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
608 item_id = atoi( gsTextArgs[1] + matches[2].rm_so );
611 price = atoi( gsTextArgs[2] );
612 if( price <= 0 && gsTextArgs[2][0] != '0' ) {
613 fprintf(stderr, "Error: Invalid price passed (must be >= 0)\n");
618 newname = gsTextArgs[3];
622 for( pos = newname; *pos; pos ++ )
624 if( !isalnum(*pos) && *pos != ' ' ) {
625 fprintf(stderr, "Error: You should only have letters, numbers and spaces in an item name\n");
631 // Connect & Authenticate
632 sock = OpenConnection(gsDispenseServer, giDispensePort);
633 if( sock < 0 ) return RV_SOCKET_ERROR;
634 ret = Authenticate(sock);
637 ret = Dispense_SetItem(sock, item_type, item_id, price, newname);
642 // Item name / pattern
645 gsItemPattern = gsTextArgs[0];
649 sock = OpenConnection(gsDispenseServer, giDispensePort);
650 if( sock < 0 ) return RV_SOCKET_ERROR;
652 // Get the user's balance
653 ret = GetUserBalance(sock);
657 PopulateItemList(sock);
659 // Disconnect from server
662 if( gsItemPattern && gsItemPattern[0] )
664 regmatch_t matches[3];
666 if( strcmp(gsItemPattern, "door") == 0 )
668 // Connect, Authenticate, dispense and close
669 sock = OpenConnection(gsDispenseServer, giDispensePort);
670 if( sock < 0 ) return RV_SOCKET_ERROR;
671 ret = Authenticate(sock);
673 ret = DispenseItem(sock, "door", 0);
677 // Item id (<type>:<num>)
678 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
683 // Get and finish ident
684 ident = gsItemPattern + matches[1].rm_so;
685 gsItemPattern[matches[1].rm_eo] = '\0';
687 id = atoi( gsItemPattern + matches[2].rm_so );
689 // Connect, Authenticate, dispense and close
690 sock = OpenConnection(gsDispenseServer, giDispensePort);
691 if( sock < 0 ) return RV_SOCKET_ERROR;
693 Dispense_ItemInfo(sock, ident, id);
695 ret = Authenticate(sock);
697 ret = DispenseItem(sock, ident, id);
701 // Item number (6 = coke)
702 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
704 i = atoi(gsItemPattern);
711 for( i = 0; i < giNumItems; i ++ )
713 // Prefix match (with case-insensitive match)
714 for( j = 0; gsItemPattern[j]; j ++ )
716 if( gaItems[i].Desc[j] == gsItemPattern[j] )
718 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
722 // Check if the prefix matched
723 if( gsItemPattern[j] != '\0' )
727 if( gaItems[i].Desc[j] == '\0' ) {
732 // Only one match allowed
737 // TODO: Allow ambiguous matches?
738 // or just print a wanrning
739 printf("Warning - Ambiguous pattern, stopping\n");
744 // Was a match found?
747 fprintf(stderr, "No item matches the passed string\n");
754 else if( giUIMode != UI_MODE_BASIC )
760 // Very basic dispense interface
761 for( i = 0; i < giNumItems; i ++ ) {
763 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
766 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
767 gaItems[i].Price, gaItems[i].Desc);
776 fgets(buffer, BUFSIZ, stdin);
780 if( buf[0] == 'q' ) break;
784 if( i != 0 || buf[0] == '0' )
786 if( i < 0 || i >= giNumItems ) {
787 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
796 // Check for a valid item ID
800 // Connect, Authenticate, dispense and close
801 sock = OpenConnection(gsDispenseServer, giDispensePort);
802 if( sock < 0 ) return RV_SOCKET_ERROR;
804 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
807 ret = Authenticate(sock);
810 for( j = 0; j < giDispenseCount; j ++ ) {
811 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
815 printf("%i items dispensed\n", j);
820 Dispense_ShowUser(sock, gsUserName);
825 // -------------------
826 // --- NCurses GUI ---
827 // -------------------
829 * \brief Render the NCurses UI
831 int ShowNCursesUI(void)
836 const int displayMinWidth = 40;
837 char *titleString = "Dispense";
842 int ret = -2; // -2: Used for marking "no return yet"
844 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
851 if( gsEffectiveUser )
852 username = gsEffectiveUser;
854 pwd = getpwuid( getuid() );
855 username = pwd->pw_name;
858 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
865 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
866 // Get item count per screen
867 // - 6: randomly chosen (Need at least 3)
868 itemCount = LINES - 6;
869 if( itemCount > maxItemIndex )
870 itemCount = maxItemIndex;
873 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
878 height = itemCount + 3;
879 width = displayMinWidth;
882 xBase = COLS/2 - width/2;
883 yBase = LINES/2 - height/2;
888 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
891 for( i = 0; i < itemCount; i ++ )
895 move( yBase + 1 + i, xBase );
900 // Check for the '...' row
901 // - Oh god, magic numbers!
902 if( (i == 0 && itemBase > 0)
903 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
905 printw(" ..."); pos += 8;
906 times = (width - pos) - 1;
907 while(times--) addch(' ');
912 yBase + 1 + i, xBase + pos, // Position
913 (width - pos) - 3, // Width
914 itemBase + i, // Index
915 !!(currentItem == itemBase + i) // Hilighted
920 // Scrollbar (if needed)
921 if( maxItemIndex > itemCount ) {
925 else if( i == itemCount - 1 ) {
929 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
930 if( i-1 == percentage*(itemCount-3)/100 ) {
944 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
947 // - Username, balance, flags
948 PrintAlign(yBase+height-1, xBase+1, width-2,
949 username, ' ', balance_str, ' ', gsUserFlags);
965 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
968 if( currentItem >= maxItemIndex ) {
971 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
978 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
981 if( currentItem < 0 ) {
982 currentItem = maxItemIndex - 1;
984 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
994 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
995 itemBase = currentItem - 2;
996 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
997 itemBase = currentItem - itemCount + 2;
1003 ret = ShowItemAt(0, 0, 0, currentItem, 0);
1005 case 0x1b: // Escape
1007 ret = -1; // -1: Return with no dispense
1011 // Check if the return value was changed
1012 if( ret != -2 ) break;
1024 * \brief Show item \a Index at (\a Col, \a Row)
1025 * \return Dispense index of item
1026 * \note Part of the NCurses UI
1028 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
1038 // - This assumes that
1039 case UI_MODE_STANDARD:
1041 // Index = -1, request limit
1042 if( Index < 0 || Index >= giNumItems+2 )
1043 return giNumItems+2;
1048 name = "Coke Machine";
1049 Index = -1; // -1 indicates a label
1056 name = gaItems[Index].Desc;
1057 price = gaItems[Index].Price;
1058 status = gaItems[Index].Status;
1066 name = "Electronic Payment System";
1067 Index = -1; // -1 indicates a label
1072 name = gaItems[Index].Desc;
1073 price = gaItems[Index].Price;
1074 status = gaItems[Index].Status;
1080 // Width = 0, don't print
1083 // 4 preceding, 5 price
1084 int nameWidth = Width - 4 - 5;
1089 // Show hilight and status
1108 printw("%-*.*s", nameWidth, nameWidth, name);
1110 // getyx(stdscr, _y, _x);
1111 // Assumes max 4 digit prices
1112 // times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
1113 // while(times--) addch(' ');
1115 printw(" %4i", price);
1119 printw("-- %s", name);
1120 getyx(stdscr, _y, _x);
1121 times = Width - 4 - (_x - Col);
1122 while(times--) addch(' ');
1127 // If the item isn't availiable for sale, return -1 (so it's skipped)
1128 if( status || price > giUserBalance )
1135 * \brief Print a three-part string at the specified position (formatted)
1136 * \note NCurses UI Helper
1138 * Prints \a Left on the left of the area, \a Right on the righthand side
1139 * and \a Mid in the middle of the area. These are padded with \a Pad1
1140 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1142 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1143 * and the arguments to these are read in that order.
1145 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1146 const char *Mid, char Pad2, const char *Right, ...)
1148 int lLen, mLen, rLen;
1153 // Get the length of the strings
1154 va_start(args, Right);
1155 lLen = vsnprintf(NULL, 0, Left, args);
1156 mLen = vsnprintf(NULL, 0, Mid, args);
1157 rLen = vsnprintf(NULL, 0, Right, args);
1161 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1162 return ; // TODO: What to do?
1168 va_start(args, Right);
1172 vsnprintf(tmp, lLen+1, Left, args);
1176 times = (Width - mLen)/2 - lLen;
1177 while(times--) addch(Pad1);
1181 vsnprintf(tmp, mLen+1, Mid, args);
1185 times = (Width - mLen)/2 - rLen;
1186 if( (Width - mLen) % 2 ) times ++;
1187 while(times--) addch(Pad2);
1191 vsnprintf(tmp, rLen+1, Right, args);
1196 // ---------------------
1197 // --- Coke Protocol ---
1198 // ---------------------
1199 int OpenConnection(const char *Host, int Port)
1201 struct hostent *host;
1202 struct sockaddr_in serverAddr;
1205 host = gethostbyname(Host);
1207 fprintf(stderr, "Unable to look up '%s'\n", Host);
1211 memset(&serverAddr, 0, sizeof(serverAddr));
1213 serverAddr.sin_family = AF_INET; // IPv4
1214 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1215 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1216 serverAddr.sin_port = htons(Port);
1218 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1220 fprintf(stderr, "Failed to create socket\n");
1224 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1226 if( geteuid() == 0 || getuid() == 0 )
1229 struct sockaddr_in localAddr;
1230 memset(&localAddr, 0, sizeof(localAddr));
1231 localAddr.sin_family = AF_INET; // IPv4
1233 // Loop through all the top ports until one is avaliable
1234 for( i = 512; i < 1024; i ++)
1236 localAddr.sin_port = htons(i); // IPv4
1237 // Attempt to bind to low port for autoauth
1238 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1242 printf("Warning: AUTOAUTH unavaliable\n");
1244 // printf("Bound to 0.0.0.0:%i\n", i);
1247 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1248 fprintf(stderr, "Failed to connect to server\n");
1252 // We're not authenticated if the connection has just opened
1253 gbIsAuthenticated = 0;
1259 * \brief Authenticate with the server
1260 * \return Boolean Failure
1262 int Authenticate(int Socket)
1267 #if ATTEMPT_PASSWORD_AUTH
1270 regmatch_t matches[4];
1273 if( gbIsAuthenticated ) return 0;
1276 pwd = getpwuid( getuid() );
1278 // Attempt automatic authentication
1279 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1281 // Check if it worked
1282 buf = ReadLine(Socket);
1284 responseCode = atoi(buf);
1285 switch( responseCode )
1287 case 200: // Autoauth succeeded, return
1291 case 401: // Untrusted, attempt password authentication
1294 #if ATTEMPT_PASSWORD_AUTH
1295 sendf(Socket, "USER %s\n", pwd->pw_name);
1296 printf("Using username %s\n", pwd->pw_name);
1298 buf = ReadLine(Socket);
1301 // Expected format: 100 SALT <something> ...
1302 // OR : 100 User Set
1303 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1304 responseCode = atoi(buf);
1305 if( responseCode != 100 ) {
1306 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1308 return RV_UNKNOWN_ERROR; // ERROR
1312 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1313 // Store it for later
1314 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1315 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1319 // Give three attempts
1320 for( i = 0; i < 3; i ++ )
1322 int ofs = strlen(pwd->pw_name)+strlen(salt);
1325 char *pass = getpass("Password: ");
1328 // Create hash string
1329 // <username><salt><hash>
1330 strcpy(tmp, pwd->pw_name);
1332 SHA1( (unsigned char*)pass, strlen(pass), h );
1333 memcpy(tmp+ofs, h, 20);
1336 SHA1( (unsigned char*)tmp, ofs+20, h );
1337 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1338 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1339 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1343 sendf(Socket, "PASS %s\n", tmpBuf);
1344 buf = ReadLine(Socket);
1346 responseCode = atoi(buf);
1348 if( responseCode == 200 ) break;
1349 // Bad username/password
1350 if( responseCode == 401 ) continue;
1352 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1354 return RV_UNKNOWN_ERROR;
1358 return RV_INVALID_USER; // 2 = Bad Password
1361 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1362 return RV_INVALID_USER;
1366 case 404: // Bad Username
1367 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1369 return RV_INVALID_USER;
1372 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1373 printf("%s\n", buf);
1375 return RV_UNKNOWN_ERROR;
1378 // Set effective user
1379 if( gsEffectiveUser ) {
1380 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1382 buf = ReadLine(Socket);
1383 responseCode = atoi(buf);
1385 switch(responseCode)
1388 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1392 printf("Only coke members can use `dispense -u`\n");
1394 return RV_PERMISSIONS;
1397 printf("Invalid user selected\n");
1399 return RV_INVALID_USER;
1402 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1403 printf("%s\n", buf);
1405 return RV_UNKNOWN_ERROR;
1411 gbIsAuthenticated = 1;
1416 int GetUserBalance(int Socket)
1418 regmatch_t matches[6];
1425 if( gsEffectiveUser ) {
1426 gsUserName = gsEffectiveUser;
1429 pwd = getpwuid( getuid() );
1430 gsUserName = strdup(pwd->pw_name);
1434 sendf(Socket, "USER_INFO %s\n", gsUserName);
1435 buf = ReadLine(Socket);
1436 responseCode = atoi(buf);
1437 switch(responseCode)
1439 case 202: break; // Ok
1442 printf("Invalid user? (USER_INFO failed)\n");
1444 return RV_INVALID_USER;
1447 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1448 printf("%s\n", buf);
1450 return RV_UNKNOWN_ERROR;
1453 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1455 giUserBalance = atoi( buf + matches[4].rm_so );
1456 gsUserFlags = strdup( buf + matches[5].rm_so );
1464 * \brief Read an item info response from the server
1465 * \param Dest Destination for the read item (strings will be on the heap)
1467 int ReadItemInfo(int Socket, tItem *Dest)
1472 regmatch_t matches[8];
1476 buf = ReadLine(Socket);
1477 responseCode = atoi(buf);
1479 switch(responseCode)
1484 printf("Bad item name\n");
1489 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1491 return RV_UNKNOWN_ERROR;
1494 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1496 buf[ matches[3].rm_eo ] = '\0';
1497 buf[ matches[5].rm_eo ] = '\0';
1498 buf[ matches[7].rm_eo ] = '\0';
1500 statusStr = &buf[ matches[5].rm_so ];
1502 Dest->ID = atoi( buf + matches[4].rm_so );
1504 if( strcmp(statusStr, "avail") == 0 )
1506 else if( strcmp(statusStr, "sold") == 0 )
1508 else if( strcmp(statusStr, "error") == 0 )
1511 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1513 return RV_UNKNOWN_ERROR;
1515 Dest->Price = atoi( buf + matches[6].rm_so );
1517 // Hack a little to reduce heap fragmentation
1519 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1520 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1521 strcpy(tmpType, buf + matches[3].rm_so);
1522 strcpy(tmpDesc, buf + matches[7].rm_so);
1524 Dest->Type = strdup( tmpType );
1525 Dest->Desc = strdup( tmpDesc );
1532 * \brief Fill the item information structure
1533 * \return Boolean Failure
1535 void PopulateItemList(int Socket)
1542 regmatch_t matches[4];
1544 // Ask server for stock list
1545 send(Socket, "ENUM_ITEMS\n", 11, 0);
1546 buf = ReadLine(Socket);
1548 //printf("Output: %s\n", buf);
1550 responseCode = atoi(buf);
1551 if( responseCode != 201 ) {
1552 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1553 exit(RV_UNKNOWN_ERROR);
1556 // - Get item list -
1559 // 201 Items <count>
1561 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1563 arrayType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1564 count = atoi( &buf[ matches[3].rm_so ] );
1567 if( strcmp(arrayType, "Items") != 0 ) {
1569 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1571 exit(RV_UNKNOWN_ERROR);
1576 gaItems = malloc( giNumItems * sizeof(tItem) );
1578 // Fetch item information
1579 for( i = 0; i < giNumItems; i ++ )
1581 ReadItemInfo( Socket, &gaItems[i] );
1585 buf = ReadLine(Socket);
1586 responseCode = atoi(buf);
1588 if( responseCode != 200 ) {
1589 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1600 * \brief Get information on an item
1601 * \return Boolean Failure
1603 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1609 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1611 ret = ReadItemInfo(Socket, &item);
1614 printf("%8s:%-2i %2i.%02i %s\n",
1616 item.Price/100, item.Price%100,
1626 * \brief Dispense an item
1627 * \return Boolean Failure
1629 int DispenseItem(int Socket, const char *Type, int ID)
1631 int ret, responseCode;
1634 // Check for a dry run
1636 printf("Dry Run - No action\n");
1641 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1642 buf = ReadLine(Socket);
1644 responseCode = atoi(buf);
1645 switch( responseCode )
1648 printf("Dispense OK\n");
1652 printf("Not authenticated\n");
1653 ret = RV_PERMISSIONS;
1656 printf("Insufficient balance\n");
1660 printf("Bad item name\n");
1664 printf("Item failed to dispense, is the slot empty?\n");
1665 ret = RV_SERVER_ERROR;
1668 printf("Dispense not possible (slot empty/permissions)\n");
1669 ret = RV_SERVER_ERROR;
1672 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1673 ret = RV_UNKNOWN_ERROR;
1682 * \brief Alter a user's balance
1684 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1687 int responseCode, rv = -1;
1689 // Check for a dry run
1691 printf("Dry Run - No action\n");
1696 if( Ammount == 0 ) {
1697 printf("An ammount would be nice\n");
1698 return RV_ARGUMENTS;
1701 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1702 buf = ReadLine(Socket);
1704 responseCode = atoi(buf);
1706 switch(responseCode)
1712 fprintf(stderr, "Insufficient balance\n");
1715 case 403: // Not in coke
1716 fprintf(stderr, "You are not in coke (sucker)\n");
1717 rv = RV_PERMISSIONS;
1719 case 404: // Unknown user
1720 fprintf(stderr, "Unknown user '%s'\n", Username);
1721 rv = RV_INVALID_USER;
1724 fprintf(stderr, "Unknown response code %i\n'%s'\n", responseCode, buf);
1725 rv = RV_UNKNOWN_RESPONSE;
1734 * \brief Set a user's balance
1735 * \note Only avaliable to dispense admins
1737 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1742 // Check for a dry run
1744 printf("Dry Run - No action\n");
1748 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1749 buf = ReadLine(Socket);
1751 responseCode = atoi(buf);
1754 switch(responseCode)
1756 case 200: return 0; // OK
1757 case 403: // Not in coke
1758 fprintf(stderr, "You are not an admin\n");
1759 return RV_PERMISSIONS;
1760 case 404: // Unknown user
1761 fprintf(stderr, "Unknown user '%s'\n", Username);
1762 return RV_INVALID_USER;
1764 fprintf(stderr, "Unknown response code %i\n", responseCode);
1765 return RV_UNKNOWN_RESPONSE;
1772 * \brief Give money to another user
1774 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1780 printf("Sorry, you can only give, you can't take.\n");
1781 return RV_ARGUMENTS;
1784 // Fast return on zero
1785 if( Ammount == 0 ) {
1786 printf("Are you actually going to give any?\n");
1787 return RV_ARGUMENTS;
1790 // Check for a dry run
1792 printf("Dry Run - No action\n");
1796 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1798 buf = ReadLine(Socket);
1799 responseCode = atoi(buf);
1801 switch(responseCode)
1804 printf("Give succeeded\n");
1805 return RV_SUCCESS; // OK
1808 fprintf(stderr, "Insufficient balance\n");
1811 case 404: // Unknown user
1812 fprintf(stderr, "Unknown user '%s'\n", Username);
1813 return RV_INVALID_USER;
1816 fprintf(stderr, "Unknown response code %i\n", responseCode);
1817 return RV_UNKNOWN_RESPONSE;
1823 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1826 int responseCode, ret = -1;
1829 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1831 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1832 return RV_ARGUMENTS;
1835 // Check username (quick)
1836 if( strchr(Username, ' ') || strchr(Username, '\n') )
1838 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1839 return RV_ARGUMENTS;
1843 sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1845 buf = ReadLine(Socket);
1846 responseCode = atoi(buf);
1847 switch(responseCode)
1850 Dispense_ShowUser(Socket, Username); // Show destination account
1854 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1855 ret = RV_PERMISSIONS;
1858 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1859 ret = RV_INVALID_USER;
1862 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1866 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1875 * \brief Donate money to the club
1877 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1883 printf("Sorry, you can only give, you can't take.\n");
1887 // Fast return on zero
1888 if( Ammount == 0 ) {
1889 printf("Are you actually going to give any?\n");
1893 // Check for a dry run
1895 printf("Dry Run - No action\n");
1899 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1900 buf = ReadLine(Socket);
1902 responseCode = atoi(buf);
1905 switch(responseCode)
1907 case 200: return 0; // OK
1910 fprintf(stderr, "Insufficient balance\n");
1914 fprintf(stderr, "Unknown response code %i\n", responseCode);
1922 * \brief Enumerate users
1924 int Dispense_EnumUsers(int Socket)
1929 regmatch_t matches[4];
1931 if( giMinimumBalance != INT_MIN ) {
1932 if( giMaximumBalance != INT_MAX ) {
1933 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1936 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1940 if( giMaximumBalance != INT_MAX ) {
1941 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1944 sendf(Socket, "ENUM_USERS\n");
1947 buf = ReadLine(Socket);
1948 responseCode = atoi(buf);
1950 switch(responseCode)
1952 case 201: break; // Ok, length follows
1955 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1960 // Get count (not actually used)
1961 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1962 nUsers = atoi( buf + matches[3].rm_so );
1963 printf("%i users returned\n", nUsers);
1968 // Read returned users
1970 buf = ReadLine(Socket);
1971 responseCode = atoi(buf);
1973 if( responseCode != 202 ) break;
1975 _PrintUserLine(buf);
1977 } while(responseCode == 202);
1979 // Check final response
1980 if( responseCode != 200 ) {
1981 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1991 int Dispense_ShowUser(int Socket, const char *Username)
1994 int responseCode, ret;
1996 sendf(Socket, "USER_INFO %s\n", Username);
1997 buf = ReadLine(Socket);
1999 responseCode = atoi(buf);
2001 switch(responseCode)
2004 _PrintUserLine(buf);
2009 printf("Unknown user '%s'\n", Username);
2014 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2024 void _PrintUserLine(const char *Line)
2026 regmatch_t matches[6];
2029 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
2034 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
2035 char username[usernameLen + 1];
2036 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
2037 char flags[flagsLen + 1];
2039 memcpy(username, Line + matches[3].rm_so, usernameLen);
2040 username[usernameLen] = '\0';
2041 memcpy(flags, Line + matches[5].rm_so, flagsLen);
2042 flags[flagsLen] = '\0';
2044 bal = atoi(Line + matches[4].rm_so);
2045 printf("%-15s: $%8.02f (%s)\n", username, ((float)bal)/100, flags);
2049 int Dispense_AddUser(int Socket, const char *Username)
2052 int responseCode, ret;
2054 // Check for a dry run
2056 printf("Dry Run - No action\n");
2060 sendf(Socket, "USER_ADD %s\n", Username);
2062 buf = ReadLine(Socket);
2063 responseCode = atoi(buf);
2065 switch(responseCode)
2068 printf("User '%s' added\n", Username);
2073 printf("Only wheel can add users\n");
2078 printf("User '%s' already exists\n", Username);
2083 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2093 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString, const char *Reason)
2096 int responseCode, ret;
2098 // Check for a dry run
2100 printf("Dry Run - No action\n");
2104 // TODO: Pre-validate the string
2106 sendf(Socket, "USER_FLAGS %s %s %s\n", Username, TypeString, Reason);
2108 buf = ReadLine(Socket);
2109 responseCode = atoi(buf);
2111 switch(responseCode)
2114 printf("User '%s' updated\n", Username);
2119 printf("Only dispense admins can modify users\n");
2120 ret = RV_PERMISSIONS;
2124 printf("User '%s' does not exist\n", Username);
2125 ret = RV_INVALID_USER;
2129 printf("Flag string is invalid\n");
2134 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2135 ret = RV_UNKNOWN_RESPONSE;
2144 int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName)
2147 int responseCode, ret;
2149 // Check for a dry run
2151 printf("Dry Run - No action\n");
2155 sendf(Socket, "UPDATE_ITEM %s:%i %i %s\n", Type, ID, NewPrice, NewName);
2157 buf = ReadLine(Socket);
2158 responseCode = atoi(buf);
2160 switch(responseCode)
2163 printf("Item %s:%i updated\n", Type, ID);
2168 printf("Only coke members can modify the slots\n");
2169 ret = RV_PERMISSIONS;
2173 printf("Invalid item passed\n");
2178 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2191 char *ReadLine(int Socket)
2193 static char buf[BUFSIZ];
2194 static int bufPos = 0;
2195 static int bufValid = 0;
2197 char *newline = NULL;
2199 char *ret = malloc(10);
2201 #if DEBUG_TRACE_SERVER
2202 printf("ReadLine: ");
2214 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2217 return strdup("599 Client Connection Error\n");
2220 buf[bufPos+len] = '\0';
2222 newline = strchr( buf+bufPos, '\n' );
2227 retLen += strlen(buf+bufPos);
2228 ret = realloc(ret, retLen + 1);
2229 strcat( ret, buf+bufPos );
2232 int newLen = newline - (buf+bufPos) + 1;
2233 bufValid = len - newLen;
2236 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2239 #if DEBUG_TRACE_SERVER
2240 printf("%i '%s'\n", retLen, ret);
2246 int sendf(int Socket, const char *Format, ...)
2251 va_start(args, Format);
2252 len = vsnprintf(NULL, 0, Format, args);
2257 va_start(args, Format);
2258 vsnprintf(buf, len+1, Format, args);
2261 #if DEBUG_TRACE_SERVER
2262 printf("sendf: %s", buf);
2265 return send(Socket, buf, len, 0);
2269 char *trim(char *string)
2273 while( isspace(*string) )
2276 for( i = strlen(string); i--; )
2278 if( isspace(string[i]) )
2287 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2291 ret = regexec(regex, string, nMatches, matches, 0);
2292 if( ret && errorMessage ) {
2293 size_t len = regerror(ret, regex, NULL, 0);
2295 regerror(ret, regex, errorStr, len);
2296 printf("string = '%s'\n", string);
2297 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2304 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2306 int ret = regcomp(regex, pattern, flags);
2308 size_t len = regerror(ret, regex, NULL, 0);
2310 regerror(ret, regex, errorStr, len);
2311 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);