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
15 #include <pwd.h> // getpwuids
16 #include <unistd.h> // close/getuid
17 #include <limits.h> // INT_MIN/INT_MAX
19 #include "../common/doregex.h"
20 #include "../common/config.h"
22 #define USE_NCURSES_INTERFACE 0
23 #define DEBUG_TRACE_SERVER 0
24 #define USE_AUTOAUTH 1
26 #define MAX_TXT_ARGS 5 // Maximum number of textual arguments (including command)
27 #define DISPENSE_MULTIPLE_MAX 20 // Maximum argument to -c
33 int main(int argc, char *argv[]);
34 int ParseArguments(int argc, char *argv[]);
35 // --- Coke Server Communication ---
37 char *trim(char *string);
38 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
39 void CompileRegex(regex_t *regex, const char *pattern, int flags);
42 const char *gsConfigFile = "/etc/opendispense/client.conf";
44 const char *gsDispenseServer = "merlo.ucc.gu.uwa.edu.au";
45 int giDispensePort = 11020;
46 int giDispenseServerSet = 0; // True if set by command line
47 int giDispensePortSet = 0; // True if set by command line
51 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
52 int gbIsAuthenticated = 0;
54 char *gsItemPattern; //!< Item pattern
55 char *gsEffectiveUser; //!< '-u' Dispense as another user
57 enum eUI_Modes giUIMode = UI_MODE_STANDARD;
58 int gbDryRun = 0; //!< '-n' Read-only
59 int gbDisallowSelectWithoutBalance = 1; //!< Don't allow items to be hilighted if not affordable
61 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
62 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
64 char *gsUserName; //!< User that dispense will happen as
65 char *gsUserFlags; //!< User's flag set
66 int giUserBalance = -1; //!< User balance (set by Authenticate)
67 int giDispenseCount = 1; //!< Number of dispenses to do
69 char *gsTextArgs[MAX_TXT_ARGS];
80 " Show interactive list\n"
81 " dispense <name>|<index>|<itemid>\n"
82 " Dispense named item (<name> matches if it is a unique prefix)\n"
84 " Show the finger output\n"
86 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "give") == 0 )
88 " dispense give <user> <amount> \"<reason>\"\n"
89 " Give money to another user\n"
92 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "donate") == 0 )
94 " dispense donate <amount> \"<reason>\"\n"
95 " Donate to the club\n"
97 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "iteminfo") == 0 )
99 " dispense iteminfo <itemid>\n"
100 " Get the name and price for an item\n"
102 // if( giTextArgc == 0 || strcmp(gsTextArgs[0], "enumitems") == 0 )
104 // " dispense enumitems\n"
105 // " List avaliable items\n"
107 if( giTextArgc == 0 )
108 printf(" == Coke members == \n");
109 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "acct") == 0 )
111 " dispense acct [<user>]\n"
112 " Show user balances\n"
113 " dispense acct <user> [+-]<amount> \"<reason>\"\n"
114 " Alter a account value\n"
115 " dispense acct <user> =<amount> \"<reason>\"\n"
116 " Set an account balance\n"
118 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "refund") == 0 )
120 " dispense refund <user> <itemid> [<price>]\n"
121 " Refund an item to a user (with optional price override)\n"
122 " Item IDs can be seen in the cokelog (in the brackets after the item name)\n"
123 " e.g. coke:6 for a coke, snack:33 for slot 33 of the snack machine\n"
125 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "slot") == 0 )
127 " dispense slot <itemid> <price> <name>\n"
128 " Rename/Re-price a slot\n"
130 if( giTextArgc == 0 )
131 printf(" == Dispense administrators ==\n");
132 if( giTextArgc == 0 || strcmp(gsTextArgs[0], "user") == 0 )
134 " dispense user add <user>\n"
135 " Create new account\n"
136 " dispense user type <user> <flags> <reason>\n"
137 " Alter a user's flags\n"
138 " <flags> is a comma-separated list of user, coke, admin, internal or disabled\n"
139 " Flags are removed by preceding the name with '-' or '!'\n"
141 if( giTextArgc == 0 )
145 " Dispense multiple times\n"
147 " Set a different user (Coke members only)\n"
151 " Use simple textual interface (instead of ncurses)\n"
153 " Dry run - Do not actually do dispenses\n"
154 " -m <min balance>\n"
155 " -M <max balance>\n"
156 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
158 " Set the config file path (default: `/etc/opendispense/client.conf'\n"
161 " 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"
171 int subcommand_finger(void)
174 int sock = OpenConnection(gsDispenseServer, giDispensePort);
175 if( sock < 0 ) return RV_SOCKET_ERROR;
178 PopulateItemList(sock);
180 printf("The UCC Coke machine.\n\n");
182 // Only get coke slot statuses
183 for( int i = 0; i <= 6; i ++ )
186 switch(gaItems[i].Status)
188 case 0: status = "Avail"; break;
189 case 1: status = "Sold "; break;
194 printf("%i - %s %3i %s\n", gaItems[i].ID, status, gaItems[i].Price, gaItems[i].Desc);
197 printf("\nMay your pink fish bing into the distance.\n");
204 // - Display/manipulate account balances
206 int subcommand_acct(void)
211 int sock = OpenConnection(gsDispenseServer, giDispensePort);
212 if( sock < 0 ) return RV_SOCKET_ERROR;
214 if( giTextArgc == 1 ) {
215 ret = Dispense_EnumUsers(sock);
220 // gsTextArgs[1]: Username
223 if( giTextArgc != 2 )
225 if( giTextArgc != 4 ) {
226 fprintf(stderr, "`dispense acct` requires a reason\n");
231 // Authentication required
232 ret = Authenticate(sock);
235 // gsTextArgs[1]: Username
236 // gsTextArgs[2]: Ammount
237 // gsTextArgs[3]: Reason
239 long int balance = strtol(gsTextArgs[2]+(gsTextArgs[2][0] == '='), &tmp, 10);
240 if(!tmp || *tmp != '\0') {
241 fprintf(stderr, "dispense acct: Value must be a decimal number of cents\n");
245 if( gsTextArgs[2][0] == '=' ) {
247 ret = Dispense_ShowUser(sock, gsTextArgs[1]);
248 ret = Dispense_SetBalance(sock, gsTextArgs[1], balance, gsTextArgs[3]);
252 ret = Dispense_AlterBalance(sock, gsTextArgs[1], balance, gsTextArgs[3]);
261 // Show user information
262 ret = Dispense_ShowUser(sock, gsTextArgs[1]);
270 // - Transfer credit from the current user to another account
272 // "Here, have some money."
274 int subcommand_give(int argc, char *args[])
279 fprintf(stderr, "`dispense give` takes three arguments\n");
284 const char *dst_acct = args[0];
285 const char *amt_str = args[1];
286 const char *message = args[2];
289 int sock = OpenConnection(gsDispenseServer, giDispensePort);
290 if( sock < 0 ) return RV_SOCKET_ERROR;
293 ret = Authenticate(sock);
297 long amt = strtol(amt_str, &end, 10);
298 if( !end || *end != '\0' ) {
299 fprintf(stderr, "dispense give: Balance is invalid, must be decimal number of cents");
302 ret = Dispense_Give(sock, dst_acct, amt, message);
310 // - User administration (Admin Only)
312 int subcommand_user(int argc, char *args[])
316 // Check argument count
318 fprintf(stderr, "Error: `dispense user` requires arguments\n");
324 int sock = OpenConnection(gsDispenseServer, giDispensePort);
325 if( sock < 0 ) return RV_SOCKET_ERROR;
327 // Attempt authentication
328 ret = Authenticate(sock);
332 if( strcmp(args[0], "add") == 0 )
334 if( giTextArgc != 3 ) {
335 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
340 ret = Dispense_AddUser(sock, args[1]);
343 else if( strcmp(args[0], "type") == 0 || strcmp(args[0], "flags") == 0 )
345 if( argc < 3 || argc > 4 ) {
346 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
351 ret = Dispense_SetUserType(sock, args[1], args[2], (argc == 3 ? "" : args[3]));
355 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
365 // - Donate money to the club
367 int subcommand_donate(int argc, char *args[])
371 // Check argument count
373 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
379 int sock = OpenConnection(gsDispenseServer, giDispensePort);
380 if( sock < 0 ) return RV_SOCKET_ERROR;
382 // Attempt authentication
383 ret = Authenticate(sock);
387 ret = Dispense_Donate(sock, atoi(args[0]), args[1]);
396 // - Refund a purchased item
398 // "Well excuuuuse me, princess"
400 int subcommand_refund(int argc, char *args[])
404 // Check argument count
405 if( argc != 2 && argc != 3 ) {
406 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
412 int sock = OpenConnection(gsDispenseServer, giDispensePort);
413 if(sock < 0) return RV_SOCKET_ERROR;
415 // Attempt authentication
416 ret = Authenticate(sock);
421 price = atoi(args[2]);
423 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
428 // Username, Item, cost
429 ret = Dispense_Refund(sock, args[0], args[1], price);
437 // `dispense iteminfo`
438 // - Get the state of an item
440 int subcommand_iteminfo(int argc, char *args[])
444 // Check argument count
446 fprintf(stderr, "Error: `dispense iteminfo` takes one argument\n");
451 char *item_id = args[0];
453 regmatch_t matches[3];
455 if( RunRegex(&gUserItemIdentRegex, item_id, 3, matches, NULL) != 0 ) {
456 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
459 char *type = item_id + matches[1].rm_so;
460 item_id[ matches[1].rm_eo ] = '\0';
461 int id = atoi( item_id + matches[2].rm_so );
463 int sock = OpenConnection(gsDispenseServer, giDispensePort);
464 if( sock < 0 ) return RV_SOCKET_ERROR;
466 ret = Dispense_ItemInfo(sock, type, id);
473 // - Update the name/price of an item
475 int subcommand_slot(int argc, char *args[])
481 fprintf(stderr, "Error: `dispense slot` takes three arguments\n");
485 char *slot_id = args[0];
486 char *price_str = args[1];
487 char *newname = args[2];
490 regmatch_t matches[3];
491 if( RunRegex(&gUserItemIdentRegex, slot_id, 3, matches, NULL) != 0 ) {
492 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
495 const char *item_type = slot_id + matches[1].rm_so;
496 slot_id[ matches[1].rm_eo ] = '\0';
497 int item_id = atoi( slot_id + matches[2].rm_so );
501 int price = strtol( price_str, &end, 0 );
502 if( price < 0 || *end != '\0' ) {
503 fprintf(stderr, "Error: Invalid price passed (must be >= 0)\n");
508 for( char *pos = newname; *pos; pos ++ )
510 if( !isalnum(*pos) && *pos != ' ' ) {
511 fprintf(stderr, "Error: You should only have letters, numbers and spaces in an item name\n");
516 // Connect & Authenticate
517 int sock = OpenConnection(gsDispenseServer, giDispensePort);
518 if( sock < 0 ) return RV_SOCKET_ERROR;
520 ret = Authenticate(sock);
524 ret = Dispense_SetItem(sock, item_type, item_id, price, newname);
531 // `dispense pincheck`
532 // - Validate a user's pin (used by the snack machine)
534 int subcommand_pincheck(int argc, char *args[])
538 if( argc < 1 || argc > 2 ) {
539 fprintf(stderr, "Error: `dispense pincheck` takes one/two arguments\n");
544 struct passwd *pwd = getpwuid( getuid() );
545 gsUserName = strdup(pwd->pw_name);
547 const char *pin = args[0];
548 const char *user = (argc > 1 ? args[1] : gsUserName);
550 int sock = OpenConnection(gsDispenseServer, giDispensePort);
551 if( sock < 0 ) return RV_SOCKET_ERROR;
553 ret = Authenticate(sock);
556 ret = DispenseCheckPin(sock, user, pin);
564 // - Set the pin of the current account
566 int subcommand_pinset(int argc, char *args[])
571 fprintf(stderr, "Error: `dispense pinset` takes one argument\n");
576 const char *pin = args[0];
578 int sock = OpenConnection(gsDispenseServer, giDispensePort);
579 if( sock < 0 ) return RV_SOCKET_ERROR;
581 ret = Authenticate(sock);
584 ret = DispenseSetPin(sock, pin);
590 int main(int argc, char *argv[])
597 // -- Create regular expressions
598 // > Code Type Count ...
599 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
600 // > Code Type Ident Status Price Desc
601 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);
602 // > Code 'SALT' salt
603 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
604 // > Code 'User' Username Balance Flags
605 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
607 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
610 ret = ParseArguments(argc, argv);
615 Config_ParseFile(gsConfigFile);
617 // Parse config values
618 if (!giDispenseServerSet) {
619 gsDispenseServer = Config_GetValue("dispense_server",0);
621 if (!giDispensePortSet) {
622 giDispensePort = Config_GetValue_Int("dispense_port",0);
627 if( strcmp(gsTextArgs[0], "finger") == 0 ) {
628 return subcommand_finger();
630 else if( strcmp(gsTextArgs[0], "acct") == 0 ) {
631 return subcommand_acct();
633 else if( strcmp(gsTextArgs[0], "give") == 0 ) {
634 return subcommand_give(giTextArgc-1, gsTextArgs+1);
636 else if( strcmp(gsTextArgs[0], "user") == 0 ) {
637 return subcommand_user(giTextArgc-1, gsTextArgs+1);
639 else if( strcmp(gsTextArgs[0], "donate") == 0 ) {
640 return subcommand_donate(giTextArgc-1, gsTextArgs+1);
642 else if( strcmp(gsTextArgs[0], "refund") == 0 ) {
643 return subcommand_refund(giTextArgc-1, gsTextArgs+1);
645 else if( strcmp(gsTextArgs[0], "iteminfo") == 0 ) {
646 return subcommand_iteminfo(giTextArgc-1, gsTextArgs+1);
648 else if( strcmp(gsTextArgs[0], "slot") == 0 ) {
649 return subcommand_slot(giTextArgc-1, gsTextArgs+1);
651 else if(strcmp(gsTextArgs[0], "pincheck") == 0) {
652 return subcommand_pincheck(giTextArgc-1, gsTextArgs+1);
654 else if(strcmp(gsTextArgs[0], "pinset") == 0) {
655 return subcommand_pinset(giTextArgc-1, gsTextArgs+1);
658 // Item name / pattern
659 gsItemPattern = gsTextArgs[0];
663 int sock = OpenConnection(gsDispenseServer, giDispensePort);
664 if( sock < 0 ) return RV_SOCKET_ERROR;
666 // Get the user's balance
667 ret = GetUserBalance(sock);
671 PopulateItemList(sock);
673 // Disconnect from server
676 if( gsItemPattern && gsItemPattern[0] )
678 regmatch_t matches[3];
680 if( strcmp(gsItemPattern, "door") == 0 )
682 // Connect, Authenticate, dispense and close
683 sock = OpenConnection(gsDispenseServer, giDispensePort);
684 if( sock < 0 ) return RV_SOCKET_ERROR;
685 ret = Authenticate(sock);
687 ret = DispenseItem(sock, "door", 0);
691 // Item id (<type>:<num>)
692 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
697 // Get and finish ident
698 ident = gsItemPattern + matches[1].rm_so;
699 gsItemPattern[matches[1].rm_eo] = '\0';
701 id = atoi( gsItemPattern + matches[2].rm_so );
703 // Connect, Authenticate, dispense and close
704 sock = OpenConnection(gsDispenseServer, giDispensePort);
705 if( sock < 0 ) return RV_SOCKET_ERROR;
707 Dispense_ItemInfo(sock, ident, id);
709 ret = Authenticate(sock);
711 ret = DispenseItem(sock, ident, id);
715 // Item number (6 = coke)
716 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
718 i = atoi(gsItemPattern);
725 for( i = 0; i < giNumItems; i ++ )
727 // Prefix match (with case-insensitive match)
728 for( j = 0; gsItemPattern[j]; j ++ )
730 if( gaItems[i].Desc[j] == gsItemPattern[j] )
732 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
736 // Check if the prefix matched
737 if( gsItemPattern[j] != '\0' )
741 if( gaItems[i].Desc[j] == '\0' ) {
746 // Only one match allowed
751 // TODO: Allow ambiguous matches?
752 // or just print a wanrning
753 printf("Warning - Ambiguous pattern, stopping\n");
758 // Was a match found?
761 fprintf(stderr, "No item matches the passed string\n");
768 else if( giUIMode != UI_MODE_BASIC )
774 // Very basic dispense interface
775 for( i = 0; i < giNumItems; i ++ ) {
777 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
780 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
781 gaItems[i].Price, gaItems[i].Desc);
790 fgets(buffer, BUFSIZ, stdin);
794 if( buf[0] == 'q' ) break;
798 if( i != 0 || buf[0] == '0' )
800 if( i < 0 || i >= giNumItems ) {
801 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
810 // Check for a valid item ID
814 // Connect, Authenticate, dispense and close
815 sock = OpenConnection(gsDispenseServer, giDispensePort);
816 if( sock < 0 ) return RV_SOCKET_ERROR;
818 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
821 ret = Authenticate(sock);
824 for( j = 0; j < giDispenseCount; j ++ ) {
825 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
829 printf("%i items dispensed\n", j);
831 Dispense_ShowUser(sock, gsUserName);
839 int ParseArguments(int argc, char *argv[])
841 for( int i = 1; i < argc; i ++ )
855 if( i > 2 && strcmp(argv[i-1], "type") == 0 )
857 if( i + 1 >= argc ) {
858 fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
862 giDispenseCount = atoi(argv[++i]);
863 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
864 fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
870 case 'm': // Minimum balance
871 if( i + 1 >= argc ) {
872 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
876 giMinimumBalance = atoi(argv[++i]);
878 case 'M': // Maximum balance
879 if( i + 1 >= argc ) {
880 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
884 giMaximumBalance = atoi(argv[++i]);
887 case 'f': // Override Config File
888 if( i + 1 >= argc ) {
889 fprintf(stderr, "%s: -f takes an argument\n", argv[0]);
893 gsConfigFile = argv[++i];
896 case 'u': // Override User
897 if( i + 1 >= argc ) {
898 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
902 gsEffectiveUser = argv[++i];
905 case 'H': // Override remote host
906 if( i + 1 >= argc ) {
907 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
911 gsDispenseServer = argv[++i];
912 giDispenseServerSet = 1;
914 case 'P': // Override remote port
915 if( i + 1 >= argc ) {
916 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
920 giDispensePort = atoi(argv[++i]);
921 giDispensePortSet = 1;
924 // Set slot name/price
926 if( giTextArgc != 0 ) {
927 fprintf(stderr, "%s: -s must appear before other arguments\n", argv[0]);
931 gsTextArgs[0] = "slot"; // HACK!!
935 case 'G': // Don't use GUI
936 giUIMode = UI_MODE_BASIC;
938 case 'D': // Drinks only
939 giUIMode = UI_MODE_DRINKSONLY;
941 case 'n': // Dry Run / read-only
945 if( strcmp(argv[i], "--help") == 0 ) {
949 else if( strcmp(argv[i], "--dry-run") == 0 ) {
952 else if( strcmp(argv[i], "--drinks-only") == 0 ) {
953 giUIMode = UI_MODE_DRINKSONLY;
955 else if( strcmp(argv[i], "--can-select-all") == 0 ) {
956 gbDisallowSelectWithoutBalance = 0;
959 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
965 // The first argument is not allowed to begin with 'i'
966 // (catches most bad flags)
967 if( giTextArgc == 0 ) {
968 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
972 if( giTextArgc == MAX_TXT_ARGS )
974 fprintf(stderr, "ERROR: Too many arguments\n");
977 gsTextArgs[giTextArgc++] = argv[i];
984 if( giTextArgc == MAX_TXT_ARGS )
986 fprintf(stderr, "ERROR: Too many arguments\n");
990 gsTextArgs[giTextArgc++] = argv[i];
999 char *trim(char *string)
1003 while( isspace(*string) )
1006 for( i = strlen(string); i--; )
1008 if( isspace(string[i]) )