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 = "merlo.ucc.gu.uwa.edu.au";
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"
164 " Item IDs can be seen in the cokelog (in the brackets after the item name)\n"
165 " e.g. coke:6 for a coke, snack:33 for slot 33 of the snack machine\n"
167 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "slot") == 0 )
169 " dispense slot <itemid> <price> <name>\n"
170 " Rename/Re-price a slot\n"
172 if( giTextArgc == 0 )
173 printf(" == Dispense administrators ==\n");
174 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "user") == 0 )
176 " dispense user add <user>\n"
177 " Create new account\n"
178 " dispense user type <user> <flags> <reason>\n"
179 " Alter a user's flags\n"
180 " <flags> is a comma-separated list of user, coke, admin, internal or disabled\n"
181 " Flags are removed by preceding the name with '-' or '!'\n"
183 if( giTextArgc == 0 )
187 " Dispense multiple times\n"
189 " Set a different user (Coke members only)\n"
193 " Use simple textual interface (instead of ncurses)\n"
195 " Dry run - Do not actually do dispenses\n"
196 " -m <min balance>\n"
197 " -M <max balance>\n"
198 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
201 " 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"
207 int main(int argc, char *argv[])
215 // -- Create regular expressions
216 // > Code Type Count ...
217 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
218 // > Code Type Ident Status Price Desc
219 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);
220 // > Code 'SALT' salt
221 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
222 // > Code 'User' Username Balance Flags
223 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
225 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
228 for( i = 1; i < argc; i ++ )
242 if( i + 1 >= argc ) {
243 fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
247 giDispenseCount = atoi(argv[++i]);
248 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
249 fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
255 case 'm': // Minimum balance
256 if( i + 1 >= argc ) {
257 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
261 giMinimumBalance = atoi(argv[++i]);
263 case 'M': // Maximum balance
264 if( i + 1 >= argc ) {
265 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
269 giMaximumBalance = atoi(argv[++i]);
272 case 'u': // Override User
273 if( i + 1 >= argc ) {
274 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
278 gsEffectiveUser = argv[++i];
281 case 'H': // Override remote host
282 if( i + 1 >= argc ) {
283 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
287 gsDispenseServer = argv[++i];
289 case 'P': // Override remote port
290 if( i + 1 >= argc ) {
291 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
295 giDispensePort = atoi(argv[++i]);
298 // Set slot name/price
300 if( giTextArgc != 0 ) {
301 fprintf(stderr, "%s: -s must appear before other arguments\n", argv[0]);
305 gsTextArgs[0] = "slot"; // HACK!!
309 case 'G': // Don't use GUI
310 giUIMode = UI_MODE_BASIC;
312 case 'D': // Drinks only
313 giUIMode = UI_MODE_DRINKSONLY;
315 case 'n': // Dry Run / read-only
319 if( strcmp(argv[i], "--help") == 0 ) {
324 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
330 // The first argument is not allowed to begin with 'i'
331 // (catches most bad flags)
332 if( giTextArgc == 0 ) {
333 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
337 if( giTextArgc == MAX_TXT_ARGS )
339 fprintf(stderr, "ERROR: Too many arguments\n");
342 gsTextArgs[giTextArgc++] = argv[i];
349 if( giTextArgc == MAX_TXT_ARGS )
351 fprintf(stderr, "ERROR: Too many arguments\n");
355 gsTextArgs[giTextArgc++] = argv[i];
362 if( strcmp(gsTextArgs[0], "acct") == 0 )
365 sock = OpenConnection(gsDispenseServer, giDispensePort);
366 if( sock < 0 ) return RV_SOCKET_ERROR;
368 if( giTextArgc == 1 ) {
369 ret = Dispense_EnumUsers(sock);
374 // gsTextArgs[1]: Username
377 if( giTextArgc != 2 )
379 if( giTextArgc != 4 ) {
380 fprintf(stderr, "`dispense acct` requires a reason\n");
385 // Authentication required
386 ret = Authenticate(sock);
389 // gsTextArgs[1]: Username
390 // gsTextArgs[2]: Ammount
391 // gsTextArgs[3]: Reason
393 if( gsTextArgs[2][0] == '=' ) {
395 if( gsTextArgs[2][1] != '0' && atoi(gsTextArgs[2]+1) == 0 ) {
396 fprintf(stderr, "Error: Invalid balance to be set\n");
400 ret = Dispense_SetBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]+1), gsTextArgs[3]);
404 ret = Dispense_AlterBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
413 // Show user information
414 ret = Dispense_ShowUser(sock, gsTextArgs[1]);
421 // - "Here, have some money."
422 else if( strcmp(gsTextArgs[0], "give") == 0 )
424 if( giTextArgc != 4 ) {
425 fprintf(stderr, "`dispense give` takes three arguments\n");
430 // gsTextArgs[1]: Destination
431 // gsTextArgs[2]: Ammount
432 // gsTextArgs[3]: Reason
435 sock = OpenConnection(gsDispenseServer, giDispensePort);
436 if( sock < 0 ) return RV_SOCKET_ERROR;
439 ret = Authenticate(sock);
442 ret = Dispense_Give(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
450 // - User administration (Admin Only)
451 if( strcmp(gsTextArgs[0], "user") == 0 )
453 // Check argument count
454 if( giTextArgc == 1 ) {
455 fprintf(stderr, "Error: `dispense user` requires arguments\n");
461 sock = OpenConnection(gsDispenseServer, giDispensePort);
462 if( sock < 0 ) return RV_SOCKET_ERROR;
464 // Attempt authentication
465 ret = Authenticate(sock);
469 if( strcmp(gsTextArgs[1], "add") == 0 )
471 if( giTextArgc != 3 ) {
472 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
477 ret = Dispense_AddUser(sock, gsTextArgs[2]);
480 else if( strcmp(gsTextArgs[1], "type") == 0 || strcmp(gsTextArgs[1], "flags") == 0 )
482 if( giTextArgc < 4 || giTextArgc > 5 ) {
483 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
488 if( giTextArgc == 4 )
489 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], "");
491 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], gsTextArgs[4]);
495 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
503 else if( strcmp(gsTextArgs[0], "donate") == 0 )
505 // Check argument count
506 if( giTextArgc != 3 ) {
507 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
513 sock = OpenConnection(gsDispenseServer, giDispensePort);
514 if( sock < 0 ) return RV_SOCKET_ERROR;
516 // Attempt authentication
517 ret = Authenticate(sock);
521 ret = Dispense_Donate(sock, atoi(gsTextArgs[1]), gsTextArgs[2]);
528 else if( strcmp(gsTextArgs[0], "refund") == 0 )
531 // Check argument count
532 if( giTextArgc != 3 && giTextArgc != 4 ) {
533 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
539 sock = OpenConnection(gsDispenseServer, giDispensePort);
540 if(sock < 0) return RV_SOCKET_ERROR;
542 // Attempt authentication
543 ret = Authenticate(sock);
546 if( giTextArgc == 4 ) {
547 price = atoi(gsTextArgs[3]);
549 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
554 // Username, Item, cost
555 ret = Dispense_Refund(sock, gsTextArgs[1], gsTextArgs[2], price);
561 // Query an item price
562 else if( strcmp(gsTextArgs[0], "iteminfo") == 0 )
564 regmatch_t matches[3];
567 // Check argument count
568 if( giTextArgc != 2 ) {
569 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
574 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
575 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
578 type = gsTextArgs[1] + matches[1].rm_so;
579 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
580 id = atoi( gsTextArgs[1] + matches[2].rm_so );
582 sock = OpenConnection(gsDispenseServer, giDispensePort);
583 if( sock < 0 ) return RV_SOCKET_ERROR;
585 ret = Dispense_ItemInfo(sock, type, id);
590 else if( strcmp(gsTextArgs[0], "slot") == 0 )
592 regmatch_t matches[3];
593 char *item_type, *newname;
597 if( giTextArgc != 4 ) {
598 fprintf(stderr, "Error: `dispense slot` takes three arguments\n");
604 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
605 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
608 item_type = gsTextArgs[1] + matches[1].rm_so;
609 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
610 item_id = atoi( gsTextArgs[1] + matches[2].rm_so );
613 price = atoi( gsTextArgs[2] );
614 if( price <= 0 && gsTextArgs[2][0] != '0' ) {
615 fprintf(stderr, "Error: Invalid price passed (must be >= 0)\n");
620 newname = gsTextArgs[3];
624 for( pos = newname; *pos; pos ++ )
626 if( !isalnum(*pos) && *pos != ' ' ) {
627 fprintf(stderr, "Error: You should only have letters, numbers and spaces in an item name\n");
633 // Connect & Authenticate
634 sock = OpenConnection(gsDispenseServer, giDispensePort);
635 if( sock < 0 ) return RV_SOCKET_ERROR;
636 ret = Authenticate(sock);
639 ret = Dispense_SetItem(sock, item_type, item_id, price, newname);
644 // Item name / pattern
647 gsItemPattern = gsTextArgs[0];
651 sock = OpenConnection(gsDispenseServer, giDispensePort);
652 if( sock < 0 ) return RV_SOCKET_ERROR;
654 // Get the user's balance
655 ret = GetUserBalance(sock);
659 PopulateItemList(sock);
661 // Disconnect from server
664 if( gsItemPattern && gsItemPattern[0] )
666 regmatch_t matches[3];
668 if( strcmp(gsItemPattern, "door") == 0 )
670 // Connect, Authenticate, dispense and close
671 sock = OpenConnection(gsDispenseServer, giDispensePort);
672 if( sock < 0 ) return RV_SOCKET_ERROR;
673 ret = Authenticate(sock);
675 ret = DispenseItem(sock, "door", 0);
679 // Item id (<type>:<num>)
680 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
685 // Get and finish ident
686 ident = gsItemPattern + matches[1].rm_so;
687 gsItemPattern[matches[1].rm_eo] = '\0';
689 id = atoi( gsItemPattern + matches[2].rm_so );
691 // Connect, Authenticate, dispense and close
692 sock = OpenConnection(gsDispenseServer, giDispensePort);
693 if( sock < 0 ) return RV_SOCKET_ERROR;
695 Dispense_ItemInfo(sock, ident, id);
697 ret = Authenticate(sock);
699 ret = DispenseItem(sock, ident, id);
703 // Item number (6 = coke)
704 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
706 i = atoi(gsItemPattern);
713 for( i = 0; i < giNumItems; i ++ )
715 // Prefix match (with case-insensitive match)
716 for( j = 0; gsItemPattern[j]; j ++ )
718 if( gaItems[i].Desc[j] == gsItemPattern[j] )
720 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
724 // Check if the prefix matched
725 if( gsItemPattern[j] != '\0' )
729 if( gaItems[i].Desc[j] == '\0' ) {
734 // Only one match allowed
739 // TODO: Allow ambiguous matches?
740 // or just print a wanrning
741 printf("Warning - Ambiguous pattern, stopping\n");
746 // Was a match found?
749 fprintf(stderr, "No item matches the passed string\n");
756 else if( giUIMode != UI_MODE_BASIC )
762 // Very basic dispense interface
763 for( i = 0; i < giNumItems; i ++ ) {
765 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
768 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
769 gaItems[i].Price, gaItems[i].Desc);
778 fgets(buffer, BUFSIZ, stdin);
782 if( buf[0] == 'q' ) break;
786 if( i != 0 || buf[0] == '0' )
788 if( i < 0 || i >= giNumItems ) {
789 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
798 // Check for a valid item ID
802 // Connect, Authenticate, dispense and close
803 sock = OpenConnection(gsDispenseServer, giDispensePort);
804 if( sock < 0 ) return RV_SOCKET_ERROR;
806 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
809 ret = Authenticate(sock);
812 for( j = 0; j < giDispenseCount; j ++ ) {
813 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
817 printf("%i items dispensed\n", j);
822 Dispense_ShowUser(sock, gsUserName);
827 // -------------------
828 // --- NCurses GUI ---
829 // -------------------
831 * \brief Render the NCurses UI
833 int ShowNCursesUI(void)
838 const int displayMinWidth = 40;
839 char *titleString = "Dispense";
844 int ret = -2; // -2: Used for marking "no return yet"
846 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
853 if( gsEffectiveUser )
854 username = gsEffectiveUser;
856 pwd = getpwuid( getuid() );
857 username = pwd->pw_name;
860 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
867 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
868 // Get item count per screen
869 // - 6: randomly chosen (Need at least 3)
870 itemCount = LINES - 6;
871 if( itemCount > maxItemIndex )
872 itemCount = maxItemIndex;
875 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
880 height = itemCount + 3;
881 width = displayMinWidth;
884 xBase = COLS/2 - width/2;
885 yBase = LINES/2 - height/2;
890 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
893 for( i = 0; i < itemCount; i ++ )
897 move( yBase + 1 + i, xBase );
902 // Check for the '...' row
903 // - Oh god, magic numbers!
904 if( (i == 0 && itemBase > 0)
905 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
907 printw(" ..."); pos += 8;
908 times = (width - pos) - 1;
909 while(times--) addch(' ');
914 yBase + 1 + i, xBase + pos, // Position
915 (width - pos) - 3, // Width
916 itemBase + i, // Index
917 !!(currentItem == itemBase + i) // Hilighted
922 // Scrollbar (if needed)
923 if( maxItemIndex > itemCount ) {
927 else if( i == itemCount - 1 ) {
931 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
932 if( i-1 == percentage*(itemCount-3)/100 ) {
946 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
949 // - Username, balance, flags
950 PrintAlign(yBase+height-1, xBase+1, width-2,
951 username, ' ', balance_str, ' ', gsUserFlags);
967 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
970 if( currentItem >= maxItemIndex ) {
973 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
980 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
983 if( currentItem < 0 ) {
984 currentItem = maxItemIndex - 1;
986 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
996 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
997 itemBase = currentItem - 2;
998 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
999 itemBase = currentItem - itemCount + 2;
1005 ret = ShowItemAt(0, 0, 0, currentItem, 0);
1007 case 0x1b: // Escape
1009 ret = -1; // -1: Return with no dispense
1013 // Check if the return value was changed
1014 if( ret != -2 ) break;
1026 * \brief Show item \a Index at (\a Col, \a Row)
1027 * \return Dispense index of item
1028 * \note Part of the NCurses UI
1030 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
1040 // - This assumes that
1041 case UI_MODE_STANDARD:
1043 // Index = -1, request limit
1044 if( Index < 0 || Index >= giNumItems+2 )
1045 return giNumItems+2;
1050 name = "Coke Machine";
1051 Index = -1; // -1 indicates a label
1058 name = gaItems[Index].Desc;
1059 price = gaItems[Index].Price;
1060 status = gaItems[Index].Status;
1068 name = "Electronic Payment System";
1069 Index = -1; // -1 indicates a label
1074 name = gaItems[Index].Desc;
1075 price = gaItems[Index].Price;
1076 status = gaItems[Index].Status;
1082 // Width = 0, don't print
1085 // 4 preceding, 5 price
1086 int nameWidth = Width - 4 - 5;
1091 // Show hilight and status
1110 printw("%-*.*s", nameWidth, nameWidth, name);
1112 // getyx(stdscr, _y, _x);
1113 // Assumes max 4 digit prices
1114 // times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
1115 // while(times--) addch(' ');
1117 printw(" %4i", price);
1121 printw("-- %s", name);
1122 getyx(stdscr, _y, _x);
1123 times = Width - 4 - (_x - Col);
1124 while(times--) addch(' ');
1129 // If the item isn't availiable for sale, return -1 (so it's skipped)
1130 if( status || price > giUserBalance )
1137 * \brief Print a three-part string at the specified position (formatted)
1138 * \note NCurses UI Helper
1140 * Prints \a Left on the left of the area, \a Right on the righthand side
1141 * and \a Mid in the middle of the area. These are padded with \a Pad1
1142 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1144 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1145 * and the arguments to these are read in that order.
1147 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1148 const char *Mid, char Pad2, const char *Right, ...)
1150 int lLen, mLen, rLen;
1155 // Get the length of the strings
1156 va_start(args, Right);
1157 lLen = vsnprintf(NULL, 0, Left, args);
1158 mLen = vsnprintf(NULL, 0, Mid, args);
1159 rLen = vsnprintf(NULL, 0, Right, args);
1163 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1164 return ; // TODO: What to do?
1170 va_start(args, Right);
1174 vsnprintf(tmp, lLen+1, Left, args);
1178 times = (Width - mLen)/2 - lLen;
1179 while(times--) addch(Pad1);
1183 vsnprintf(tmp, mLen+1, Mid, args);
1187 times = (Width - mLen)/2 - rLen;
1188 if( (Width - mLen) % 2 ) times ++;
1189 while(times--) addch(Pad2);
1193 vsnprintf(tmp, rLen+1, Right, args);
1198 // ---------------------
1199 // --- Coke Protocol ---
1200 // ---------------------
1201 int OpenConnection(const char *Host, int Port)
1203 struct hostent *host;
1204 struct sockaddr_in serverAddr;
1207 host = gethostbyname(Host);
1209 fprintf(stderr, "Unable to look up '%s'\n", Host);
1213 memset(&serverAddr, 0, sizeof(serverAddr));
1215 serverAddr.sin_family = AF_INET; // IPv4
1216 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1217 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1218 serverAddr.sin_port = htons(Port);
1220 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1222 fprintf(stderr, "Failed to create socket\n");
1226 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1228 if( geteuid() == 0 || getuid() == 0 )
1231 struct sockaddr_in localAddr;
1232 memset(&localAddr, 0, sizeof(localAddr));
1233 localAddr.sin_family = AF_INET; // IPv4
1235 // Loop through all the top ports until one is avaliable
1236 for( i = 512; i < 1024; i ++)
1238 localAddr.sin_port = htons(i); // IPv4
1239 // Attempt to bind to low port for autoauth
1240 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1244 printf("Warning: AUTOAUTH unavaliable\n");
1246 // printf("Bound to 0.0.0.0:%i\n", i);
1249 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1250 fprintf(stderr, "Failed to connect to server\n");
1254 // We're not authenticated if the connection has just opened
1255 gbIsAuthenticated = 0;
1261 * \brief Authenticate with the server
1262 * \return Boolean Failure
1264 int Authenticate(int Socket)
1269 #if ATTEMPT_PASSWORD_AUTH
1272 regmatch_t matches[4];
1275 if( gbIsAuthenticated ) return 0;
1278 pwd = getpwuid( getuid() );
1280 // Attempt automatic authentication
1281 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1283 // Check if it worked
1284 buf = ReadLine(Socket);
1286 responseCode = atoi(buf);
1287 switch( responseCode )
1289 case 200: // Autoauth succeeded, return
1293 case 401: // Untrusted, attempt password authentication
1296 #if ATTEMPT_PASSWORD_AUTH
1297 sendf(Socket, "USER %s\n", pwd->pw_name);
1298 printf("Using username %s\n", pwd->pw_name);
1300 buf = ReadLine(Socket);
1303 // Expected format: 100 SALT <something> ...
1304 // OR : 100 User Set
1305 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1306 responseCode = atoi(buf);
1307 if( responseCode != 100 ) {
1308 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1310 return RV_UNKNOWN_ERROR; // ERROR
1314 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1315 // Store it for later
1316 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1317 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1321 // Give three attempts
1322 for( i = 0; i < 3; i ++ )
1324 int ofs = strlen(pwd->pw_name)+strlen(salt);
1327 char *pass = getpass("Password: ");
1330 // Create hash string
1331 // <username><salt><hash>
1332 strcpy(tmp, pwd->pw_name);
1334 SHA1( (unsigned char*)pass, strlen(pass), h );
1335 memcpy(tmp+ofs, h, 20);
1338 SHA1( (unsigned char*)tmp, ofs+20, h );
1339 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1340 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1341 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1345 sendf(Socket, "PASS %s\n", tmpBuf);
1346 buf = ReadLine(Socket);
1348 responseCode = atoi(buf);
1350 if( responseCode == 200 ) break;
1351 // Bad username/password
1352 if( responseCode == 401 ) continue;
1354 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1356 return RV_UNKNOWN_ERROR;
1360 return RV_INVALID_USER; // 2 = Bad Password
1363 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1364 return RV_INVALID_USER;
1368 case 404: // Bad Username
1369 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1371 return RV_INVALID_USER;
1374 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1375 printf("%s\n", buf);
1377 return RV_UNKNOWN_ERROR;
1380 // Set effective user
1381 if( gsEffectiveUser ) {
1382 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1384 buf = ReadLine(Socket);
1385 responseCode = atoi(buf);
1387 switch(responseCode)
1390 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1394 printf("Only coke members can use `dispense -u`\n");
1396 return RV_PERMISSIONS;
1399 printf("Invalid user selected\n");
1401 return RV_INVALID_USER;
1404 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1405 printf("%s\n", buf);
1407 return RV_UNKNOWN_ERROR;
1413 gbIsAuthenticated = 1;
1418 int GetUserBalance(int Socket)
1420 regmatch_t matches[6];
1427 if( gsEffectiveUser ) {
1428 gsUserName = gsEffectiveUser;
1431 pwd = getpwuid( getuid() );
1432 gsUserName = strdup(pwd->pw_name);
1436 sendf(Socket, "USER_INFO %s\n", gsUserName);
1437 buf = ReadLine(Socket);
1438 responseCode = atoi(buf);
1439 switch(responseCode)
1441 case 202: break; // Ok
1444 printf("Invalid user? (USER_INFO failed)\n");
1446 return RV_INVALID_USER;
1449 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1450 printf("%s\n", buf);
1452 return RV_UNKNOWN_ERROR;
1455 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1457 giUserBalance = atoi( buf + matches[4].rm_so );
1458 gsUserFlags = strdup( buf + matches[5].rm_so );
1466 * \brief Read an item info response from the server
1467 * \param Dest Destination for the read item (strings will be on the heap)
1469 int ReadItemInfo(int Socket, tItem *Dest)
1474 regmatch_t matches[8];
1478 buf = ReadLine(Socket);
1479 responseCode = atoi(buf);
1481 switch(responseCode)
1486 printf("Bad item name\n");
1491 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1493 return RV_UNKNOWN_ERROR;
1496 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1498 buf[ matches[3].rm_eo ] = '\0';
1499 buf[ matches[5].rm_eo ] = '\0';
1500 buf[ matches[7].rm_eo ] = '\0';
1502 statusStr = &buf[ matches[5].rm_so ];
1504 Dest->ID = atoi( buf + matches[4].rm_so );
1506 if( strcmp(statusStr, "avail") == 0 )
1508 else if( strcmp(statusStr, "sold") == 0 )
1510 else if( strcmp(statusStr, "error") == 0 )
1513 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1515 return RV_UNKNOWN_ERROR;
1517 Dest->Price = atoi( buf + matches[6].rm_so );
1519 // Hack a little to reduce heap fragmentation
1521 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1522 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1523 strcpy(tmpType, buf + matches[3].rm_so);
1524 strcpy(tmpDesc, buf + matches[7].rm_so);
1526 Dest->Type = strdup( tmpType );
1527 Dest->Desc = strdup( tmpDesc );
1534 * \brief Fill the item information structure
1535 * \return Boolean Failure
1537 void PopulateItemList(int Socket)
1544 regmatch_t matches[4];
1546 // Ask server for stock list
1547 send(Socket, "ENUM_ITEMS\n", 11, 0);
1548 buf = ReadLine(Socket);
1550 //printf("Output: %s\n", buf);
1552 responseCode = atoi(buf);
1553 if( responseCode != 201 ) {
1554 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1555 exit(RV_UNKNOWN_ERROR);
1558 // - Get item list -
1561 // 201 Items <count>
1563 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1565 arrayType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1566 count = atoi( &buf[ matches[3].rm_so ] );
1569 if( strcmp(arrayType, "Items") != 0 ) {
1571 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1573 exit(RV_UNKNOWN_ERROR);
1578 gaItems = malloc( giNumItems * sizeof(tItem) );
1580 // Fetch item information
1581 for( i = 0; i < giNumItems; i ++ )
1583 ReadItemInfo( Socket, &gaItems[i] );
1587 buf = ReadLine(Socket);
1588 responseCode = atoi(buf);
1590 if( responseCode != 200 ) {
1591 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1602 * \brief Get information on an item
1603 * \return Boolean Failure
1605 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1611 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1613 ret = ReadItemInfo(Socket, &item);
1616 printf("%8s:%-2i %2i.%02i %s\n",
1618 item.Price/100, item.Price%100,
1628 * \brief Dispense an item
1629 * \return Boolean Failure
1631 int DispenseItem(int Socket, const char *Type, int ID)
1633 int ret, responseCode;
1636 // Check for a dry run
1638 printf("Dry Run - No action\n");
1643 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1644 buf = ReadLine(Socket);
1646 responseCode = atoi(buf);
1647 switch( responseCode )
1650 printf("Dispense OK\n");
1654 printf("Not authenticated\n");
1655 ret = RV_PERMISSIONS;
1658 printf("Insufficient balance\n");
1662 printf("Bad item name\n");
1666 printf("Item failed to dispense, is the slot empty?\n");
1667 ret = RV_SERVER_ERROR;
1670 printf("Dispense not possible (slot empty/permissions)\n");
1671 ret = RV_SERVER_ERROR;
1674 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1675 ret = RV_UNKNOWN_ERROR;
1684 * \brief Alter a user's balance
1686 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1689 int responseCode, rv = -1;
1691 // Check for a dry run
1693 printf("Dry Run - No action\n");
1698 if( Ammount == 0 ) {
1699 printf("An ammount would be nice\n");
1700 return RV_ARGUMENTS;
1703 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1704 buf = ReadLine(Socket);
1706 responseCode = atoi(buf);
1708 switch(responseCode)
1714 fprintf(stderr, "Insufficient balance\n");
1717 case 403: // Not in coke
1718 fprintf(stderr, "You are not in coke (sucker)\n");
1719 rv = RV_PERMISSIONS;
1721 case 404: // Unknown user
1722 fprintf(stderr, "Unknown user '%s'\n", Username);
1723 rv = RV_INVALID_USER;
1726 fprintf(stderr, "Unknown response code %i\n'%s'\n", responseCode, buf);
1727 rv = RV_UNKNOWN_RESPONSE;
1736 * \brief Set a user's balance
1737 * \note Only avaliable to dispense admins
1739 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1744 // Check for a dry run
1746 printf("Dry Run - No action\n");
1750 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1751 buf = ReadLine(Socket);
1753 responseCode = atoi(buf);
1756 switch(responseCode)
1758 case 200: return 0; // OK
1759 case 403: // Not in coke
1760 fprintf(stderr, "You are not an admin\n");
1761 return RV_PERMISSIONS;
1762 case 404: // Unknown user
1763 fprintf(stderr, "Unknown user '%s'\n", Username);
1764 return RV_INVALID_USER;
1766 fprintf(stderr, "Unknown response code %i\n", responseCode);
1767 return RV_UNKNOWN_RESPONSE;
1774 * \brief Give money to another user
1776 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1782 printf("Sorry, you can only give, you can't take.\n");
1783 return RV_ARGUMENTS;
1786 // Fast return on zero
1787 if( Ammount == 0 ) {
1788 printf("Are you actually going to give any?\n");
1789 return RV_ARGUMENTS;
1792 // Check for a dry run
1794 printf("Dry Run - No action\n");
1798 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1800 buf = ReadLine(Socket);
1801 responseCode = atoi(buf);
1803 switch(responseCode)
1806 printf("Give succeeded\n");
1807 return RV_SUCCESS; // OK
1810 fprintf(stderr, "Insufficient balance\n");
1813 case 404: // Unknown user
1814 fprintf(stderr, "Unknown user '%s'\n", Username);
1815 return RV_INVALID_USER;
1818 fprintf(stderr, "Unknown response code %i\n", responseCode);
1819 return RV_UNKNOWN_RESPONSE;
1825 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1828 int responseCode, ret = -1;
1831 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1833 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1834 return RV_ARGUMENTS;
1837 // Check username (quick)
1838 if( strchr(Username, ' ') || strchr(Username, '\n') )
1840 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1841 return RV_ARGUMENTS;
1845 sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1847 buf = ReadLine(Socket);
1848 responseCode = atoi(buf);
1849 switch(responseCode)
1852 Dispense_ShowUser(Socket, Username); // Show destination account
1856 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1857 ret = RV_PERMISSIONS;
1860 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1861 ret = RV_INVALID_USER;
1864 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1868 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1877 * \brief Donate money to the club
1879 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1885 printf("Sorry, you can only give, you can't take.\n");
1889 // Fast return on zero
1890 if( Ammount == 0 ) {
1891 printf("Are you actually going to give any?\n");
1895 // Check for a dry run
1897 printf("Dry Run - No action\n");
1901 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1902 buf = ReadLine(Socket);
1904 responseCode = atoi(buf);
1907 switch(responseCode)
1909 case 200: return 0; // OK
1912 fprintf(stderr, "Insufficient balance\n");
1916 fprintf(stderr, "Unknown response code %i\n", responseCode);
1924 * \brief Enumerate users
1926 int Dispense_EnumUsers(int Socket)
1931 regmatch_t matches[4];
1933 if( giMinimumBalance != INT_MIN ) {
1934 if( giMaximumBalance != INT_MAX ) {
1935 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1938 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1942 if( giMaximumBalance != INT_MAX ) {
1943 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1946 sendf(Socket, "ENUM_USERS\n");
1949 buf = ReadLine(Socket);
1950 responseCode = atoi(buf);
1952 switch(responseCode)
1954 case 201: break; // Ok, length follows
1957 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1962 // Get count (not actually used)
1963 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1964 nUsers = atoi( buf + matches[3].rm_so );
1965 printf("%i users returned\n", nUsers);
1970 // Read returned users
1972 buf = ReadLine(Socket);
1973 responseCode = atoi(buf);
1975 if( responseCode != 202 ) break;
1977 _PrintUserLine(buf);
1979 } while(responseCode == 202);
1981 // Check final response
1982 if( responseCode != 200 ) {
1983 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1993 int Dispense_ShowUser(int Socket, const char *Username)
1996 int responseCode, ret;
1998 sendf(Socket, "USER_INFO %s\n", Username);
1999 buf = ReadLine(Socket);
2001 responseCode = atoi(buf);
2003 switch(responseCode)
2006 _PrintUserLine(buf);
2011 printf("Unknown user '%s'\n", Username);
2016 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2026 void _PrintUserLine(const char *Line)
2028 regmatch_t matches[6];
2031 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
2036 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
2037 char username[usernameLen + 1];
2038 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
2039 char flags[flagsLen + 1];
2041 memcpy(username, Line + matches[3].rm_so, usernameLen);
2042 username[usernameLen] = '\0';
2043 memcpy(flags, Line + matches[5].rm_so, flagsLen);
2044 flags[flagsLen] = '\0';
2046 bal = atoi(Line + matches[4].rm_so);
2047 printf("%-15s: $%8.02f (%s)\n", username, ((float)bal)/100, flags);
2051 int Dispense_AddUser(int Socket, const char *Username)
2054 int responseCode, ret;
2056 // Check for a dry run
2058 printf("Dry Run - No action\n");
2062 sendf(Socket, "USER_ADD %s\n", Username);
2064 buf = ReadLine(Socket);
2065 responseCode = atoi(buf);
2067 switch(responseCode)
2070 printf("User '%s' added\n", Username);
2075 printf("Only wheel can add users\n");
2080 printf("User '%s' already exists\n", Username);
2085 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2095 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString, const char *Reason)
2098 int responseCode, ret;
2100 // Check for a dry run
2102 printf("Dry Run - No action\n");
2106 // TODO: Pre-validate the string
2108 sendf(Socket, "USER_FLAGS %s %s %s\n", Username, TypeString, Reason);
2110 buf = ReadLine(Socket);
2111 responseCode = atoi(buf);
2113 switch(responseCode)
2116 printf("User '%s' updated\n", Username);
2121 printf("Only dispense admins can modify users\n");
2122 ret = RV_PERMISSIONS;
2126 printf("User '%s' does not exist\n", Username);
2127 ret = RV_INVALID_USER;
2131 printf("Flag string is invalid\n");
2136 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2137 ret = RV_UNKNOWN_RESPONSE;
2146 int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName)
2149 int responseCode, ret;
2151 // Check for a dry run
2153 printf("Dry Run - No action\n");
2157 sendf(Socket, "UPDATE_ITEM %s:%i %i %s\n", Type, ID, NewPrice, NewName);
2159 buf = ReadLine(Socket);
2160 responseCode = atoi(buf);
2162 switch(responseCode)
2165 printf("Item %s:%i updated\n", Type, ID);
2170 printf("Only coke members can modify the slots\n");
2171 ret = RV_PERMISSIONS;
2175 printf("Invalid item passed\n");
2180 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2193 char *ReadLine(int Socket)
2195 static char buf[BUFSIZ];
2196 static int bufPos = 0;
2197 static int bufValid = 0;
2199 char *newline = NULL;
2201 char *ret = malloc(10);
2203 #if DEBUG_TRACE_SERVER
2204 printf("ReadLine: ");
2216 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2219 return strdup("599 Client Connection Error\n");
2222 buf[bufPos+len] = '\0';
2224 newline = strchr( buf+bufPos, '\n' );
2229 retLen += strlen(buf+bufPos);
2230 ret = realloc(ret, retLen + 1);
2231 strcat( ret, buf+bufPos );
2234 int newLen = newline - (buf+bufPos) + 1;
2235 bufValid = len - newLen;
2238 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2241 #if DEBUG_TRACE_SERVER
2242 printf("%i '%s'\n", retLen, ret);
2248 int sendf(int Socket, const char *Format, ...)
2253 va_start(args, Format);
2254 len = vsnprintf(NULL, 0, Format, args);
2259 va_start(args, Format);
2260 vsnprintf(buf, len+1, Format, args);
2263 #if DEBUG_TRACE_SERVER
2264 printf("sendf: %s", buf);
2267 return send(Socket, buf, len, 0);
2271 char *trim(char *string)
2275 while( isspace(*string) )
2278 for( i = strlen(string); i--; )
2280 if( isspace(string[i]) )
2289 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2293 ret = regexec(regex, string, nMatches, matches, 0);
2294 if( ret && errorMessage ) {
2295 size_t len = regerror(ret, regex, NULL, 0);
2297 regerror(ret, regex, errorStr, len);
2298 printf("string = '%s'\n", string);
2299 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2306 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2308 int ret = regcomp(regex, pattern, flags);
2310 size_t len = regerror(ret, regex, NULL, 0);
2312 regerror(ret, regex, errorStr, len);
2313 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);