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> <amount> \"<reason>\"\n"
141 " Give money to another user\n"
144 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "donate") == 0 )
146 " dispense donate <amount> \"<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> [+-]<amount> \"<reason>\"\n"
166 " Alter a account value\n"
167 " dispense acct <user> =<amount> \"<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 = 50;
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 - snprintf(NULL, 0, " %4i", price);
1120 // Show hilight and status
1139 printw("%-*.*s", nameWidth, nameWidth, name);
1141 printw(" %4i", price);
1145 printw("-- %-*.*s ", Width-4, Width-4, name);
1149 // If the item isn't availiable for sale, return -1 (so it's skipped)
1150 if( status || (price > giUserBalance && gbDisallowSelectWithoutBalance) )
1157 * \brief Print a three-part string at the specified position (formatted)
1158 * \note NCurses UI Helper
1160 * Prints \a Left on the left of the area, \a Right on the righthand side
1161 * and \a Mid in the middle of the area. These are padded with \a Pad1
1162 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1164 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1165 * and the arguments to these are read in that order.
1167 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1168 const char *Mid, char Pad2, const char *Right, ...)
1170 int lLen, mLen, rLen;
1175 // Get the length of the strings
1176 va_start(args, Right);
1177 lLen = vsnprintf(NULL, 0, Left, args);
1178 mLen = vsnprintf(NULL, 0, Mid, args);
1179 rLen = vsnprintf(NULL, 0, Right, args);
1183 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1184 return ; // TODO: What to do?
1190 va_start(args, Right);
1194 vsnprintf(tmp, lLen+1, Left, args);
1198 times = (Width - mLen)/2 - lLen;
1199 while(times--) addch(Pad1);
1203 vsnprintf(tmp, mLen+1, Mid, args);
1207 times = (Width - mLen)/2 - rLen;
1208 if( (Width - mLen) % 2 ) times ++;
1209 while(times--) addch(Pad2);
1213 vsnprintf(tmp, rLen+1, Right, args);
1218 // ---------------------
1219 // --- Coke Protocol ---
1220 // ---------------------
1221 int OpenConnection(const char *Host, int Port)
1223 struct hostent *host;
1224 struct sockaddr_in serverAddr;
1227 host = gethostbyname(Host);
1229 fprintf(stderr, "Unable to look up '%s'\n", Host);
1233 memset(&serverAddr, 0, sizeof(serverAddr));
1235 serverAddr.sin_family = AF_INET; // IPv4
1236 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1237 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1238 serverAddr.sin_port = htons(Port);
1240 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1242 fprintf(stderr, "Failed to create socket\n");
1246 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1248 if( geteuid() == 0 || getuid() == 0 )
1251 struct sockaddr_in localAddr;
1252 memset(&localAddr, 0, sizeof(localAddr));
1253 localAddr.sin_family = AF_INET; // IPv4
1255 // Loop through all the top ports until one is avaliable
1256 for( i = 512; i < 1024; i ++)
1258 localAddr.sin_port = htons(i); // IPv4
1259 // Attempt to bind to low port for autoauth
1260 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1264 printf("Warning: AUTOAUTH unavaliable\n");
1266 // printf("Bound to 0.0.0.0:%i\n", i);
1269 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1270 fprintf(stderr, "Failed to connect to server\n");
1274 // We're not authenticated if the connection has just opened
1275 gbIsAuthenticated = 0;
1281 * \brief Authenticate with the server
1282 * \return Boolean Failure
1284 int Authenticate(int Socket)
1289 #if ATTEMPT_PASSWORD_AUTH
1292 regmatch_t matches[4];
1295 if( gbIsAuthenticated ) return 0;
1298 pwd = getpwuid( getuid() );
1300 // Attempt automatic authentication
1301 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1303 // Check if it worked
1304 buf = ReadLine(Socket);
1306 responseCode = atoi(buf);
1307 switch( responseCode )
1309 case 200: // Autoauth succeeded, return
1313 case 401: // Untrusted, attempt password authentication
1316 #if ATTEMPT_PASSWORD_AUTH
1317 sendf(Socket, "USER %s\n", pwd->pw_name);
1318 printf("Using username %s\n", pwd->pw_name);
1320 buf = ReadLine(Socket);
1323 // Expected format: 100 SALT <something> ...
1324 // OR : 100 User Set
1325 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1326 responseCode = atoi(buf);
1327 if( responseCode != 100 ) {
1328 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1330 return RV_UNKNOWN_ERROR; // ERROR
1334 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1335 // Store it for later
1336 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1337 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1341 // Give three attempts
1342 for( i = 0; i < 3; i ++ )
1344 int ofs = strlen(pwd->pw_name)+strlen(salt);
1347 char *pass = getpass("Password: ");
1350 // Create hash string
1351 // <username><salt><hash>
1352 strcpy(tmp, pwd->pw_name);
1354 SHA1( (unsigned char*)pass, strlen(pass), h );
1355 memcpy(tmp+ofs, h, 20);
1358 SHA1( (unsigned char*)tmp, ofs+20, h );
1359 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1360 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1361 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1365 sendf(Socket, "PASS %s\n", tmpBuf);
1366 buf = ReadLine(Socket);
1368 responseCode = atoi(buf);
1370 if( responseCode == 200 ) break;
1371 // Bad username/password
1372 if( responseCode == 401 ) continue;
1374 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1376 return RV_UNKNOWN_ERROR;
1380 return RV_INVALID_USER; // 2 = Bad Password
1383 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1384 return RV_INVALID_USER;
1388 case 404: // Bad Username
1389 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1391 return RV_INVALID_USER;
1394 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1395 printf("%s\n", buf);
1397 return RV_UNKNOWN_ERROR;
1400 // Set effective user
1401 if( gsEffectiveUser ) {
1402 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1404 buf = ReadLine(Socket);
1405 responseCode = atoi(buf);
1407 switch(responseCode)
1410 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1414 printf("Only coke members can use `dispense -u`\n");
1416 return RV_PERMISSIONS;
1419 printf("Invalid user selected\n");
1421 return RV_INVALID_USER;
1424 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1425 printf("%s\n", buf);
1427 return RV_UNKNOWN_ERROR;
1433 gbIsAuthenticated = 1;
1438 int GetUserBalance(int Socket)
1440 regmatch_t matches[6];
1447 if( gsEffectiveUser ) {
1448 gsUserName = gsEffectiveUser;
1451 pwd = getpwuid( getuid() );
1452 gsUserName = strdup(pwd->pw_name);
1456 sendf(Socket, "USER_INFO %s\n", gsUserName);
1457 buf = ReadLine(Socket);
1458 responseCode = atoi(buf);
1459 switch(responseCode)
1461 case 202: break; // Ok
1464 printf("Invalid user? (USER_INFO failed)\n");
1466 return RV_INVALID_USER;
1469 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1470 printf("%s\n", buf);
1472 return RV_UNKNOWN_ERROR;
1475 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1477 giUserBalance = atoi( buf + matches[4].rm_so );
1478 gsUserFlags = strdup( buf + matches[5].rm_so );
1486 * \brief Read an item info response from the server
1487 * \param Dest Destination for the read item (strings will be on the heap)
1489 int ReadItemInfo(int Socket, tItem *Dest)
1494 regmatch_t matches[8];
1498 buf = ReadLine(Socket);
1499 responseCode = atoi(buf);
1501 switch(responseCode)
1506 printf("Bad item name\n");
1511 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1513 return RV_UNKNOWN_ERROR;
1516 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1518 buf[ matches[3].rm_eo ] = '\0';
1519 buf[ matches[5].rm_eo ] = '\0';
1520 buf[ matches[7].rm_eo ] = '\0';
1522 statusStr = &buf[ matches[5].rm_so ];
1524 Dest->ID = atoi( buf + matches[4].rm_so );
1526 if( strcmp(statusStr, "avail") == 0 )
1528 else if( strcmp(statusStr, "sold") == 0 )
1530 else if( strcmp(statusStr, "error") == 0 )
1533 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1535 return RV_UNKNOWN_ERROR;
1537 Dest->Price = atoi( buf + matches[6].rm_so );
1539 // Hack a little to reduce heap fragmentation
1541 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1542 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1543 strcpy(tmpType, buf + matches[3].rm_so);
1544 strcpy(tmpDesc, buf + matches[7].rm_so);
1546 Dest->Type = strdup( tmpType );
1547 Dest->Desc = strdup( tmpDesc );
1554 * \brief Fill the item information structure
1555 * \return Boolean Failure
1557 void PopulateItemList(int Socket)
1564 regmatch_t matches[4];
1566 // Ask server for stock list
1567 send(Socket, "ENUM_ITEMS\n", 11, 0);
1568 buf = ReadLine(Socket);
1570 //printf("Output: %s\n", buf);
1572 responseCode = atoi(buf);
1573 if( responseCode != 201 ) {
1574 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1575 exit(RV_UNKNOWN_ERROR);
1578 // - Get item list -
1581 // 201 Items <count>
1583 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1585 arrayType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1586 count = atoi( &buf[ matches[3].rm_so ] );
1589 if( strcmp(arrayType, "Items") != 0 ) {
1591 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1593 exit(RV_UNKNOWN_ERROR);
1598 gaItems = malloc( giNumItems * sizeof(tItem) );
1600 // Fetch item information
1601 for( i = 0; i < giNumItems; i ++ )
1603 ReadItemInfo( Socket, &gaItems[i] );
1607 buf = ReadLine(Socket);
1608 responseCode = atoi(buf);
1610 if( responseCode != 200 ) {
1611 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1622 * \brief Get information on an item
1623 * \return Boolean Failure
1625 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1631 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1633 ret = ReadItemInfo(Socket, &item);
1636 printf("%8s:%-2i %2i.%02i %s\n",
1638 item.Price/100, item.Price%100,
1648 * \brief Dispense an item
1649 * \return Boolean Failure
1651 int DispenseItem(int Socket, const char *Type, int ID)
1653 int ret, responseCode;
1656 // Check for a dry run
1658 printf("Dry Run - No action\n");
1663 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1664 buf = ReadLine(Socket);
1666 responseCode = atoi(buf);
1667 switch( responseCode )
1670 printf("Dispense OK\n");
1674 printf("Not authenticated\n");
1675 ret = RV_PERMISSIONS;
1678 printf("Insufficient balance\n");
1682 printf("Bad item name\n");
1686 printf("Item failed to dispense, is the slot empty?\n");
1687 ret = RV_SERVER_ERROR;
1690 printf("Dispense not possible (slot empty/permissions)\n");
1691 ret = RV_SERVER_ERROR;
1694 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1695 ret = RV_UNKNOWN_ERROR;
1704 * \brief Alter a user's balance
1706 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1709 int responseCode, rv = -1;
1711 // Check for a dry run
1713 printf("Dry Run - No action\n");
1718 if( Ammount == 0 ) {
1719 printf("An amount would be nice\n");
1720 return RV_ARGUMENTS;
1723 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1724 buf = ReadLine(Socket);
1726 responseCode = atoi(buf);
1728 switch(responseCode)
1734 fprintf(stderr, "Insufficient balance\n");
1737 case 403: // Not in coke
1738 fprintf(stderr, "You are not in coke (sucker)\n");
1739 rv = RV_PERMISSIONS;
1741 case 404: // Unknown user
1742 fprintf(stderr, "Unknown user '%s'\n", Username);
1743 rv = RV_INVALID_USER;
1746 fprintf(stderr, "Unknown response code %i\n'%s'\n", responseCode, buf);
1747 rv = RV_UNKNOWN_RESPONSE;
1756 * \brief Set a user's balance
1757 * \note Only avaliable to dispense admins
1759 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1764 // Check for a dry run
1766 printf("Dry Run - No action\n");
1770 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1771 buf = ReadLine(Socket);
1773 responseCode = atoi(buf);
1776 switch(responseCode)
1778 case 200: return 0; // OK
1779 case 403: // Not in coke
1780 fprintf(stderr, "You are not an admin\n");
1781 return RV_PERMISSIONS;
1782 case 404: // Unknown user
1783 fprintf(stderr, "Unknown user '%s'\n", Username);
1784 return RV_INVALID_USER;
1786 fprintf(stderr, "Unknown response code %i\n", responseCode);
1787 return RV_UNKNOWN_RESPONSE;
1794 * \brief Give money to another user
1796 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1802 printf("Sorry, you can only give, you can't take.\n");
1803 return RV_ARGUMENTS;
1806 // Fast return on zero
1807 if( Ammount == 0 ) {
1808 printf("Are you actually going to give any?\n");
1809 return RV_ARGUMENTS;
1812 // Check for a dry run
1814 printf("Dry Run - No action\n");
1818 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1820 buf = ReadLine(Socket);
1821 responseCode = atoi(buf);
1823 switch(responseCode)
1826 printf("Give succeeded\n");
1827 return RV_SUCCESS; // OK
1830 fprintf(stderr, "Insufficient balance\n");
1833 case 404: // Unknown user
1834 fprintf(stderr, "Unknown user '%s'\n", Username);
1835 return RV_INVALID_USER;
1838 fprintf(stderr, "Unknown response code %i\n", responseCode);
1839 return RV_UNKNOWN_RESPONSE;
1845 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1848 int responseCode, ret = -1;
1851 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1853 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1854 return RV_ARGUMENTS;
1857 // Check username (quick)
1858 if( strchr(Username, ' ') || strchr(Username, '\n') )
1860 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1861 return RV_ARGUMENTS;
1865 sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1867 buf = ReadLine(Socket);
1868 responseCode = atoi(buf);
1869 switch(responseCode)
1872 Dispense_ShowUser(Socket, Username); // Show destination account
1876 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1877 ret = RV_PERMISSIONS;
1880 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1881 ret = RV_INVALID_USER;
1884 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1888 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1897 * \brief Donate money to the club
1899 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1905 printf("Sorry, you can only give, you can't take.\n");
1909 // Fast return on zero
1910 if( Ammount == 0 ) {
1911 printf("Are you actually going to give any?\n");
1915 // Check for a dry run
1917 printf("Dry Run - No action\n");
1921 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1922 buf = ReadLine(Socket);
1924 responseCode = atoi(buf);
1927 switch(responseCode)
1929 case 200: return 0; // OK
1932 fprintf(stderr, "Insufficient balance\n");
1936 fprintf(stderr, "Unknown response code %i\n", responseCode);
1944 * \brief Enumerate users
1946 int Dispense_EnumUsers(int Socket)
1951 regmatch_t matches[4];
1953 if( giMinimumBalance != INT_MIN ) {
1954 if( giMaximumBalance != INT_MAX ) {
1955 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1958 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1962 if( giMaximumBalance != INT_MAX ) {
1963 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1966 sendf(Socket, "ENUM_USERS\n");
1969 buf = ReadLine(Socket);
1970 responseCode = atoi(buf);
1972 switch(responseCode)
1974 case 201: break; // Ok, length follows
1977 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1982 // Get count (not actually used)
1983 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1984 nUsers = atoi( buf + matches[3].rm_so );
1985 printf("%i users returned\n", nUsers);
1990 // Read returned users
1992 buf = ReadLine(Socket);
1993 responseCode = atoi(buf);
1995 if( responseCode != 202 ) break;
1997 _PrintUserLine(buf);
1999 } while(responseCode == 202);
2001 // Check final response
2002 if( responseCode != 200 ) {
2003 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
2013 int Dispense_ShowUser(int Socket, const char *Username)
2016 int responseCode, ret;
2018 sendf(Socket, "USER_INFO %s\n", Username);
2019 buf = ReadLine(Socket);
2021 responseCode = atoi(buf);
2023 switch(responseCode)
2026 _PrintUserLine(buf);
2031 printf("Unknown user '%s'\n", Username);
2036 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2046 void _PrintUserLine(const char *Line)
2048 regmatch_t matches[6];
2051 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
2056 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
2057 char username[usernameLen + 1];
2058 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
2059 char flags[flagsLen + 1];
2061 memcpy(username, Line + matches[3].rm_so, usernameLen);
2062 username[usernameLen] = '\0';
2063 memcpy(flags, Line + matches[5].rm_so, flagsLen);
2064 flags[flagsLen] = '\0';
2066 bal = atoi(Line + matches[4].rm_so);
2067 printf("%-15s: $%8.02f (%s)\n", username, ((float)bal)/100, flags);
2071 int Dispense_AddUser(int Socket, const char *Username)
2074 int responseCode, ret;
2076 // Check for a dry run
2078 printf("Dry Run - No action\n");
2082 sendf(Socket, "USER_ADD %s\n", Username);
2084 buf = ReadLine(Socket);
2085 responseCode = atoi(buf);
2087 switch(responseCode)
2090 printf("User '%s' added\n", Username);
2095 printf("Only wheel can add users\n");
2100 printf("User '%s' already exists\n", Username);
2105 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2115 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString, const char *Reason)
2118 int responseCode, ret;
2120 // Check for a dry run
2122 printf("Dry Run - No action\n");
2126 // TODO: Pre-validate the string
2128 sendf(Socket, "USER_FLAGS %s %s %s\n", Username, TypeString, Reason);
2130 buf = ReadLine(Socket);
2131 responseCode = atoi(buf);
2133 switch(responseCode)
2136 printf("User '%s' updated\n", Username);
2141 printf("Only dispense admins can modify users\n");
2142 ret = RV_PERMISSIONS;
2146 printf("User '%s' does not exist\n", Username);
2147 ret = RV_INVALID_USER;
2151 printf("Flag string is invalid\n");
2156 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2157 ret = RV_UNKNOWN_RESPONSE;
2166 int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName)
2169 int responseCode, ret;
2171 // Check for a dry run
2173 printf("Dry Run - No action\n");
2177 sendf(Socket, "UPDATE_ITEM %s:%i %i %s\n", Type, ID, NewPrice, NewName);
2179 buf = ReadLine(Socket);
2180 responseCode = atoi(buf);
2182 switch(responseCode)
2185 printf("Item %s:%i updated\n", Type, ID);
2190 printf("Only coke members can modify the slots\n");
2191 ret = RV_PERMISSIONS;
2195 printf("Invalid item passed\n");
2200 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2213 char *ReadLine(int Socket)
2215 static char buf[BUFSIZ];
2216 static int bufPos = 0;
2217 static int bufValid = 0;
2219 char *newline = NULL;
2221 char *ret = malloc(10);
2223 #if DEBUG_TRACE_SERVER
2224 printf("ReadLine: ");
2236 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2239 return strdup("599 Client Connection Error\n");
2242 buf[bufPos+len] = '\0';
2244 newline = strchr( buf+bufPos, '\n' );
2249 retLen += strlen(buf+bufPos);
2250 ret = realloc(ret, retLen + 1);
2251 strcat( ret, buf+bufPos );
2254 int newLen = newline - (buf+bufPos) + 1;
2255 bufValid = len - newLen;
2258 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2262 #if DEBUG_TRACE_SERVER
2263 printf("%i '%s'\n", retLen, ret);
2269 int sendf(int Socket, const char *Format, ...)
2274 va_start(args, Format);
2275 len = vsnprintf(NULL, 0, Format, args);
2280 va_start(args, Format);
2281 vsnprintf(buf, len+1, Format, args);
2284 #if DEBUG_TRACE_SERVER
2285 printf("sendf: %s", buf);
2288 return send(Socket, buf, len, 0);
2292 char *trim(char *string)
2296 while( isspace(*string) )
2299 for( i = strlen(string); i--; )
2301 if( isspace(string[i]) )
2310 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2314 ret = regexec(regex, string, nMatches, matches, 0);
2315 if( ret && errorMessage ) {
2316 size_t len = regerror(ret, regex, NULL, 0);
2318 regerror(ret, regex, errorStr, len);
2319 printf("string = '%s'\n", string);
2320 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2327 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2329 int ret = regcomp(regex, pattern, flags);
2331 size_t len = regerror(ret, regex, NULL, 0);
2333 regerror(ret, regex, errorStr, len);
2334 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);