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]);
405 // TODO: Preserve ret if non-zero
407 // Show user information
408 ret = Dispense_ShowUser(sock, gsTextArgs[1]);
415 // - "Here, have some money."
416 else if( strcmp(gsTextArgs[0], "give") == 0 )
418 if( giTextArgc != 4 ) {
419 fprintf(stderr, "`dispense give` takes three arguments\n");
424 // gsTextArgs[1]: Destination
425 // gsTextArgs[2]: Ammount
426 // gsTextArgs[3]: Reason
429 sock = OpenConnection(gsDispenseServer, giDispensePort);
430 if( sock < 0 ) return RV_SOCKET_ERROR;
433 ret = Authenticate(sock);
436 ret = Dispense_Give(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
444 // - User administration (Admin Only)
445 if( strcmp(gsTextArgs[0], "user") == 0 )
447 // Check argument count
448 if( giTextArgc == 1 ) {
449 fprintf(stderr, "Error: `dispense user` requires arguments\n");
455 sock = OpenConnection(gsDispenseServer, giDispensePort);
456 if( sock < 0 ) return RV_SOCKET_ERROR;
458 // Attempt authentication
459 ret = Authenticate(sock);
463 if( strcmp(gsTextArgs[1], "add") == 0 )
465 if( giTextArgc != 3 ) {
466 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
471 ret = Dispense_AddUser(sock, gsTextArgs[2]);
474 else if( strcmp(gsTextArgs[1], "type") == 0 || strcmp(gsTextArgs[1], "flags") == 0 )
476 if( giTextArgc < 4 || giTextArgc > 5 ) {
477 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
482 if( giTextArgc == 4 )
483 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], "");
485 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], gsTextArgs[4]);
489 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
497 else if( strcmp(gsTextArgs[0], "donate") == 0 )
499 // Check argument count
500 if( giTextArgc != 3 ) {
501 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
507 sock = OpenConnection(gsDispenseServer, giDispensePort);
508 if( sock < 0 ) return RV_SOCKET_ERROR;
510 // Attempt authentication
511 ret = Authenticate(sock);
515 ret = Dispense_Donate(sock, atoi(gsTextArgs[1]), gsTextArgs[2]);
522 else if( strcmp(gsTextArgs[0], "refund") == 0 )
525 // Check argument count
526 if( giTextArgc != 3 && giTextArgc != 4 ) {
527 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
533 sock = OpenConnection(gsDispenseServer, giDispensePort);
534 if(sock < 0) return RV_SOCKET_ERROR;
536 // Attempt authentication
537 ret = Authenticate(sock);
540 if( giTextArgc == 4 ) {
541 price = atoi(gsTextArgs[3]);
543 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
548 // Username, Item, cost
549 ret = Dispense_Refund(sock, gsTextArgs[1], gsTextArgs[2], price);
553 return RV_UNKNOWN_ERROR;
555 // Query an item price
556 else if( strcmp(gsTextArgs[0], "iteminfo") == 0 )
558 regmatch_t matches[3];
561 // Check argument count
562 if( giTextArgc != 2 ) {
563 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
568 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
569 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
572 type = gsTextArgs[1] + matches[1].rm_so;
573 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
574 id = atoi( gsTextArgs[1] + matches[2].rm_so );
576 sock = OpenConnection(gsDispenseServer, giDispensePort);
577 if( sock < 0 ) return RV_SOCKET_ERROR;
579 ret = Dispense_ItemInfo(sock, type, id);
584 else if( strcmp(gsTextArgs[0], "slot") == 0 )
586 regmatch_t matches[3];
587 char *item_type, *newname;
591 if( giTextArgc != 4 ) {
592 fprintf(stderr, "Error: `dispense slot` takes three arguments\n");
598 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
599 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
602 item_type = gsTextArgs[1] + matches[1].rm_so;
603 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
604 item_id = atoi( gsTextArgs[1] + matches[2].rm_so );
607 price = atoi( gsTextArgs[2] );
608 if( price <= 0 && gsTextArgs[2][0] != '0' ) {
609 fprintf(stderr, "Error: Invalid price passed (must be >= 0)\n");
614 newname = gsTextArgs[3];
618 for( pos = newname; *pos; pos ++ )
620 if( !isalnum(*pos) && *pos != ' ' ) {
621 fprintf(stderr, "Error: You should only have letters, numbers and spaces in an item name\n");
627 // Connect & Authenticate
628 sock = OpenConnection(gsDispenseServer, giDispensePort);
629 if( sock < 0 ) return RV_SOCKET_ERROR;
630 ret = Authenticate(sock);
633 ret = Dispense_SetItem(sock, item_type, item_id, price, newname);
638 // Item name / pattern
641 gsItemPattern = gsTextArgs[0];
645 sock = OpenConnection(gsDispenseServer, giDispensePort);
646 if( sock < 0 ) return RV_SOCKET_ERROR;
648 // Get the user's balance
649 ret = GetUserBalance(sock);
653 PopulateItemList(sock);
655 // Disconnect from server
658 if( gsItemPattern && gsItemPattern[0] )
660 regmatch_t matches[3];
662 if( strcmp(gsItemPattern, "door") == 0 )
664 // Connect, Authenticate, dispense and close
665 sock = OpenConnection(gsDispenseServer, giDispensePort);
666 if( sock < 0 ) return RV_SOCKET_ERROR;
667 ret = Authenticate(sock);
669 ret = DispenseItem(sock, "door", 0);
673 // Item id (<type>:<num>)
674 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
679 // Get and finish ident
680 ident = gsItemPattern + matches[1].rm_so;
681 gsItemPattern[matches[1].rm_eo] = '\0';
683 id = atoi( gsItemPattern + matches[2].rm_so );
685 // Connect, Authenticate, dispense and close
686 sock = OpenConnection(gsDispenseServer, giDispensePort);
687 if( sock < 0 ) return RV_SOCKET_ERROR;
689 Dispense_ItemInfo(sock, ident, id);
691 ret = Authenticate(sock);
693 ret = DispenseItem(sock, ident, id);
697 // Item number (6 = coke)
698 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
700 i = atoi(gsItemPattern);
707 for( i = 0; i < giNumItems; i ++ )
709 // Prefix match (with case-insensitive match)
710 for( j = 0; gsItemPattern[j]; j ++ )
712 if( gaItems[i].Desc[j] == gsItemPattern[j] )
714 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
718 // Check if the prefix matched
719 if( gsItemPattern[j] != '\0' )
723 if( gaItems[i].Desc[j] == '\0' ) {
728 // Only one match allowed
733 // TODO: Allow ambiguous matches?
734 // or just print a wanrning
735 printf("Warning - Ambiguous pattern, stopping\n");
740 // Was a match found?
743 fprintf(stderr, "No item matches the passed string\n");
750 else if( giUIMode != UI_MODE_BASIC )
756 // Very basic dispense interface
757 for( i = 0; i < giNumItems; i ++ ) {
759 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
762 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
763 gaItems[i].Price, gaItems[i].Desc);
772 fgets(buffer, BUFSIZ, stdin);
776 if( buf[0] == 'q' ) break;
780 if( i != 0 || buf[0] == '0' )
782 if( i < 0 || i >= giNumItems ) {
783 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
792 // Check for a valid item ID
796 // Connect, Authenticate, dispense and close
797 sock = OpenConnection(gsDispenseServer, giDispensePort);
798 if( sock < 0 ) return RV_SOCKET_ERROR;
800 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
803 ret = Authenticate(sock);
806 for( j = 0; j < giDispenseCount; j ++ ) {
807 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
811 printf("%i items dispensed\n", j);
816 Dispense_ShowUser(sock, gsUserName);
821 // -------------------
822 // --- NCurses GUI ---
823 // -------------------
825 * \brief Render the NCurses UI
827 int ShowNCursesUI(void)
832 const int displayMinWidth = 40;
833 char *titleString = "Dispense";
838 int ret = -2; // -2: Used for marking "no return yet"
840 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
847 if( gsEffectiveUser )
848 username = gsEffectiveUser;
850 pwd = getpwuid( getuid() );
851 username = pwd->pw_name;
854 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
861 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
862 // Get item count per screen
863 // - 6: randomly chosen (Need at least 3)
864 itemCount = LINES - 6;
865 if( itemCount > maxItemIndex )
866 itemCount = maxItemIndex;
869 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
874 height = itemCount + 3;
875 width = displayMinWidth;
878 xBase = COLS/2 - width/2;
879 yBase = LINES/2 - height/2;
884 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
887 for( i = 0; i < itemCount; i ++ )
891 move( yBase + 1 + i, xBase );
896 // Check for the '...' row
897 // - Oh god, magic numbers!
898 if( (i == 0 && itemBase > 0)
899 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
901 printw(" ..."); pos += 8;
902 times = (width - pos) - 1;
903 while(times--) addch(' ');
908 yBase + 1 + i, xBase + pos, // Position
909 (width - pos) - 3, // Width
910 itemBase + i, // Index
911 !!(currentItem == itemBase + i) // Hilighted
916 // Scrollbar (if needed)
917 if( maxItemIndex > itemCount ) {
921 else if( i == itemCount - 1 ) {
925 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
926 if( i-1 == percentage*(itemCount-3)/100 ) {
940 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
943 // - Username, balance, flags
944 PrintAlign(yBase+height-1, xBase+1, width-2,
945 username, ' ', balance_str, ' ', gsUserFlags);
961 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
964 if( currentItem >= maxItemIndex ) {
967 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
974 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
977 if( currentItem < 0 ) {
978 currentItem = maxItemIndex - 1;
980 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
990 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
991 itemBase = currentItem - 2;
992 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
993 itemBase = currentItem - itemCount + 2;
999 ret = ShowItemAt(0, 0, 0, currentItem, 0);
1001 case 0x1b: // Escape
1003 ret = -1; // -1: Return with no dispense
1007 // Check if the return value was changed
1008 if( ret != -2 ) break;
1020 * \brief Show item \a Index at (\a Col, \a Row)
1021 * \return Dispense index of item
1022 * \note Part of the NCurses UI
1024 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
1034 // - This assumes that
1035 case UI_MODE_STANDARD:
1037 // Index = -1, request limit
1038 if( Index < 0 || Index >= giNumItems+2 )
1039 return giNumItems+2;
1044 name = "Coke Machine";
1045 Index = -1; // -1 indicates a label
1052 name = gaItems[Index].Desc;
1053 price = gaItems[Index].Price;
1054 status = gaItems[Index].Status;
1062 name = "Electronic Payment System";
1063 Index = -1; // -1 indicates a label
1068 name = gaItems[Index].Desc;
1069 price = gaItems[Index].Price;
1070 status = gaItems[Index].Status;
1076 // Width = 0, don't print
1079 // 4 preceding, 5 price
1080 int nameWidth = Width - 4 - 5;
1085 // Show hilight and status
1104 printw("%-*.*s", nameWidth, nameWidth, name);
1106 // getyx(stdscr, _y, _x);
1107 // Assumes max 4 digit prices
1108 // times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
1109 // while(times--) addch(' ');
1111 printw(" %4i", price);
1115 printw("-- %s", name);
1116 getyx(stdscr, _y, _x);
1117 times = Width - 4 - (_x - Col);
1118 while(times--) addch(' ');
1123 // If the item isn't availiable for sale, return -1 (so it's skipped)
1124 if( status || price >= giUserBalance )
1131 * \brief Print a three-part string at the specified position (formatted)
1132 * \note NCurses UI Helper
1134 * Prints \a Left on the left of the area, \a Right on the righthand side
1135 * and \a Mid in the middle of the area. These are padded with \a Pad1
1136 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1138 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1139 * and the arguments to these are read in that order.
1141 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1142 const char *Mid, char Pad2, const char *Right, ...)
1144 int lLen, mLen, rLen;
1149 // Get the length of the strings
1150 va_start(args, Right);
1151 lLen = vsnprintf(NULL, 0, Left, args);
1152 mLen = vsnprintf(NULL, 0, Mid, args);
1153 rLen = vsnprintf(NULL, 0, Right, args);
1157 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1158 return ; // TODO: What to do?
1164 va_start(args, Right);
1168 vsnprintf(tmp, lLen+1, Left, args);
1172 times = (Width - mLen)/2 - lLen;
1173 while(times--) addch(Pad1);
1177 vsnprintf(tmp, mLen+1, Mid, args);
1181 times = (Width - mLen)/2 - rLen;
1182 if( (Width - mLen) % 2 ) times ++;
1183 while(times--) addch(Pad2);
1187 vsnprintf(tmp, rLen+1, Right, args);
1192 // ---------------------
1193 // --- Coke Protocol ---
1194 // ---------------------
1195 int OpenConnection(const char *Host, int Port)
1197 struct hostent *host;
1198 struct sockaddr_in serverAddr;
1201 host = gethostbyname(Host);
1203 fprintf(stderr, "Unable to look up '%s'\n", Host);
1207 memset(&serverAddr, 0, sizeof(serverAddr));
1209 serverAddr.sin_family = AF_INET; // IPv4
1210 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1211 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1212 serverAddr.sin_port = htons(Port);
1214 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1216 fprintf(stderr, "Failed to create socket\n");
1220 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1222 if( geteuid() == 0 || getuid() == 0 )
1225 struct sockaddr_in localAddr;
1226 memset(&localAddr, 0, sizeof(localAddr));
1227 localAddr.sin_family = AF_INET; // IPv4
1229 // Loop through all the top ports until one is avaliable
1230 for( i = 512; i < 1024; i ++)
1232 localAddr.sin_port = htons(i); // IPv4
1233 // Attempt to bind to low port for autoauth
1234 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1238 printf("Warning: AUTOAUTH unavaliable\n");
1240 // printf("Bound to 0.0.0.0:%i\n", i);
1243 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1244 fprintf(stderr, "Failed to connect to server\n");
1248 // We're not authenticated if the connection has just opened
1249 gbIsAuthenticated = 0;
1255 * \brief Authenticate with the server
1256 * \return Boolean Failure
1258 int Authenticate(int Socket)
1263 #if ATTEMPT_PASSWORD_AUTH
1266 regmatch_t matches[4];
1269 if( gbIsAuthenticated ) return 0;
1272 pwd = getpwuid( getuid() );
1274 // Attempt automatic authentication
1275 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1277 // Check if it worked
1278 buf = ReadLine(Socket);
1280 responseCode = atoi(buf);
1281 switch( responseCode )
1283 case 200: // Autoauth succeeded, return
1287 case 401: // Untrusted, attempt password authentication
1290 #if ATTEMPT_PASSWORD_AUTH
1291 sendf(Socket, "USER %s\n", pwd->pw_name);
1292 printf("Using username %s\n", pwd->pw_name);
1294 buf = ReadLine(Socket);
1297 // Expected format: 100 SALT <something> ...
1298 // OR : 100 User Set
1299 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1300 responseCode = atoi(buf);
1301 if( responseCode != 100 ) {
1302 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1304 return RV_UNKNOWN_ERROR; // ERROR
1308 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1309 // Store it for later
1310 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1311 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1315 // Give three attempts
1316 for( i = 0; i < 3; i ++ )
1318 int ofs = strlen(pwd->pw_name)+strlen(salt);
1321 char *pass = getpass("Password: ");
1324 // Create hash string
1325 // <username><salt><hash>
1326 strcpy(tmp, pwd->pw_name);
1328 SHA1( (unsigned char*)pass, strlen(pass), h );
1329 memcpy(tmp+ofs, h, 20);
1332 SHA1( (unsigned char*)tmp, ofs+20, h );
1333 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1334 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1335 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1339 sendf(Socket, "PASS %s\n", tmpBuf);
1340 buf = ReadLine(Socket);
1342 responseCode = atoi(buf);
1344 if( responseCode == 200 ) break;
1345 // Bad username/password
1346 if( responseCode == 401 ) continue;
1348 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1350 return RV_UNKNOWN_ERROR;
1354 return RV_INVALID_USER; // 2 = Bad Password
1357 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1358 return RV_INVALID_USER;
1362 case 404: // Bad Username
1363 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1365 return RV_INVALID_USER;
1368 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1369 printf("%s\n", buf);
1371 return RV_UNKNOWN_ERROR;
1374 // Set effective user
1375 if( gsEffectiveUser ) {
1376 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1378 buf = ReadLine(Socket);
1379 responseCode = atoi(buf);
1381 switch(responseCode)
1384 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1388 printf("Only coke members can use `dispense -u`\n");
1390 return RV_PERMISSIONS;
1393 printf("Invalid user selected\n");
1395 return RV_INVALID_USER;
1398 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1399 printf("%s\n", buf);
1401 return RV_UNKNOWN_ERROR;
1407 gbIsAuthenticated = 1;
1412 int GetUserBalance(int Socket)
1414 regmatch_t matches[6];
1421 if( gsEffectiveUser ) {
1422 gsUserName = gsEffectiveUser;
1425 pwd = getpwuid( getuid() );
1426 gsUserName = strdup(pwd->pw_name);
1430 sendf(Socket, "USER_INFO %s\n", gsUserName);
1431 buf = ReadLine(Socket);
1432 responseCode = atoi(buf);
1433 switch(responseCode)
1435 case 202: break; // Ok
1438 printf("Invalid user? (USER_INFO failed)\n");
1440 return RV_INVALID_USER;
1443 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1444 printf("%s\n", buf);
1446 return RV_UNKNOWN_ERROR;
1449 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1451 giUserBalance = atoi( buf + matches[4].rm_so );
1452 gsUserFlags = strdup( buf + matches[5].rm_so );
1460 * \brief Read an item info response from the server
1461 * \param Dest Destination for the read item (strings will be on the heap)
1463 int ReadItemInfo(int Socket, tItem *Dest)
1468 regmatch_t matches[8];
1472 buf = ReadLine(Socket);
1473 responseCode = atoi(buf);
1475 switch(responseCode)
1480 printf("Bad item name\n");
1485 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1487 return RV_UNKNOWN_ERROR;
1490 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1492 buf[ matches[3].rm_eo ] = '\0';
1493 buf[ matches[5].rm_eo ] = '\0';
1494 buf[ matches[7].rm_eo ] = '\0';
1496 statusStr = &buf[ matches[5].rm_so ];
1498 Dest->ID = atoi( buf + matches[4].rm_so );
1500 if( strcmp(statusStr, "avail") == 0 )
1502 else if( strcmp(statusStr, "sold") == 0 )
1504 else if( strcmp(statusStr, "error") == 0 )
1507 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1509 return RV_UNKNOWN_ERROR;
1511 Dest->Price = atoi( buf + matches[6].rm_so );
1513 // Hack a little to reduce heap fragmentation
1515 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1516 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1517 strcpy(tmpType, buf + matches[3].rm_so);
1518 strcpy(tmpDesc, buf + matches[7].rm_so);
1520 Dest->Type = strdup( tmpType );
1521 Dest->Desc = strdup( tmpDesc );
1528 * \brief Fill the item information structure
1529 * \return Boolean Failure
1531 void PopulateItemList(int Socket)
1536 char *itemType, *itemStart;
1538 regmatch_t matches[4];
1540 // Ask server for stock list
1541 send(Socket, "ENUM_ITEMS\n", 11, 0);
1542 buf = ReadLine(Socket);
1544 //printf("Output: %s\n", buf);
1546 responseCode = atoi(buf);
1547 if( responseCode != 201 ) {
1548 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1549 exit(RV_UNKNOWN_ERROR);
1552 // - Get item list -
1555 // 201 Items <count>
1557 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1559 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1560 count = atoi( &buf[ matches[3].rm_so ] );
1563 if( strcmp(itemType, "Items") != 0 ) {
1565 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1567 exit(RV_UNKNOWN_ERROR);
1570 itemStart = &buf[ matches[3].rm_eo ];
1575 gaItems = malloc( giNumItems * sizeof(tItem) );
1577 // Fetch item information
1578 for( i = 0; i < giNumItems; i ++ )
1580 ReadItemInfo( Socket, &gaItems[i] );
1584 buf = ReadLine(Socket);
1585 responseCode = atoi(buf);
1587 if( responseCode != 200 ) {
1588 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1599 * \brief Get information on an item
1600 * \return Boolean Failure
1602 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1608 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1610 ret = ReadItemInfo(Socket, &item);
1613 printf("%8s:%-2i %2i.%02i %s\n",
1615 item.Price/100, item.Price%100,
1625 * \brief Dispense an item
1626 * \return Boolean Failure
1628 int DispenseItem(int Socket, const char *Type, int ID)
1630 int ret, responseCode;
1633 // Check for a dry run
1635 printf("Dry Run - No action\n");
1640 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1641 buf = ReadLine(Socket);
1643 responseCode = atoi(buf);
1644 switch( responseCode )
1647 printf("Dispense OK\n");
1651 printf("Not authenticated\n");
1652 ret = RV_PERMISSIONS;
1655 printf("Insufficient balance\n");
1659 printf("Bad item name\n");
1663 printf("Item failed to dispense, is the slot empty?\n");
1664 ret = RV_SERVER_ERROR;
1667 printf("Dispense not possible (slot empty/permissions)\n");
1668 ret = RV_SERVER_ERROR;
1671 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1672 ret = RV_UNKNOWN_ERROR;
1681 * \brief Alter a user's balance
1683 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1688 // Check for a dry run
1690 printf("Dry Run - No action\n");
1695 if( Ammount == 0 ) {
1696 printf("An ammount would be nice\n");
1697 return RV_ARGUMENTS;
1700 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1701 buf = ReadLine(Socket);
1703 responseCode = atoi(buf);
1706 switch(responseCode)
1708 case 200: return 0; // OK
1710 fprintf(stderr, "Insufficient balance\n");
1712 case 403: // Not in coke
1713 fprintf(stderr, "You are not in coke (sucker)\n");
1714 return RV_PERMISSIONS;
1715 case 404: // Unknown user
1716 fprintf(stderr, "Unknown user '%s'\n", Username);
1717 return RV_INVALID_USER;
1719 fprintf(stderr, "Unknown response code %i\n", responseCode);
1720 return RV_UNKNOWN_RESPONSE;
1727 * \brief Set a user's balance
1728 * \note Only avaliable to dispense admins
1730 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1735 // Check for a dry run
1737 printf("Dry Run - No action\n");
1741 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1742 buf = ReadLine(Socket);
1744 responseCode = atoi(buf);
1747 switch(responseCode)
1749 case 200: return 0; // OK
1750 case 403: // Not in coke
1751 fprintf(stderr, "You are not an admin\n");
1752 return RV_PERMISSIONS;
1753 case 404: // Unknown user
1754 fprintf(stderr, "Unknown user '%s'\n", Username);
1755 return RV_INVALID_USER;
1757 fprintf(stderr, "Unknown response code %i\n", responseCode);
1758 return RV_UNKNOWN_RESPONSE;
1765 * \brief Give money to another user
1767 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1773 printf("Sorry, you can only give, you can't take.\n");
1774 return RV_ARGUMENTS;
1777 // Fast return on zero
1778 if( Ammount == 0 ) {
1779 printf("Are you actually going to give any?\n");
1780 return RV_ARGUMENTS;
1783 // Check for a dry run
1785 printf("Dry Run - No action\n");
1789 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1791 buf = ReadLine(Socket);
1792 responseCode = atoi(buf);
1794 switch(responseCode)
1797 printf("Give succeeded\n");
1798 return RV_SUCCESS; // OK
1801 fprintf(stderr, "Insufficient balance\n");
1804 case 404: // Unknown user
1805 fprintf(stderr, "Unknown user '%s'\n", Username);
1806 return RV_INVALID_USER;
1809 fprintf(stderr, "Unknown response code %i\n", responseCode);
1810 return RV_UNKNOWN_RESPONSE;
1816 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1819 int responseCode, ret = -1;
1822 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1824 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1825 return RV_ARGUMENTS;
1828 // Check username (quick)
1829 if( strchr(Username, ' ') || strchr(Username, '\n') )
1831 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1832 return RV_ARGUMENTS;
1836 sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1838 buf = ReadLine(Socket);
1839 responseCode = atoi(buf);
1840 switch(responseCode)
1843 Dispense_ShowUser(Socket, Username); // Show destination account
1847 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1848 ret = RV_PERMISSIONS;
1851 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1852 ret = RV_INVALID_USER;
1855 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1859 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1868 * \brief Donate money to the club
1870 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1876 printf("Sorry, you can only give, you can't take.\n");
1880 // Fast return on zero
1881 if( Ammount == 0 ) {
1882 printf("Are you actually going to give any?\n");
1886 // Check for a dry run
1888 printf("Dry Run - No action\n");
1892 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1893 buf = ReadLine(Socket);
1895 responseCode = atoi(buf);
1898 switch(responseCode)
1900 case 200: return 0; // OK
1903 fprintf(stderr, "Insufficient balance\n");
1907 fprintf(stderr, "Unknown response code %i\n", responseCode);
1915 * \brief Enumerate users
1917 int Dispense_EnumUsers(int Socket)
1922 regmatch_t matches[4];
1924 if( giMinimumBalance != INT_MIN ) {
1925 if( giMaximumBalance != INT_MAX ) {
1926 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1929 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1933 if( giMaximumBalance != INT_MAX ) {
1934 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1937 sendf(Socket, "ENUM_USERS\n");
1940 buf = ReadLine(Socket);
1941 responseCode = atoi(buf);
1943 switch(responseCode)
1945 case 201: break; // Ok, length follows
1948 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1953 // Get count (not actually used)
1954 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1955 nUsers = atoi( buf + matches[3].rm_so );
1956 printf("%i users returned\n", nUsers);
1961 // Read returned users
1963 buf = ReadLine(Socket);
1964 responseCode = atoi(buf);
1966 if( responseCode != 202 ) break;
1968 _PrintUserLine(buf);
1970 } while(responseCode == 202);
1972 // Check final response
1973 if( responseCode != 200 ) {
1974 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1984 int Dispense_ShowUser(int Socket, const char *Username)
1987 int responseCode, ret;
1989 sendf(Socket, "USER_INFO %s\n", Username);
1990 buf = ReadLine(Socket);
1992 responseCode = atoi(buf);
1994 switch(responseCode)
1997 _PrintUserLine(buf);
2002 printf("Unknown user '%s'\n", Username);
2007 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2017 void _PrintUserLine(const char *Line)
2019 regmatch_t matches[6];
2022 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
2027 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
2028 char username[usernameLen + 1];
2029 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
2030 char flags[flagsLen + 1];
2032 memcpy(username, Line + matches[3].rm_so, usernameLen);
2033 username[usernameLen] = '\0';
2034 memcpy(flags, Line + matches[5].rm_so, flagsLen);
2035 flags[flagsLen] = '\0';
2037 bal = atoi(Line + matches[4].rm_so);
2038 printf("%-15s: $%8.02f (%s)\n", username, ((float)bal)/100, flags);
2042 int Dispense_AddUser(int Socket, const char *Username)
2045 int responseCode, ret;
2047 // Check for a dry run
2049 printf("Dry Run - No action\n");
2053 sendf(Socket, "USER_ADD %s\n", Username);
2055 buf = ReadLine(Socket);
2056 responseCode = atoi(buf);
2058 switch(responseCode)
2061 printf("User '%s' added\n", Username);
2066 printf("Only wheel can add users\n");
2071 printf("User '%s' already exists\n", Username);
2076 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2086 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString, const char *Reason)
2089 int responseCode, ret;
2091 // Check for a dry run
2093 printf("Dry Run - No action\n");
2097 // TODO: Pre-validate the string
2099 sendf(Socket, "USER_FLAGS %s %s %s\n", Username, TypeString, Reason);
2101 buf = ReadLine(Socket);
2102 responseCode = atoi(buf);
2104 switch(responseCode)
2107 printf("User '%s' updated\n", Username);
2112 printf("Only dispense admins can modify users\n");
2113 ret = RV_PERMISSIONS;
2117 printf("User '%s' does not exist\n", Username);
2118 ret = RV_INVALID_USER;
2122 printf("Flag string is invalid\n");
2127 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2128 ret = RV_UNKNOWN_RESPONSE;
2137 int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName)
2140 int responseCode, ret;
2142 // Check for a dry run
2144 printf("Dry Run - No action\n");
2148 sendf(Socket, "UPDATE_ITEM %s:%i %i %s\n", Type, ID, NewPrice, NewName);
2150 buf = ReadLine(Socket);
2151 responseCode = atoi(buf);
2153 switch(responseCode)
2156 printf("Item %s:%i updated\n", Type, ID);
2161 printf("Only coke members can modify the slots\n");
2162 ret = RV_PERMISSIONS;
2166 printf("Invalid item passed\n");
2171 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2184 char *ReadLine(int Socket)
2186 static char buf[BUFSIZ];
2187 static int bufPos = 0;
2188 static int bufValid = 0;
2190 char *newline = NULL;
2192 char *ret = malloc(10);
2194 #if DEBUG_TRACE_SERVER
2195 printf("ReadLine: ");
2207 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2210 return strdup("499 Client Connection Error\n");
2212 buf[bufPos+len] = '\0';
2215 newline = strchr( buf+bufPos, '\n' );
2220 retLen += strlen(buf+bufPos);
2221 ret = realloc(ret, retLen + 1);
2222 strcat( ret, buf+bufPos );
2225 int newLen = newline - (buf+bufPos) + 1;
2226 bufValid = len - newLen;
2229 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2232 #if DEBUG_TRACE_SERVER
2233 printf("%i '%s'\n", retLen, ret);
2239 int sendf(int Socket, const char *Format, ...)
2244 va_start(args, Format);
2245 len = vsnprintf(NULL, 0, Format, args);
2250 va_start(args, Format);
2251 vsnprintf(buf, len+1, Format, args);
2254 #if DEBUG_TRACE_SERVER
2255 printf("sendf: %s", buf);
2258 return send(Socket, buf, len, 0);
2262 char *trim(char *string)
2266 while( isspace(*string) )
2269 for( i = strlen(string); i--; )
2271 if( isspace(string[i]) )
2280 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2284 ret = regexec(regex, string, nMatches, matches, 0);
2285 if( ret && errorMessage ) {
2286 size_t len = regerror(ret, regex, NULL, 0);
2288 regerror(ret, regex, errorStr, len);
2289 printf("string = '%s'\n", string);
2290 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2297 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2299 int ret = regcomp(regex, pattern, flags);
2301 size_t len = regerror(ret, regex, NULL, 0);
2303 regerror(ret, regex, errorStr, len);
2304 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);