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 || strcmp(gsTextArgs[0], "enumitems") == 0 )
151 // " dispense enumitems\n"
152 // " List avaliable items\n"
154 if( giTextArgc == 0 )
155 printf(" == Coke members == \n");
156 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "acct") == 0 )
158 " dispense acct [<user>]\n"
159 " Show user balances\n"
160 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
161 " Alter a account value\n"
162 " dispense acct <user> =<ammount> \"<reason>\"\n"
163 " Set an account balance\n"
165 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "refund") == 0 )
167 " dispense refund <user> <itemid> [<price>]\n"
168 " Refund an item to a user (with optional price override)\n"
169 " Item IDs can be seen in the cokelog (in the brackets after the item name)\n"
170 " e.g. coke:6 for a coke, snack:33 for slot 33 of the snack machine\n"
172 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "slot") == 0 )
174 " dispense slot <itemid> <price> <name>\n"
175 " Rename/Re-price a slot\n"
177 if( giTextArgc == 0 )
178 printf(" == Dispense administrators ==\n");
179 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "user") == 0 )
181 " dispense user add <user>\n"
182 " Create new account\n"
183 " dispense user type <user> <flags> <reason>\n"
184 " Alter a user's flags\n"
185 " <flags> is a comma-separated list of user, coke, admin, internal or disabled\n"
186 " Flags are removed by preceding the name with '-' or '!'\n"
188 if( giTextArgc == 0 )
192 " Dispense multiple times\n"
194 " Set a different user (Coke members only)\n"
198 " Use simple textual interface (instead of ncurses)\n"
200 " Dry run - Do not actually do dispenses\n"
201 " -m <min balance>\n"
202 " -M <max balance>\n"
203 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
206 " 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"
212 int main(int argc, char *argv[])
220 // -- Create regular expressions
221 // > Code Type Count ...
222 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
223 // > Code Type Ident Status Price Desc
224 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);
225 // > Code 'SALT' salt
226 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
227 // > Code 'User' Username Balance Flags
228 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
230 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
233 for( i = 1; i < argc; i ++ )
247 if( i + 1 >= argc ) {
248 fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
252 giDispenseCount = atoi(argv[++i]);
253 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
254 fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
260 case 'm': // Minimum balance
261 if( i + 1 >= argc ) {
262 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
266 giMinimumBalance = atoi(argv[++i]);
268 case 'M': // Maximum balance
269 if( i + 1 >= argc ) {
270 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
274 giMaximumBalance = atoi(argv[++i]);
277 case 'u': // Override User
278 if( i + 1 >= argc ) {
279 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
283 gsEffectiveUser = argv[++i];
286 case 'H': // Override remote host
287 if( i + 1 >= argc ) {
288 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
292 gsDispenseServer = argv[++i];
294 case 'P': // Override remote port
295 if( i + 1 >= argc ) {
296 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
300 giDispensePort = atoi(argv[++i]);
303 // Set slot name/price
305 if( giTextArgc != 0 ) {
306 fprintf(stderr, "%s: -s must appear before other arguments\n", argv[0]);
310 gsTextArgs[0] = "slot"; // HACK!!
314 case 'G': // Don't use GUI
315 giUIMode = UI_MODE_BASIC;
317 case 'D': // Drinks only
318 giUIMode = UI_MODE_DRINKSONLY;
320 case 'n': // Dry Run / read-only
324 if( strcmp(argv[i], "--help") == 0 ) {
329 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
335 // The first argument is not allowed to begin with 'i'
336 // (catches most bad flags)
337 if( giTextArgc == 0 ) {
338 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
342 if( giTextArgc == MAX_TXT_ARGS )
344 fprintf(stderr, "ERROR: Too many arguments\n");
347 gsTextArgs[giTextArgc++] = argv[i];
354 if( giTextArgc == MAX_TXT_ARGS )
356 fprintf(stderr, "ERROR: Too many arguments\n");
360 gsTextArgs[giTextArgc++] = argv[i];
367 if( strcmp(gsTextArgs[0], "acct") == 0 )
370 sock = OpenConnection(gsDispenseServer, giDispensePort);
371 if( sock < 0 ) return RV_SOCKET_ERROR;
373 if( giTextArgc == 1 ) {
374 ret = Dispense_EnumUsers(sock);
379 // gsTextArgs[1]: Username
382 if( giTextArgc != 2 )
384 if( giTextArgc != 4 ) {
385 fprintf(stderr, "`dispense acct` requires a reason\n");
390 // Authentication required
391 ret = Authenticate(sock);
394 // gsTextArgs[1]: Username
395 // gsTextArgs[2]: Ammount
396 // gsTextArgs[3]: Reason
398 if( gsTextArgs[2][0] == '=' ) {
400 if( gsTextArgs[2][1] != '0' && atoi(gsTextArgs[2]+1) == 0 ) {
401 fprintf(stderr, "Error: Invalid balance to be set\n");
405 ret = Dispense_SetBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]+1), gsTextArgs[3]);
409 ret = Dispense_AlterBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
418 // Show user information
419 ret = Dispense_ShowUser(sock, gsTextArgs[1]);
426 // - "Here, have some money."
427 else if( strcmp(gsTextArgs[0], "give") == 0 )
429 if( giTextArgc != 4 ) {
430 fprintf(stderr, "`dispense give` takes three arguments\n");
435 // gsTextArgs[1]: Destination
436 // gsTextArgs[2]: Ammount
437 // gsTextArgs[3]: Reason
440 sock = OpenConnection(gsDispenseServer, giDispensePort);
441 if( sock < 0 ) return RV_SOCKET_ERROR;
444 ret = Authenticate(sock);
447 ret = Dispense_Give(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
455 // - User administration (Admin Only)
456 if( strcmp(gsTextArgs[0], "user") == 0 )
458 // Check argument count
459 if( giTextArgc == 1 ) {
460 fprintf(stderr, "Error: `dispense user` requires arguments\n");
466 sock = OpenConnection(gsDispenseServer, giDispensePort);
467 if( sock < 0 ) return RV_SOCKET_ERROR;
469 // Attempt authentication
470 ret = Authenticate(sock);
474 if( strcmp(gsTextArgs[1], "add") == 0 )
476 if( giTextArgc != 3 ) {
477 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
482 ret = Dispense_AddUser(sock, gsTextArgs[2]);
485 else if( strcmp(gsTextArgs[1], "type") == 0 || strcmp(gsTextArgs[1], "flags") == 0 )
487 if( giTextArgc < 4 || giTextArgc > 5 ) {
488 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
493 if( giTextArgc == 4 )
494 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], "");
496 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], gsTextArgs[4]);
500 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
508 else if( strcmp(gsTextArgs[0], "donate") == 0 )
510 // Check argument count
511 if( giTextArgc != 3 ) {
512 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
518 sock = OpenConnection(gsDispenseServer, giDispensePort);
519 if( sock < 0 ) return RV_SOCKET_ERROR;
521 // Attempt authentication
522 ret = Authenticate(sock);
526 ret = Dispense_Donate(sock, atoi(gsTextArgs[1]), gsTextArgs[2]);
533 else if( strcmp(gsTextArgs[0], "refund") == 0 )
536 // Check argument count
537 if( giTextArgc != 3 && giTextArgc != 4 ) {
538 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
544 sock = OpenConnection(gsDispenseServer, giDispensePort);
545 if(sock < 0) return RV_SOCKET_ERROR;
547 // Attempt authentication
548 ret = Authenticate(sock);
551 if( giTextArgc == 4 ) {
552 price = atoi(gsTextArgs[3]);
554 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
559 // Username, Item, cost
560 ret = Dispense_Refund(sock, gsTextArgs[1], gsTextArgs[2], price);
566 // Query an item price
567 else if( strcmp(gsTextArgs[0], "iteminfo") == 0 )
569 regmatch_t matches[3];
572 // Check argument count
573 if( giTextArgc != 2 ) {
574 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
579 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
580 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
583 type = gsTextArgs[1] + matches[1].rm_so;
584 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
585 id = atoi( gsTextArgs[1] + matches[2].rm_so );
587 sock = OpenConnection(gsDispenseServer, giDispensePort);
588 if( sock < 0 ) return RV_SOCKET_ERROR;
590 ret = Dispense_ItemInfo(sock, type, id);
595 else if( strcmp(gsTextArgs[0], "slot") == 0 )
597 regmatch_t matches[3];
598 char *item_type, *newname;
602 if( giTextArgc != 4 ) {
603 fprintf(stderr, "Error: `dispense slot` takes three arguments\n");
609 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
610 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
613 item_type = gsTextArgs[1] + matches[1].rm_so;
614 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
615 item_id = atoi( gsTextArgs[1] + matches[2].rm_so );
618 price = atoi( gsTextArgs[2] );
619 if( price <= 0 && gsTextArgs[2][0] != '0' ) {
620 fprintf(stderr, "Error: Invalid price passed (must be >= 0)\n");
625 newname = gsTextArgs[3];
629 for( pos = newname; *pos; pos ++ )
631 if( !isalnum(*pos) && *pos != ' ' ) {
632 fprintf(stderr, "Error: You should only have letters, numbers and spaces in an item name\n");
638 // Connect & Authenticate
639 sock = OpenConnection(gsDispenseServer, giDispensePort);
640 if( sock < 0 ) return RV_SOCKET_ERROR;
641 ret = Authenticate(sock);
644 ret = Dispense_SetItem(sock, item_type, item_id, price, newname);
649 // Item name / pattern
652 gsItemPattern = gsTextArgs[0];
656 sock = OpenConnection(gsDispenseServer, giDispensePort);
657 if( sock < 0 ) return RV_SOCKET_ERROR;
659 // Get the user's balance
660 ret = GetUserBalance(sock);
664 PopulateItemList(sock);
666 // Disconnect from server
669 if( gsItemPattern && gsItemPattern[0] )
671 regmatch_t matches[3];
673 if( strcmp(gsItemPattern, "door") == 0 )
675 // Connect, Authenticate, dispense and close
676 sock = OpenConnection(gsDispenseServer, giDispensePort);
677 if( sock < 0 ) return RV_SOCKET_ERROR;
678 ret = Authenticate(sock);
680 ret = DispenseItem(sock, "door", 0);
684 // Item id (<type>:<num>)
685 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
690 // Get and finish ident
691 ident = gsItemPattern + matches[1].rm_so;
692 gsItemPattern[matches[1].rm_eo] = '\0';
694 id = atoi( gsItemPattern + matches[2].rm_so );
696 // Connect, Authenticate, dispense and close
697 sock = OpenConnection(gsDispenseServer, giDispensePort);
698 if( sock < 0 ) return RV_SOCKET_ERROR;
700 Dispense_ItemInfo(sock, ident, id);
702 ret = Authenticate(sock);
704 ret = DispenseItem(sock, ident, id);
708 // Item number (6 = coke)
709 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
711 i = atoi(gsItemPattern);
718 for( i = 0; i < giNumItems; i ++ )
720 // Prefix match (with case-insensitive match)
721 for( j = 0; gsItemPattern[j]; j ++ )
723 if( gaItems[i].Desc[j] == gsItemPattern[j] )
725 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
729 // Check if the prefix matched
730 if( gsItemPattern[j] != '\0' )
734 if( gaItems[i].Desc[j] == '\0' ) {
739 // Only one match allowed
744 // TODO: Allow ambiguous matches?
745 // or just print a wanrning
746 printf("Warning - Ambiguous pattern, stopping\n");
751 // Was a match found?
754 fprintf(stderr, "No item matches the passed string\n");
761 else if( giUIMode != UI_MODE_BASIC )
767 // Very basic dispense interface
768 for( i = 0; i < giNumItems; i ++ ) {
770 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
773 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
774 gaItems[i].Price, gaItems[i].Desc);
783 fgets(buffer, BUFSIZ, stdin);
787 if( buf[0] == 'q' ) break;
791 if( i != 0 || buf[0] == '0' )
793 if( i < 0 || i >= giNumItems ) {
794 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
803 // Check for a valid item ID
807 // Connect, Authenticate, dispense and close
808 sock = OpenConnection(gsDispenseServer, giDispensePort);
809 if( sock < 0 ) return RV_SOCKET_ERROR;
811 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
814 ret = Authenticate(sock);
817 for( j = 0; j < giDispenseCount; j ++ ) {
818 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
822 printf("%i items dispensed\n", j);
824 Dispense_ShowUser(sock, gsUserName);
832 // -------------------
833 // --- NCurses GUI ---
834 // -------------------
836 * \brief Render the NCurses UI
838 int ShowNCursesUI(void)
843 const int displayMinWidth = 40;
844 char *titleString = "Dispense";
849 int ret = -2; // -2: Used for marking "no return yet"
851 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
858 if( gsEffectiveUser )
859 username = gsEffectiveUser;
861 pwd = getpwuid( getuid() );
862 username = pwd->pw_name;
865 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
872 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
873 // Get item count per screen
874 // - 6: randomly chosen (Need at least 3)
875 itemCount = LINES - 6;
876 if( itemCount > maxItemIndex )
877 itemCount = maxItemIndex;
880 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
885 height = itemCount + 3;
886 width = displayMinWidth;
889 xBase = COLS/2 - width/2;
890 yBase = LINES/2 - height/2;
895 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
898 for( i = 0; i < itemCount; i ++ )
902 move( yBase + 1 + i, xBase );
907 // Check for the '...' row
908 // - Oh god, magic numbers!
909 if( (i == 0 && itemBase > 0)
910 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
912 printw(" ..."); pos += 8;
913 times = (width - pos) - 1;
914 while(times--) addch(' ');
919 yBase + 1 + i, xBase + pos, // Position
920 (width - pos) - 3, // Width
921 itemBase + i, // Index
922 !!(currentItem == itemBase + i) // Hilighted
927 // Scrollbar (if needed)
928 if( maxItemIndex > itemCount ) {
932 else if( i == itemCount - 1 ) {
936 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
937 if( i-1 == percentage*(itemCount-3)/100 ) {
951 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
954 // - Username, balance, flags
955 PrintAlign(yBase+height-1, xBase+1, width-2,
956 username, ' ', balance_str, ' ', gsUserFlags);
972 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
975 if( currentItem >= maxItemIndex ) {
978 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
985 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
988 if( currentItem < 0 ) {
989 currentItem = maxItemIndex - 1;
991 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
1001 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
1002 itemBase = currentItem - 2;
1003 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
1004 itemBase = currentItem - itemCount + 2;
1010 ret = ShowItemAt(0, 0, 0, currentItem, 0);
1012 case 0x1b: // Escape
1014 ret = -1; // -1: Return with no dispense
1018 // Check if the return value was changed
1019 if( ret != -2 ) break;
1031 * \brief Show item \a Index at (\a Col, \a Row)
1032 * \return Dispense index of item
1033 * \note Part of the NCurses UI
1035 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
1045 // - This assumes that
1046 case UI_MODE_STANDARD:
1048 // Index = -1, request limit
1049 if( Index < 0 || Index >= giNumItems+2 )
1050 return giNumItems+2;
1055 name = "Coke Machine";
1056 Index = -1; // -1 indicates a label
1063 name = gaItems[Index].Desc;
1064 price = gaItems[Index].Price;
1065 status = gaItems[Index].Status;
1073 name = "Electronic Payment System";
1074 Index = -1; // -1 indicates a label
1079 name = gaItems[Index].Desc;
1080 price = gaItems[Index].Price;
1081 status = gaItems[Index].Status;
1087 // Width = 0, don't print
1090 // 4 preceding, 5 price
1091 int nameWidth = Width - 4 - 5;
1096 // Show hilight and status
1115 printw("%-*.*s", nameWidth, nameWidth, name);
1117 // getyx(stdscr, _y, _x);
1118 // Assumes max 4 digit prices
1119 // times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
1120 // while(times--) addch(' ');
1122 printw(" %4i", price);
1126 printw("-- %s", name);
1127 getyx(stdscr, _y, _x);
1128 times = Width - 4 - (_x - Col);
1129 while(times--) addch(' ');
1134 // If the item isn't availiable for sale, return -1 (so it's skipped)
1135 if( status || price > giUserBalance )
1142 * \brief Print a three-part string at the specified position (formatted)
1143 * \note NCurses UI Helper
1145 * Prints \a Left on the left of the area, \a Right on the righthand side
1146 * and \a Mid in the middle of the area. These are padded with \a Pad1
1147 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1149 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1150 * and the arguments to these are read in that order.
1152 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1153 const char *Mid, char Pad2, const char *Right, ...)
1155 int lLen, mLen, rLen;
1160 // Get the length of the strings
1161 va_start(args, Right);
1162 lLen = vsnprintf(NULL, 0, Left, args);
1163 mLen = vsnprintf(NULL, 0, Mid, args);
1164 rLen = vsnprintf(NULL, 0, Right, args);
1168 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1169 return ; // TODO: What to do?
1175 va_start(args, Right);
1179 vsnprintf(tmp, lLen+1, Left, args);
1183 times = (Width - mLen)/2 - lLen;
1184 while(times--) addch(Pad1);
1188 vsnprintf(tmp, mLen+1, Mid, args);
1192 times = (Width - mLen)/2 - rLen;
1193 if( (Width - mLen) % 2 ) times ++;
1194 while(times--) addch(Pad2);
1198 vsnprintf(tmp, rLen+1, Right, args);
1203 // ---------------------
1204 // --- Coke Protocol ---
1205 // ---------------------
1206 int OpenConnection(const char *Host, int Port)
1208 struct hostent *host;
1209 struct sockaddr_in serverAddr;
1212 host = gethostbyname(Host);
1214 fprintf(stderr, "Unable to look up '%s'\n", Host);
1218 memset(&serverAddr, 0, sizeof(serverAddr));
1220 serverAddr.sin_family = AF_INET; // IPv4
1221 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1222 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1223 serverAddr.sin_port = htons(Port);
1225 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1227 fprintf(stderr, "Failed to create socket\n");
1231 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1233 if( geteuid() == 0 || getuid() == 0 )
1236 struct sockaddr_in localAddr;
1237 memset(&localAddr, 0, sizeof(localAddr));
1238 localAddr.sin_family = AF_INET; // IPv4
1240 // Loop through all the top ports until one is avaliable
1241 for( i = 512; i < 1024; i ++)
1243 localAddr.sin_port = htons(i); // IPv4
1244 // Attempt to bind to low port for autoauth
1245 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1249 printf("Warning: AUTOAUTH unavaliable\n");
1251 // printf("Bound to 0.0.0.0:%i\n", i);
1254 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1255 fprintf(stderr, "Failed to connect to server\n");
1259 // We're not authenticated if the connection has just opened
1260 gbIsAuthenticated = 0;
1266 * \brief Authenticate with the server
1267 * \return Boolean Failure
1269 int Authenticate(int Socket)
1274 #if ATTEMPT_PASSWORD_AUTH
1277 regmatch_t matches[4];
1280 if( gbIsAuthenticated ) return 0;
1283 pwd = getpwuid( getuid() );
1285 // Attempt automatic authentication
1286 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1288 // Check if it worked
1289 buf = ReadLine(Socket);
1291 responseCode = atoi(buf);
1292 switch( responseCode )
1294 case 200: // Autoauth succeeded, return
1298 case 401: // Untrusted, attempt password authentication
1301 #if ATTEMPT_PASSWORD_AUTH
1302 sendf(Socket, "USER %s\n", pwd->pw_name);
1303 printf("Using username %s\n", pwd->pw_name);
1305 buf = ReadLine(Socket);
1308 // Expected format: 100 SALT <something> ...
1309 // OR : 100 User Set
1310 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1311 responseCode = atoi(buf);
1312 if( responseCode != 100 ) {
1313 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1315 return RV_UNKNOWN_ERROR; // ERROR
1319 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1320 // Store it for later
1321 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1322 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1326 // Give three attempts
1327 for( i = 0; i < 3; i ++ )
1329 int ofs = strlen(pwd->pw_name)+strlen(salt);
1332 char *pass = getpass("Password: ");
1335 // Create hash string
1336 // <username><salt><hash>
1337 strcpy(tmp, pwd->pw_name);
1339 SHA1( (unsigned char*)pass, strlen(pass), h );
1340 memcpy(tmp+ofs, h, 20);
1343 SHA1( (unsigned char*)tmp, ofs+20, h );
1344 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1345 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1346 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1350 sendf(Socket, "PASS %s\n", tmpBuf);
1351 buf = ReadLine(Socket);
1353 responseCode = atoi(buf);
1355 if( responseCode == 200 ) break;
1356 // Bad username/password
1357 if( responseCode == 401 ) continue;
1359 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1361 return RV_UNKNOWN_ERROR;
1365 return RV_INVALID_USER; // 2 = Bad Password
1368 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1369 return RV_INVALID_USER;
1373 case 404: // Bad Username
1374 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1376 return RV_INVALID_USER;
1379 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1380 printf("%s\n", buf);
1382 return RV_UNKNOWN_ERROR;
1385 // Set effective user
1386 if( gsEffectiveUser ) {
1387 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1389 buf = ReadLine(Socket);
1390 responseCode = atoi(buf);
1392 switch(responseCode)
1395 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1399 printf("Only coke members can use `dispense -u`\n");
1401 return RV_PERMISSIONS;
1404 printf("Invalid user selected\n");
1406 return RV_INVALID_USER;
1409 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1410 printf("%s\n", buf);
1412 return RV_UNKNOWN_ERROR;
1418 gbIsAuthenticated = 1;
1423 int GetUserBalance(int Socket)
1425 regmatch_t matches[6];
1432 if( gsEffectiveUser ) {
1433 gsUserName = gsEffectiveUser;
1436 pwd = getpwuid( getuid() );
1437 gsUserName = strdup(pwd->pw_name);
1441 sendf(Socket, "USER_INFO %s\n", gsUserName);
1442 buf = ReadLine(Socket);
1443 responseCode = atoi(buf);
1444 switch(responseCode)
1446 case 202: break; // Ok
1449 printf("Invalid user? (USER_INFO failed)\n");
1451 return RV_INVALID_USER;
1454 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1455 printf("%s\n", buf);
1457 return RV_UNKNOWN_ERROR;
1460 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1462 giUserBalance = atoi( buf + matches[4].rm_so );
1463 gsUserFlags = strdup( buf + matches[5].rm_so );
1471 * \brief Read an item info response from the server
1472 * \param Dest Destination for the read item (strings will be on the heap)
1474 int ReadItemInfo(int Socket, tItem *Dest)
1479 regmatch_t matches[8];
1483 buf = ReadLine(Socket);
1484 responseCode = atoi(buf);
1486 switch(responseCode)
1491 printf("Bad item name\n");
1496 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1498 return RV_UNKNOWN_ERROR;
1501 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1503 buf[ matches[3].rm_eo ] = '\0';
1504 buf[ matches[5].rm_eo ] = '\0';
1505 buf[ matches[7].rm_eo ] = '\0';
1507 statusStr = &buf[ matches[5].rm_so ];
1509 Dest->ID = atoi( buf + matches[4].rm_so );
1511 if( strcmp(statusStr, "avail") == 0 )
1513 else if( strcmp(statusStr, "sold") == 0 )
1515 else if( strcmp(statusStr, "error") == 0 )
1518 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1520 return RV_UNKNOWN_ERROR;
1522 Dest->Price = atoi( buf + matches[6].rm_so );
1524 // Hack a little to reduce heap fragmentation
1526 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1527 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1528 strcpy(tmpType, buf + matches[3].rm_so);
1529 strcpy(tmpDesc, buf + matches[7].rm_so);
1531 Dest->Type = strdup( tmpType );
1532 Dest->Desc = strdup( tmpDesc );
1539 * \brief Fill the item information structure
1540 * \return Boolean Failure
1542 void PopulateItemList(int Socket)
1549 regmatch_t matches[4];
1551 // Ask server for stock list
1552 send(Socket, "ENUM_ITEMS\n", 11, 0);
1553 buf = ReadLine(Socket);
1555 //printf("Output: %s\n", buf);
1557 responseCode = atoi(buf);
1558 if( responseCode != 201 ) {
1559 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1560 exit(RV_UNKNOWN_ERROR);
1563 // - Get item list -
1566 // 201 Items <count>
1568 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1570 arrayType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1571 count = atoi( &buf[ matches[3].rm_so ] );
1574 if( strcmp(arrayType, "Items") != 0 ) {
1576 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1578 exit(RV_UNKNOWN_ERROR);
1583 gaItems = malloc( giNumItems * sizeof(tItem) );
1585 // Fetch item information
1586 for( i = 0; i < giNumItems; i ++ )
1588 ReadItemInfo( Socket, &gaItems[i] );
1592 buf = ReadLine(Socket);
1593 responseCode = atoi(buf);
1595 if( responseCode != 200 ) {
1596 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1607 * \brief Get information on an item
1608 * \return Boolean Failure
1610 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1616 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1618 ret = ReadItemInfo(Socket, &item);
1621 printf("%8s:%-2i %2i.%02i %s\n",
1623 item.Price/100, item.Price%100,
1633 * \brief Dispense an item
1634 * \return Boolean Failure
1636 int DispenseItem(int Socket, const char *Type, int ID)
1638 int ret, responseCode;
1641 // Check for a dry run
1643 printf("Dry Run - No action\n");
1648 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1649 buf = ReadLine(Socket);
1651 responseCode = atoi(buf);
1652 switch( responseCode )
1655 printf("Dispense OK\n");
1659 printf("Not authenticated\n");
1660 ret = RV_PERMISSIONS;
1663 printf("Insufficient balance\n");
1667 printf("Bad item name\n");
1671 printf("Item failed to dispense, is the slot empty?\n");
1672 ret = RV_SERVER_ERROR;
1675 printf("Dispense not possible (slot empty/permissions)\n");
1676 ret = RV_SERVER_ERROR;
1679 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1680 ret = RV_UNKNOWN_ERROR;
1689 * \brief Alter a user's balance
1691 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1694 int responseCode, rv = -1;
1696 // Check for a dry run
1698 printf("Dry Run - No action\n");
1703 if( Ammount == 0 ) {
1704 printf("An ammount would be nice\n");
1705 return RV_ARGUMENTS;
1708 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1709 buf = ReadLine(Socket);
1711 responseCode = atoi(buf);
1713 switch(responseCode)
1719 fprintf(stderr, "Insufficient balance\n");
1722 case 403: // Not in coke
1723 fprintf(stderr, "You are not in coke (sucker)\n");
1724 rv = RV_PERMISSIONS;
1726 case 404: // Unknown user
1727 fprintf(stderr, "Unknown user '%s'\n", Username);
1728 rv = RV_INVALID_USER;
1731 fprintf(stderr, "Unknown response code %i\n'%s'\n", responseCode, buf);
1732 rv = RV_UNKNOWN_RESPONSE;
1741 * \brief Set a user's balance
1742 * \note Only avaliable to dispense admins
1744 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1749 // Check for a dry run
1751 printf("Dry Run - No action\n");
1755 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1756 buf = ReadLine(Socket);
1758 responseCode = atoi(buf);
1761 switch(responseCode)
1763 case 200: return 0; // OK
1764 case 403: // Not in coke
1765 fprintf(stderr, "You are not an admin\n");
1766 return RV_PERMISSIONS;
1767 case 404: // Unknown user
1768 fprintf(stderr, "Unknown user '%s'\n", Username);
1769 return RV_INVALID_USER;
1771 fprintf(stderr, "Unknown response code %i\n", responseCode);
1772 return RV_UNKNOWN_RESPONSE;
1779 * \brief Give money to another user
1781 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1787 printf("Sorry, you can only give, you can't take.\n");
1788 return RV_ARGUMENTS;
1791 // Fast return on zero
1792 if( Ammount == 0 ) {
1793 printf("Are you actually going to give any?\n");
1794 return RV_ARGUMENTS;
1797 // Check for a dry run
1799 printf("Dry Run - No action\n");
1803 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1805 buf = ReadLine(Socket);
1806 responseCode = atoi(buf);
1808 switch(responseCode)
1811 printf("Give succeeded\n");
1812 return RV_SUCCESS; // OK
1815 fprintf(stderr, "Insufficient balance\n");
1818 case 404: // Unknown user
1819 fprintf(stderr, "Unknown user '%s'\n", Username);
1820 return RV_INVALID_USER;
1823 fprintf(stderr, "Unknown response code %i\n", responseCode);
1824 return RV_UNKNOWN_RESPONSE;
1830 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1833 int responseCode, ret = -1;
1836 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1838 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1839 return RV_ARGUMENTS;
1842 // Check username (quick)
1843 if( strchr(Username, ' ') || strchr(Username, '\n') )
1845 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1846 return RV_ARGUMENTS;
1850 sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1852 buf = ReadLine(Socket);
1853 responseCode = atoi(buf);
1854 switch(responseCode)
1857 Dispense_ShowUser(Socket, Username); // Show destination account
1861 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1862 ret = RV_PERMISSIONS;
1865 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1866 ret = RV_INVALID_USER;
1869 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1873 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1882 * \brief Donate money to the club
1884 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1890 printf("Sorry, you can only give, you can't take.\n");
1894 // Fast return on zero
1895 if( Ammount == 0 ) {
1896 printf("Are you actually going to give any?\n");
1900 // Check for a dry run
1902 printf("Dry Run - No action\n");
1906 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1907 buf = ReadLine(Socket);
1909 responseCode = atoi(buf);
1912 switch(responseCode)
1914 case 200: return 0; // OK
1917 fprintf(stderr, "Insufficient balance\n");
1921 fprintf(stderr, "Unknown response code %i\n", responseCode);
1929 * \brief Enumerate users
1931 int Dispense_EnumUsers(int Socket)
1936 regmatch_t matches[4];
1938 if( giMinimumBalance != INT_MIN ) {
1939 if( giMaximumBalance != INT_MAX ) {
1940 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1943 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1947 if( giMaximumBalance != INT_MAX ) {
1948 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1951 sendf(Socket, "ENUM_USERS\n");
1954 buf = ReadLine(Socket);
1955 responseCode = atoi(buf);
1957 switch(responseCode)
1959 case 201: break; // Ok, length follows
1962 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1967 // Get count (not actually used)
1968 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1969 nUsers = atoi( buf + matches[3].rm_so );
1970 printf("%i users returned\n", nUsers);
1975 // Read returned users
1977 buf = ReadLine(Socket);
1978 responseCode = atoi(buf);
1980 if( responseCode != 202 ) break;
1982 _PrintUserLine(buf);
1984 } while(responseCode == 202);
1986 // Check final response
1987 if( responseCode != 200 ) {
1988 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1998 int Dispense_ShowUser(int Socket, const char *Username)
2001 int responseCode, ret;
2003 sendf(Socket, "USER_INFO %s\n", Username);
2004 buf = ReadLine(Socket);
2006 responseCode = atoi(buf);
2008 switch(responseCode)
2011 _PrintUserLine(buf);
2016 printf("Unknown user '%s'\n", Username);
2021 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2031 void _PrintUserLine(const char *Line)
2033 regmatch_t matches[6];
2036 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
2041 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
2042 char username[usernameLen + 1];
2043 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
2044 char flags[flagsLen + 1];
2046 memcpy(username, Line + matches[3].rm_so, usernameLen);
2047 username[usernameLen] = '\0';
2048 memcpy(flags, Line + matches[5].rm_so, flagsLen);
2049 flags[flagsLen] = '\0';
2051 bal = atoi(Line + matches[4].rm_so);
2052 printf("%-15s: $%8.02f (%s)\n", username, ((float)bal)/100, flags);
2056 int Dispense_AddUser(int Socket, const char *Username)
2059 int responseCode, ret;
2061 // Check for a dry run
2063 printf("Dry Run - No action\n");
2067 sendf(Socket, "USER_ADD %s\n", Username);
2069 buf = ReadLine(Socket);
2070 responseCode = atoi(buf);
2072 switch(responseCode)
2075 printf("User '%s' added\n", Username);
2080 printf("Only wheel can add users\n");
2085 printf("User '%s' already exists\n", Username);
2090 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2100 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString, const char *Reason)
2103 int responseCode, ret;
2105 // Check for a dry run
2107 printf("Dry Run - No action\n");
2111 // TODO: Pre-validate the string
2113 sendf(Socket, "USER_FLAGS %s %s %s\n", Username, TypeString, Reason);
2115 buf = ReadLine(Socket);
2116 responseCode = atoi(buf);
2118 switch(responseCode)
2121 printf("User '%s' updated\n", Username);
2126 printf("Only dispense admins can modify users\n");
2127 ret = RV_PERMISSIONS;
2131 printf("User '%s' does not exist\n", Username);
2132 ret = RV_INVALID_USER;
2136 printf("Flag string is invalid\n");
2141 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2142 ret = RV_UNKNOWN_RESPONSE;
2151 int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName)
2154 int responseCode, ret;
2156 // Check for a dry run
2158 printf("Dry Run - No action\n");
2162 sendf(Socket, "UPDATE_ITEM %s:%i %i %s\n", Type, ID, NewPrice, NewName);
2164 buf = ReadLine(Socket);
2165 responseCode = atoi(buf);
2167 switch(responseCode)
2170 printf("Item %s:%i updated\n", Type, ID);
2175 printf("Only coke members can modify the slots\n");
2176 ret = RV_PERMISSIONS;
2180 printf("Invalid item passed\n");
2185 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2198 char *ReadLine(int Socket)
2200 static char buf[BUFSIZ];
2201 static int bufPos = 0;
2202 static int bufValid = 0;
2204 char *newline = NULL;
2206 char *ret = malloc(10);
2208 #if DEBUG_TRACE_SERVER
2209 printf("ReadLine: ");
2221 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2224 return strdup("599 Client Connection Error\n");
2227 buf[bufPos+len] = '\0';
2229 newline = strchr( buf+bufPos, '\n' );
2234 retLen += strlen(buf+bufPos);
2235 ret = realloc(ret, retLen + 1);
2236 strcat( ret, buf+bufPos );
2239 int newLen = newline - (buf+bufPos) + 1;
2240 bufValid = len - newLen;
2243 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2246 #if DEBUG_TRACE_SERVER
2247 printf("%i '%s'\n", retLen, ret);
2253 int sendf(int Socket, const char *Format, ...)
2258 va_start(args, Format);
2259 len = vsnprintf(NULL, 0, Format, args);
2264 va_start(args, Format);
2265 vsnprintf(buf, len+1, Format, args);
2268 #if DEBUG_TRACE_SERVER
2269 printf("sendf: %s", buf);
2272 return send(Socket, buf, len, 0);
2276 char *trim(char *string)
2280 while( isspace(*string) )
2283 for( i = strlen(string); i--; )
2285 if( isspace(string[i]) )
2294 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2298 ret = regexec(regex, string, nMatches, matches, 0);
2299 if( ret && errorMessage ) {
2300 size_t len = regerror(ret, regex, NULL, 0);
2302 regerror(ret, regex, errorStr, len);
2303 printf("string = '%s'\n", string);
2304 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2311 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2313 int ret = regcomp(regex, pattern, flags);
2315 size_t len = regerror(ret, regex, NULL, 0);
2317 regerror(ret, regex, errorStr, len);
2318 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);