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
111 int giUIMode = UI_MODE_STANDARD;
112 int gbDryRun = 0; //!< '-n' Read-only
113 int gbDisallowSelectWithoutBalance = 1; //!< Don't allow items to be hilighted if not affordable
115 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
116 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
118 char *gsUserName; //!< User that dispense will happen as
119 char *gsUserFlags; //!< User's flag set
120 int giUserBalance = -1; //!< User balance (set by Authenticate)
121 int giDispenseCount = 1; //!< Number of dispenses to do
123 char *gsTextArgs[MAX_TXT_ARGS];
129 printf( "Usage:\n" );
130 if( giTextArgc == 0 )
134 " Show interactive list\n"
135 " dispense <name>|<index>|<itemid>\n"
136 " Dispense named item (<name> matches if it is a unique prefix)\n"
138 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "give") == 0 )
140 " dispense give <user> <ammount> \"<reason>\"\n"
141 " Give money to another user\n"
144 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "donate") == 0 )
146 " dispense donate <ammount> \"<reason>\"\n"
147 " Donate to the club\n"
149 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "iteminfo") == 0 )
151 " dispense iteminfo <itemid>\n"
152 " Get the name and price for an item\n"
154 // if( giTextArgc == 0 || strcmp(gsTextArgs[0], "enumitems") == 0 )
156 // " dispense enumitems\n"
157 // " List avaliable items\n"
159 if( giTextArgc == 0 )
160 printf(" == Coke members == \n");
161 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "acct") == 0 )
163 " dispense acct [<user>]\n"
164 " Show user balances\n"
165 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
166 " Alter a account value\n"
167 " dispense acct <user> =<ammount> \"<reason>\"\n"
168 " Set an account balance\n"
170 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "refund") == 0 )
172 " dispense refund <user> <itemid> [<price>]\n"
173 " Refund an item to a user (with optional price override)\n"
174 " Item IDs can be seen in the cokelog (in the brackets after the item name)\n"
175 " e.g. coke:6 for a coke, snack:33 for slot 33 of the snack machine\n"
177 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "slot") == 0 )
179 " dispense slot <itemid> <price> <name>\n"
180 " Rename/Re-price a slot\n"
182 if( giTextArgc == 0 )
183 printf(" == Dispense administrators ==\n");
184 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "user") == 0 )
186 " dispense user add <user>\n"
187 " Create new account\n"
188 " dispense user type <user> <flags> <reason>\n"
189 " Alter a user's flags\n"
190 " <flags> is a comma-separated list of user, coke, admin, internal or disabled\n"
191 " Flags are removed by preceding the name with '-' or '!'\n"
193 if( giTextArgc == 0 )
197 " Dispense multiple times\n"
199 " Set a different user (Coke members only)\n"
203 " Use simple textual interface (instead of ncurses)\n"
205 " Dry run - Do not actually do dispenses\n"
206 " -m <min balance>\n"
207 " -M <max balance>\n"
208 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
211 " 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"
217 int main(int argc, char *argv[])
225 // -- Create regular expressions
226 // > Code Type Count ...
227 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
228 // > Code Type Ident Status Price Desc
229 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);
230 // > Code 'SALT' salt
231 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
232 // > Code 'User' Username Balance Flags
233 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
235 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
238 for( i = 1; i < argc; i ++ )
252 if( i + 1 >= argc ) {
253 fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
257 giDispenseCount = atoi(argv[++i]);
258 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
259 fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
265 case 'm': // Minimum balance
266 if( i + 1 >= argc ) {
267 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
271 giMinimumBalance = atoi(argv[++i]);
273 case 'M': // Maximum balance
274 if( i + 1 >= argc ) {
275 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
279 giMaximumBalance = atoi(argv[++i]);
282 case 'u': // Override User
283 if( i + 1 >= argc ) {
284 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
288 gsEffectiveUser = argv[++i];
291 case 'H': // Override remote host
292 if( i + 1 >= argc ) {
293 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
297 gsDispenseServer = argv[++i];
299 case 'P': // Override remote port
300 if( i + 1 >= argc ) {
301 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
305 giDispensePort = atoi(argv[++i]);
308 // Set slot name/price
310 if( giTextArgc != 0 ) {
311 fprintf(stderr, "%s: -s must appear before other arguments\n", argv[0]);
315 gsTextArgs[0] = "slot"; // HACK!!
319 case 'G': // Don't use GUI
320 giUIMode = UI_MODE_BASIC;
322 case 'D': // Drinks only
323 giUIMode = UI_MODE_DRINKSONLY;
325 case 'n': // Dry Run / read-only
329 if( strcmp(argv[i], "--help") == 0 ) {
333 else if( strcmp(argv[i], "--dry-run") == 0 ) {
336 else if( strcmp(argv[i], "--drinks-only") == 0 ) {
337 giUIMode = UI_MODE_DRINKSONLY;
339 else if( strcmp(argv[i], "--can-select-all") == 0 ) {
340 gbDisallowSelectWithoutBalance = 0;
343 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
349 // The first argument is not allowed to begin with 'i'
350 // (catches most bad flags)
351 if( giTextArgc == 0 ) {
352 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
356 if( giTextArgc == MAX_TXT_ARGS )
358 fprintf(stderr, "ERROR: Too many arguments\n");
361 gsTextArgs[giTextArgc++] = argv[i];
368 if( giTextArgc == MAX_TXT_ARGS )
370 fprintf(stderr, "ERROR: Too many arguments\n");
374 gsTextArgs[giTextArgc++] = argv[i];
381 if( strcmp(gsTextArgs[0], "acct") == 0 )
384 sock = OpenConnection(gsDispenseServer, giDispensePort);
385 if( sock < 0 ) return RV_SOCKET_ERROR;
387 if( giTextArgc == 1 ) {
388 ret = Dispense_EnumUsers(sock);
393 // gsTextArgs[1]: Username
396 if( giTextArgc != 2 )
398 if( giTextArgc != 4 ) {
399 fprintf(stderr, "`dispense acct` requires a reason\n");
404 // Authentication required
405 ret = Authenticate(sock);
408 // gsTextArgs[1]: Username
409 // gsTextArgs[2]: Ammount
410 // gsTextArgs[3]: Reason
412 if( gsTextArgs[2][0] == '=' ) {
414 if( gsTextArgs[2][1] != '0' && atoi(gsTextArgs[2]+1) == 0 ) {
415 fprintf(stderr, "Error: Invalid balance to be set\n");
419 ret = Dispense_SetBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]+1), gsTextArgs[3]);
423 ret = Dispense_AlterBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
432 // Show user information
433 ret = Dispense_ShowUser(sock, gsTextArgs[1]);
440 // - "Here, have some money."
441 else if( strcmp(gsTextArgs[0], "give") == 0 )
443 if( giTextArgc != 4 ) {
444 fprintf(stderr, "`dispense give` takes three arguments\n");
449 // gsTextArgs[1]: Destination
450 // gsTextArgs[2]: Ammount
451 // gsTextArgs[3]: Reason
454 sock = OpenConnection(gsDispenseServer, giDispensePort);
455 if( sock < 0 ) return RV_SOCKET_ERROR;
458 ret = Authenticate(sock);
461 ret = Dispense_Give(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
469 // - User administration (Admin Only)
470 if( strcmp(gsTextArgs[0], "user") == 0 )
472 // Check argument count
473 if( giTextArgc == 1 ) {
474 fprintf(stderr, "Error: `dispense user` requires arguments\n");
480 sock = OpenConnection(gsDispenseServer, giDispensePort);
481 if( sock < 0 ) return RV_SOCKET_ERROR;
483 // Attempt authentication
484 ret = Authenticate(sock);
488 if( strcmp(gsTextArgs[1], "add") == 0 )
490 if( giTextArgc != 3 ) {
491 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
496 ret = Dispense_AddUser(sock, gsTextArgs[2]);
499 else if( strcmp(gsTextArgs[1], "type") == 0 || strcmp(gsTextArgs[1], "flags") == 0 )
501 if( giTextArgc < 4 || giTextArgc > 5 ) {
502 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
507 if( giTextArgc == 4 )
508 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], "");
510 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], gsTextArgs[4]);
514 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
522 else if( strcmp(gsTextArgs[0], "donate") == 0 )
524 // Check argument count
525 if( giTextArgc != 3 ) {
526 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
532 sock = OpenConnection(gsDispenseServer, giDispensePort);
533 if( sock < 0 ) return RV_SOCKET_ERROR;
535 // Attempt authentication
536 ret = Authenticate(sock);
540 ret = Dispense_Donate(sock, atoi(gsTextArgs[1]), gsTextArgs[2]);
547 else if( strcmp(gsTextArgs[0], "refund") == 0 )
550 // Check argument count
551 if( giTextArgc != 3 && giTextArgc != 4 ) {
552 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
558 sock = OpenConnection(gsDispenseServer, giDispensePort);
559 if(sock < 0) return RV_SOCKET_ERROR;
561 // Attempt authentication
562 ret = Authenticate(sock);
565 if( giTextArgc == 4 ) {
566 price = atoi(gsTextArgs[3]);
568 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
573 // Username, Item, cost
574 ret = Dispense_Refund(sock, gsTextArgs[1], gsTextArgs[2], price);
580 // Query an item price
581 else if( strcmp(gsTextArgs[0], "iteminfo") == 0 )
583 regmatch_t matches[3];
586 // Check argument count
587 if( giTextArgc != 2 ) {
588 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
593 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
594 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
597 type = gsTextArgs[1] + matches[1].rm_so;
598 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
599 id = atoi( gsTextArgs[1] + matches[2].rm_so );
601 sock = OpenConnection(gsDispenseServer, giDispensePort);
602 if( sock < 0 ) return RV_SOCKET_ERROR;
604 ret = Dispense_ItemInfo(sock, type, id);
609 else if( strcmp(gsTextArgs[0], "slot") == 0 )
611 regmatch_t matches[3];
612 char *item_type, *newname;
616 if( giTextArgc != 4 ) {
617 fprintf(stderr, "Error: `dispense slot` takes three arguments\n");
623 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
624 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
627 item_type = gsTextArgs[1] + matches[1].rm_so;
628 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
629 item_id = atoi( gsTextArgs[1] + matches[2].rm_so );
632 price = atoi( gsTextArgs[2] );
633 if( price <= 0 && gsTextArgs[2][0] != '0' ) {
634 fprintf(stderr, "Error: Invalid price passed (must be >= 0)\n");
639 newname = gsTextArgs[3];
643 for( pos = newname; *pos; pos ++ )
645 if( !isalnum(*pos) && *pos != ' ' ) {
646 fprintf(stderr, "Error: You should only have letters, numbers and spaces in an item name\n");
652 // Connect & Authenticate
653 sock = OpenConnection(gsDispenseServer, giDispensePort);
654 if( sock < 0 ) return RV_SOCKET_ERROR;
655 ret = Authenticate(sock);
658 ret = Dispense_SetItem(sock, item_type, item_id, price, newname);
663 // Item name / pattern
666 gsItemPattern = gsTextArgs[0];
670 sock = OpenConnection(gsDispenseServer, giDispensePort);
671 if( sock < 0 ) return RV_SOCKET_ERROR;
673 // Get the user's balance
674 ret = GetUserBalance(sock);
678 PopulateItemList(sock);
680 // Disconnect from server
683 if( gsItemPattern && gsItemPattern[0] )
685 regmatch_t matches[3];
687 if( strcmp(gsItemPattern, "door") == 0 )
689 // Connect, Authenticate, dispense and close
690 sock = OpenConnection(gsDispenseServer, giDispensePort);
691 if( sock < 0 ) return RV_SOCKET_ERROR;
692 ret = Authenticate(sock);
694 ret = DispenseItem(sock, "door", 0);
698 // Item id (<type>:<num>)
699 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
704 // Get and finish ident
705 ident = gsItemPattern + matches[1].rm_so;
706 gsItemPattern[matches[1].rm_eo] = '\0';
708 id = atoi( gsItemPattern + matches[2].rm_so );
710 // Connect, Authenticate, dispense and close
711 sock = OpenConnection(gsDispenseServer, giDispensePort);
712 if( sock < 0 ) return RV_SOCKET_ERROR;
714 Dispense_ItemInfo(sock, ident, id);
716 ret = Authenticate(sock);
718 ret = DispenseItem(sock, ident, id);
722 // Item number (6 = coke)
723 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
725 i = atoi(gsItemPattern);
732 for( i = 0; i < giNumItems; i ++ )
734 // Prefix match (with case-insensitive match)
735 for( j = 0; gsItemPattern[j]; j ++ )
737 if( gaItems[i].Desc[j] == gsItemPattern[j] )
739 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
743 // Check if the prefix matched
744 if( gsItemPattern[j] != '\0' )
748 if( gaItems[i].Desc[j] == '\0' ) {
753 // Only one match allowed
758 // TODO: Allow ambiguous matches?
759 // or just print a wanrning
760 printf("Warning - Ambiguous pattern, stopping\n");
765 // Was a match found?
768 fprintf(stderr, "No item matches the passed string\n");
775 else if( giUIMode != UI_MODE_BASIC )
781 // Very basic dispense interface
782 for( i = 0; i < giNumItems; i ++ ) {
784 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
787 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
788 gaItems[i].Price, gaItems[i].Desc);
797 fgets(buffer, BUFSIZ, stdin);
801 if( buf[0] == 'q' ) break;
805 if( i != 0 || buf[0] == '0' )
807 if( i < 0 || i >= giNumItems ) {
808 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
817 // Check for a valid item ID
821 // Connect, Authenticate, dispense and close
822 sock = OpenConnection(gsDispenseServer, giDispensePort);
823 if( sock < 0 ) return RV_SOCKET_ERROR;
825 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
828 ret = Authenticate(sock);
831 for( j = 0; j < giDispenseCount; j ++ ) {
832 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
836 printf("%i items dispensed\n", j);
838 Dispense_ShowUser(sock, gsUserName);
846 // -------------------
847 // --- NCurses GUI ---
848 // -------------------
850 * \brief Render the NCurses UI
852 int ShowNCursesUI(void)
857 const int displayMinWidth = 40;
858 char *titleString = "Dispense";
863 int ret = -2; // -2: Used for marking "no return yet"
865 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
872 if( gsEffectiveUser )
873 username = gsEffectiveUser;
875 pwd = getpwuid( getuid() );
876 username = pwd->pw_name;
879 snprintf(balance_str, sizeof(balance_str), "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
886 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
887 // Get item count per screen
888 // - 6: randomly chosen (Need at least 3)
889 items_in_view = LINES - 6;
890 if( items_in_view > maxItemIndex )
891 items_in_view = maxItemIndex;
894 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
899 height = items_in_view + 3;
900 width = displayMinWidth;
903 xBase = COLS/2 - width/2;
904 yBase = LINES/2 - height/2;
909 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
912 for( i = 0; i < items_in_view; i ++ )
916 move( yBase + 1 + i, xBase );
921 // Check for the '...' row
922 // - Oh god, magic numbers!
923 if( (i == 0 && itemBase > 0)
924 || (i == items_in_view - 1 && itemBase < maxItemIndex - items_in_view) )
926 printw(" ..."); pos += 8;
927 times = (width - pos) - 1;
928 while(times--) addch(' ');
933 yBase + 1 + i, xBase + pos, // Position
934 (width - pos) - 3, // Width
935 itemBase + i, // Index
936 !!(currentItem == itemBase + i) // Hilighted
941 // Scrollbar (if needed)
942 if( maxItemIndex > items_in_view ) {
946 else if( i == items_in_view - 1 ) {
950 int percentage = itemBase * 100 / (maxItemIndex-items_in_view);
951 if( i-1 == percentage*(items_in_view-3)/100 ) {
965 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
968 // - Username, balance, flags
969 PrintAlign(yBase+height-1, xBase+1, width-2,
970 username, ' ', balance_str, ' ', gsUserFlags);
986 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
989 if( currentItem >= maxItemIndex ) {
992 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
999 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
1002 if( currentItem < 0 ) {
1003 currentItem = maxItemIndex - 1;
1004 // Skip over spacers
1005 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
1015 // Scroll only if needed
1016 if( items_in_view < maxItemIndex )
1018 // - If the current item is above the second item shown, and we're not at the top
1019 if( currentItem < itemBase + 2 && itemBase > 0 ) {
1020 itemBase = currentItem - 2;
1021 if(itemBase < 0) itemBase = 0;
1023 // - If the current item is below the second item show, and we're not at the bottom
1024 if( currentItem > itemBase + items_in_view - 2 && itemBase + items_in_view < maxItemIndex ) {
1025 itemBase = currentItem - items_in_view + 2;
1026 if( itemBase > maxItemIndex - items_in_view )
1027 itemBase = maxItemIndex - items_in_view;
1035 ret = ShowItemAt(0, 0, 0, currentItem, 0);
1037 case 0x1b: // Escape
1039 ret = -1; // -1: Return with no dispense
1043 // Check if the return value was changed
1044 if( ret != -2 ) break;
1056 * \brief Show item \a Index at (\a Col, \a Row)
1057 * \return Dispense index of item
1058 * \note Part of the NCurses UI
1060 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
1069 // - This assumes that
1070 case UI_MODE_STANDARD:
1072 // Index = -1, request limit
1073 if( Index < 0 || Index >= giNumItems+2 )
1074 return giNumItems+2;
1079 name = "Coke Machine";
1080 Index = -1; // -1 indicates a label
1087 name = gaItems[Index].Desc;
1088 price = gaItems[Index].Price;
1089 status = gaItems[Index].Status;
1097 name = "Electronic Payment System";
1098 Index = -1; // -1 indicates a label
1103 name = gaItems[Index].Desc;
1104 price = gaItems[Index].Price;
1105 status = gaItems[Index].Status;
1111 // Width = 0, don't print
1114 // 4 preceding, 5 price
1115 int nameWidth = Width - 4 - 5;
1120 // Show hilight and status
1139 if( price > 100*100 ) {
1142 if( price > 1000*100 ) {
1146 printw("%-*.*s", nameWidth, nameWidth, name);
1148 // 99.99 should be enough
1149 printw(" %4i", price);
1153 printw("-- %-*.*s ", Width-4, Width-4, name);
1157 // If the item isn't availiable for sale, return -1 (so it's skipped)
1158 if( status || (price > giUserBalance && gbDisallowSelectWithoutBalance) )
1165 * \brief Print a three-part string at the specified position (formatted)
1166 * \note NCurses UI Helper
1168 * Prints \a Left on the left of the area, \a Right on the righthand side
1169 * and \a Mid in the middle of the area. These are padded with \a Pad1
1170 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1172 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1173 * and the arguments to these are read in that order.
1175 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1176 const char *Mid, char Pad2, const char *Right, ...)
1178 int lLen, mLen, rLen;
1183 // Get the length of the strings
1184 va_start(args, Right);
1185 lLen = vsnprintf(NULL, 0, Left, args);
1186 mLen = vsnprintf(NULL, 0, Mid, args);
1187 rLen = vsnprintf(NULL, 0, Right, args);
1191 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1192 return ; // TODO: What to do?
1198 va_start(args, Right);
1202 vsnprintf(tmp, lLen+1, Left, args);
1206 times = (Width - mLen)/2 - lLen;
1207 while(times--) addch(Pad1);
1211 vsnprintf(tmp, mLen+1, Mid, args);
1215 times = (Width - mLen)/2 - rLen;
1216 if( (Width - mLen) % 2 ) times ++;
1217 while(times--) addch(Pad2);
1221 vsnprintf(tmp, rLen+1, Right, args);
1226 // ---------------------
1227 // --- Coke Protocol ---
1228 // ---------------------
1229 int OpenConnection(const char *Host, int Port)
1231 struct hostent *host;
1232 struct sockaddr_in serverAddr;
1235 host = gethostbyname(Host);
1237 fprintf(stderr, "Unable to look up '%s'\n", Host);
1241 memset(&serverAddr, 0, sizeof(serverAddr));
1243 serverAddr.sin_family = AF_INET; // IPv4
1244 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1245 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1246 serverAddr.sin_port = htons(Port);
1248 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1250 fprintf(stderr, "Failed to create socket\n");
1254 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1256 if( geteuid() == 0 || getuid() == 0 )
1259 struct sockaddr_in localAddr;
1260 memset(&localAddr, 0, sizeof(localAddr));
1261 localAddr.sin_family = AF_INET; // IPv4
1263 // Loop through all the top ports until one is avaliable
1264 for( i = 512; i < 1024; i ++)
1266 localAddr.sin_port = htons(i); // IPv4
1267 // Attempt to bind to low port for autoauth
1268 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1272 printf("Warning: AUTOAUTH unavaliable\n");
1274 // printf("Bound to 0.0.0.0:%i\n", i);
1277 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1278 fprintf(stderr, "Failed to connect to server\n");
1282 // We're not authenticated if the connection has just opened
1283 gbIsAuthenticated = 0;
1289 * \brief Authenticate with the server
1290 * \return Boolean Failure
1292 int Authenticate(int Socket)
1297 #if ATTEMPT_PASSWORD_AUTH
1300 regmatch_t matches[4];
1303 if( gbIsAuthenticated ) return 0;
1306 pwd = getpwuid( getuid() );
1308 // Attempt automatic authentication
1309 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1311 // Check if it worked
1312 buf = ReadLine(Socket);
1314 responseCode = atoi(buf);
1315 switch( responseCode )
1317 case 200: // Autoauth succeeded, return
1321 case 401: // Untrusted, attempt password authentication
1324 #if ATTEMPT_PASSWORD_AUTH
1325 sendf(Socket, "USER %s\n", pwd->pw_name);
1326 printf("Using username %s\n", pwd->pw_name);
1328 buf = ReadLine(Socket);
1331 // Expected format: 100 SALT <something> ...
1332 // OR : 100 User Set
1333 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1334 responseCode = atoi(buf);
1335 if( responseCode != 100 ) {
1336 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1338 return RV_UNKNOWN_ERROR; // ERROR
1342 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1343 // Store it for later
1344 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1345 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1349 // Give three attempts
1350 for( i = 0; i < 3; i ++ )
1352 int ofs = strlen(pwd->pw_name)+strlen(salt);
1355 char *pass = getpass("Password: ");
1358 // Create hash string
1359 // <username><salt><hash>
1360 strcpy(tmp, pwd->pw_name);
1362 SHA1( (unsigned char*)pass, strlen(pass), h );
1363 memcpy(tmp+ofs, h, 20);
1366 SHA1( (unsigned char*)tmp, ofs+20, h );
1367 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1368 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1369 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1373 sendf(Socket, "PASS %s\n", tmpBuf);
1374 buf = ReadLine(Socket);
1376 responseCode = atoi(buf);
1378 if( responseCode == 200 ) break;
1379 // Bad username/password
1380 if( responseCode == 401 ) continue;
1382 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1384 return RV_UNKNOWN_ERROR;
1388 return RV_INVALID_USER; // 2 = Bad Password
1391 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1392 return RV_INVALID_USER;
1396 case 404: // Bad Username
1397 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1399 return RV_INVALID_USER;
1402 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1403 printf("%s\n", buf);
1405 return RV_UNKNOWN_ERROR;
1408 // Set effective user
1409 if( gsEffectiveUser ) {
1410 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1412 buf = ReadLine(Socket);
1413 responseCode = atoi(buf);
1415 switch(responseCode)
1418 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1422 printf("Only coke members can use `dispense -u`\n");
1424 return RV_PERMISSIONS;
1427 printf("Invalid user selected\n");
1429 return RV_INVALID_USER;
1432 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1433 printf("%s\n", buf);
1435 return RV_UNKNOWN_ERROR;
1441 gbIsAuthenticated = 1;
1446 int GetUserBalance(int Socket)
1448 regmatch_t matches[6];
1455 if( gsEffectiveUser ) {
1456 gsUserName = gsEffectiveUser;
1459 pwd = getpwuid( getuid() );
1460 gsUserName = strdup(pwd->pw_name);
1464 sendf(Socket, "USER_INFO %s\n", gsUserName);
1465 buf = ReadLine(Socket);
1466 responseCode = atoi(buf);
1467 switch(responseCode)
1469 case 202: break; // Ok
1472 printf("Invalid user? (USER_INFO failed)\n");
1474 return RV_INVALID_USER;
1477 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1478 printf("%s\n", buf);
1480 return RV_UNKNOWN_ERROR;
1483 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1485 giUserBalance = atoi( buf + matches[4].rm_so );
1486 gsUserFlags = strdup( buf + matches[5].rm_so );
1494 * \brief Read an item info response from the server
1495 * \param Dest Destination for the read item (strings will be on the heap)
1497 int ReadItemInfo(int Socket, tItem *Dest)
1502 regmatch_t matches[8];
1506 buf = ReadLine(Socket);
1507 responseCode = atoi(buf);
1509 switch(responseCode)
1514 printf("Bad item name\n");
1519 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1521 return RV_UNKNOWN_ERROR;
1524 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1526 buf[ matches[3].rm_eo ] = '\0';
1527 buf[ matches[5].rm_eo ] = '\0';
1528 buf[ matches[7].rm_eo ] = '\0';
1530 statusStr = &buf[ matches[5].rm_so ];
1532 Dest->ID = atoi( buf + matches[4].rm_so );
1534 if( strcmp(statusStr, "avail") == 0 )
1536 else if( strcmp(statusStr, "sold") == 0 )
1538 else if( strcmp(statusStr, "error") == 0 )
1541 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1543 return RV_UNKNOWN_ERROR;
1545 Dest->Price = atoi( buf + matches[6].rm_so );
1547 // Hack a little to reduce heap fragmentation
1549 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1550 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1551 strcpy(tmpType, buf + matches[3].rm_so);
1552 strcpy(tmpDesc, buf + matches[7].rm_so);
1554 Dest->Type = strdup( tmpType );
1555 Dest->Desc = strdup( tmpDesc );
1562 * \brief Fill the item information structure
1563 * \return Boolean Failure
1565 void PopulateItemList(int Socket)
1572 regmatch_t matches[4];
1574 // Ask server for stock list
1575 send(Socket, "ENUM_ITEMS\n", 11, 0);
1576 buf = ReadLine(Socket);
1578 //printf("Output: %s\n", buf);
1580 responseCode = atoi(buf);
1581 if( responseCode != 201 ) {
1582 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1583 exit(RV_UNKNOWN_ERROR);
1586 // - Get item list -
1589 // 201 Items <count>
1591 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1593 arrayType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1594 count = atoi( &buf[ matches[3].rm_so ] );
1597 if( strcmp(arrayType, "Items") != 0 ) {
1599 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1601 exit(RV_UNKNOWN_ERROR);
1606 gaItems = malloc( giNumItems * sizeof(tItem) );
1608 // Fetch item information
1609 for( i = 0; i < giNumItems; i ++ )
1611 ReadItemInfo( Socket, &gaItems[i] );
1615 buf = ReadLine(Socket);
1616 responseCode = atoi(buf);
1618 if( responseCode != 200 ) {
1619 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1630 * \brief Get information on an item
1631 * \return Boolean Failure
1633 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1639 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1641 ret = ReadItemInfo(Socket, &item);
1644 printf("%8s:%-2i %2i.%02i %s\n",
1646 item.Price/100, item.Price%100,
1656 * \brief Dispense an item
1657 * \return Boolean Failure
1659 int DispenseItem(int Socket, const char *Type, int ID)
1661 int ret, responseCode;
1664 // Check for a dry run
1666 printf("Dry Run - No action\n");
1671 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1672 buf = ReadLine(Socket);
1674 responseCode = atoi(buf);
1675 switch( responseCode )
1678 printf("Dispense OK\n");
1682 printf("Not authenticated\n");
1683 ret = RV_PERMISSIONS;
1686 printf("Insufficient balance\n");
1690 printf("Bad item name\n");
1694 printf("Item failed to dispense, is the slot empty?\n");
1695 ret = RV_SERVER_ERROR;
1698 printf("Dispense not possible (slot empty/permissions)\n");
1699 ret = RV_SERVER_ERROR;
1702 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1703 ret = RV_UNKNOWN_ERROR;
1712 * \brief Alter a user's balance
1714 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1717 int responseCode, rv = -1;
1719 // Check for a dry run
1721 printf("Dry Run - No action\n");
1726 if( Ammount == 0 ) {
1727 printf("An ammount would be nice\n");
1728 return RV_ARGUMENTS;
1731 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1732 buf = ReadLine(Socket);
1734 responseCode = atoi(buf);
1736 switch(responseCode)
1742 fprintf(stderr, "Insufficient balance\n");
1745 case 403: // Not in coke
1746 fprintf(stderr, "You are not in coke (sucker)\n");
1747 rv = RV_PERMISSIONS;
1749 case 404: // Unknown user
1750 fprintf(stderr, "Unknown user '%s'\n", Username);
1751 rv = RV_INVALID_USER;
1754 fprintf(stderr, "Unknown response code %i\n'%s'\n", responseCode, buf);
1755 rv = RV_UNKNOWN_RESPONSE;
1764 * \brief Set a user's balance
1765 * \note Only avaliable to dispense admins
1767 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1772 // Check for a dry run
1774 printf("Dry Run - No action\n");
1778 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1779 buf = ReadLine(Socket);
1781 responseCode = atoi(buf);
1784 switch(responseCode)
1786 case 200: return 0; // OK
1787 case 403: // Not in coke
1788 fprintf(stderr, "You are not an admin\n");
1789 return RV_PERMISSIONS;
1790 case 404: // Unknown user
1791 fprintf(stderr, "Unknown user '%s'\n", Username);
1792 return RV_INVALID_USER;
1794 fprintf(stderr, "Unknown response code %i\n", responseCode);
1795 return RV_UNKNOWN_RESPONSE;
1802 * \brief Give money to another user
1804 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1810 printf("Sorry, you can only give, you can't take.\n");
1811 return RV_ARGUMENTS;
1814 // Fast return on zero
1815 if( Ammount == 0 ) {
1816 printf("Are you actually going to give any?\n");
1817 return RV_ARGUMENTS;
1820 // Check for a dry run
1822 printf("Dry Run - No action\n");
1826 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1828 buf = ReadLine(Socket);
1829 responseCode = atoi(buf);
1831 switch(responseCode)
1834 printf("Give succeeded\n");
1835 return RV_SUCCESS; // OK
1838 fprintf(stderr, "Insufficient balance\n");
1841 case 404: // Unknown user
1842 fprintf(stderr, "Unknown user '%s'\n", Username);
1843 return RV_INVALID_USER;
1846 fprintf(stderr, "Unknown response code %i\n", responseCode);
1847 return RV_UNKNOWN_RESPONSE;
1853 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1856 int responseCode, ret = -1;
1859 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1861 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1862 return RV_ARGUMENTS;
1865 // Check username (quick)
1866 if( strchr(Username, ' ') || strchr(Username, '\n') )
1868 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1869 return RV_ARGUMENTS;
1873 sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1875 buf = ReadLine(Socket);
1876 responseCode = atoi(buf);
1877 switch(responseCode)
1880 Dispense_ShowUser(Socket, Username); // Show destination account
1884 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1885 ret = RV_PERMISSIONS;
1888 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1889 ret = RV_INVALID_USER;
1892 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1896 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1905 * \brief Donate money to the club
1907 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1913 printf("Sorry, you can only give, you can't take.\n");
1917 // Fast return on zero
1918 if( Ammount == 0 ) {
1919 printf("Are you actually going to give any?\n");
1923 // Check for a dry run
1925 printf("Dry Run - No action\n");
1929 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1930 buf = ReadLine(Socket);
1932 responseCode = atoi(buf);
1935 switch(responseCode)
1937 case 200: return 0; // OK
1940 fprintf(stderr, "Insufficient balance\n");
1944 fprintf(stderr, "Unknown response code %i\n", responseCode);
1952 * \brief Enumerate users
1954 int Dispense_EnumUsers(int Socket)
1959 regmatch_t matches[4];
1961 if( giMinimumBalance != INT_MIN ) {
1962 if( giMaximumBalance != INT_MAX ) {
1963 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1966 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1970 if( giMaximumBalance != INT_MAX ) {
1971 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1974 sendf(Socket, "ENUM_USERS\n");
1977 buf = ReadLine(Socket);
1978 responseCode = atoi(buf);
1980 switch(responseCode)
1982 case 201: break; // Ok, length follows
1985 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1990 // Get count (not actually used)
1991 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1992 nUsers = atoi( buf + matches[3].rm_so );
1993 printf("%i users returned\n", nUsers);
1998 // Read returned users
2000 buf = ReadLine(Socket);
2001 responseCode = atoi(buf);
2003 if( responseCode != 202 ) break;
2005 _PrintUserLine(buf);
2007 } while(responseCode == 202);
2009 // Check final response
2010 if( responseCode != 200 ) {
2011 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
2021 int Dispense_ShowUser(int Socket, const char *Username)
2024 int responseCode, ret;
2026 sendf(Socket, "USER_INFO %s\n", Username);
2027 buf = ReadLine(Socket);
2029 responseCode = atoi(buf);
2031 switch(responseCode)
2034 _PrintUserLine(buf);
2039 printf("Unknown user '%s'\n", Username);
2044 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2054 void _PrintUserLine(const char *Line)
2056 regmatch_t matches[6];
2059 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
2064 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
2065 char username[usernameLen + 1];
2066 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
2067 char flags[flagsLen + 1];
2069 memcpy(username, Line + matches[3].rm_so, usernameLen);
2070 username[usernameLen] = '\0';
2071 memcpy(flags, Line + matches[5].rm_so, flagsLen);
2072 flags[flagsLen] = '\0';
2074 bal = atoi(Line + matches[4].rm_so);
2075 printf("%-15s: $%8.02f (%s)\n", username, ((float)bal)/100, flags);
2079 int Dispense_AddUser(int Socket, const char *Username)
2082 int responseCode, ret;
2084 // Check for a dry run
2086 printf("Dry Run - No action\n");
2090 sendf(Socket, "USER_ADD %s\n", Username);
2092 buf = ReadLine(Socket);
2093 responseCode = atoi(buf);
2095 switch(responseCode)
2098 printf("User '%s' added\n", Username);
2103 printf("Only wheel can add users\n");
2108 printf("User '%s' already exists\n", Username);
2113 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2123 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString, const char *Reason)
2126 int responseCode, ret;
2128 // Check for a dry run
2130 printf("Dry Run - No action\n");
2134 // TODO: Pre-validate the string
2136 sendf(Socket, "USER_FLAGS %s %s %s\n", Username, TypeString, Reason);
2138 buf = ReadLine(Socket);
2139 responseCode = atoi(buf);
2141 switch(responseCode)
2144 printf("User '%s' updated\n", Username);
2149 printf("Only dispense admins can modify users\n");
2150 ret = RV_PERMISSIONS;
2154 printf("User '%s' does not exist\n", Username);
2155 ret = RV_INVALID_USER;
2159 printf("Flag string is invalid\n");
2164 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2165 ret = RV_UNKNOWN_RESPONSE;
2174 int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName)
2177 int responseCode, ret;
2179 // Check for a dry run
2181 printf("Dry Run - No action\n");
2185 sendf(Socket, "UPDATE_ITEM %s:%i %i %s\n", Type, ID, NewPrice, NewName);
2187 buf = ReadLine(Socket);
2188 responseCode = atoi(buf);
2190 switch(responseCode)
2193 printf("Item %s:%i updated\n", Type, ID);
2198 printf("Only coke members can modify the slots\n");
2199 ret = RV_PERMISSIONS;
2203 printf("Invalid item passed\n");
2208 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2221 char *ReadLine(int Socket)
2223 static char buf[BUFSIZ];
2224 static int bufPos = 0;
2225 static int bufValid = 0;
2227 char *newline = NULL;
2229 char *ret = malloc(10);
2231 #if DEBUG_TRACE_SERVER
2232 printf("ReadLine: ");
2244 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2247 return strdup("599 Client Connection Error\n");
2250 buf[bufPos+len] = '\0';
2252 newline = strchr( buf+bufPos, '\n' );
2257 retLen += strlen(buf+bufPos);
2258 ret = realloc(ret, retLen + 1);
2259 strcat( ret, buf+bufPos );
2262 int newLen = newline - (buf+bufPos) + 1;
2263 bufValid = len - newLen;
2266 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2269 #if DEBUG_TRACE_SERVER
2270 printf("%i '%s'\n", retLen, ret);
2276 int sendf(int Socket, const char *Format, ...)
2281 va_start(args, Format);
2282 len = vsnprintf(NULL, 0, Format, args);
2287 va_start(args, Format);
2288 vsnprintf(buf, len+1, Format, args);
2291 #if DEBUG_TRACE_SERVER
2292 printf("sendf: %s", buf);
2295 return send(Socket, buf, len, 0);
2299 char *trim(char *string)
2303 while( isspace(*string) )
2306 for( i = strlen(string); i--; )
2308 if( isspace(string[i]) )
2317 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2321 ret = regexec(regex, string, nMatches, matches, 0);
2322 if( ret && errorMessage ) {
2323 size_t len = regerror(ret, regex, NULL, 0);
2325 regerror(ret, regex, errorStr, len);
2326 printf("string = '%s'\n", string);
2327 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2334 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2336 int ret = regcomp(regex, pattern, flags);
2338 size_t len = regerror(ret, regex, NULL, 0);
2340 regerror(ret, regex, errorStr, len);
2341 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);