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( text_argc + 1 == MAX_TXT_ARGS )
278 fprintf(stderr, "ERROR: Too many arguments\n");
281 text_args[text_argc++] = argv[i];
288 if( text_argc + 1 == MAX_TXT_ARGS )
290 fprintf(stderr, "ERROR: Too many arguments\n");
294 text_args[text_argc++] = argv[i];
301 if( strcmp(text_args[0], "acct") == 0 )
304 sock = OpenConnection(gsDispenseServer, giDispensePort);
305 if( sock < 0 ) return RV_SOCKET_ERROR;
307 if( text_argc == 1 ) {
308 ret = Dispense_EnumUsers(sock);
313 // text_args[1]: Username
318 if( text_argc != 4 ) {
319 fprintf(stderr, "`dispense acct` requires a reason\n");
324 // Authentication required
325 ret = Authenticate(sock);
328 // text_args[1]: Username
329 // text_args[2]: Ammount
330 // text_args[3]: Reason
332 if( text_args[2][0] == '=' ) {
334 if( text_args[2][1] != '0' && atoi(text_args[2]+1) == 0 ) {
335 fprintf(stderr, "Error: Invalid balance to be set\n");
339 ret = Dispense_SetBalance(sock, text_args[1], atoi(text_args[2]+1), text_args[3]);
343 ret = Dispense_AlterBalance(sock, text_args[1], atoi(text_args[2]), text_args[3]);
346 // TODO: Preserve ret if non-zero
348 // Show user information
349 ret = Dispense_ShowUser(sock, text_args[1]);
356 // - "Here, have some money."
357 if( strcmp(text_args[0], "give") == 0 )
359 if( text_argc != 4 ) {
360 fprintf(stderr, "`dispense give` takes three arguments\n");
365 // text_args[1]: Destination
366 // text_args[2]: Ammount
367 // text_args[3]: Reason
370 sock = OpenConnection(gsDispenseServer, giDispensePort);
371 if( sock < 0 ) return RV_SOCKET_ERROR;
374 ret = Authenticate(sock);
377 ret = Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
385 // - User administration (Admin Only)
386 if( strcmp(text_args[0], "user") == 0 )
388 // Check argument count
389 if( text_argc == 1 ) {
390 fprintf(stderr, "Error: `dispense user` requires arguments\n");
396 sock = OpenConnection(gsDispenseServer, giDispensePort);
397 if( sock < 0 ) return RV_SOCKET_ERROR;
399 // Attempt authentication
400 ret = Authenticate(sock);
404 if( strcmp(text_args[1], "add") == 0 )
406 if( text_argc != 3 ) {
407 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
412 ret = Dispense_AddUser(sock, text_args[2]);
415 else if( strcmp(text_args[1], "type") == 0 || strcmp(text_args[1], "flags") == 0 )
417 if( text_argc != 4 ) {
418 fprintf(stderr, "Error: `dispense user flags` requires two arguments\n");
423 ret = Dispense_SetUserType(sock, text_args[2], text_args[3]);
427 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
435 else if( strcmp(text_args[0], "donate") == 0 )
437 // Check argument count
438 if( text_argc != 3 ) {
439 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
445 sock = OpenConnection(gsDispenseServer, giDispensePort);
446 if( sock < 0 ) return RV_SOCKET_ERROR;
448 // Attempt authentication
449 ret = Authenticate(sock);
453 ret = Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
460 else if( strcmp(text_args[0], "refund") == 0 )
463 // Check argument count
464 if( text_argc != 3 && text_argc != 4 ) {
465 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
471 sock = OpenConnection(gsDispenseServer, giDispensePort);
472 if(sock < 0) return RV_SOCKET_ERROR;
474 // Attempt authentication
475 ret = Authenticate(sock);
478 if( text_argc == 4 ) {
479 price = atoi(text_args[3]);
481 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
486 // Username, Item, cost
487 ret = Dispense_Refund(sock, text_args[1], text_args[2], price);
491 return RV_UNKNOWN_ERROR;
493 // Query an item price
494 else if( strcmp(text_args[0], "iteminfo") == 0 )
496 regmatch_t matches[3];
499 // Check argument count
500 if( text_argc != 2 ) {
501 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
506 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
507 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
510 type = text_args[1] + matches[1].rm_so;
511 text_args[1][ matches[1].rm_eo ] = '\0';
512 id = atoi( text_args[1] + matches[2].rm_so );
514 sock = OpenConnection(gsDispenseServer, giDispensePort);
515 if( sock < 0 ) return RV_SOCKET_ERROR;
517 ret = Dispense_ItemInfo(sock, type, id);
521 // Item name / pattern
523 gsItemPattern = text_args[0];
527 sock = OpenConnection(gsDispenseServer, giDispensePort);
528 if( sock < 0 ) return RV_SOCKET_ERROR;
530 // Get the user's balance
531 ret = GetUserBalance(sock);
535 PopulateItemList(sock);
537 // Disconnect from server
540 if( gsItemPattern && gsItemPattern[0] )
542 regmatch_t matches[3];
544 if( strcmp(gsItemPattern, "door") == 0 )
546 // Connect, Authenticate, dispense and close
547 sock = OpenConnection(gsDispenseServer, giDispensePort);
548 if( sock < 0 ) return RV_SOCKET_ERROR;
549 ret = Authenticate(sock);
551 ret = DispenseItem(sock, "door", 0);
555 // Item id (<type>:<num>)
556 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
561 // Get and finish ident
562 ident = gsItemPattern + matches[1].rm_so;
563 gsItemPattern[matches[1].rm_eo] = '\0';
565 id = atoi( gsItemPattern + matches[2].rm_so );
567 // Connect, Authenticate, dispense and close
568 sock = OpenConnection(gsDispenseServer, giDispensePort);
569 if( sock < 0 ) return RV_SOCKET_ERROR;
571 Dispense_ItemInfo(sock, ident, id);
573 ret = Authenticate(sock);
575 ret = DispenseItem(sock, ident, id);
579 // Item number (6 = coke)
580 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
582 i = atoi(gsItemPattern);
589 for( i = 0; i < giNumItems; i ++ )
591 // Prefix match (with case-insensitive match)
592 for( j = 0; gsItemPattern[j]; j ++ )
594 if( gaItems[i].Desc[j] == gsItemPattern[j] )
596 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
600 // Check if the prefix matched
601 if( gsItemPattern[j] != '\0' )
605 if( gaItems[i].Desc[j] == '\0' ) {
610 // Only one match allowed
615 // TODO: Allow ambiguous matches?
616 // or just print a wanrning
617 printf("Warning - Ambiguous pattern, stopping\n");
622 // Was a match found?
625 fprintf(stderr, "No item matches the passed string\n");
632 else if( giUIMode != UI_MODE_BASIC )
638 // Very basic dispense interface
639 for( i = 0; i < giNumItems; i ++ ) {
641 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
644 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
645 gaItems[i].Price, gaItems[i].Desc);
654 fgets(buffer, BUFSIZ, stdin);
658 if( buf[0] == 'q' ) break;
662 if( i != 0 || buf[0] == '0' )
664 if( i < 0 || i >= giNumItems ) {
665 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
674 // Check for a valid item ID
678 // Connect, Authenticate, dispense and close
679 sock = OpenConnection(gsDispenseServer, giDispensePort);
680 if( sock < 0 ) return RV_SOCKET_ERROR;
682 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
685 ret = Authenticate(sock);
688 for( j = 0; j < giDispenseCount; j ++ ) {
689 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
693 printf("%i items dispensed\n", j);
701 // -------------------
702 // --- NCurses GUI ---
703 // -------------------
705 * \brief Render the NCurses UI
707 int ShowNCursesUI(void)
712 const int displayMinWidth = 40;
713 char *titleString = "Dispense";
718 int ret = -2; // -2: Used for marking "no return yet"
720 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
727 if( gsEffectiveUser )
728 username = gsEffectiveUser;
730 pwd = getpwuid( getuid() );
731 username = pwd->pw_name;
734 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
741 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
742 // Get item count per screen
743 // - 6: randomly chosen (Need at least 3)
744 itemCount = LINES - 6;
745 if( itemCount > maxItemIndex )
746 itemCount = maxItemIndex;
749 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
754 height = itemCount + 3;
755 width = displayMinWidth;
758 xBase = COLS/2 - width/2;
759 yBase = LINES/2 - height/2;
764 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
767 for( i = 0; i < itemCount; i ++ )
771 move( yBase + 1 + i, xBase );
776 // Check for the '...' row
777 // - Oh god, magic numbers!
778 if( (i == 0 && itemBase > 0)
779 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
781 printw(" ..."); pos += 8;
782 times = (width - pos) - 1;
783 while(times--) addch(' ');
788 yBase + 1 + i, xBase + pos, // Position
789 (width - pos) - 3, // Width
790 itemBase + i, // Index
791 !!(currentItem == itemBase + i) // Hilighted
796 // Scrollbar (if needed)
797 if( maxItemIndex > itemCount ) {
801 else if( i == itemCount - 1 ) {
805 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
806 if( i-1 == percentage*(itemCount-3)/100 ) {
820 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
823 // - Username, balance, flags
824 PrintAlign(yBase+height-1, xBase+1, width-2,
825 username, ' ', balance_str, ' ', gsUserFlags);
841 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
844 if( currentItem >= maxItemIndex ) {
847 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
854 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
857 if( currentItem < 0 ) {
858 currentItem = maxItemIndex - 1;
860 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
870 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
871 itemBase = currentItem - 2;
872 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
873 itemBase = currentItem - itemCount + 2;
879 ret = ShowItemAt(0, 0, 0, currentItem, 0);
883 ret = -1; // -1: Return with no dispense
887 // Check if the return value was changed
888 if( ret != -2 ) break;
900 * \brief Show item \a Index at (\a Col, \a Row)
901 * \return Dispense index of item
902 * \note Part of the NCurses UI
904 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
914 // - This assumes that
915 case UI_MODE_STANDARD:
917 // Index = -1, request limit
918 if( Index < 0 || Index >= giNumItems+2 )
924 name = "Coke Machine";
925 Index = -1; // -1 indicates a label
932 name = gaItems[Index].Desc;
933 price = gaItems[Index].Price;
934 status = gaItems[Index].Status;
942 name = "Electronic Payment System";
943 Index = -1; // -1 indicates a label
948 name = gaItems[Index].Desc;
949 price = gaItems[Index].Price;
950 status = gaItems[Index].Status;
956 // Width = 0, don't print
959 // 4 preceding, 5 price
960 int nameWidth = Width - 4 - 5;
965 // Show hilight and status
984 printw("%-*.*s", nameWidth, nameWidth, name);
986 // getyx(stdscr, _y, _x);
987 // Assumes max 4 digit prices
988 // times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
989 // while(times--) addch(' ');
991 printw(" %4i", price);
995 printw("-- %s", name);
996 getyx(stdscr, _y, _x);
997 times = Width - 4 - (_x - Col);
998 while(times--) addch(' ');
1003 // If the item isn't availiable for sale, return -1 (so it's skipped)
1011 * \brief Print a three-part string at the specified position (formatted)
1012 * \note NCurses UI Helper
1014 * Prints \a Left on the left of the area, \a Right on the righthand side
1015 * and \a Mid in the middle of the area. These are padded with \a Pad1
1016 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1018 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1019 * and the arguments to these are read in that order.
1021 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1022 const char *Mid, char Pad2, const char *Right, ...)
1024 int lLen, mLen, rLen;
1029 // Get the length of the strings
1030 va_start(args, Right);
1031 lLen = vsnprintf(NULL, 0, Left, args);
1032 mLen = vsnprintf(NULL, 0, Mid, args);
1033 rLen = vsnprintf(NULL, 0, Right, args);
1037 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1038 return ; // TODO: What to do?
1044 va_start(args, Right);
1048 vsnprintf(tmp, lLen+1, Left, args);
1052 times = (Width - mLen)/2 - lLen;
1053 while(times--) addch(Pad1);
1057 vsnprintf(tmp, mLen+1, Mid, args);
1061 times = (Width - mLen)/2 - rLen;
1062 if( (Width - mLen) % 2 ) times ++;
1063 while(times--) addch(Pad2);
1067 vsnprintf(tmp, rLen+1, Right, args);
1072 // ---------------------
1073 // --- Coke Protocol ---
1074 // ---------------------
1075 int OpenConnection(const char *Host, int Port)
1077 struct hostent *host;
1078 struct sockaddr_in serverAddr;
1081 host = gethostbyname(Host);
1083 fprintf(stderr, "Unable to look up '%s'\n", Host);
1087 memset(&serverAddr, 0, sizeof(serverAddr));
1089 serverAddr.sin_family = AF_INET; // IPv4
1090 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1091 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1092 serverAddr.sin_port = htons(Port);
1094 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1096 fprintf(stderr, "Failed to create socket\n");
1100 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1102 if( geteuid() == 0 || getuid() == 0 )
1105 struct sockaddr_in localAddr;
1106 memset(&localAddr, 0, sizeof(localAddr));
1107 localAddr.sin_family = AF_INET; // IPv4
1109 // Loop through all the top ports until one is avaliable
1110 for( i = 512; i < 1024; i ++)
1112 localAddr.sin_port = htons(i); // IPv4
1113 // Attempt to bind to low port for autoauth
1114 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1118 printf("Warning: AUTOAUTH unavaliable\n");
1120 // printf("Bound to 0.0.0.0:%i\n", i);
1123 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1124 fprintf(stderr, "Failed to connect to server\n");
1128 // We're not authenticated if the connection has just opened
1129 gbIsAuthenticated = 0;
1135 * \brief Authenticate with the server
1136 * \return Boolean Failure
1138 int Authenticate(int Socket)
1143 #if ATTEMPT_PASSWORD_AUTH
1146 regmatch_t matches[4];
1149 if( gbIsAuthenticated ) return 0;
1152 pwd = getpwuid( getuid() );
1154 // Attempt automatic authentication
1155 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1157 // Check if it worked
1158 buf = ReadLine(Socket);
1160 responseCode = atoi(buf);
1161 switch( responseCode )
1163 case 200: // Autoauth succeeded, return
1167 case 401: // Untrusted, attempt password authentication
1170 #if ATTEMPT_PASSWORD_AUTH
1171 sendf(Socket, "USER %s\n", pwd->pw_name);
1172 printf("Using username %s\n", pwd->pw_name);
1174 buf = ReadLine(Socket);
1177 // Expected format: 100 SALT <something> ...
1178 // OR : 100 User Set
1179 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1180 responseCode = atoi(buf);
1181 if( responseCode != 100 ) {
1182 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1184 return RV_UNKNOWN_ERROR; // ERROR
1188 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1189 // Store it for later
1190 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1191 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1195 // Give three attempts
1196 for( i = 0; i < 3; i ++ )
1198 int ofs = strlen(pwd->pw_name)+strlen(salt);
1201 char *pass = getpass("Password: ");
1204 // Create hash string
1205 // <username><salt><hash>
1206 strcpy(tmp, pwd->pw_name);
1208 SHA1( (unsigned char*)pass, strlen(pass), h );
1209 memcpy(tmp+ofs, h, 20);
1212 SHA1( (unsigned char*)tmp, ofs+20, h );
1213 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1214 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1215 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1219 sendf(Socket, "PASS %s\n", tmpBuf);
1220 buf = ReadLine(Socket);
1222 responseCode = atoi(buf);
1224 if( responseCode == 200 ) break;
1225 // Bad username/password
1226 if( responseCode == 401 ) continue;
1228 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1230 return RV_UNKNOWN_ERROR;
1234 return RV_INVALID_USER; // 2 = Bad Password
1237 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1238 return RV_INVALID_USER;
1242 case 404: // Bad Username
1243 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1245 return RV_INVALID_USER;
1248 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1249 printf("%s\n", buf);
1251 return RV_UNKNOWN_ERROR;
1254 // Set effective user
1255 if( gsEffectiveUser ) {
1256 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1258 buf = ReadLine(Socket);
1259 responseCode = atoi(buf);
1261 switch(responseCode)
1264 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1268 printf("Only coke members can use `dispense -u`\n");
1270 return RV_PERMISSIONS;
1273 printf("Invalid user selected\n");
1275 return RV_INVALID_USER;
1278 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1279 printf("%s\n", buf);
1281 return RV_UNKNOWN_ERROR;
1287 gbIsAuthenticated = 1;
1292 int GetUserBalance(int Socket)
1294 regmatch_t matches[6];
1301 if( gsEffectiveUser ) {
1302 gsUserName = gsEffectiveUser;
1305 pwd = getpwuid( getuid() );
1306 gsUserName = strdup(pwd->pw_name);
1310 sendf(Socket, "USER_INFO %s\n", gsUserName);
1311 buf = ReadLine(Socket);
1312 responseCode = atoi(buf);
1313 switch(responseCode)
1315 case 202: break; // Ok
1318 printf("Invalid user? (USER_INFO failed)\n");
1320 return RV_INVALID_USER;
1323 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1324 printf("%s\n", buf);
1326 return RV_UNKNOWN_ERROR;
1329 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1331 giUserBalance = atoi( buf + matches[4].rm_so );
1332 gsUserFlags = strdup( buf + matches[5].rm_so );
1340 * \brief Read an item info response from the server
1341 * \param Dest Destination for the read item (strings will be on the heap)
1343 int ReadItemInfo(int Socket, tItem *Dest)
1348 regmatch_t matches[8];
1352 buf = ReadLine(Socket);
1353 responseCode = atoi(buf);
1355 switch(responseCode)
1360 printf("Bad item name\n");
1365 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1367 return RV_UNKNOWN_ERROR;
1370 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1372 buf[ matches[3].rm_eo ] = '\0';
1373 buf[ matches[5].rm_eo ] = '\0';
1374 buf[ matches[7].rm_eo ] = '\0';
1376 statusStr = &buf[ matches[5].rm_so ];
1378 Dest->ID = atoi( buf + matches[4].rm_so );
1380 if( strcmp(statusStr, "avail") == 0 )
1382 else if( strcmp(statusStr, "sold") == 0 )
1384 else if( strcmp(statusStr, "error") == 0 )
1387 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1389 return RV_UNKNOWN_ERROR;
1391 Dest->Price = atoi( buf + matches[6].rm_so );
1393 // Hack a little to reduce heap fragmentation
1395 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1396 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1397 strcpy(tmpType, buf + matches[3].rm_so);
1398 strcpy(tmpDesc, buf + matches[7].rm_so);
1400 Dest->Type = strdup( tmpType );
1401 Dest->Desc = strdup( tmpDesc );
1408 * \brief Fill the item information structure
1409 * \return Boolean Failure
1411 void PopulateItemList(int Socket)
1416 char *itemType, *itemStart;
1418 regmatch_t matches[4];
1420 // Ask server for stock list
1421 send(Socket, "ENUM_ITEMS\n", 11, 0);
1422 buf = ReadLine(Socket);
1424 //printf("Output: %s\n", buf);
1426 responseCode = atoi(buf);
1427 if( responseCode != 201 ) {
1428 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1429 exit(RV_UNKNOWN_ERROR);
1432 // - Get item list -
1435 // 201 Items <count>
1437 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1439 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1440 count = atoi( &buf[ matches[3].rm_so ] );
1443 if( strcmp(itemType, "Items") != 0 ) {
1445 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1447 exit(RV_UNKNOWN_ERROR);
1450 itemStart = &buf[ matches[3].rm_eo ];
1455 gaItems = malloc( giNumItems * sizeof(tItem) );
1457 // Fetch item information
1458 for( i = 0; i < giNumItems; i ++ )
1460 ReadItemInfo( Socket, &gaItems[i] );
1464 buf = ReadLine(Socket);
1465 responseCode = atoi(buf);
1467 if( responseCode != 200 ) {
1468 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1479 * \brief Get information on an item
1480 * \return Boolean Failure
1482 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1488 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1490 ret = ReadItemInfo(Socket, &item);
1493 printf("%8s:%-2i %2i.%02i %s\n",
1495 item.Price/100, item.Price%100,
1505 * \brief Dispense an item
1506 * \return Boolean Failure
1508 int DispenseItem(int Socket, const char *Type, int ID)
1510 int ret, responseCode;
1513 // Check for a dry run
1515 printf("Dry Run - No action\n");
1520 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1521 buf = ReadLine(Socket);
1523 responseCode = atoi(buf);
1524 switch( responseCode )
1527 printf("Dispense OK\n");
1531 printf("Not authenticated\n");
1532 ret = RV_PERMISSIONS;
1535 printf("Insufficient balance\n");
1539 printf("Bad item name\n");
1543 printf("Item failed to dispense, is the slot empty?\n");
1544 ret = RV_SERVER_ERROR;
1547 printf("Dispense not possible (slot empty/permissions)\n");
1548 ret = RV_SERVER_ERROR;
1551 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1552 ret = RV_UNKNOWN_ERROR;
1561 * \brief Alter a user's balance
1563 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1568 // Check for a dry run
1570 printf("Dry Run - No action\n");
1575 if( Ammount == 0 ) {
1576 printf("An ammount would be nice\n");
1577 return RV_ARGUMENTS;
1580 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1581 buf = ReadLine(Socket);
1583 responseCode = atoi(buf);
1586 switch(responseCode)
1588 case 200: return 0; // OK
1590 fprintf(stderr, "Insufficient balance\n");
1592 case 403: // Not in coke
1593 fprintf(stderr, "You are not in coke (sucker)\n");
1594 return RV_PERMISSIONS;
1595 case 404: // Unknown user
1596 fprintf(stderr, "Unknown user '%s'\n", Username);
1597 return RV_INVALID_USER;
1599 fprintf(stderr, "Unknown response code %i\n", responseCode);
1600 return RV_UNKNOWN_RESPONSE;
1607 * \brief Set a user's balance
1608 * \note Only avaliable to dispense admins
1610 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1615 // Check for a dry run
1617 printf("Dry Run - No action\n");
1621 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1622 buf = ReadLine(Socket);
1624 responseCode = atoi(buf);
1627 switch(responseCode)
1629 case 200: return 0; // OK
1630 case 403: // Not in coke
1631 fprintf(stderr, "You are not an admin\n");
1632 return RV_PERMISSIONS;
1633 case 404: // Unknown user
1634 fprintf(stderr, "Unknown user '%s'\n", Username);
1635 return RV_INVALID_USER;
1637 fprintf(stderr, "Unknown response code %i\n", responseCode);
1638 return RV_UNKNOWN_RESPONSE;
1645 * \brief Give money to another user
1647 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1653 printf("Sorry, you can only give, you can't take.\n");
1654 return RV_ARGUMENTS;
1657 // Fast return on zero
1658 if( Ammount == 0 ) {
1659 printf("Are you actually going to give any?\n");
1660 return RV_ARGUMENTS;
1663 // Check for a dry run
1665 printf("Dry Run - No action\n");
1669 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1671 buf = ReadLine(Socket);
1672 responseCode = atoi(buf);
1674 switch(responseCode)
1677 printf("Give succeeded\n");
1678 return RV_SUCCESS; // OK
1681 fprintf(stderr, "Insufficient balance\n");
1684 case 404: // Unknown user
1685 fprintf(stderr, "Unknown user '%s'\n", Username);
1686 return RV_INVALID_USER;
1689 fprintf(stderr, "Unknown response code %i\n", responseCode);
1690 return RV_UNKNOWN_RESPONSE;
1696 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1699 int responseCode, ret = -1;
1702 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1704 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1705 return RV_ARGUMENTS;
1708 // Check username (quick)
1709 if( strchr(Username, ' ') || strchr(Username, '\n') )
1711 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1712 return RV_ARGUMENTS;
1716 sendf(Socket, "REFUND %s %s %i\n", Username, Item, PriceOverride);
1718 buf = ReadLine(Socket);
1719 responseCode = atoi(buf);
1720 switch(responseCode)
1723 Dispense_ShowUser(Socket, Username); // Show destination account
1727 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1728 ret = RV_PERMISSIONS;
1731 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1732 ret = RV_INVALID_USER;
1735 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1739 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1748 * \brief Donate money to the club
1750 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1756 printf("Sorry, you can only give, you can't take.\n");
1760 // Fast return on zero
1761 if( Ammount == 0 ) {
1762 printf("Are you actually going to give any?\n");
1766 // Check for a dry run
1768 printf("Dry Run - No action\n");
1772 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1773 buf = ReadLine(Socket);
1775 responseCode = atoi(buf);
1778 switch(responseCode)
1780 case 200: return 0; // OK
1783 fprintf(stderr, "Insufficient balance\n");
1787 fprintf(stderr, "Unknown response code %i\n", responseCode);
1795 * \brief Enumerate users
1797 int Dispense_EnumUsers(int Socket)
1802 regmatch_t matches[4];
1804 if( giMinimumBalance != INT_MIN ) {
1805 if( giMaximumBalance != INT_MAX ) {
1806 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1809 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1813 if( giMaximumBalance != INT_MAX ) {
1814 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1817 sendf(Socket, "ENUM_USERS\n");
1820 buf = ReadLine(Socket);
1821 responseCode = atoi(buf);
1823 switch(responseCode)
1825 case 201: break; // Ok, length follows
1828 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1833 // Get count (not actually used)
1834 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1835 nUsers = atoi( buf + matches[3].rm_so );
1836 printf("%i users returned\n", nUsers);
1841 // Read returned users
1843 buf = ReadLine(Socket);
1844 responseCode = atoi(buf);
1846 if( responseCode != 202 ) break;
1848 _PrintUserLine(buf);
1850 } while(responseCode == 202);
1852 // Check final response
1853 if( responseCode != 200 ) {
1854 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1864 int Dispense_ShowUser(int Socket, const char *Username)
1867 int responseCode, ret;
1869 sendf(Socket, "USER_INFO %s\n", Username);
1870 buf = ReadLine(Socket);
1872 responseCode = atoi(buf);
1874 switch(responseCode)
1877 _PrintUserLine(buf);
1882 printf("Unknown user '%s'\n", Username);
1887 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1897 void _PrintUserLine(const char *Line)
1899 regmatch_t matches[6];
1902 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1907 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1908 char username[usernameLen + 1];
1909 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1910 char flags[flagsLen + 1];
1912 memcpy(username, Line + matches[3].rm_so, usernameLen);
1913 username[usernameLen] = '\0';
1914 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1915 flags[flagsLen] = '\0';
1917 bal = atoi(Line + matches[4].rm_so);
1918 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1922 int Dispense_AddUser(int Socket, const char *Username)
1925 int responseCode, ret;
1927 // Check for a dry run
1929 printf("Dry Run - No action\n");
1933 sendf(Socket, "USER_ADD %s\n", Username);
1935 buf = ReadLine(Socket);
1936 responseCode = atoi(buf);
1938 switch(responseCode)
1941 printf("User '%s' added\n", Username);
1946 printf("Only wheel can add users\n");
1951 printf("User '%s' already exists\n", Username);
1956 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1966 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1969 int responseCode, ret;
1971 // Check for a dry run
1973 printf("Dry Run - No action\n");
1977 // TODO: Pre-validate the string
1979 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1981 buf = ReadLine(Socket);
1982 responseCode = atoi(buf);
1984 switch(responseCode)
1987 printf("User '%s' updated\n", Username);
1992 printf("Only wheel can modify users\n");
1997 printf("User '%s' does not exist\n", Username);
2002 printf("Flag string is invalid\n");
2007 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2020 char *ReadLine(int Socket)
2022 static char buf[BUFSIZ];
2023 static int bufPos = 0;
2024 static int bufValid = 0;
2026 char *newline = NULL;
2028 char *ret = malloc(10);
2030 #if DEBUG_TRACE_SERVER
2031 printf("ReadLine: ");
2043 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2044 buf[bufPos+len] = '\0';
2047 newline = strchr( buf+bufPos, '\n' );
2052 retLen += strlen(buf+bufPos);
2053 ret = realloc(ret, retLen + 1);
2054 strcat( ret, buf+bufPos );
2057 int newLen = newline - (buf+bufPos) + 1;
2058 bufValid = len - newLen;
2061 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2064 #if DEBUG_TRACE_SERVER
2065 printf("%i '%s'\n", retLen, ret);
2071 int sendf(int Socket, const char *Format, ...)
2076 va_start(args, Format);
2077 len = vsnprintf(NULL, 0, Format, args);
2082 va_start(args, Format);
2083 vsnprintf(buf, len+1, Format, args);
2086 #if DEBUG_TRACE_SERVER
2087 printf("sendf: %s", buf);
2090 return send(Socket, buf, len, 0);
2094 char *trim(char *string)
2098 while( isspace(*string) )
2101 for( i = strlen(string); i--; )
2103 if( isspace(string[i]) )
2112 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2116 ret = regexec(regex, string, nMatches, matches, 0);
2117 if( ret && errorMessage ) {
2118 size_t len = regerror(ret, regex, NULL, 0);
2120 regerror(ret, regex, errorStr, len);
2121 printf("string = '%s'\n", string);
2122 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2129 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2131 int ret = regcomp(regex, pattern, flags);
2133 size_t len = regerror(ret, regex, NULL, 0);
2135 regerror(ret, regex, errorStr, len);
2136 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);