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_UNKNOWN_ERROR = -1,
57 typedef struct sItem {
60 int Status; // 0: Availiable, 1: Sold out, -1: Error
66 int main(int argc, char *argv[]);
69 int ShowNCursesUI(void);
70 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted);
71 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
72 // --- Coke Server Communication ---
73 int OpenConnection(const char *Host, int Port);
74 int Authenticate(int Socket);
75 int GetUserBalance(int Socket);
76 void PopulateItemList(int Socket);
77 int Dispense_ItemInfo(int Socket, const char *Type, int ID);
78 int DispenseItem(int Socket, const char *Type, int ID);
79 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
80 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
81 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
82 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride);
83 int Dispense_Donate(int Socket, int Ammount, const char *Reason);
84 int Dispense_EnumUsers(int Socket);
85 int Dispense_ShowUser(int Socket, const char *Username);
86 void _PrintUserLine(const char *Line);
87 int Dispense_AddUser(int Socket, const char *Username);
88 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
90 char *ReadLine(int Socket);
91 int sendf(int Socket, const char *Format, ...);
92 char *trim(char *string);
93 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
94 void CompileRegex(regex_t *regex, const char *pattern, int flags);
97 char *gsDispenseServer = "heathred";
98 int giDispensePort = 11020;
102 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
103 int gbIsAuthenticated = 0;
105 char *gsItemPattern; //!< Item pattern
106 char *gsEffectiveUser; //!< '-u' Dispense as another user
107 int giUIMode = UI_MODE_STANDARD;
108 int gbDryRun = 0; //!< '-n' Read-only
109 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
110 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
111 char *gsUserName; //!< User that dispense will happen as
112 char *gsUserFlags; //!< User's flag set
113 int giUserBalance=-1; //!< User balance (set by Authenticate)
114 int giDispenseCount = 1; //!< Number of dispenses to do
117 int main(int argc, char *argv[])
122 char *text_args[MAX_TXT_ARGS]; // Non-flag arguments
127 // -- Create regular expressions
128 // > Code Type Count ...
129 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
130 // > Code Type Ident Status Price Desc
131 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);
132 // > Code 'SALT' salt
133 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
134 // > Code 'User' Username Balance Flags
135 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
137 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
140 for( i = 1; i < argc; i ++ )
154 if( i + 1 >= argc ) {
155 fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
159 giDispenseCount = atoi(argv[++i]);
160 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
161 fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
167 case 'm': // Minimum balance
168 if( i + 1 >= argc ) {
169 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
173 giMinimumBalance = atoi(argv[++i]);
175 case 'M': // Maximum balance
176 if( i + 1 >= argc ) {
177 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
181 giMaximumBalance = atoi(argv[++i]);
184 case 'u': // Override User
185 if( i + 1 >= argc ) {
186 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
190 gsEffectiveUser = argv[++i];
193 case 'H': // Override remote host
194 if( i + 1 >= argc ) {
195 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
199 gsDispenseServer = argv[++i];
201 case 'P': // Override remote port
202 if( i + 1 >= argc ) {
203 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
207 giDispensePort = atoi(argv[++i]);
210 case 'G': // Don't use GUI
211 giUIMode = UI_MODE_BASIC;
213 case 'D': // Drinks only
214 giUIMode = UI_MODE_DRINKSONLY;
216 case 'n': // Dry Run / read-only
220 if( text_argc + 1 == MAX_TXT_ARGS )
222 fprintf(stderr, "ERROR: Too many arguments\n");
225 text_args[text_argc++] = argv[i];
232 if( text_argc + 1 == MAX_TXT_ARGS )
234 fprintf(stderr, "ERROR: Too many arguments\n");
238 text_args[text_argc++] = argv[i];
245 if( strcmp(text_args[0], "acct") == 0 )
248 sock = OpenConnection(gsDispenseServer, giDispensePort);
249 if( sock < 0 ) return RV_SOCKET_ERROR;
251 if( text_argc == 1 ) {
252 ret = Dispense_EnumUsers(sock);
257 // text_args[1]: Username
262 if( text_argc != 4 ) {
263 fprintf(stderr, "`dispense acct` requires a reason\n");
268 // Authentication required
269 ret = Authenticate(sock);
272 // text_args[1]: Username
273 // text_args[2]: Ammount
274 // text_args[3]: Reason
276 if( text_args[2][0] == '=' ) {
278 if( text_args[2][1] != '0' && atoi(text_args[2]+1) == 0 ) {
279 fprintf(stderr, "Error: Invalid balance to be set\n");
283 ret = Dispense_SetBalance(sock, text_args[1], atoi(text_args[2]+1), text_args[3]);
287 ret = Dispense_AlterBalance(sock, text_args[1], atoi(text_args[2]), text_args[3]);
290 // TODO: Preserve ret if non-zero
292 // Show user information
293 ret = Dispense_ShowUser(sock, text_args[1]);
300 // - "Here, have some money."
301 if( strcmp(text_args[0], "give") == 0 )
303 if( text_argc != 4 ) {
304 fprintf(stderr, "`dispense give` takes three arguments\n");
309 // text_args[1]: Destination
310 // text_args[2]: Ammount
311 // text_args[3]: Reason
314 sock = OpenConnection(gsDispenseServer, giDispensePort);
315 if( sock < 0 ) return RV_SOCKET_ERROR;
318 ret = Authenticate(sock);
321 ret = Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
329 // - User administration (Admin Only)
330 if( strcmp(text_args[0], "user") == 0 )
332 // Check argument count
333 if( text_argc == 1 ) {
334 fprintf(stderr, "Error: `dispense user` requires arguments\n");
340 sock = OpenConnection(gsDispenseServer, giDispensePort);
341 if( sock < 0 ) return RV_SOCKET_ERROR;
343 // Attempt authentication
344 ret = Authenticate(sock);
348 if( strcmp(text_args[1], "add") == 0 )
350 if( text_argc != 3 ) {
351 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
356 ret = Dispense_AddUser(sock, text_args[2]);
359 else if( strcmp(text_args[1], "type") == 0 || strcmp(text_args[1], "flags") == 0 )
361 if( text_argc != 4 ) {
362 fprintf(stderr, "Error: `dispense user flags` requires two arguments\n");
367 ret = Dispense_SetUserType(sock, text_args[2], text_args[3]);
371 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
379 else if( strcmp(text_args[0], "donate") == 0 )
381 // Check argument count
382 if( text_argc != 3 ) {
383 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
389 sock = OpenConnection(gsDispenseServer, giDispensePort);
390 if( sock < 0 ) return RV_SOCKET_ERROR;
392 // Attempt authentication
393 ret = Authenticate(sock);
397 ret = Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
404 else if( strcmp(text_args[0], "refund") == 0 )
407 // Check argument count
408 if( text_argc != 3 && text_argc != 4 ) {
409 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
415 sock = OpenConnection(gsDispenseServer, giDispensePort);
416 if(sock < 0) return RV_SOCKET_ERROR;
418 // Attempt authentication
419 ret = Authenticate(sock);
422 if( text_argc == 4 ) {
423 price = atoi(text_args[3]);
425 fprintf(stderr, "Error: Override price is invalid (should be > 0)\n");
430 // Username, Item, cost
431 ret = Dispense_Refund(sock, text_args[1], text_args[2], price);
435 return RV_UNKNOWN_ERROR;
437 // Query an item price
438 else if( strcmp(text_args[0], "iteminfo") == 0 )
440 regmatch_t matches[3];
443 // Check argument count
444 if( text_argc != 2 ) {
445 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
450 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
451 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
454 type = text_args[1] + matches[1].rm_so;
455 text_args[1][ matches[1].rm_eo ] = '\0';
456 id = atoi( text_args[1] + matches[2].rm_so );
458 sock = OpenConnection(gsDispenseServer, giDispensePort);
459 if( sock < 0 ) return RV_SOCKET_ERROR;
461 ret = Dispense_ItemInfo(sock, type, id);
465 // Item name / pattern
467 gsItemPattern = text_args[0];
471 sock = OpenConnection(gsDispenseServer, giDispensePort);
472 if( sock < 0 ) return RV_SOCKET_ERROR;
474 // Get the user's balance
475 ret = GetUserBalance(sock);
479 PopulateItemList(sock);
481 // Disconnect from server
484 if( gsItemPattern && gsItemPattern[0] )
486 regmatch_t matches[3];
488 if( strcmp(gsItemPattern, "door") == 0 )
490 // Connect, Authenticate, dispense and close
491 sock = OpenConnection(gsDispenseServer, giDispensePort);
492 if( sock < 0 ) return RV_SOCKET_ERROR;
493 ret = Authenticate(sock);
495 ret = DispenseItem(sock, "door", 0);
499 // Item id (<type>:<num>)
500 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
505 // Get and finish ident
506 ident = gsItemPattern + matches[1].rm_so;
507 gsItemPattern[matches[1].rm_eo] = '\0';
509 id = atoi( gsItemPattern + matches[2].rm_so );
511 // Connect, Authenticate, dispense and close
512 sock = OpenConnection(gsDispenseServer, giDispensePort);
513 if( sock < 0 ) return RV_SOCKET_ERROR;
515 Dispense_ItemInfo(sock, ident, id);
517 ret = Authenticate(sock);
519 ret = DispenseItem(sock, ident, id);
523 // Item number (6 = coke)
524 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
526 i = atoi(gsItemPattern);
533 for( i = 0; i < giNumItems; i ++ )
535 // Prefix match (with case-insensitive match)
536 for( j = 0; gsItemPattern[j]; j ++ )
538 if( gaItems[i].Desc[j] == gsItemPattern[j] )
540 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
544 // Check if the prefix matched
545 if( gsItemPattern[j] != '\0' )
549 if( gaItems[i].Desc[j] == '\0' ) {
554 // Only one match allowed
559 // TODO: Allow ambiguous matches?
560 // or just print a wanrning
561 printf("Warning - Ambiguous pattern, stopping\n");
566 // Was a match found?
569 fprintf(stderr, "No item matches the passed string\n");
576 else if( giUIMode != UI_MODE_BASIC )
582 // Very basic dispense interface
583 for( i = 0; i < giNumItems; i ++ ) {
585 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
588 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
589 gaItems[i].Price, gaItems[i].Desc);
598 fgets(buffer, BUFSIZ, stdin);
602 if( buf[0] == 'q' ) break;
606 if( i != 0 || buf[0] == '0' )
608 if( i < 0 || i >= giNumItems ) {
609 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
618 // Check for a valid item ID
622 // Connect, Authenticate, dispense and close
623 sock = OpenConnection(gsDispenseServer, giDispensePort);
624 if( sock < 0 ) return RV_SOCKET_ERROR;
626 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
629 ret = Authenticate(sock);
632 for( j = 0; j < giDispenseCount; j ++ ) {
633 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
637 printf("%i items dispensed\n", j);
651 " Show interactive list\n"
652 " dispense <name>|<index>|<itemid>\n"
653 " Dispense named item (<name> matches if it is a unique prefix)\n"
654 " dispense give <user> <ammount> \"<reason>\"\n"
655 " Give money to another user\n"
656 " dispense donate <ammount> \"<reason>\"\n"
657 " Donate to the club\n"
658 " dispense iteminfo <type>:<id>\n"
659 " Get the name and price for an item\n"
660 " == Coke members == \n"
661 " dispense acct [<user>]\n"
662 " Show user balances\n"
663 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
664 " Alter a account value\n"
665 " == Dispense administrators ==\n"
666 " dispense acct <user> =<ammount> \"<reason>\"\n"
667 " Set an account balance\n"
668 " dispense user add <user>\n"
669 " Create new coke account (Admins only)\n"
670 " dispense user type <user> <flags>\n"
671 " Alter a user's flags\n"
672 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
673 " Flags are removed by preceding the name with '-' or '!'\n"
677 " Dispense multiple times\n"
679 " Set a different user (Coke members only)\n"
683 " Use alternate GUI\n"
684 " -m <min balance>\n"
685 " -M <max balance>\n"
686 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
690 // -------------------
691 // --- NCurses GUI ---
692 // -------------------
694 * \brief Render the NCurses UI
696 int ShowNCursesUI(void)
701 const int displayMinWidth = 40;
702 char *titleString = "Dispense";
707 int ret = -2; // -2: Used for marking "no return yet"
709 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
716 if( gsEffectiveUser )
717 username = gsEffectiveUser;
719 pwd = getpwuid( getuid() );
720 username = pwd->pw_name;
723 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
730 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
731 // Get item count per screen
732 // - 6: randomly chosen (Need at least 3)
733 itemCount = LINES - 6;
734 if( itemCount > maxItemIndex )
735 itemCount = maxItemIndex;
738 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
743 height = itemCount + 3;
744 width = displayMinWidth;
747 xBase = COLS/2 - width/2;
748 yBase = LINES/2 - height/2;
753 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
756 for( i = 0; i < itemCount; i ++ )
760 move( yBase + 1 + i, xBase );
765 // Check for the '...' row
766 // - Oh god, magic numbers!
767 if( (i == 0 && itemBase > 0)
768 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
770 printw(" ..."); pos += 8;
771 times = (width - pos) - 1;
772 while(times--) addch(' ');
777 yBase + 1 + i, xBase + pos, // Position
778 (width - pos) - 3, // Width
779 itemBase + i, // Index
780 !!(currentItem == itemBase + i) // Hilighted
785 // Scrollbar (if needed)
786 if( maxItemIndex > itemCount ) {
790 else if( i == itemCount - 1 ) {
794 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
795 if( i-1 == percentage*(itemCount-3)/100 ) {
809 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
812 // - Username, balance, flags
813 PrintAlign(yBase+height-1, xBase+1, width-2,
814 username, ' ', balance_str, ' ', gsUserFlags);
830 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
833 if( currentItem >= maxItemIndex ) {
836 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
843 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
846 if( currentItem < 0 ) {
847 currentItem = maxItemIndex - 1;
849 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
859 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
860 itemBase = currentItem - 2;
861 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
862 itemBase = currentItem - itemCount + 2;
868 ret = ShowItemAt(0, 0, 0, currentItem, 0);
872 ret = -1; // -1: Return with no dispense
876 // Check if the return value was changed
877 if( ret != -2 ) break;
889 * \brief Show item \a Index at (\a Col, \a Row)
890 * \return Dispense index of item
891 * \note Part of the NCurses UI
893 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
903 // - This assumes that
904 case UI_MODE_STANDARD:
906 // Index = -1, request limit
907 if( Index < 0 || Index >= giNumItems+2 )
913 name = "Coke Machine";
914 Index = -1; // -1 indicates a label
921 name = gaItems[Index].Desc;
922 price = gaItems[Index].Price;
923 status = gaItems[Index].Status;
931 name = "Electronic Payment System";
932 Index = -1; // -1 indicates a label
937 name = gaItems[Index].Desc;
938 price = gaItems[Index].Price;
939 status = gaItems[Index].Status;
945 // Width = 0, don't print
948 // 4 preceding, 5 price
949 int nameWidth = Width - 4 - 5;
954 // Show hilight and status
973 printw("%-*.*s", nameWidth, nameWidth, name);
975 // getyx(stdscr, _y, _x);
976 // Assumes max 4 digit prices
977 // times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
978 // while(times--) addch(' ');
980 printw(" %4i", price);
984 printw("-- %s", name);
985 getyx(stdscr, _y, _x);
986 times = Width - 4 - (_x - Col);
987 while(times--) addch(' ');
992 // If the item isn't availiable for sale, return -1 (so it's skipped)
1000 * \brief Print a three-part string at the specified position (formatted)
1001 * \note NCurses UI Helper
1003 * Prints \a Left on the left of the area, \a Right on the righthand side
1004 * and \a Mid in the middle of the area. These are padded with \a Pad1
1005 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
1007 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
1008 * and the arguments to these are read in that order.
1010 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
1011 const char *Mid, char Pad2, const char *Right, ...)
1013 int lLen, mLen, rLen;
1018 // Get the length of the strings
1019 va_start(args, Right);
1020 lLen = vsnprintf(NULL, 0, Left, args);
1021 mLen = vsnprintf(NULL, 0, Mid, args);
1022 rLen = vsnprintf(NULL, 0, Right, args);
1026 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1027 return ; // TODO: What to do?
1033 va_start(args, Right);
1037 vsnprintf(tmp, lLen+1, Left, args);
1041 times = (Width - mLen)/2 - lLen;
1042 while(times--) addch(Pad1);
1046 vsnprintf(tmp, mLen+1, Mid, args);
1050 times = (Width - mLen)/2 - rLen;
1051 if( (Width - mLen) % 2 ) times ++;
1052 while(times--) addch(Pad2);
1056 vsnprintf(tmp, rLen+1, Right, args);
1061 // ---------------------
1062 // --- Coke Protocol ---
1063 // ---------------------
1064 int OpenConnection(const char *Host, int Port)
1066 struct hostent *host;
1067 struct sockaddr_in serverAddr;
1070 host = gethostbyname(Host);
1072 fprintf(stderr, "Unable to look up '%s'\n", Host);
1076 memset(&serverAddr, 0, sizeof(serverAddr));
1078 serverAddr.sin_family = AF_INET; // IPv4
1079 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1080 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1081 serverAddr.sin_port = htons(Port);
1083 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1085 fprintf(stderr, "Failed to create socket\n");
1089 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1091 if( geteuid() == 0 || getuid() == 0 )
1094 struct sockaddr_in localAddr;
1095 memset(&localAddr, 0, sizeof(localAddr));
1096 localAddr.sin_family = AF_INET; // IPv4
1098 // Loop through all the top ports until one is avaliable
1099 for( i = 512; i < 1024; i ++)
1101 localAddr.sin_port = htons(i); // IPv4
1102 // Attempt to bind to low port for autoauth
1103 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1107 printf("Warning: AUTOAUTH unavaliable\n");
1109 // printf("Bound to 0.0.0.0:%i\n", i);
1112 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1113 fprintf(stderr, "Failed to connect to server\n");
1117 // We're not authenticated if the connection has just opened
1118 gbIsAuthenticated = 0;
1124 * \brief Authenticate with the server
1125 * \return Boolean Failure
1127 int Authenticate(int Socket)
1132 #if ATTEMPT_PASSWORD_AUTH
1135 regmatch_t matches[4];
1138 if( gbIsAuthenticated ) return 0;
1141 pwd = getpwuid( getuid() );
1143 // Attempt automatic authentication
1144 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1146 // Check if it worked
1147 buf = ReadLine(Socket);
1149 responseCode = atoi(buf);
1150 switch( responseCode )
1152 case 200: // Autoauth succeeded, return
1156 case 401: // Untrusted, attempt password authentication
1159 #if ATTEMPT_PASSWORD_AUTH
1160 sendf(Socket, "USER %s\n", pwd->pw_name);
1161 printf("Using username %s\n", pwd->pw_name);
1163 buf = ReadLine(Socket);
1166 // Expected format: 100 SALT <something> ...
1167 // OR : 100 User Set
1168 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1169 responseCode = atoi(buf);
1170 if( responseCode != 100 ) {
1171 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1173 return RV_UNKNOWN_ERROR; // ERROR
1177 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1178 // Store it for later
1179 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1180 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1184 // Give three attempts
1185 for( i = 0; i < 3; i ++ )
1187 int ofs = strlen(pwd->pw_name)+strlen(salt);
1190 char *pass = getpass("Password: ");
1193 // Create hash string
1194 // <username><salt><hash>
1195 strcpy(tmp, pwd->pw_name);
1197 SHA1( (unsigned char*)pass, strlen(pass), h );
1198 memcpy(tmp+ofs, h, 20);
1201 SHA1( (unsigned char*)tmp, ofs+20, h );
1202 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1203 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1204 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1208 sendf(Socket, "PASS %s\n", tmpBuf);
1209 buf = ReadLine(Socket);
1211 responseCode = atoi(buf);
1213 if( responseCode == 200 ) break;
1214 // Bad username/password
1215 if( responseCode == 401 ) continue;
1217 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1219 return RV_UNKNOWN_ERROR;
1223 return RV_INVALID_USER; // 2 = Bad Password
1226 fprintf(stderr, "Untrusted host, AUTOAUTH unavaliable\n");
1227 return RV_INVALID_USER;
1231 case 404: // Bad Username
1232 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1234 return RV_INVALID_USER;
1237 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1238 printf("%s\n", buf);
1240 return RV_UNKNOWN_ERROR;
1243 // Set effective user
1244 if( gsEffectiveUser ) {
1245 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1247 buf = ReadLine(Socket);
1248 responseCode = atoi(buf);
1250 switch(responseCode)
1253 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1257 printf("Only coke members can use `dispense -u`\n");
1259 return RV_PERMISSIONS;
1262 printf("Invalid user selected\n");
1264 return RV_INVALID_USER;
1267 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1268 printf("%s\n", buf);
1270 return RV_UNKNOWN_ERROR;
1276 gbIsAuthenticated = 1;
1281 int GetUserBalance(int Socket)
1283 regmatch_t matches[6];
1290 if( gsEffectiveUser ) {
1291 gsUserName = gsEffectiveUser;
1294 pwd = getpwuid( getuid() );
1295 gsUserName = strdup(pwd->pw_name);
1299 sendf(Socket, "USER_INFO %s\n", gsUserName);
1300 buf = ReadLine(Socket);
1301 responseCode = atoi(buf);
1302 switch(responseCode)
1304 case 202: break; // Ok
1307 printf("Invalid user? (USER_INFO failed)\n");
1309 return RV_INVALID_USER;
1312 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1313 printf("%s\n", buf);
1315 return RV_UNKNOWN_ERROR;
1318 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1320 giUserBalance = atoi( buf + matches[4].rm_so );
1321 gsUserFlags = strdup( buf + matches[5].rm_so );
1329 * \brief Read an item info response from the server
1330 * \param Dest Destination for the read item (strings will be on the heap)
1332 int ReadItemInfo(int Socket, tItem *Dest)
1337 regmatch_t matches[8];
1341 buf = ReadLine(Socket);
1342 responseCode = atoi(buf);
1344 switch(responseCode)
1349 printf("Bad item name\n");
1354 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1356 return RV_UNKNOWN_ERROR;
1359 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1361 buf[ matches[3].rm_eo ] = '\0';
1362 buf[ matches[5].rm_eo ] = '\0';
1363 buf[ matches[7].rm_eo ] = '\0';
1365 statusStr = &buf[ matches[5].rm_so ];
1367 Dest->ID = atoi( buf + matches[4].rm_so );
1369 if( strcmp(statusStr, "avail") == 0 )
1371 else if( strcmp(statusStr, "sold") == 0 )
1373 else if( strcmp(statusStr, "error") == 0 )
1376 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1378 return RV_UNKNOWN_ERROR;
1380 Dest->Price = atoi( buf + matches[6].rm_so );
1382 // Hack a little to reduce heap fragmentation
1384 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1385 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1386 strcpy(tmpType, buf + matches[3].rm_so);
1387 strcpy(tmpDesc, buf + matches[7].rm_so);
1389 Dest->Type = strdup( tmpType );
1390 Dest->Desc = strdup( tmpDesc );
1397 * \brief Fill the item information structure
1398 * \return Boolean Failure
1400 void PopulateItemList(int Socket)
1405 char *itemType, *itemStart;
1407 regmatch_t matches[4];
1409 // Ask server for stock list
1410 send(Socket, "ENUM_ITEMS\n", 11, 0);
1411 buf = ReadLine(Socket);
1413 //printf("Output: %s\n", buf);
1415 responseCode = atoi(buf);
1416 if( responseCode != 201 ) {
1417 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1418 exit(RV_UNKNOWN_ERROR);
1421 // - Get item list -
1424 // 201 Items <count>
1426 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1428 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1429 count = atoi( &buf[ matches[3].rm_so ] );
1432 if( strcmp(itemType, "Items") != 0 ) {
1434 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1436 exit(RV_UNKNOWN_ERROR);
1439 itemStart = &buf[ matches[3].rm_eo ];
1444 gaItems = malloc( giNumItems * sizeof(tItem) );
1446 // Fetch item information
1447 for( i = 0; i < giNumItems; i ++ )
1449 ReadItemInfo( Socket, &gaItems[i] );
1453 buf = ReadLine(Socket);
1454 responseCode = atoi(buf);
1456 if( responseCode != 200 ) {
1457 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1468 * \brief Get information on an item
1469 * \return Boolean Failure
1471 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1477 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1479 ret = ReadItemInfo(Socket, &item);
1482 printf("%8s:%-2i %2i.%02i %s\n",
1484 item.Price/100, item.Price%100,
1494 * \brief Dispense an item
1495 * \return Boolean Failure
1497 int DispenseItem(int Socket, const char *Type, int ID)
1499 int ret, responseCode;
1502 // Check for a dry run
1504 printf("Dry Run - No action\n");
1509 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1510 buf = ReadLine(Socket);
1512 responseCode = atoi(buf);
1513 switch( responseCode )
1516 printf("Dispense OK\n");
1520 printf("Not authenticated\n");
1521 ret = RV_PERMISSIONS;
1524 printf("Insufficient balance\n");
1528 printf("Bad item name\n");
1532 printf("Item failed to dispense, is the slot empty?\n");
1536 printf("Dispense not possible (slot empty/permissions)\n");
1540 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1541 ret = RV_UNKNOWN_ERROR;
1550 * \brief Alter a user's balance
1552 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1557 // Check for a dry run
1559 printf("Dry Run - No action\n");
1564 if( Ammount == 0 ) {
1565 printf("An ammount would be nice\n");
1566 return RV_ARGUMENTS;
1569 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1570 buf = ReadLine(Socket);
1572 responseCode = atoi(buf);
1575 switch(responseCode)
1577 case 200: return 0; // OK
1579 fprintf(stderr, "Insufficient balance\n");
1581 case 403: // Not in coke
1582 fprintf(stderr, "You are not in coke (sucker)\n");
1584 case 404: // Unknown user
1585 fprintf(stderr, "Unknown user '%s'\n", Username);
1588 fprintf(stderr, "Unknown response code %i\n", responseCode);
1596 * \brief Set a user's balance
1597 * \note Only avaliable to dispense admins
1599 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1604 // Check for a dry run
1606 printf("Dry Run - No action\n");
1610 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1611 buf = ReadLine(Socket);
1613 responseCode = atoi(buf);
1616 switch(responseCode)
1618 case 200: return 0; // OK
1619 case 403: // Not in coke
1620 fprintf(stderr, "You are not an admin\n");
1622 case 404: // Unknown user
1623 fprintf(stderr, "Unknown user '%s'\n", Username);
1626 fprintf(stderr, "Unknown response code %i\n", responseCode);
1634 * \brief Give money to another user
1636 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1642 printf("Sorry, you can only give, you can't take.\n");
1646 // Fast return on zero
1647 if( Ammount == 0 ) {
1648 printf("Are you actually going to give any?\n");
1652 // Check for a dry run
1654 printf("Dry Run - No action\n");
1658 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1660 buf = ReadLine(Socket);
1661 responseCode = atoi(buf);
1663 switch(responseCode)
1666 printf("Give succeeded\n");
1670 fprintf(stderr, "Insufficient balance\n");
1673 case 404: // Unknown user
1674 fprintf(stderr, "Unknown user '%s'\n", Username);
1678 fprintf(stderr, "Unknown response code %i\n", responseCode);
1685 int Dispense_Refund(int Socket, const char *Username, const char *Item, int PriceOverride)
1688 int responseCode, ret = -1;
1691 if( RunRegex(&gUserItemIdentRegex, Item, 0, NULL, NULL) != 0 )
1693 fprintf(stderr, "Error: Invalid item ID passed (should be <type>:<num>)\n");
1694 return RV_ARGUMENTS;
1697 // Check username (quick)
1698 if( strchr(Username, ' ') || strchr(Username, '\n') )
1700 fprintf(stderr, "Error: Username is invalid (no spaces or newlines please)\n");
1701 return RV_ARGUMENTS;
1705 sendf(Socket, "REFUND %s %s %i", Username, Item, PriceOverride);
1707 buf = ReadLine(Socket);
1708 responseCode = atoi(buf);
1709 switch(responseCode)
1712 Dispense_ShowUser(Socket, Username); // Show destination account
1716 fprintf(stderr, "Refund access is only avaliable to coke members\n");
1717 ret = RV_PERMISSIONS;
1720 fprintf(stderr, "Unknown user '%s' passed\n", Username);
1721 ret = RV_INVALID_USER;
1724 fprintf(stderr, "Invalid item '%s' passed\n", Item);
1728 fprintf(stderr, "Unknown response from server %i\n%s\n", responseCode, buf);
1737 * \brief Donate money to the club
1739 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1745 printf("Sorry, you can only give, you can't take.\n");
1749 // Fast return on zero
1750 if( Ammount == 0 ) {
1751 printf("Are you actually going to give any?\n");
1755 // Check for a dry run
1757 printf("Dry Run - No action\n");
1761 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1762 buf = ReadLine(Socket);
1764 responseCode = atoi(buf);
1767 switch(responseCode)
1769 case 200: return 0; // OK
1772 fprintf(stderr, "Insufficient balance\n");
1776 fprintf(stderr, "Unknown response code %i\n", responseCode);
1784 * \brief Enumerate users
1786 int Dispense_EnumUsers(int Socket)
1791 regmatch_t matches[4];
1793 if( giMinimumBalance != INT_MIN ) {
1794 if( giMaximumBalance != INT_MAX ) {
1795 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1798 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1802 if( giMaximumBalance != INT_MAX ) {
1803 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1806 sendf(Socket, "ENUM_USERS\n");
1809 buf = ReadLine(Socket);
1810 responseCode = atoi(buf);
1812 switch(responseCode)
1814 case 201: break; // Ok, length follows
1817 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1822 // Get count (not actually used)
1823 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1824 nUsers = atoi( buf + matches[3].rm_so );
1825 printf("%i users returned\n", nUsers);
1830 // Read returned users
1832 buf = ReadLine(Socket);
1833 responseCode = atoi(buf);
1835 if( responseCode != 202 ) break;
1837 _PrintUserLine(buf);
1839 } while(responseCode == 202);
1841 // Check final response
1842 if( responseCode != 200 ) {
1843 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1853 int Dispense_ShowUser(int Socket, const char *Username)
1856 int responseCode, ret;
1858 sendf(Socket, "USER_INFO %s\n", Username);
1859 buf = ReadLine(Socket);
1861 responseCode = atoi(buf);
1863 switch(responseCode)
1866 _PrintUserLine(buf);
1871 printf("Unknown user '%s'\n", Username);
1876 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1886 void _PrintUserLine(const char *Line)
1888 regmatch_t matches[6];
1891 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1896 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1897 char username[usernameLen + 1];
1898 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1899 char flags[flagsLen + 1];
1901 memcpy(username, Line + matches[3].rm_so, usernameLen);
1902 username[usernameLen] = '\0';
1903 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1904 flags[flagsLen] = '\0';
1906 bal = atoi(Line + matches[4].rm_so);
1907 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1911 int Dispense_AddUser(int Socket, const char *Username)
1914 int responseCode, ret;
1916 // Check for a dry run
1918 printf("Dry Run - No action\n");
1922 sendf(Socket, "USER_ADD %s\n", Username);
1924 buf = ReadLine(Socket);
1925 responseCode = atoi(buf);
1927 switch(responseCode)
1930 printf("User '%s' added\n", Username);
1935 printf("Only wheel can add users\n");
1940 printf("User '%s' already exists\n", Username);
1945 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1955 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1958 int responseCode, ret;
1960 // Check for a dry run
1962 printf("Dry Run - No action\n");
1966 // TODO: Pre-validate the string
1968 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1970 buf = ReadLine(Socket);
1971 responseCode = atoi(buf);
1973 switch(responseCode)
1976 printf("User '%s' updated\n", Username);
1981 printf("Only wheel can modify users\n");
1986 printf("User '%s' does not exist\n", Username);
1991 printf("Flag string is invalid\n");
1996 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
2009 char *ReadLine(int Socket)
2011 static char buf[BUFSIZ];
2012 static int bufPos = 0;
2013 static int bufValid = 0;
2015 char *newline = NULL;
2017 char *ret = malloc(10);
2019 #if DEBUG_TRACE_SERVER
2020 printf("ReadLine: ");
2032 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
2033 buf[bufPos+len] = '\0';
2036 newline = strchr( buf+bufPos, '\n' );
2041 retLen += strlen(buf+bufPos);
2042 ret = realloc(ret, retLen + 1);
2043 strcat( ret, buf+bufPos );
2046 int newLen = newline - (buf+bufPos) + 1;
2047 bufValid = len - newLen;
2050 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
2053 #if DEBUG_TRACE_SERVER
2054 printf("%i '%s'\n", retLen, ret);
2060 int sendf(int Socket, const char *Format, ...)
2065 va_start(args, Format);
2066 len = vsnprintf(NULL, 0, Format, args);
2071 va_start(args, Format);
2072 vsnprintf(buf, len+1, Format, args);
2075 #if DEBUG_TRACE_SERVER
2076 printf("sendf: %s", buf);
2079 return send(Socket, buf, len, 0);
2083 char *trim(char *string)
2087 while( isspace(*string) )
2090 for( i = strlen(string); i--; )
2092 if( isspace(string[i]) )
2101 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2105 ret = regexec(regex, string, nMatches, matches, 0);
2106 if( ret && errorMessage ) {
2107 size_t len = regerror(ret, regex, NULL, 0);
2109 regerror(ret, regex, errorStr, len);
2110 printf("string = '%s'\n", string);
2111 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2118 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2120 int ret = regcomp(regex, pattern, flags);
2122 size_t len = regerror(ret, regex, NULL, 0);
2124 regerror(ret, regex, errorStr, len);
2125 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);