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);
92 char *ReadLine(int Socket);
93 int sendf(int Socket, const char *Format, ...);
94 char *trim(char *string);
95 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
96 void CompileRegex(regex_t *regex, const char *pattern, int flags);
99 char *gsDispenseServer = "heathred";
100 int giDispensePort = 11020;
104 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
105 int gbIsAuthenticated = 0;
107 char *gsItemPattern; //!< Item pattern
108 char *gsEffectiveUser; //!< '-u' Dispense as another user
109 int giUIMode = UI_MODE_STANDARD;
110 int gbDryRun = 0; //!< '-n' Read-only
111 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
112 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
113 char *gsUserName; //!< User that dispense will happen as
114 char *gsUserFlags; //!< User's flag set
115 int giUserBalance=-1; //!< User balance (set by Authenticate)
116 int giDispenseCount = 1; //!< Number of dispenses to do
125 " Show interactive list\n"
126 " dispense <name>|<index>|<itemid>\n"
127 " Dispense named item (<name> matches if it is a unique prefix)\n"
128 " dispense give <user> <ammount> \"<reason>\"\n"
129 " Give money to another user\n"
130 " dispense donate <ammount> \"<reason>\"\n"
131 " Donate to the club\n"
132 " dispense iteminfo <itemid>\n"
133 " Get the name and price for an item\n"
134 " == Coke members == \n"
135 " dispense acct [<user>]\n"
136 " Show user balances\n"
137 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
138 " Alter a account value\n"
139 " dispense refund <user> <itemid> [<price>]\n"
140 " Refund an item to a user (with optional price override)\n"
141 " == Dispense administrators ==\n"
142 " dispense acct <user> =<ammount> \"<reason>\"\n"
143 " Set an account balance\n"
144 " dispense user add <user>\n"
145 " Create new account\n"
146 " dispense user type <user> <flags>\n"
147 " Alter a user's flags\n"
148 " <flags> is a comma-separated list of user, coke, admin, internal or disabled\n"
149 " Flags are removed by preceding the name with '-' or '!'\n"
153 " Dispense multiple times\n"
155 " Set a different user (Coke members only)\n"
159 " Use alternate GUI\n"
161 " Dry run - Do not actually do dispenses\n"
162 " -m <min balance>\n"
163 " -M <max balance>\n"
164 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
167 " 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"
173 int main(int argc, char *argv[])
178 char *text_args[MAX_TXT_ARGS]; // Non-flag arguments
183 // -- Create regular expressions
184 // > Code Type Count ...
185 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
186 // > Code Type Ident Status Price Desc
187 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);
188 // > Code 'SALT' salt
189 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
190 // > Code 'User' Username Balance Flags
191 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
193 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
196 for( i = 1; i < argc; i ++ )
210 if( i + 1 >= argc ) {
211 fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
215 giDispenseCount = atoi(argv[++i]);
216 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
217 fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
223 case 'm': // Minimum balance
224 if( i + 1 >= argc ) {
225 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
229 giMinimumBalance = atoi(argv[++i]);
231 case 'M': // Maximum balance
232 if( i + 1 >= argc ) {
233 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
237 giMaximumBalance = atoi(argv[++i]);
240 case 'u': // Override User
241 if( i + 1 >= argc ) {
242 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
246 gsEffectiveUser = argv[++i];
249 case 'H': // Override remote host
250 if( i + 1 >= argc ) {
251 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
255 gsDispenseServer = argv[++i];
257 case 'P': // Override remote port
258 if( i + 1 >= argc ) {
259 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
263 giDispensePort = atoi(argv[++i]);
266 case 'G': // Don't use GUI
267 giUIMode = UI_MODE_BASIC;
269 case 'D': // Drinks only
270 giUIMode = UI_MODE_DRINKSONLY;
272 case 'n': // Dry Run / read-only
276 if( !isdigit(argv[i][0]) ) {
277 fprintf(stderr, "%s: Unknown switch '%s'\n", argv[0], argv[i]);
281 if( text_argc + 1 == MAX_TXT_ARGS )
283 fprintf(stderr, "ERROR: Too many arguments\n");
286 text_args[text_argc++] = argv[i];
293 if( text_argc + 1 == MAX_TXT_ARGS )
295 fprintf(stderr, "ERROR: Too many arguments\n");
299 text_args[text_argc++] = argv[i];
306 if( strcmp(text_args[0], "acct") == 0 )
309 sock = OpenConnection(gsDispenseServer, giDispensePort);
310 if( sock < 0 ) return RV_SOCKET_ERROR;
312 if( text_argc == 1 ) {
313 ret = Dispense_EnumUsers(sock);
318 // text_args[1]: Username
323 if( text_argc != 4 ) {
324 fprintf(stderr, "`dispense acct` requires a reason\n");
329 // Authentication required
330 ret = Authenticate(sock);
333 // text_args[1]: Username
334 // text_args[2]: Ammount
335 // text_args[3]: Reason
337 if( text_args[2][0] == '=' ) {
339 if( text_args[2][1] != '0' && atoi(text_args[2]+1) == 0 ) {
340 fprintf(stderr, "Error: Invalid balance to be set\n");
344 ret = Dispense_SetBalance(sock, text_args[1], atoi(text_args[2]+1), text_args[3]);
348 ret = Dispense_AlterBalance(sock, text_args[1], atoi(text_args[2]), text_args[3]);
351 // TODO: Preserve ret if non-zero
353 // Show user information
354 ret = Dispense_ShowUser(sock, text_args[1]);
361 // - "Here, have some money."
362 if( strcmp(text_args[0], "give") == 0 )
364 if( text_argc != 4 ) {
365 fprintf(stderr, "`dispense give` takes three arguments\n");
370 // text_args[1]: Destination
371 // text_args[2]: Ammount
372 // text_args[3]: Reason
375 sock = OpenConnection(gsDispenseServer, giDispensePort);
376 if( sock < 0 ) return RV_SOCKET_ERROR;
379 ret = Authenticate(sock);
382 ret = Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
390 // - User administration (Admin Only)
391 if( strcmp(text_args[0], "user") == 0 )
393 // Check argument count
394 if( text_argc == 1 ) {
395 fprintf(stderr, "Error: `dispense user` requires arguments\n");
401 sock = OpenConnection(gsDispenseServer, giDispensePort);
402 if( sock < 0 ) return RV_SOCKET_ERROR;
404 // Attempt authentication
405 ret = Authenticate(sock);
409 if( strcmp(text_args[1], "add") == 0 )
411 if( text_argc != 3 ) {
412 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
417 ret = Dispense_AddUser(sock, text_args[2]);
420 else if( strcmp(text_args[1], "type") == 0 || strcmp(text_args[1], "flags") == 0 )
422 if( text_argc != 4 ) {
423 fprintf(stderr, "Error: `dispense user flags` requires two arguments\n");
428 ret = Dispense_SetUserType(sock, text_args[2], text_args[3]);
432 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
440 else if( strcmp(text_args[0], "donate") == 0 )
442 // Check argument count
443 if( text_argc != 3 ) {
444 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
450 sock = OpenConnection(gsDispenseServer, giDispensePort);
451 if( sock < 0 ) return RV_SOCKET_ERROR;
453 // Attempt authentication
454 ret = Authenticate(sock);
458 ret = Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
465 else if( strcmp(text_args[0], "refund") == 0 )
468 // Check argument count
469 if( text_argc != 3 && text_argc != 4 ) {
470 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
476 sock = OpenConnection(gsDispenseServer, giDispensePort);
477 if(sock < 0) return RV_SOCKET_ERROR;
479 // Attempt authentication
480 ret = Authenticate(sock);
483 if( text_argc == 4 ) {
484 price = atoi(text_args[3]);
486 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
491 // Username, Item, cost
492 ret = Dispense_Refund(sock, text_args[1], text_args[2], price);
496 return RV_UNKNOWN_ERROR;
498 // Query an item price
499 else if( strcmp(text_args[0], "iteminfo") == 0 )
501 regmatch_t matches[3];
504 // Check argument count
505 if( text_argc != 2 ) {
506 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
511 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
512 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
515 type = text_args[1] + matches[1].rm_so;
516 text_args[1][ matches[1].rm_eo ] = '\0';
517 id = atoi( text_args[1] + matches[2].rm_so );
519 sock = OpenConnection(gsDispenseServer, giDispensePort);
520 if( sock < 0 ) return RV_SOCKET_ERROR;
522 ret = Dispense_ItemInfo(sock, type, id);
526 // Item name / pattern
528 gsItemPattern = text_args[0];
532 sock = OpenConnection(gsDispenseServer, giDispensePort);
533 if( sock < 0 ) return RV_SOCKET_ERROR;
535 // Get the user's balance
536 ret = GetUserBalance(sock);
540 PopulateItemList(sock);
542 // Disconnect from server
545 if( gsItemPattern && gsItemPattern[0] )
547 regmatch_t matches[3];
549 if( strcmp(gsItemPattern, "door") == 0 )
551 // Connect, Authenticate, dispense and close
552 sock = OpenConnection(gsDispenseServer, giDispensePort);
553 if( sock < 0 ) return RV_SOCKET_ERROR;
554 ret = Authenticate(sock);
556 ret = DispenseItem(sock, "door", 0);
560 // Item id (<type>:<num>)
561 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
566 // Get and finish ident
567 ident = gsItemPattern + matches[1].rm_so;
568 gsItemPattern[matches[1].rm_eo] = '\0';
570 id = atoi( gsItemPattern + matches[2].rm_so );
572 // Connect, Authenticate, dispense and close
573 sock = OpenConnection(gsDispenseServer, giDispensePort);
574 if( sock < 0 ) return RV_SOCKET_ERROR;
576 Dispense_ItemInfo(sock, ident, id);
578 ret = Authenticate(sock);
580 ret = DispenseItem(sock, ident, id);
584 // Item number (6 = coke)
585 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
587 i = atoi(gsItemPattern);
594 for( i = 0; i < giNumItems; i ++ )
596 // Prefix match (with case-insensitive match)
597 for( j = 0; gsItemPattern[j]; j ++ )
599 if( gaItems[i].Desc[j] == gsItemPattern[j] )
601 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
605 // Check if the prefix matched
606 if( gsItemPattern[j] != '\0' )
610 if( gaItems[i].Desc[j] == '\0' ) {
615 // Only one match allowed
620 // TODO: Allow ambiguous matches?
621 // or just print a wanrning
622 printf("Warning - Ambiguous pattern, stopping\n");
627 // Was a match found?
630 fprintf(stderr, "No item matches the passed string\n");
637 else if( giUIMode != UI_MODE_BASIC )
643 // Very basic dispense interface
644 for( i = 0; i < giNumItems; i ++ ) {
646 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
649 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
650 gaItems[i].Price, gaItems[i].Desc);
659 fgets(buffer, BUFSIZ, stdin);
663 if( buf[0] == 'q' ) break;
667 if( i != 0 || buf[0] == '0' )
669 if( i < 0 || i >= giNumItems ) {
670 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
679 // Check for a valid item ID
683 // Connect, Authenticate, dispense and close
684 sock = OpenConnection(gsDispenseServer, giDispensePort);
685 if( sock < 0 ) return RV_SOCKET_ERROR;
687 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
690 ret = Authenticate(sock);
693 for( j = 0; j < giDispenseCount; j ++ ) {
694 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
698 printf("%i items dispensed\n", j);
706 // -------------------
707 // --- NCurses GUI ---
708 // -------------------
710 * \brief Render the NCurses UI
712 int ShowNCursesUI(void)
717 const int displayMinWidth = 40;
718 char *titleString = "Dispense";
723 int ret = -2; // -2: Used for marking "no return yet"
725 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
732 if( gsEffectiveUser )
733 username = gsEffectiveUser;
735 pwd = getpwuid( getuid() );
736 username = pwd->pw_name;
739 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
746 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
747 // Get item count per screen
748 // - 6: randomly chosen (Need at least 3)
749 itemCount = LINES - 6;
750 if( itemCount > maxItemIndex )
751 itemCount = maxItemIndex;
754 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
759 height = itemCount + 3;
760 width = displayMinWidth;
763 xBase = COLS/2 - width/2;
764 yBase = LINES/2 - height/2;
769 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
772 for( i = 0; i < itemCount; i ++ )
776 move( yBase + 1 + i, xBase );
781 // Check for the '...' row
782 // - Oh god, magic numbers!
783 if( (i == 0 && itemBase > 0)
784 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
786 printw(" ..."); pos += 8;
787 times = (width - pos) - 1;
788 while(times--) addch(' ');
793 yBase + 1 + i, xBase + pos, // Position
794 (width - pos) - 3, // Width
795 itemBase + i, // Index
796 !!(currentItem == itemBase + i) // Hilighted
801 // Scrollbar (if needed)
802 if( maxItemIndex > itemCount ) {
806 else if( i == itemCount - 1 ) {
810 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
811 if( i-1 == percentage*(itemCount-3)/100 ) {
825 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
828 // - Username, balance, flags
829 PrintAlign(yBase+height-1, xBase+1, width-2,
830 username, ' ', balance_str, ' ', gsUserFlags);
846 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
849 if( currentItem >= maxItemIndex ) {
852 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
859 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
862 if( currentItem < 0 ) {
863 currentItem = maxItemIndex - 1;
865 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
875 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
876 itemBase = currentItem - 2;
877 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
878 itemBase = currentItem - itemCount + 2;
884 ret = ShowItemAt(0, 0, 0, currentItem, 0);
888 ret = -1; // -1: Return with no dispense
892 // Check if the return value was changed
893 if( ret != -2 ) break;
905 * \brief Show item \a Index at (\a Col, \a Row)
906 * \return Dispense index of item
907 * \note Part of the NCurses UI
909 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
919 // - This assumes that
920 case UI_MODE_STANDARD:
922 // Index = -1, request limit
923 if( Index < 0 || Index >= giNumItems+2 )
929 name = "Coke Machine";
930 Index = -1; // -1 indicates a label
937 name = gaItems[Index].Desc;
938 price = gaItems[Index].Price;
939 status = gaItems[Index].Status;
947 name = "Electronic Payment System";
948 Index = -1; // -1 indicates a label
953 name = gaItems[Index].Desc;
954 price = gaItems[Index].Price;
955 status = gaItems[Index].Status;
961 // Width = 0, don't print
964 // 4 preceding, 5 price
965 int nameWidth = Width - 4 - 5;
970 // Show hilight and status
989 printw("%-*.*s", nameWidth, nameWidth, name);
991 // getyx(stdscr, _y, _x);
992 // Assumes max 4 digit prices
993 // times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
994 // while(times--) addch(' ');
996 printw(" %4i", price);
1000 printw("-- %s", name);
1001 getyx(stdscr, _y, _x);
1002 times = Width - 4 - (_x - Col);
1003 while(times--) addch(' ');
1008 // If the item isn't availiable for sale, return -1 (so it's skipped)
1016 * \brief Print a three-part string at the specified position (formatted)
1017 * \note NCurses UI Helper
1019 * Prints \a Left on the left of the area, \a Right on the righthand side
1020 * and \a Mid in the middle of the area. These are padded with \a Pad1
1021 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1023 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1024 * and the arguments to these are read in that order.
1026 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1027 const char *Mid, char Pad2, const char *Right, ...)
1029 int lLen, mLen, rLen;
1034 // Get the length of the strings
1035 va_start(args, Right);
1036 lLen = vsnprintf(NULL, 0, Left, args);
1037 mLen = vsnprintf(NULL, 0, Mid, args);
1038 rLen = vsnprintf(NULL, 0, Right, args);
1042 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1043 return ; // TODO: What to do?
1049 va_start(args, Right);
1053 vsnprintf(tmp, lLen+1, Left, args);
1057 times = (Width - mLen)/2 - lLen;
1058 while(times--) addch(Pad1);
1062 vsnprintf(tmp, mLen+1, Mid, args);
1066 times = (Width - mLen)/2 - rLen;
1067 if( (Width - mLen) % 2 ) times ++;
1068 while(times--) addch(Pad2);
1072 vsnprintf(tmp, rLen+1, Right, args);
1077 // ---------------------
1078 // --- Coke Protocol ---
1079 // ---------------------
1080 int OpenConnection(const char *Host, int Port)
1082 struct hostent *host;
1083 struct sockaddr_in serverAddr;
1086 host = gethostbyname(Host);
1088 fprintf(stderr, "Unable to look up '%s'\n", Host);
1092 memset(&serverAddr, 0, sizeof(serverAddr));
1094 serverAddr.sin_family = AF_INET; // IPv4
1095 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1096 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1097 serverAddr.sin_port = htons(Port);
1099 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1101 fprintf(stderr, "Failed to create socket\n");
1105 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1107 if( geteuid() == 0 || getuid() == 0 )
1110 struct sockaddr_in localAddr;
1111 memset(&localAddr, 0, sizeof(localAddr));
1112 localAddr.sin_family = AF_INET; // IPv4
1114 // Loop through all the top ports until one is avaliable
1115 for( i = 512; i < 1024; i ++)
1117 localAddr.sin_port = htons(i); // IPv4
1118 // Attempt to bind to low port for autoauth
1119 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1123 printf("Warning: AUTOAUTH unavaliable\n");
1125 // printf("Bound to 0.0.0.0:%i\n", i);
1128 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1129 fprintf(stderr, "Failed to connect to server\n");
1133 // We're not authenticated if the connection has just opened
1134 gbIsAuthenticated = 0;
1140 * \brief Authenticate with the server
1141 * \return Boolean Failure
1143 int Authenticate(int Socket)
1148 #if ATTEMPT_PASSWORD_AUTH
1151 regmatch_t matches[4];
1154 if( gbIsAuthenticated ) return 0;
1157 pwd = getpwuid( getuid() );
1159 // Attempt automatic authentication
1160 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1162 // Check if it worked
1163 buf = ReadLine(Socket);
1165 responseCode = atoi(buf);
1166 switch( responseCode )
1168 case 200: // Autoauth succeeded, return
1172 case 401: // Untrusted, attempt password authentication
1175 #if ATTEMPT_PASSWORD_AUTH
1176 sendf(Socket, "USER %s\n", pwd->pw_name);
1177 printf("Using username %s\n", pwd->pw_name);
1179 buf = ReadLine(Socket);
1182 // Expected format: 100 SALT <something> ...
1183 // OR : 100 User Set
1184 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1185 responseCode = atoi(buf);
1186 if( responseCode != 100 ) {
1187 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1189 return RV_UNKNOWN_ERROR; // ERROR
1193 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1194 // Store it for later
1195 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1196 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1200 // Give three attempts
1201 for( i = 0; i < 3; i ++ )
1203 int ofs = strlen(pwd->pw_name)+strlen(salt);
1206 char *pass = getpass("Password: ");
1209 // Create hash string
1210 // <username><salt><hash>
1211 strcpy(tmp, pwd->pw_name);
1213 SHA1( (unsigned char*)pass, strlen(pass), h );
1214 memcpy(tmp+ofs, h, 20);
1217 SHA1( (unsigned char*)tmp, ofs+20, h );
1218 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1219 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1220 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1224 sendf(Socket, "PASS %s\n", tmpBuf);
1225 buf = ReadLine(Socket);
1227 responseCode = atoi(buf);
1229 if( responseCode == 200 ) break;
1230 // Bad username/password
1231 if( responseCode == 401 ) continue;
1233 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1235 return RV_UNKNOWN_ERROR;
1239 return RV_INVALID_USER; // 2 = Bad Password
1242 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1243 return RV_INVALID_USER;
1247 case 404: // Bad Username
1248 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1250 return RV_INVALID_USER;
1253 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1254 printf("%s\n", buf);
1256 return RV_UNKNOWN_ERROR;
1259 // Set effective user
1260 if( gsEffectiveUser ) {
1261 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1263 buf = ReadLine(Socket);
1264 responseCode = atoi(buf);
1266 switch(responseCode)
1269 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1273 printf("Only coke members can use `dispense -u`\n");
1275 return RV_PERMISSIONS;
1278 printf("Invalid user selected\n");
1280 return RV_INVALID_USER;
1283 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1284 printf("%s\n", buf);
1286 return RV_UNKNOWN_ERROR;
1292 gbIsAuthenticated = 1;
1297 int GetUserBalance(int Socket)
1299 regmatch_t matches[6];
1306 if( gsEffectiveUser ) {
1307 gsUserName = gsEffectiveUser;
1310 pwd = getpwuid( getuid() );
1311 gsUserName = strdup(pwd->pw_name);
1315 sendf(Socket, "USER_INFO %s\n", gsUserName);
1316 buf = ReadLine(Socket);
1317 responseCode = atoi(buf);
1318 switch(responseCode)
1320 case 202: break; // Ok
1323 printf("Invalid user? (USER_INFO failed)\n");
1325 return RV_INVALID_USER;
1328 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1329 printf("%s\n", buf);
1331 return RV_UNKNOWN_ERROR;
1334 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1336 giUserBalance = atoi( buf + matches[4].rm_so );
1337 gsUserFlags = strdup( buf + matches[5].rm_so );
1345 * \brief Read an item info response from the server
1346 * \param Dest Destination for the read item (strings will be on the heap)
1348 int ReadItemInfo(int Socket, tItem *Dest)
1353 regmatch_t matches[8];
1357 buf = ReadLine(Socket);
1358 responseCode = atoi(buf);
1360 switch(responseCode)
1365 printf("Bad item name\n");
1370 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1372 return RV_UNKNOWN_ERROR;
1375 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1377 buf[ matches[3].rm_eo ] = '\0';
1378 buf[ matches[5].rm_eo ] = '\0';
1379 buf[ matches[7].rm_eo ] = '\0';
1381 statusStr = &buf[ matches[5].rm_so ];
1383 Dest->ID = atoi( buf + matches[4].rm_so );
1385 if( strcmp(statusStr, "avail") == 0 )
1387 else if( strcmp(statusStr, "sold") == 0 )
1389 else if( strcmp(statusStr, "error") == 0 )
1392 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1394 return RV_UNKNOWN_ERROR;
1396 Dest->Price = atoi( buf + matches[6].rm_so );
1398 // Hack a little to reduce heap fragmentation
1400 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1401 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1402 strcpy(tmpType, buf + matches[3].rm_so);
1403 strcpy(tmpDesc, buf + matches[7].rm_so);
1405 Dest->Type = strdup( tmpType );
1406 Dest->Desc = strdup( tmpDesc );
1413 * \brief Fill the item information structure
1414 * \return Boolean Failure
1416 void PopulateItemList(int Socket)
1421 char *itemType, *itemStart;
1423 regmatch_t matches[4];
1425 // Ask server for stock list
1426 send(Socket, "ENUM_ITEMS\n", 11, 0);
1427 buf = ReadLine(Socket);
1429 //printf("Output: %s\n", buf);
1431 responseCode = atoi(buf);
1432 if( responseCode != 201 ) {
1433 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1434 exit(RV_UNKNOWN_ERROR);
1437 // - Get item list -
1440 // 201 Items <count>
1442 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1444 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1445 count = atoi( &buf[ matches[3].rm_so ] );
1448 if( strcmp(itemType, "Items") != 0 ) {
1450 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1452 exit(RV_UNKNOWN_ERROR);
1455 itemStart = &buf[ matches[3].rm_eo ];
1460 gaItems = malloc( giNumItems * sizeof(tItem) );
1462 // Fetch item information
1463 for( i = 0; i < giNumItems; i ++ )
1465 ReadItemInfo( Socket, &gaItems[i] );
1469 buf = ReadLine(Socket);
1470 responseCode = atoi(buf);
1472 if( responseCode != 200 ) {
1473 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1484 * \brief Get information on an item
1485 * \return Boolean Failure
1487 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1493 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1495 ret = ReadItemInfo(Socket, &item);
1498 printf("%8s:%-2i %2i.%02i %s\n",
1500 item.Price/100, item.Price%100,
1510 * \brief Dispense an item
1511 * \return Boolean Failure
1513 int DispenseItem(int Socket, const char *Type, int ID)
1515 int ret, responseCode;
1518 // Check for a dry run
1520 printf("Dry Run - No action\n");
1525 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1526 buf = ReadLine(Socket);
1528 responseCode = atoi(buf);
1529 switch( responseCode )
1532 printf("Dispense OK\n");
1536 printf("Not authenticated\n");
1537 ret = RV_PERMISSIONS;
1540 printf("Insufficient balance\n");
1544 printf("Bad item name\n");
1548 printf("Item failed to dispense, is the slot empty?\n");
1549 ret = RV_SERVER_ERROR;
1552 printf("Dispense not possible (slot empty/permissions)\n");
1553 ret = RV_SERVER_ERROR;
1556 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1557 ret = RV_UNKNOWN_ERROR;
1566 * \brief Alter a user's balance
1568 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1573 // Check for a dry run
1575 printf("Dry Run - No action\n");
1580 if( Ammount == 0 ) {
1581 printf("An ammount would be nice\n");
1582 return RV_ARGUMENTS;
1585 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1586 buf = ReadLine(Socket);
1588 responseCode = atoi(buf);
1591 switch(responseCode)
1593 case 200: return 0; // OK
1595 fprintf(stderr, "Insufficient balance\n");
1597 case 403: // Not in coke
1598 fprintf(stderr, "You are not in coke (sucker)\n");
1599 return RV_PERMISSIONS;
1600 case 404: // Unknown user
1601 fprintf(stderr, "Unknown user '%s'\n", Username);
1602 return RV_INVALID_USER;
1604 fprintf(stderr, "Unknown response code %i\n", responseCode);
1605 return RV_UNKNOWN_RESPONSE;
1612 * \brief Set a user's balance
1613 * \note Only avaliable to dispense admins
1615 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1620 // Check for a dry run
1622 printf("Dry Run - No action\n");
1626 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1627 buf = ReadLine(Socket);
1629 responseCode = atoi(buf);
1632 switch(responseCode)
1634 case 200: return 0; // OK
1635 case 403: // Not in coke
1636 fprintf(stderr, "You are not an admin\n");
1637 return RV_PERMISSIONS;
1638 case 404: // Unknown user
1639 fprintf(stderr, "Unknown user '%s'\n", Username);
1640 return RV_INVALID_USER;
1642 fprintf(stderr, "Unknown response code %i\n", responseCode);
1643 return RV_UNKNOWN_RESPONSE;
1650 * \brief Give money to another user
1652 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1658 printf("Sorry, you can only give, you can't take.\n");
1659 return RV_ARGUMENTS;
1662 // Fast return on zero
1663 if( Ammount == 0 ) {
1664 printf("Are you actually going to give any?\n");
1665 return RV_ARGUMENTS;
1668 // Check for a dry run
1670 printf("Dry Run - No action\n");
1674 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1676 buf = ReadLine(Socket);
1677 responseCode = atoi(buf);
1679 switch(responseCode)
1682 printf("Give succeeded\n");
1683 return RV_SUCCESS; // OK
1686 fprintf(stderr, "Insufficient balance\n");
1689 case 404: // Unknown user
1690 fprintf(stderr, "Unknown user '%s'\n", Username);
1691 return RV_INVALID_USER;
1694 fprintf(stderr, "Unknown response code %i\n", responseCode);
1695 return RV_UNKNOWN_RESPONSE;
1701 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1704 int responseCode, ret = -1;
1707 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1709 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1710 return RV_ARGUMENTS;
1713 // Check username (quick)
1714 if( strchr(Username, ' ') || strchr(Username, '\n') )
1716 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1717 return RV_ARGUMENTS;
1721 sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1723 buf = ReadLine(Socket);
1724 responseCode = atoi(buf);
1725 switch(responseCode)
1728 Dispense_ShowUser(Socket, Username); // Show destination account
1732 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1733 ret = RV_PERMISSIONS;
1736 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1737 ret = RV_INVALID_USER;
1740 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1744 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1753 * \brief Donate money to the club
1755 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1761 printf("Sorry, you can only give, you can't take.\n");
1765 // Fast return on zero
1766 if( Ammount == 0 ) {
1767 printf("Are you actually going to give any?\n");
1771 // Check for a dry run
1773 printf("Dry Run - No action\n");
1777 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1778 buf = ReadLine(Socket);
1780 responseCode = atoi(buf);
1783 switch(responseCode)
1785 case 200: return 0; // OK
1788 fprintf(stderr, "Insufficient balance\n");
1792 fprintf(stderr, "Unknown response code %i\n", responseCode);
1800 * \brief Enumerate users
1802 int Dispense_EnumUsers(int Socket)
1807 regmatch_t matches[4];
1809 if( giMinimumBalance != INT_MIN ) {
1810 if( giMaximumBalance != INT_MAX ) {
1811 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1814 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1818 if( giMaximumBalance != INT_MAX ) {
1819 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1822 sendf(Socket, "ENUM_USERS\n");
1825 buf = ReadLine(Socket);
1826 responseCode = atoi(buf);
1828 switch(responseCode)
1830 case 201: break; // Ok, length follows
1833 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1838 // Get count (not actually used)
1839 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1840 nUsers = atoi( buf + matches[3].rm_so );
1841 printf("%i users returned\n", nUsers);
1846 // Read returned users
1848 buf = ReadLine(Socket);
1849 responseCode = atoi(buf);
1851 if( responseCode != 202 ) break;
1853 _PrintUserLine(buf);
1855 } while(responseCode == 202);
1857 // Check final response
1858 if( responseCode != 200 ) {
1859 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1869 int Dispense_ShowUser(int Socket, const char *Username)
1872 int responseCode, ret;
1874 sendf(Socket, "USER_INFO %s\n", Username);
1875 buf = ReadLine(Socket);
1877 responseCode = atoi(buf);
1879 switch(responseCode)
1882 _PrintUserLine(buf);
1887 printf("Unknown user '%s'\n", Username);
1892 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1902 void _PrintUserLine(const char *Line)
1904 regmatch_t matches[6];
1907 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1912 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1913 char username[usernameLen + 1];
1914 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1915 char flags[flagsLen + 1];
1917 memcpy(username, Line + matches[3].rm_so, usernameLen);
1918 username[usernameLen] = '\0';
1919 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1920 flags[flagsLen] = '\0';
1922 bal = atoi(Line + matches[4].rm_so);
1923 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1927 int Dispense_AddUser(int Socket, const char *Username)
1930 int responseCode, ret;
1932 // Check for a dry run
1934 printf("Dry Run - No action\n");
1938 sendf(Socket, "USER_ADD %s\n", Username);
1940 buf = ReadLine(Socket);
1941 responseCode = atoi(buf);
1943 switch(responseCode)
1946 printf("User '%s' added\n", Username);
1951 printf("Only wheel can add users\n");
1956 printf("User '%s' already exists\n", Username);
1961 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1971 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1974 int responseCode, ret;
1976 // Check for a dry run
1978 printf("Dry Run - No action\n");
1982 // TODO: Pre-validate the string
1984 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1986 buf = ReadLine(Socket);
1987 responseCode = atoi(buf);
1989 switch(responseCode)
1992 printf("User '%s' updated\n", Username);
1997 printf("Only wheel can modify users\n");
2002 printf("User '%s' does not exist\n", Username);
2007 printf("Flag string is invalid\n");
2012 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2025 char *ReadLine(int Socket)
2027 static char buf[BUFSIZ];
2028 static int bufPos = 0;
2029 static int bufValid = 0;
2031 char *newline = NULL;
2033 char *ret = malloc(10);
2035 #if DEBUG_TRACE_SERVER
2036 printf("ReadLine: ");
2048 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2049 buf[bufPos+len] = '\0';
2052 newline = strchr( buf+bufPos, '\n' );
2057 retLen += strlen(buf+bufPos);
2058 ret = realloc(ret, retLen + 1);
2059 strcat( ret, buf+bufPos );
2062 int newLen = newline - (buf+bufPos) + 1;
2063 bufValid = len - newLen;
2066 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2069 #if DEBUG_TRACE_SERVER
2070 printf("%i '%s'\n", retLen, ret);
2076 int sendf(int Socket, const char *Format, ...)
2081 va_start(args, Format);
2082 len = vsnprintf(NULL, 0, Format, args);
2087 va_start(args, Format);
2088 vsnprintf(buf, len+1, Format, args);
2091 #if DEBUG_TRACE_SERVER
2092 printf("sendf: %s", buf);
2095 return send(Socket, buf, len, 0);
2099 char *trim(char *string)
2103 while( isspace(*string) )
2106 for( i = strlen(string); i--; )
2108 if( isspace(string[i]) )
2117 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2121 ret = regexec(regex, string, nMatches, matches, 0);
2122 if( ret && errorMessage ) {
2123 size_t len = regerror(ret, regex, NULL, 0);
2125 regerror(ret, regex, errorStr, len);
2126 printf("string = '%s'\n", string);
2127 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2134 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2136 int ret = regcomp(regex, pattern, flags);
2138 size_t len = regerror(ret, regex, NULL, 0);
2140 regerror(ret, regex, errorStr, len);
2141 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);