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 " Show the finger output\n"
140 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "give") == 0 )
142 " dispense give <user> <amount> \"<reason>\"\n"
143 " Give money to another user\n"
146 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "donate") == 0 )
148 " dispense donate <amount> \"<reason>\"\n"
149 " Donate to the club\n"
151 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "iteminfo") == 0 )
153 " dispense iteminfo <itemid>\n"
154 " Get the name and price for an item\n"
156 // if( giTextArgc == 0 || strcmp(gsTextArgs[0], "enumitems") == 0 )
158 // " dispense enumitems\n"
159 // " List avaliable items\n"
161 if( giTextArgc == 0 )
162 printf(" == Coke members == \n");
163 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "acct") == 0 )
165 " dispense acct [<user>]\n"
166 " Show user balances\n"
167 " dispense acct <user> [+-]<amount> \"<reason>\"\n"
168 " Alter a account value\n"
169 " dispense acct <user> =<amount> \"<reason>\"\n"
170 " Set an account balance\n"
172 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "refund") == 0 )
174 " dispense refund <user> <itemid> [<price>]\n"
175 " Refund an item to a user (with optional price override)\n"
176 " Item IDs can be seen in the cokelog (in the brackets after the item name)\n"
177 " e.g. coke:6 for a coke, snack:33 for slot 33 of the snack machine\n"
179 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "slot") == 0 )
181 " dispense slot <itemid> <price> <name>\n"
182 " Rename/Re-price a slot\n"
184 if( giTextArgc == 0 )
185 printf(" == Dispense administrators ==\n");
186 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "user") == 0 )
188 " dispense user add <user>\n"
189 " Create new account\n"
190 " dispense user type <user> <flags> <reason>\n"
191 " Alter a user's flags\n"
192 " <flags> is a comma-separated list of user, coke, admin, internal or disabled\n"
193 " Flags are removed by preceding the name with '-' or '!'\n"
195 if( giTextArgc == 0 )
199 " Dispense multiple times\n"
201 " Set a different user (Coke members only)\n"
205 " Use simple textual interface (instead of ncurses)\n"
207 " Dry run - Do not actually do dispenses\n"
208 " -m <min balance>\n"
209 " -M <max balance>\n"
210 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
213 " 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"
219 int main(int argc, char *argv[])
227 // -- Create regular expressions
228 // > Code Type Count ...
229 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
230 // > Code Type Ident Status Price Desc
231 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);
232 // > Code 'SALT' salt
233 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
234 // > Code 'User' Username Balance Flags
235 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
237 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
240 for( i = 1; i < argc; i ++ )
254 if( i + 1 >= argc ) {
255 fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
259 giDispenseCount = atoi(argv[++i]);
260 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
261 fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
267 case 'm': // Minimum balance
268 if( i + 1 >= argc ) {
269 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
273 giMinimumBalance = atoi(argv[++i]);
275 case 'M': // Maximum balance
276 if( i + 1 >= argc ) {
277 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
281 giMaximumBalance = atoi(argv[++i]);
284 case 'u': // Override User
285 if( i + 1 >= argc ) {
286 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
290 gsEffectiveUser = argv[++i];
293 case 'H': // Override remote host
294 if( i + 1 >= argc ) {
295 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
299 gsDispenseServer = argv[++i];
301 case 'P': // Override remote port
302 if( i + 1 >= argc ) {
303 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
307 giDispensePort = atoi(argv[++i]);
310 // Set slot name/price
312 if( giTextArgc != 0 ) {
313 fprintf(stderr, "%s: -s must appear before other arguments\n", argv[0]);
317 gsTextArgs[0] = "slot"; // HACK!!
321 case 'G': // Don't use GUI
322 giUIMode = UI_MODE_BASIC;
324 case 'D': // Drinks only
325 giUIMode = UI_MODE_DRINKSONLY;
327 case 'n': // Dry Run / read-only
331 if( strcmp(argv[i], "--help") == 0 ) {
335 else if( strcmp(argv[i], "--dry-run") == 0 ) {
338 else if( strcmp(argv[i], "--drinks-only") == 0 ) {
339 giUIMode = UI_MODE_DRINKSONLY;
341 else if( strcmp(argv[i], "--can-select-all") == 0 ) {
342 gbDisallowSelectWithoutBalance = 0;
345 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
351 // The first argument is not allowed to begin with 'i'
352 // (catches most bad flags)
353 if( giTextArgc == 0 ) {
354 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
358 if( giTextArgc == MAX_TXT_ARGS )
360 fprintf(stderr, "ERROR: Too many arguments\n");
363 gsTextArgs[giTextArgc++] = argv[i];
370 if( giTextArgc == MAX_TXT_ARGS )
372 fprintf(stderr, "ERROR: Too many arguments\n");
376 gsTextArgs[giTextArgc++] = argv[i];
383 if( strcmp(gsTextArgs[0], "finger") == 0 )
386 sock = OpenConnection(gsDispenseServer, giDispensePort);
387 if( sock < 0 ) return RV_SOCKET_ERROR;
390 PopulateItemList(sock);
392 printf("The UCC Coke machine.\n\n");
394 // Only get coke slot statuses
395 for( i = 0; i <= 6; i ++ )
398 switch(gaItems[i].Status)
400 case 0: status = "Avail"; break;
401 case 1: status = "Sold "; break;
406 printf("%i - %s %3i %s\n", gaItems[i].ID, status, gaItems[i].Price, gaItems[i].Desc);
410 printf("\nMay your pink fish bing into the distance.\n");
418 if( strcmp(gsTextArgs[0], "acct") == 0 )
421 sock = OpenConnection(gsDispenseServer, giDispensePort);
422 if( sock < 0 ) return RV_SOCKET_ERROR;
424 if( giTextArgc == 1 ) {
425 ret = Dispense_EnumUsers(sock);
430 // gsTextArgs[1]: Username
433 if( giTextArgc != 2 )
435 if( giTextArgc != 4 ) {
436 fprintf(stderr, "`dispense acct` requires a reason\n");
441 // Authentication required
442 ret = Authenticate(sock);
445 // gsTextArgs[1]: Username
446 // gsTextArgs[2]: Ammount
447 // gsTextArgs[3]: Reason
449 if( gsTextArgs[2][0] == '=' ) {
451 if( gsTextArgs[2][1] != '0' && atoi(gsTextArgs[2]+1) == 0 ) {
452 fprintf(stderr, "Error: Invalid balance to be set\n");
456 ret = Dispense_SetBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]+1), gsTextArgs[3]);
460 ret = Dispense_AlterBalance(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
469 // Show user information
470 ret = Dispense_ShowUser(sock, gsTextArgs[1]);
477 // - "Here, have some money."
478 else if( strcmp(gsTextArgs[0], "give") == 0 )
480 if( giTextArgc != 4 ) {
481 fprintf(stderr, "`dispense give` takes three arguments\n");
486 // gsTextArgs[1]: Destination
487 // gsTextArgs[2]: Ammount
488 // gsTextArgs[3]: Reason
491 sock = OpenConnection(gsDispenseServer, giDispensePort);
492 if( sock < 0 ) return RV_SOCKET_ERROR;
495 ret = Authenticate(sock);
498 ret = Dispense_Give(sock, gsTextArgs[1], atoi(gsTextArgs[2]), gsTextArgs[3]);
506 // - User administration (Admin Only)
507 if( strcmp(gsTextArgs[0], "user") == 0 )
509 // Check argument count
510 if( giTextArgc == 1 ) {
511 fprintf(stderr, "Error: `dispense user` requires arguments\n");
517 sock = OpenConnection(gsDispenseServer, giDispensePort);
518 if( sock < 0 ) return RV_SOCKET_ERROR;
520 // Attempt authentication
521 ret = Authenticate(sock);
525 if( strcmp(gsTextArgs[1], "add") == 0 )
527 if( giTextArgc != 3 ) {
528 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
533 ret = Dispense_AddUser(sock, gsTextArgs[2]);
536 else if( strcmp(gsTextArgs[1], "type") == 0 || strcmp(gsTextArgs[1], "flags") == 0 )
538 if( giTextArgc < 4 || giTextArgc > 5 ) {
539 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
544 if( giTextArgc == 4 )
545 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], "");
547 ret = Dispense_SetUserType(sock, gsTextArgs[2], gsTextArgs[3], gsTextArgs[4]);
551 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
559 else if( strcmp(gsTextArgs[0], "donate") == 0 )
561 // Check argument count
562 if( giTextArgc != 3 ) {
563 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
569 sock = OpenConnection(gsDispenseServer, giDispensePort);
570 if( sock < 0 ) return RV_SOCKET_ERROR;
572 // Attempt authentication
573 ret = Authenticate(sock);
577 ret = Dispense_Donate(sock, atoi(gsTextArgs[1]), gsTextArgs[2]);
584 else if( strcmp(gsTextArgs[0], "refund") == 0 )
587 // Check argument count
588 if( giTextArgc != 3 && giTextArgc != 4 ) {
589 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
595 sock = OpenConnection(gsDispenseServer, giDispensePort);
596 if(sock < 0) return RV_SOCKET_ERROR;
598 // Attempt authentication
599 ret = Authenticate(sock);
602 if( giTextArgc == 4 ) {
603 price = atoi(gsTextArgs[3]);
605 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
610 // Username, Item, cost
611 ret = Dispense_Refund(sock, gsTextArgs[1], gsTextArgs[2], price);
617 // Query an item price
618 else if( strcmp(gsTextArgs[0], "iteminfo") == 0 )
620 regmatch_t matches[3];
623 // Check argument count
624 if( giTextArgc != 2 ) {
625 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
630 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
631 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
634 type = gsTextArgs[1] + matches[1].rm_so;
635 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
636 id = atoi( gsTextArgs[1] + matches[2].rm_so );
638 sock = OpenConnection(gsDispenseServer, giDispensePort);
639 if( sock < 0 ) return RV_SOCKET_ERROR;
641 ret = Dispense_ItemInfo(sock, type, id);
646 else if( strcmp(gsTextArgs[0], "slot") == 0 )
648 regmatch_t matches[3];
649 char *item_type, *newname;
653 if( giTextArgc != 4 ) {
654 fprintf(stderr, "Error: `dispense slot` takes three arguments\n");
660 if( RunRegex(&gUserItemIdentRegex, gsTextArgs[1], 3, matches, NULL) != 0 ) {
661 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
664 item_type = gsTextArgs[1] + matches[1].rm_so;
665 gsTextArgs[1][ matches[1].rm_eo ] = '\0';
666 item_id = atoi( gsTextArgs[1] + matches[2].rm_so );
669 price = atoi( gsTextArgs[2] );
670 if( price <= 0 && gsTextArgs[2][0] != '0' ) {
671 fprintf(stderr, "Error: Invalid price passed (must be >= 0)\n");
676 newname = gsTextArgs[3];
680 for( pos = newname; *pos; pos ++ )
682 if( !isalnum(*pos) && *pos != ' ' ) {
683 fprintf(stderr, "Error: You should only have letters, numbers and spaces in an item name\n");
689 // Connect & Authenticate
690 sock = OpenConnection(gsDispenseServer, giDispensePort);
691 if( sock < 0 ) return RV_SOCKET_ERROR;
692 ret = Authenticate(sock);
695 ret = Dispense_SetItem(sock, item_type, item_id, price, newname);
700 // Item name / pattern
703 gsItemPattern = gsTextArgs[0];
707 sock = OpenConnection(gsDispenseServer, giDispensePort);
708 if( sock < 0 ) return RV_SOCKET_ERROR;
710 // Get the user's balance
711 ret = GetUserBalance(sock);
715 PopulateItemList(sock);
717 // Disconnect from server
720 if( gsItemPattern && gsItemPattern[0] )
722 regmatch_t matches[3];
724 if( strcmp(gsItemPattern, "door") == 0 )
726 // Connect, Authenticate, dispense and close
727 sock = OpenConnection(gsDispenseServer, giDispensePort);
728 if( sock < 0 ) return RV_SOCKET_ERROR;
729 ret = Authenticate(sock);
731 ret = DispenseItem(sock, "door", 0);
735 // Item id (<type>:<num>)
736 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
741 // Get and finish ident
742 ident = gsItemPattern + matches[1].rm_so;
743 gsItemPattern[matches[1].rm_eo] = '\0';
745 id = atoi( gsItemPattern + matches[2].rm_so );
747 // Connect, Authenticate, dispense and close
748 sock = OpenConnection(gsDispenseServer, giDispensePort);
749 if( sock < 0 ) return RV_SOCKET_ERROR;
751 Dispense_ItemInfo(sock, ident, id);
753 ret = Authenticate(sock);
755 ret = DispenseItem(sock, ident, id);
759 // Item number (6 = coke)
760 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
762 i = atoi(gsItemPattern);
769 for( i = 0; i < giNumItems; i ++ )
771 // Prefix match (with case-insensitive match)
772 for( j = 0; gsItemPattern[j]; j ++ )
774 if( gaItems[i].Desc[j] == gsItemPattern[j] )
776 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
780 // Check if the prefix matched
781 if( gsItemPattern[j] != '\0' )
785 if( gaItems[i].Desc[j] == '\0' ) {
790 // Only one match allowed
795 // TODO: Allow ambiguous matches?
796 // or just print a wanrning
797 printf("Warning - Ambiguous pattern, stopping\n");
802 // Was a match found?
805 fprintf(stderr, "No item matches the passed string\n");
812 else if( giUIMode != UI_MODE_BASIC )
818 // Very basic dispense interface
819 for( i = 0; i < giNumItems; i ++ ) {
821 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
824 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
825 gaItems[i].Price, gaItems[i].Desc);
834 fgets(buffer, BUFSIZ, stdin);
838 if( buf[0] == 'q' ) break;
842 if( i != 0 || buf[0] == '0' )
844 if( i < 0 || i >= giNumItems ) {
845 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
854 // Check for a valid item ID
858 // Connect, Authenticate, dispense and close
859 sock = OpenConnection(gsDispenseServer, giDispensePort);
860 if( sock < 0 ) return RV_SOCKET_ERROR;
862 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
865 ret = Authenticate(sock);
868 for( j = 0; j < giDispenseCount; j ++ ) {
869 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
873 printf("%i items dispensed\n", j);
875 Dispense_ShowUser(sock, gsUserName);
883 // -------------------
884 // --- NCurses GUI ---
885 // -------------------
887 * \brief Render the NCurses UI
889 int ShowNCursesUI(void)
894 const int displayMinWidth = 50;
895 char *titleString = "Dispense";
900 int ret = -2; // -2: Used for marking "no return yet"
902 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
909 if( gsEffectiveUser )
910 username = gsEffectiveUser;
912 pwd = getpwuid( getuid() );
913 username = pwd->pw_name;
916 snprintf(balance_str, sizeof(balance_str), "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
923 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
924 // Get item count per screen
925 // - 6: randomly chosen (Need at least 3)
926 items_in_view = LINES - 6;
927 if( items_in_view > maxItemIndex )
928 items_in_view = maxItemIndex;
931 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
936 height = items_in_view + 3;
937 width = displayMinWidth;
940 xBase = COLS/2 - width/2;
941 yBase = LINES/2 - height/2;
946 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
949 for( i = 0; i < items_in_view; i ++ )
953 move( yBase + 1 + i, xBase );
958 // Check for the '...' row
959 // - Oh god, magic numbers!
960 if( (i == 0 && itemBase > 0)
961 || (i == items_in_view - 1 && itemBase < maxItemIndex - items_in_view) )
963 printw(" ..."); pos += 8;
964 times = (width - pos) - 1;
965 while(times--) addch(' ');
970 yBase + 1 + i, xBase + pos, // Position
971 (width - pos) - 3, // Width
972 itemBase + i, // Index
973 !!(currentItem == itemBase + i) // Hilighted
978 // Scrollbar (if needed)
979 if( maxItemIndex > items_in_view ) {
983 else if( i == items_in_view - 1 ) {
987 int percentage = itemBase * 100 / (maxItemIndex-items_in_view);
988 if( i-1 == percentage*(items_in_view-3)/100 ) {
1002 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
1005 // - Username, balance, flags
1006 PrintAlign(yBase+height-1, xBase+1, width-2,
1007 username, ' ', balance_str, ' ', gsUserFlags);
1013 if( ch == '\x1B' ) {
1022 // Skip over spacers
1023 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
1026 if( currentItem >= maxItemIndex ) {
1028 // Skip over spacers
1029 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
1035 // Skip over spacers
1036 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
1039 if( currentItem < 0 ) {
1040 currentItem = maxItemIndex - 1;
1041 // Skip over spacers
1042 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
1052 // Scroll only if needed
1053 if( items_in_view < maxItemIndex )
1055 // - If the current item is above the second item shown, and we're not at the top
1056 if( currentItem < itemBase + 2 && itemBase > 0 ) {
1057 itemBase = currentItem - 2;
1058 if(itemBase < 0) itemBase = 0;
1060 // - If the current item is below the second item show, and we're not at the bottom
1061 if( currentItem > itemBase + items_in_view - 2 && itemBase + items_in_view < maxItemIndex ) {
1062 itemBase = currentItem - items_in_view + 2;
1063 if( itemBase > maxItemIndex - items_in_view )
1064 itemBase = maxItemIndex - items_in_view;
1072 ret = ShowItemAt(0, 0, 0, currentItem, 0);
1074 case 0x1b: // Escape
1076 ret = -1; // -1: Return with no dispense
1080 // Check if the return value was changed
1081 if( ret != -2 ) break;
1093 * \brief Show item \a Index at (\a Col, \a Row)
1094 * \return Dispense index of item
1095 * \note Part of the NCurses UI
1097 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
1106 // - This assumes that
1107 case UI_MODE_STANDARD:
1109 // Index = -1, request limit
1110 if( Index < 0 || Index >= giNumItems+2 )
1111 return giNumItems+2;
1116 name = "Coke Machine";
1117 Index = -1; // -1 indicates a label
1124 name = gaItems[Index].Desc;
1125 price = gaItems[Index].Price;
1126 status = gaItems[Index].Status;
1134 name = "Electronic Payment System";
1135 Index = -1; // -1 indicates a label
1140 name = gaItems[Index].Desc;
1141 price = gaItems[Index].Price;
1142 status = gaItems[Index].Status;
1148 // Width = 0, don't print
1151 // 4 preceding, 5 price
1152 int nameWidth = Width - 4 - snprintf(NULL, 0, " %4i", price);
1157 // Show hilight and status
1176 printw("%-*.*s", nameWidth, nameWidth, name);
1178 printw(" %4i", price);
1182 printw("-- %-*.*s ", Width-4, Width-4, name);
1186 // If the item isn't availiable for sale, return -1 (so it's skipped)
1187 if( status || (price > giUserBalance && gbDisallowSelectWithoutBalance) )
1194 * \brief Print a three-part string at the specified position (formatted)
1195 * \note NCurses UI Helper
1197 * Prints \a Left on the left of the area, \a Right on the righthand side
1198 * and \a Mid in the middle of the area. These are padded with \a Pad1
1199 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1201 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1202 * and the arguments to these are read in that order.
1204 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1205 const char *Mid, char Pad2, const char *Right, ...)
1207 int lLen, mLen, rLen;
1212 // Get the length of the strings
1213 va_start(args, Right);
1214 lLen = vsnprintf(NULL, 0, Left, args);
1215 mLen = vsnprintf(NULL, 0, Mid, args);
1216 rLen = vsnprintf(NULL, 0, Right, args);
1220 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1221 return ; // TODO: What to do?
1227 va_start(args, Right);
1231 vsnprintf(tmp, lLen+1, Left, args);
1235 times = (Width - mLen)/2 - lLen;
1236 while(times--) addch(Pad1);
1240 vsnprintf(tmp, mLen+1, Mid, args);
1244 times = (Width - mLen)/2 - rLen;
1245 if( (Width - mLen) % 2 ) times ++;
1246 while(times--) addch(Pad2);
1250 vsnprintf(tmp, rLen+1, Right, args);
1255 // ---------------------
1256 // --- Coke Protocol ---
1257 // ---------------------
1258 int OpenConnection(const char *Host, int Port)
1260 struct hostent *host;
1261 struct sockaddr_in serverAddr;
1264 host = gethostbyname(Host);
1266 fprintf(stderr, "Unable to look up '%s'\n", Host);
1270 memset(&serverAddr, 0, sizeof(serverAddr));
1272 serverAddr.sin_family = AF_INET; // IPv4
1273 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1274 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1275 serverAddr.sin_port = htons(Port);
1277 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1279 fprintf(stderr, "Failed to create socket\n");
1283 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1285 if( geteuid() == 0 || getuid() == 0 )
1288 struct sockaddr_in localAddr;
1289 memset(&localAddr, 0, sizeof(localAddr));
1290 localAddr.sin_family = AF_INET; // IPv4
1292 // Loop through all the top ports until one is avaliable
1293 for( i = 512; i < 1024; i ++)
1295 localAddr.sin_port = htons(i); // IPv4
1296 // Attempt to bind to low port for autoauth
1297 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1301 printf("Warning: AUTOAUTH unavaliable\n");
1303 // printf("Bound to 0.0.0.0:%i\n", i);
1306 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1307 fprintf(stderr, "Failed to connect to server\n");
1311 // We're not authenticated if the connection has just opened
1312 gbIsAuthenticated = 0;
1317 int Authenticate_AutoAuth(int Socket, const char *Username)
1323 // Attempt automatic authentication
1324 sendf(Socket, "AUTOAUTH %s\n", Username);
1326 // Check if it worked
1327 buf = ReadLine(Socket);
1329 responseCode = atoi(buf);
1330 switch( responseCode )
1332 case 200: // Autoauth succeeded, return
1336 case 401: // Untrusted
1337 // fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1338 ret = RV_PERMISSIONS;
1340 case 404: // Bad Username
1341 fprintf(stderr, "Bad Username '%s'\n", Username);
1342 ret = RV_INVALID_USER;
1346 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1347 printf("%s\n", buf);
1348 ret = RV_UNKNOWN_ERROR;
1356 int Authenticate_AuthIdent(int Socket)
1362 // Attempt automatic authentication
1363 sendf(Socket, "AUTHIDENT\n");
1365 // Check if it worked
1366 buf = ReadLine(Socket);
1368 responseCode = atoi(buf);
1369 switch( responseCode )
1371 case 200: // Autoauth succeeded, return
1375 case 401: // Untrusted
1376 // fprintf(stderr, "Untrusted host, AUTHIDENT unavaliable\n");
1377 ret = RV_PERMISSIONS;
1381 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1382 printf("%s\n", buf);
1383 ret = RV_UNKNOWN_RESPONSE;
1392 int Authenticate_Password(int Socket, const char *Username)
1394 #if USE_PASSWORD_AUTH
1399 regmatch_t matches[4];
1401 sendf(Socket, "USER %s\n", Username);
1402 printf("Using username %s\n", Username);
1404 buf = ReadLine(Socket);
1407 // Expected format: 100 SALT <something> ...
1408 // OR : 100 User Set
1409 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1410 responseCode = atoi(buf);
1411 if( responseCode != 100 ) {
1412 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1414 return RV_UNKNOWN_ERROR; // ERROR
1418 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1419 // Store it for later
1420 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1421 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1425 // Give three attempts
1426 for( i = 0; i < 3; i ++ )
1428 int ofs = strlen(Username)+strlen(salt);
1431 char *pass = getpass("Password: ");
1434 // Create hash string
1435 // <username><salt><hash>
1436 strcpy(tmp, Username);
1438 SHA1( (unsigned char*)pass, strlen(pass), h );
1439 memcpy(tmp+ofs, h, 20);
1442 SHA1( (unsigned char*)tmp, ofs+20, h );
1443 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1444 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1445 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1449 sendf(Socket, "PASS %s\n", tmpBuf);
1450 buf = ReadLine(Socket);
1452 responseCode = atoi(buf);
1454 if( responseCode == 200 ) break;
1455 // Bad username/password
1456 if( responseCode == 401 ) continue;
1458 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1464 return RV_INVALID_USER; // 2 = Bad Password
1468 return RV_INVALID_USER;
1473 * \brief Authenticate with the server
1474 * \return Boolean Failure
1476 int Authenticate(int Socket)
1480 if( gbIsAuthenticated ) return 0;
1483 pwd = getpwuid( getuid() );
1486 if( Authenticate_AutoAuth(Socket, pwd->pw_name) == 0 )
1488 else if( Authenticate_AuthIdent(Socket) == 0 )
1490 else if( Authenticate_Password(Socket, pwd->pw_name) == 0 )
1491 return RV_INVALID_USER;
1493 // Set effective user
1494 if( gsEffectiveUser ) {
1497 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1499 buf = ReadLine(Socket);
1500 responseCode = atoi(buf);
1502 switch(responseCode)
1505 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1509 printf("Only coke members can use `dispense -u`\n");
1511 return RV_PERMISSIONS;
1514 printf("Invalid user selected\n");
1516 return RV_INVALID_USER;
1519 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1520 printf("%s\n", buf);
1522 return RV_UNKNOWN_ERROR;
1528 gbIsAuthenticated = 1;
1533 int GetUserBalance(int Socket)
1535 regmatch_t matches[6];
1542 if( gsEffectiveUser ) {
1543 gsUserName = gsEffectiveUser;
1546 pwd = getpwuid( getuid() );
1547 gsUserName = strdup(pwd->pw_name);
1551 sendf(Socket, "USER_INFO %s\n", gsUserName);
1552 buf = ReadLine(Socket);
1553 responseCode = atoi(buf);
1554 switch(responseCode)
1556 case 202: break; // Ok
1559 printf("Invalid user? (USER_INFO failed)\n");
1561 return RV_INVALID_USER;
1564 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1565 printf("%s\n", buf);
1567 return RV_UNKNOWN_ERROR;
1570 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1572 giUserBalance = atoi( buf + matches[4].rm_so );
1573 gsUserFlags = strdup( buf + matches[5].rm_so );
1581 * \brief Read an item info response from the server
1582 * \param Dest Destination for the read item (strings will be on the heap)
1584 int ReadItemInfo(int Socket, tItem *Dest)
1589 regmatch_t matches[8];
1593 buf = ReadLine(Socket);
1594 responseCode = atoi(buf);
1596 switch(responseCode)
1601 printf("Bad item name\n");
1606 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1608 return RV_UNKNOWN_ERROR;
1611 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1613 buf[ matches[3].rm_eo ] = '\0';
1614 buf[ matches[5].rm_eo ] = '\0';
1615 buf[ matches[7].rm_eo ] = '\0';
1617 statusStr = &buf[ matches[5].rm_so ];
1619 Dest->ID = atoi( buf + matches[4].rm_so );
1621 if( strcmp(statusStr, "avail") == 0 )
1623 else if( strcmp(statusStr, "sold") == 0 )
1625 else if( strcmp(statusStr, "error") == 0 )
1628 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1630 return RV_UNKNOWN_ERROR;
1632 Dest->Price = atoi( buf + matches[6].rm_so );
1634 // Hack a little to reduce heap fragmentation
1636 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1637 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1638 strcpy(tmpType, buf + matches[3].rm_so);
1639 strcpy(tmpDesc, buf + matches[7].rm_so);
1641 Dest->Type = strdup( tmpType );
1642 Dest->Desc = strdup( tmpDesc );
1649 * \brief Fill the item information structure
1650 * \return Boolean Failure
1652 void PopulateItemList(int Socket)
1659 regmatch_t matches[4];
1661 // Ask server for stock list
1662 send(Socket, "ENUM_ITEMS\n", 11, 0);
1663 buf = ReadLine(Socket);
1665 //printf("Output: %s\n", buf);
1667 responseCode = atoi(buf);
1668 if( responseCode != 201 ) {
1669 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1670 exit(RV_UNKNOWN_ERROR);
1673 // - Get item list -
1676 // 201 Items <count>
1678 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1680 arrayType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1681 count = atoi( &buf[ matches[3].rm_so ] );
1684 if( strcmp(arrayType, "Items") != 0 ) {
1686 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1688 exit(RV_UNKNOWN_ERROR);
1693 gaItems = malloc( giNumItems * sizeof(tItem) );
1695 // Fetch item information
1696 for( i = 0; i < giNumItems; i ++ )
1698 ReadItemInfo( Socket, &gaItems[i] );
1702 buf = ReadLine(Socket);
1703 responseCode = atoi(buf);
1705 if( responseCode != 200 ) {
1706 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1717 * \brief Get information on an item
1718 * \return Boolean Failure
1720 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1726 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1728 ret = ReadItemInfo(Socket, &item);
1731 printf("%8s:%-2i %2i.%02i %s\n",
1733 item.Price/100, item.Price%100,
1743 * \brief Dispense an item
1744 * \return Boolean Failure
1746 int DispenseItem(int Socket, const char *Type, int ID)
1748 int ret, responseCode;
1751 // Check for a dry run
1753 printf("Dry Run - No action\n");
1758 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1759 buf = ReadLine(Socket);
1761 responseCode = atoi(buf);
1762 switch( responseCode )
1765 printf("Dispense OK\n");
1769 printf("Not authenticated\n");
1770 ret = RV_PERMISSIONS;
1773 printf("Insufficient balance\n");
1777 printf("Bad item name\n");
1781 printf("Item failed to dispense, is the slot empty?\n");
1782 ret = RV_SERVER_ERROR;
1785 printf("Dispense not possible (slot empty/permissions)\n");
1786 ret = RV_SERVER_ERROR;
1789 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1790 ret = RV_UNKNOWN_ERROR;
1799 * \brief Alter a user's balance
1801 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1804 int responseCode, rv = -1;
1806 // Check for a dry run
1808 printf("Dry Run - No action\n");
1813 if( Ammount == 0 ) {
1814 printf("An amount would be nice\n");
1815 return RV_ARGUMENTS;
1818 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1819 buf = ReadLine(Socket);
1821 responseCode = atoi(buf);
1823 switch(responseCode)
1829 fprintf(stderr, "Insufficient balance\n");
1832 case 403: // Not in coke
1833 fprintf(stderr, "You are not in coke (sucker)\n");
1834 rv = RV_PERMISSIONS;
1836 case 404: // Unknown user
1837 fprintf(stderr, "Unknown user '%s'\n", Username);
1838 rv = RV_INVALID_USER;
1841 fprintf(stderr, "Unknown response code %i\n'%s'\n", responseCode, buf);
1842 rv = RV_UNKNOWN_RESPONSE;
1851 * \brief Set a user's balance
1852 * \note Only avaliable to dispense admins
1854 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1859 // Check for a dry run
1861 printf("Dry Run - No action\n");
1865 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1866 buf = ReadLine(Socket);
1868 responseCode = atoi(buf);
1871 switch(responseCode)
1873 case 200: return 0; // OK
1874 case 403: // Not in coke
1875 fprintf(stderr, "You are not an admin\n");
1876 return RV_PERMISSIONS;
1877 case 404: // Unknown user
1878 fprintf(stderr, "Unknown user '%s'\n", Username);
1879 return RV_INVALID_USER;
1881 fprintf(stderr, "Unknown response code %i\n", responseCode);
1882 return RV_UNKNOWN_RESPONSE;
1889 * \brief Give money to another user
1891 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1897 printf("Sorry, you can only give, you can't take.\n");
1898 return RV_ARGUMENTS;
1901 // Fast return on zero
1902 if( Ammount == 0 ) {
1903 printf("Are you actually going to give any?\n");
1904 return RV_ARGUMENTS;
1907 // Check for a dry run
1909 printf("Dry Run - No action\n");
1913 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1915 buf = ReadLine(Socket);
1916 responseCode = atoi(buf);
1918 switch(responseCode)
1921 printf("Give succeeded\n");
1922 return RV_SUCCESS; // OK
1925 fprintf(stderr, "Insufficient balance\n");
1928 case 404: // Unknown user
1929 fprintf(stderr, "Unknown user '%s'\n", Username);
1930 return RV_INVALID_USER;
1933 fprintf(stderr, "Unknown response code %i\n", responseCode);
1934 return RV_UNKNOWN_RESPONSE;
1940 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1943 int responseCode, ret = -1;
1946 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1948 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1949 return RV_ARGUMENTS;
1952 // Check username (quick)
1953 if( strchr(Username, ' ') || strchr(Username, '\n') )
1955 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1956 return RV_ARGUMENTS;
1960 sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1962 buf = ReadLine(Socket);
1963 responseCode = atoi(buf);
1964 switch(responseCode)
1967 Dispense_ShowUser(Socket, Username); // Show destination account
1971 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1972 ret = RV_PERMISSIONS;
1975 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1976 ret = RV_INVALID_USER;
1979 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1983 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1992 * \brief Donate money to the club
1994 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
2000 printf("Sorry, you can only give, you can't take.\n");
2004 // Fast return on zero
2005 if( Ammount == 0 ) {
2006 printf("Are you actually going to give any?\n");
2010 // Check for a dry run
2012 printf("Dry Run - No action\n");
2016 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
2017 buf = ReadLine(Socket);
2019 responseCode = atoi(buf);
2022 switch(responseCode)
2024 case 200: return 0; // OK
2027 fprintf(stderr, "Insufficient balance\n");
2031 fprintf(stderr, "Unknown response code %i\n", responseCode);
2039 * \brief Enumerate users
2041 int Dispense_EnumUsers(int Socket)
2046 regmatch_t matches[4];
2048 if( giMinimumBalance != INT_MIN ) {
2049 if( giMaximumBalance != INT_MAX ) {
2050 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
2053 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
2057 if( giMaximumBalance != INT_MAX ) {
2058 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
2061 sendf(Socket, "ENUM_USERS\n");
2064 buf = ReadLine(Socket);
2065 responseCode = atoi(buf);
2067 switch(responseCode)
2069 case 201: break; // Ok, length follows
2072 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
2077 // Get count (not actually used)
2078 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
2079 nUsers = atoi( buf + matches[3].rm_so );
2080 printf("%i users returned\n", nUsers);
2085 // Read returned users
2087 buf = ReadLine(Socket);
2088 responseCode = atoi(buf);
2090 if( responseCode != 202 ) break;
2092 _PrintUserLine(buf);
2094 } while(responseCode == 202);
2096 // Check final response
2097 if( responseCode != 200 ) {
2098 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
2108 int Dispense_ShowUser(int Socket, const char *Username)
2111 int responseCode, ret;
2113 sendf(Socket, "USER_INFO %s\n", Username);
2114 buf = ReadLine(Socket);
2116 responseCode = atoi(buf);
2118 switch(responseCode)
2121 _PrintUserLine(buf);
2126 printf("Unknown user '%s'\n", Username);
2131 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2141 void _PrintUserLine(const char *Line)
2143 regmatch_t matches[6];
2146 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
2151 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
2152 char username[usernameLen + 1];
2153 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
2154 char flags[flagsLen + 1];
2156 memcpy(username, Line + matches[3].rm_so, usernameLen);
2157 username[usernameLen] = '\0';
2158 memcpy(flags, Line + matches[5].rm_so, flagsLen);
2159 flags[flagsLen] = '\0';
2161 bal = atoi(Line + matches[4].rm_so);
2162 printf("%-15s: $%8.02f (%s)\n", username, ((float)bal)/100, flags);
2166 int Dispense_AddUser(int Socket, const char *Username)
2169 int responseCode, ret;
2171 // Check for a dry run
2173 printf("Dry Run - No action\n");
2177 sendf(Socket, "USER_ADD %s\n", Username);
2179 buf = ReadLine(Socket);
2180 responseCode = atoi(buf);
2182 switch(responseCode)
2185 printf("User '%s' added\n", Username);
2190 printf("Only wheel can add users\n");
2195 printf("User '%s' already exists\n", Username);
2200 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2210 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString, const char *Reason)
2213 int responseCode, ret;
2215 // Check for a dry run
2217 printf("Dry Run - No action\n");
2221 // TODO: Pre-validate the string
2223 sendf(Socket, "USER_FLAGS %s %s %s\n", Username, TypeString, Reason);
2225 buf = ReadLine(Socket);
2226 responseCode = atoi(buf);
2228 switch(responseCode)
2231 printf("User '%s' updated\n", Username);
2236 printf("Only dispense admins can modify users\n");
2237 ret = RV_PERMISSIONS;
2241 printf("User '%s' does not exist\n", Username);
2242 ret = RV_INVALID_USER;
2246 printf("Flag string is invalid\n");
2251 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2252 ret = RV_UNKNOWN_RESPONSE;
2261 int Dispense_SetItem(int Socket, const char *Type, int ID, int NewPrice, const char *NewName)
2264 int responseCode, ret;
2266 // Check for a dry run
2268 printf("Dry Run - No action\n");
2272 sendf(Socket, "UPDATE_ITEM %s:%i %i %s\n", Type, ID, NewPrice, NewName);
2274 buf = ReadLine(Socket);
2275 responseCode = atoi(buf);
2277 switch(responseCode)
2280 printf("Item %s:%i updated\n", Type, ID);
2285 printf("Only coke members can modify the slots\n");
2286 ret = RV_PERMISSIONS;
2290 printf("Invalid item passed\n");
2295 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2308 char *ReadLine(int Socket)
2310 static char buf[BUFSIZ];
2311 static int bufPos = 0;
2312 static int bufValid = 0;
2314 char *newline = NULL;
2316 char *ret = malloc(10);
2318 #if DEBUG_TRACE_SERVER
2319 printf("ReadLine: ");
2331 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2334 return strdup("599 Client Connection Error\n");
2337 buf[bufPos+len] = '\0';
2339 newline = strchr( buf+bufPos, '\n' );
2344 retLen += strlen(buf+bufPos);
2345 ret = realloc(ret, retLen + 1);
2346 strcat( ret, buf+bufPos );
2349 int newLen = newline - (buf+bufPos) + 1;
2350 bufValid = len - newLen;
2353 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2357 #if DEBUG_TRACE_SERVER
2358 printf("%i '%s'\n", retLen, ret);
2364 int sendf(int Socket, const char *Format, ...)
2369 va_start(args, Format);
2370 len = vsnprintf(NULL, 0, Format, args);
2375 va_start(args, Format);
2376 vsnprintf(buf, len+1, Format, args);
2379 #if DEBUG_TRACE_SERVER
2380 printf("sendf: %s", buf);
2383 return send(Socket, buf, len, 0);
2387 char *trim(char *string)
2391 while( isspace(*string) )
2394 for( i = strlen(string); i--; )
2396 if( isspace(string[i]) )
2405 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2409 ret = regexec(regex, string, nMatches, matches, 0);
2410 if( ret && errorMessage ) {
2411 size_t len = regerror(ret, regex, NULL, 0);
2413 regerror(ret, regex, errorStr, len);
2414 printf("string = '%s'\n", string);
2415 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2422 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2424 int ret = regcomp(regex, pattern, flags);
2426 size_t len = regerror(ret, regex, NULL, 0);
2428 regerror(ret, regex, errorStr, len);
2429 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);