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_Donate(int Socket, int Ammount, const char *Reason);
83 int Dispense_EnumUsers(int Socket);
84 int Dispense_ShowUser(int Socket, const char *Username);
85 void _PrintUserLine(const char *Line);
86 int Dispense_AddUser(int Socket, const char *Username);
87 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
89 char *ReadLine(int Socket);
90 int sendf(int Socket, const char *Format, ...);
91 char *trim(char *string);
92 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
93 void CompileRegex(regex_t *regex, const char *pattern, int flags);
96 char *gsDispenseServer = "heathred";
97 int giDispensePort = 11020;
101 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
102 int gbIsAuthenticated = 0;
104 char *gsItemPattern; //!< Item pattern
105 char *gsEffectiveUser; //!< '-u' Dispense as another user
106 int giUIMode = UI_MODE_STANDARD;
107 int gbDryRun = 0; //!< '-n' Read-only
108 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
109 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
110 char *gsUserName; //!< User that dispense will happen as
111 char *gsUserFlags; //!< User's flag set
112 int giUserBalance=-1; //!< User balance (set by Authenticate)
113 int giDispenseCount = 1; //!< Number of dispenses to do
116 int main(int argc, char *argv[])
121 char *text_args[MAX_TXT_ARGS]; // Non-flag arguments
126 // -- Create regular expressions
127 // > Code Type Count ...
128 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
129 // > Code Type Ident Status Price Desc
130 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);
131 // > Code 'SALT' salt
132 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
133 // > Code 'User' Username Balance Flags
134 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
136 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
139 for( i = 1; i < argc; i ++ )
153 if( i + 1 >= argc ) {
154 fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
158 giDispenseCount = atoi(argv[++i]);
159 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
160 fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
166 case 'm': // Minimum balance
167 if( i + 1 >= argc ) {
168 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
172 giMinimumBalance = atoi(argv[++i]);
174 case 'M': // Maximum balance
175 if( i + 1 >= argc ) {
176 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
180 giMaximumBalance = atoi(argv[++i]);
183 case 'u': // Override User
184 if( i + 1 >= argc ) {
185 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
189 gsEffectiveUser = argv[++i];
192 case 'H': // Override remote host
193 if( i + 1 >= argc ) {
194 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
198 gsDispenseServer = argv[++i];
200 case 'P': // Override remote port
201 if( i + 1 >= argc ) {
202 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
206 giDispensePort = atoi(argv[++i]);
209 case 'G': // Don't use GUI
210 giUIMode = UI_MODE_BASIC;
212 case 'D': // Drinks only
213 giUIMode = UI_MODE_DRINKSONLY;
215 case 'n': // Dry Run / read-only
219 if( text_argc + 1 == MAX_TXT_ARGS )
221 fprintf(stderr, "ERROR: Too many arguments\n");
224 text_args[text_argc++] = argv[i];
231 if( text_argc + 1 == MAX_TXT_ARGS )
233 fprintf(stderr, "ERROR: Too many arguments\n");
237 text_args[text_argc++] = argv[i];
244 if( strcmp(text_args[0], "acct") == 0 )
247 sock = OpenConnection(gsDispenseServer, giDispensePort);
248 if( sock < 0 ) return RV_SOCKET_ERROR;
250 if( text_argc == 1 ) {
251 ret = Dispense_EnumUsers(sock);
256 // text_args[1]: Username
261 // Authentication required
262 ret = Authenticate(sock);
265 // text_args[1]: Username
266 // text_args[2]: Ammount
267 // text_args[3]: Reason
269 if( text_args[2][0] == '=' ) {
271 if( text_args[2][1] != '0' && atoi(text_args[2]+1) == 0 ) {
272 fprintf(stderr, "Error: Invalid balance to be set\n");
276 ret = Dispense_SetBalance(sock, text_args[1], atoi(text_args[2]+1), text_args[3]);
280 ret = Dispense_AlterBalance(sock, text_args[1], atoi(text_args[2]), text_args[3]);
283 // TODO: Preserve ret if non-zero
285 // Show user information
286 ret = Dispense_ShowUser(sock, text_args[1]);
293 // - "Here, have some money."
294 if( strcmp(text_args[0], "give") == 0 )
296 if( text_argc != 4 ) {
297 fprintf(stderr, "`dispense give` takes three arguments\n");
302 // text_args[1]: Destination
303 // text_args[2]: Ammount
304 // text_args[3]: Reason
307 sock = OpenConnection(gsDispenseServer, giDispensePort);
308 if( sock < 0 ) return RV_SOCKET_ERROR;
311 ret = Authenticate(sock);
314 ret = Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
322 // - User administration (Admin Only)
323 if( strcmp(text_args[0], "user") == 0 )
325 // Check argument count
326 if( text_argc == 1 ) {
327 fprintf(stderr, "Error: `dispense user` requires arguments\n");
333 sock = OpenConnection(gsDispenseServer, giDispensePort);
334 if( sock < 0 ) return RV_SOCKET_ERROR;
336 // Attempt authentication
337 ret = Authenticate(sock);
341 if( strcmp(text_args[1], "add") == 0 )
343 if( text_argc != 3 ) {
344 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
349 ret = Dispense_AddUser(sock, text_args[2]);
352 else if( strcmp(text_args[1], "type") == 0 || strcmp(text_args[1], "flags") == 0 )
354 if( text_argc != 4 ) {
355 fprintf(stderr, "Error: `dispense user flags` requires two arguments\n");
360 ret = Dispense_SetUserType(sock, text_args[2], text_args[3]);
364 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
372 else if( strcmp(text_args[0], "donate") == 0 )
374 // Check argument count
375 if( text_argc != 3 ) {
376 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
382 sock = OpenConnection(gsDispenseServer, giDispensePort);
383 if( sock < 0 ) return RV_SOCKET_ERROR;
385 // Attempt authentication
386 ret = Authenticate(sock);
390 ret = Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
397 else if( strcmp(text_args[0], "refund") == 0 )
399 // Check argument count
400 if( text_argc != 3 && text_argc != 4 ) {
401 fprintf(stderr, "Error: `dispense refund` takes 2 or 3 arguments\n");
407 sock = OpenConnection(gsDispenseServer, giDispensePort);
408 if(sock < 0) return RV_SOCKET_ERROR;
410 // Attempt authentication
411 ret = Authenticate(sock);
416 return RV_UNKNOWN_ERROR;
418 // Query an item price
419 else if( strcmp(text_args[0], "iteminfo") == 0 )
421 regmatch_t matches[3];
424 // Check argument count
425 if( text_argc != 2 ) {
426 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
431 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
432 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
435 type = text_args[1] + matches[1].rm_so;
436 text_args[1][ matches[1].rm_eo ] = '\0';
437 id = atoi( text_args[1] + matches[2].rm_so );
439 sock = OpenConnection(gsDispenseServer, giDispensePort);
440 if( sock < 0 ) return RV_SOCKET_ERROR;
442 ret = Dispense_ItemInfo(sock, type, id);
446 // Item name / pattern
448 gsItemPattern = text_args[0];
452 sock = OpenConnection(gsDispenseServer, giDispensePort);
453 if( sock < 0 ) return RV_SOCKET_ERROR;
455 // Get the user's balance
456 ret = GetUserBalance(sock);
460 PopulateItemList(sock);
462 // Disconnect from server
465 if( gsItemPattern && gsItemPattern[0] )
467 regmatch_t matches[3];
469 if( strcmp(gsItemPattern, "door") == 0 )
471 // Connect, Authenticate, dispense and close
472 sock = OpenConnection(gsDispenseServer, giDispensePort);
473 if( sock < 0 ) return RV_SOCKET_ERROR;
474 ret = Authenticate(sock);
476 ret = DispenseItem(sock, "door", 0);
480 // Item id (<type>:<num>)
481 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
486 // Get and finish ident
487 ident = gsItemPattern + matches[1].rm_so;
488 gsItemPattern[matches[1].rm_eo] = '\0';
490 id = atoi( gsItemPattern + matches[2].rm_so );
492 // Connect, Authenticate, dispense and close
493 sock = OpenConnection(gsDispenseServer, giDispensePort);
494 if( sock < 0 ) return RV_SOCKET_ERROR;
496 Dispense_ItemInfo(sock, ident, id);
498 ret = Authenticate(sock);
500 ret = DispenseItem(sock, ident, id);
504 // Item number (6 = coke)
505 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
507 i = atoi(gsItemPattern);
514 for( i = 0; i < giNumItems; i ++ )
516 // Prefix match (with case-insensitive match)
517 for( j = 0; gsItemPattern[j]; j ++ )
519 if( gaItems[i].Desc[j] == gsItemPattern[j] )
521 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
525 // Check if the prefix matched
526 if( gsItemPattern[j] != '\0' )
530 if( gaItems[i].Desc[j] == '\0' ) {
535 // Only one match allowed
540 // TODO: Allow ambiguous matches?
541 // or just print a wanrning
542 printf("Warning - Ambiguous pattern, stopping\n");
547 // Was a match found?
550 fprintf(stderr, "No item matches the passed string\n");
557 else if( giUIMode != UI_MODE_BASIC )
563 // Very basic dispense interface
564 for( i = 0; i < giNumItems; i ++ ) {
566 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
569 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
570 gaItems[i].Price, gaItems[i].Desc);
579 fgets(buffer, BUFSIZ, stdin);
583 if( buf[0] == 'q' ) break;
587 if( i != 0 || buf[0] == '0' )
589 if( i < 0 || i >= giNumItems ) {
590 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
599 // Check for a valid item ID
603 // Connect, Authenticate, dispense and close
604 sock = OpenConnection(gsDispenseServer, giDispensePort);
605 if( sock < 0 ) return RV_SOCKET_ERROR;
607 ret = Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
610 ret = Authenticate(sock);
613 for( j = 0; j < giDispenseCount; j ++ ) {
614 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
618 printf("%i items dispensed\n", j);
632 " Show interactive list\n"
633 " dispense <name>|<index>|<itemid>\n"
634 " Dispense named item (<name> matches if it is a unique prefix)\n"
635 " dispense give <user> <ammount> \"<reason>\"\n"
636 " Give money to another user\n"
637 " dispense donate <ammount> \"<reason>\"\n"
638 " Donate to the club\n"
639 " dispense iteminfo <type>:<id>\n"
640 " Get the name and price for an item\n"
641 " == Coke members == \n"
642 " dispense acct [<user>]\n"
643 " Show user balances\n"
644 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
645 " Alter a account value\n"
646 " == Dispense administrators ==\n"
647 " dispense acct <user> =<ammount> \"<reason>\"\n"
648 " Set an account balance\n"
649 " dispense user add <user>\n"
650 " Create new coke account (Admins only)\n"
651 " dispense user type <user> <flags>\n"
652 " Alter a user's flags\n"
653 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
654 " Flags are removed by preceding the name with '-' or '!'\n"
658 " Dispense multiple times\n"
660 " Set a different user (Coke members only)\n"
664 " Use alternate GUI\n"
665 " -m <min balance>\n"
666 " -M <max balance>\n"
667 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
671 // -------------------
672 // --- NCurses GUI ---
673 // -------------------
675 * \brief Render the NCurses UI
677 int ShowNCursesUI(void)
679 // TODO: ncurses interface (with separation between item classes)
680 // - Hmm... that would require standardising the item ID to be <class>:<index>
685 const int displayMinWidth = 40;
686 char *titleString = "Dispense";
691 int ret = -2; // -2: Used for marking "no return yet"
693 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
700 if( gsEffectiveUser )
701 username = gsEffectiveUser;
703 pwd = getpwuid( getuid() );
704 username = pwd->pw_name;
707 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
714 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
715 // Get item count per screen
716 // - 6: randomly chosen (Need at least 3)
717 itemCount = LINES - 6;
718 if( itemCount > maxItemIndex )
719 itemCount = maxItemIndex;
722 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
727 height = itemCount + 3;
728 width = displayMinWidth;
731 xBase = COLS/2 - width/2;
732 yBase = LINES/2 - height/2;
737 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
740 for( i = 0; i < itemCount; i ++ )
744 move( yBase + 1 + i, xBase );
749 // Check for the '...' row
750 // - Oh god, magic numbers!
751 if( (i == 0 && itemBase > 0)
752 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
754 printw(" ..."); pos += 8;
755 times = (width - pos) - 1;
756 while(times--) addch(' ');
761 yBase + 1 + i, xBase + pos, // Position
762 (width - pos) - 3, // Width
763 itemBase + i, // Index
764 !!(currentItem == itemBase + i) // Hilighted
769 // Scrollbar (if needed)
770 if( maxItemIndex > itemCount ) {
774 else if( i == itemCount - 1 ) {
778 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
779 if( i-1 == percentage*(itemCount-3)/100 ) {
793 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
796 // - Username, balance, flags
797 PrintAlign(yBase+height-1, xBase+1, width-2,
798 username, ' ', balance_str, ' ', gsUserFlags);
814 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
817 if( currentItem >= maxItemIndex ) {
820 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
827 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
830 if( currentItem < 0 ) {
831 currentItem = maxItemIndex - 1;
833 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
843 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
844 itemBase = currentItem - 2;
845 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
846 itemBase = currentItem - itemCount + 2;
852 ret = ShowItemAt(0, 0, 0, currentItem, 0);
855 ret = -1; // -1: Return with no dispense
859 // Check if the return value was changed
860 if( ret != -2 ) break;
872 * \brief Show item \a Index at (\a Col, \a Row)
873 * \return Dispense index of item
874 * \note Part of the NCurses UI
876 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
886 // - This assumes that
887 case UI_MODE_STANDARD:
889 // Index = -1, request limit
890 if( Index < 0 || Index >= giNumItems+2 )
896 name = "Coke Machine";
897 Index = -1; // -1 indicates a label
904 name = gaItems[Index].Desc;
905 price = gaItems[Index].Price;
906 status = gaItems[Index].Status;
914 name = "Electronic Payment System";
915 Index = -1; // -1 indicates a label
920 name = gaItems[Index].Desc;
921 price = gaItems[Index].Price;
922 status = gaItems[Index].Status;
928 // Width = 0, don't print
931 // 4 preceding, 5 price
932 int nameWidth = Width - 4 - 5;
937 // Show hilight and status
956 printw("%-*.*s", nameWidth, nameWidth, name);
958 // getyx(stdscr, _y, _x);
959 // Assumes max 4 digit prices
960 // times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
961 // while(times--) addch(' ');
963 printw(" %4i", price);
967 printw("-- %s", name);
968 getyx(stdscr, _y, _x);
969 times = Width - 4 - (_x - Col);
970 while(times--) addch(' ');
975 // If the item isn't availiable for sale, return -1 (so it's skipped)
983 * \brief Print a three-part string at the specified position (formatted)
984 * \note NCurses UI Helper
986 * Prints \a Left on the left of the area, \a Right on the righthand side
987 * and \a Mid in the middle of the area. These are padded with \a Pad1
988 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
990 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
991 * and the arguments to these are read in that order.
993 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
994 const char *Mid, char Pad2, const char *Right, ...)
996 int lLen, mLen, rLen;
1001 // Get the length of the strings
1002 va_start(args, Right);
1003 lLen = vsnprintf(NULL, 0, Left, args);
1004 mLen = vsnprintf(NULL, 0, Mid, args);
1005 rLen = vsnprintf(NULL, 0, Right, args);
1009 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
1010 return ; // TODO: What to do?
1016 va_start(args, Right);
1020 vsnprintf(tmp, lLen+1, Left, args);
1024 times = (Width - mLen)/2 - lLen;
1025 while(times--) addch(Pad1);
1029 vsnprintf(tmp, mLen+1, Mid, args);
1033 times = (Width - mLen)/2 - rLen;
1034 if( (Width - mLen) % 2 ) times ++;
1035 while(times--) addch(Pad2);
1039 vsnprintf(tmp, rLen+1, Right, args);
1044 // ---------------------
1045 // --- Coke Protocol ---
1046 // ---------------------
1047 int OpenConnection(const char *Host, int Port)
1049 struct hostent *host;
1050 struct sockaddr_in serverAddr;
1053 host = gethostbyname(Host);
1055 fprintf(stderr, "Unable to look up '%s'\n", Host);
1059 memset(&serverAddr, 0, sizeof(serverAddr));
1061 serverAddr.sin_family = AF_INET; // IPv4
1062 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1063 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1064 serverAddr.sin_port = htons(Port);
1066 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1068 fprintf(stderr, "Failed to create socket\n");
1072 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1074 if( geteuid() == 0 || getuid() == 0 )
1077 struct sockaddr_in localAddr;
1078 memset(&localAddr, 0, sizeof(localAddr));
1079 localAddr.sin_family = AF_INET; // IPv4
1081 // Loop through all the top ports until one is avaliable
1082 for( i = 512; i < 1024; i ++)
1084 localAddr.sin_port = htons(i); // IPv4
1085 // Attempt to bind to low port for autoauth
1086 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1090 printf("Warning: AUTOAUTH unavaliable\n");
1092 // printf("Bound to 0.0.0.0:%i\n", i);
1095 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1096 fprintf(stderr, "Failed to connect to server\n");
1104 * \brief Authenticate with the server
1105 * \return Boolean Failure
1107 int Authenticate(int Socket)
1114 regmatch_t matches[4];
1116 if( gbIsAuthenticated ) return 0;
1119 pwd = getpwuid( getuid() );
1121 // Attempt automatic authentication
1122 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1124 // Check if it worked
1125 buf = ReadLine(Socket);
1127 responseCode = atoi(buf);
1128 switch( responseCode )
1130 case 200: // Autoauth succeeded, return
1134 case 401: // Untrusted, attempt password authentication
1137 sendf(Socket, "USER %s\n", pwd->pw_name);
1138 printf("Using username %s\n", pwd->pw_name);
1140 buf = ReadLine(Socket);
1143 // Expected format: 100 SALT <something> ...
1144 // OR : 100 User Set
1145 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1146 responseCode = atoi(buf);
1147 if( responseCode != 100 ) {
1148 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1150 return RV_UNKNOWN_ERROR; // ERROR
1154 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1155 // Store it for later
1156 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1157 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1161 // Give three attempts
1162 for( i = 0; i < 3; i ++ )
1164 int ofs = strlen(pwd->pw_name)+strlen(salt);
1167 char *pass = getpass("Password: ");
1170 // Create hash string
1171 // <username><salt><hash>
1172 strcpy(tmp, pwd->pw_name);
1174 SHA1( (unsigned char*)pass, strlen(pass), h );
1175 memcpy(tmp+ofs, h, 20);
1178 SHA1( (unsigned char*)tmp, ofs+20, h );
1179 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1180 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1181 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1185 sendf(Socket, "PASS %s\n", tmpBuf);
1186 buf = ReadLine(Socket);
1188 responseCode = atoi(buf);
1190 if( responseCode == 200 ) break;
1191 // Bad username/password
1192 if( responseCode == 401 ) continue;
1194 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1196 return RV_UNKNOWN_ERROR;
1200 return RV_INVALID_USER; // 2 = Bad Password
1203 case 404: // Bad Username
1204 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1206 return RV_INVALID_USER;
1209 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1210 printf("%s\n", buf);
1212 return RV_UNKNOWN_ERROR;
1215 // Set effective user
1216 if( gsEffectiveUser ) {
1217 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1219 buf = ReadLine(Socket);
1220 responseCode = atoi(buf);
1222 switch(responseCode)
1225 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1229 printf("Only coke members can use `dispense -u`\n");
1231 return RV_PERMISSIONS;
1234 printf("Invalid user selected\n");
1236 return RV_INVALID_USER;
1239 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1240 printf("%s\n", buf);
1242 return RV_UNKNOWN_ERROR;
1248 gbIsAuthenticated = 1;
1253 int GetUserBalance(int Socket)
1255 regmatch_t matches[6];
1262 if( gsEffectiveUser ) {
1263 gsUserName = gsEffectiveUser;
1266 pwd = getpwuid( getuid() );
1267 gsUserName = strdup(pwd->pw_name);
1271 sendf(Socket, "USER_INFO %s\n", gsUserName);
1272 buf = ReadLine(Socket);
1273 responseCode = atoi(buf);
1274 switch(responseCode)
1276 case 202: break; // Ok
1279 printf("Invalid user? (USER_INFO failed)\n");
1281 return RV_INVALID_USER;
1284 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1285 printf("%s\n", buf);
1287 return RV_UNKNOWN_ERROR;
1290 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1292 giUserBalance = atoi( buf + matches[4].rm_so );
1293 gsUserFlags = strdup( buf + matches[5].rm_so );
1301 * \brief Read an item info response from the server
1302 * \param Dest Destination for the read item (strings will be on the heap)
1304 int ReadItemInfo(int Socket, tItem *Dest)
1309 regmatch_t matches[8];
1313 buf = ReadLine(Socket);
1314 responseCode = atoi(buf);
1316 switch(responseCode)
1321 printf("Bad item name\n");
1326 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1328 return RV_UNKNOWN_ERROR;
1331 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1333 buf[ matches[3].rm_eo ] = '\0';
1334 buf[ matches[5].rm_eo ] = '\0';
1335 buf[ matches[7].rm_eo ] = '\0';
1337 statusStr = &buf[ matches[5].rm_so ];
1339 Dest->ID = atoi( buf + matches[4].rm_so );
1341 if( strcmp(statusStr, "avail") == 0 )
1343 else if( strcmp(statusStr, "sold") == 0 )
1345 else if( strcmp(statusStr, "error") == 0 )
1348 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1350 return RV_UNKNOWN_ERROR;
1352 Dest->Price = atoi( buf + matches[6].rm_so );
1354 // Hack a little to reduce heap fragmentation
1356 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1357 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1358 strcpy(tmpType, buf + matches[3].rm_so);
1359 strcpy(tmpDesc, buf + matches[7].rm_so);
1361 Dest->Type = strdup( tmpType );
1362 Dest->Desc = strdup( tmpDesc );
1369 * \brief Fill the item information structure
1370 * \return Boolean Failure
1372 void PopulateItemList(int Socket)
1377 char *itemType, *itemStart;
1379 regmatch_t matches[4];
1381 // Ask server for stock list
1382 send(Socket, "ENUM_ITEMS\n", 11, 0);
1383 buf = ReadLine(Socket);
1385 //printf("Output: %s\n", buf);
1387 responseCode = atoi(buf);
1388 if( responseCode != 201 ) {
1389 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1390 exit(RV_UNKNOWN_ERROR);
1393 // - Get item list -
1396 // 201 Items <count>
1398 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1400 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1401 count = atoi( &buf[ matches[3].rm_so ] );
1404 if( strcmp(itemType, "Items") != 0 ) {
1406 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1408 exit(RV_UNKNOWN_ERROR);
1411 itemStart = &buf[ matches[3].rm_eo ];
1416 gaItems = malloc( giNumItems * sizeof(tItem) );
1418 // Fetch item information
1419 for( i = 0; i < giNumItems; i ++ )
1421 ReadItemInfo( Socket, &gaItems[i] );
1425 buf = ReadLine(Socket);
1426 responseCode = atoi(buf);
1428 if( responseCode != 200 ) {
1429 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1440 * \brief Get information on an item
1441 * \return Boolean Failure
1443 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1449 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1451 ret = ReadItemInfo(Socket, &item);
1454 printf("%8s:%-2i %2i.%02i %s\n",
1456 item.Price/100, item.Price%100,
1466 * \brief Dispense an item
1467 * \return Boolean Failure
1469 int DispenseItem(int Socket, const char *Type, int ID)
1471 int ret, responseCode;
1474 // Check for a dry run
1476 printf("Dry Run - No action\n");
1481 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1482 buf = ReadLine(Socket);
1484 responseCode = atoi(buf);
1485 switch( responseCode )
1488 printf("Dispense OK\n");
1492 printf("Not authenticated\n");
1493 ret = RV_PERMISSIONS;
1496 printf("Insufficient balance\n");
1500 printf("Bad item name\n");
1504 printf("Item failed to dispense, is the slot empty?\n");
1508 printf("Dispense not possible (slot empty/permissions)\n");
1512 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1513 ret = RV_UNKNOWN_ERROR;
1522 * \brief Alter a user's balance
1524 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1529 // Check for a dry run
1531 printf("Dry Run - No action\n");
1536 if( Ammount == 0 ) {
1537 printf("An ammount would be nice\n");
1538 return RV_ARGUMENTS;
1541 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1542 buf = ReadLine(Socket);
1544 responseCode = atoi(buf);
1547 switch(responseCode)
1549 case 200: return 0; // OK
1551 fprintf(stderr, "Insufficient balance\n");
1553 case 403: // Not in coke
1554 fprintf(stderr, "You are not in coke (sucker)\n");
1556 case 404: // Unknown user
1557 fprintf(stderr, "Unknown user '%s'\n", Username);
1560 fprintf(stderr, "Unknown response code %i\n", responseCode);
1568 * \brief Set a user's balance
1569 * \note Only avaliable to dispense admins
1571 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1576 // Check for a dry run
1578 printf("Dry Run - No action\n");
1582 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1583 buf = ReadLine(Socket);
1585 responseCode = atoi(buf);
1588 switch(responseCode)
1590 case 200: return 0; // OK
1591 case 403: // Not in coke
1592 fprintf(stderr, "You are not an admin\n");
1594 case 404: // Unknown user
1595 fprintf(stderr, "Unknown user '%s'\n", Username);
1598 fprintf(stderr, "Unknown response code %i\n", responseCode);
1606 * \brief Give money to another user
1608 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1614 printf("Sorry, you can only give, you can't take.\n");
1618 // Fast return on zero
1619 if( Ammount == 0 ) {
1620 printf("Are you actually going to give any?\n");
1624 // Check for a dry run
1626 printf("Dry Run - No action\n");
1630 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1631 buf = ReadLine(Socket);
1633 responseCode = atoi(buf);
1636 switch(responseCode)
1639 printf("Give succeeded\n");
1643 fprintf(stderr, "Insufficient balance\n");
1646 case 404: // Unknown user
1647 fprintf(stderr, "Unknown user '%s'\n", Username);
1651 fprintf(stderr, "Unknown response code %i\n", responseCode);
1660 * \brief Donate money to the club
1662 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1668 printf("Sorry, you can only give, you can't take.\n");
1672 // Fast return on zero
1673 if( Ammount == 0 ) {
1674 printf("Are you actually going to give any?\n");
1678 // Check for a dry run
1680 printf("Dry Run - No action\n");
1684 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1685 buf = ReadLine(Socket);
1687 responseCode = atoi(buf);
1690 switch(responseCode)
1692 case 200: return 0; // OK
1695 fprintf(stderr, "Insufficient balance\n");
1699 fprintf(stderr, "Unknown response code %i\n", responseCode);
1707 * \brief Enumerate users
1709 int Dispense_EnumUsers(int Socket)
1714 regmatch_t matches[4];
1716 if( giMinimumBalance != INT_MIN ) {
1717 if( giMaximumBalance != INT_MAX ) {
1718 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1721 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1725 if( giMaximumBalance != INT_MAX ) {
1726 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1729 sendf(Socket, "ENUM_USERS\n");
1732 buf = ReadLine(Socket);
1733 responseCode = atoi(buf);
1735 switch(responseCode)
1737 case 201: break; // Ok, length follows
1740 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1745 // Get count (not actually used)
1746 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1747 nUsers = atoi( buf + matches[3].rm_so );
1748 printf("%i users returned\n", nUsers);
1753 // Read returned users
1755 buf = ReadLine(Socket);
1756 responseCode = atoi(buf);
1758 if( responseCode != 202 ) break;
1760 _PrintUserLine(buf);
1762 } while(responseCode == 202);
1764 // Check final response
1765 if( responseCode != 200 ) {
1766 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1776 int Dispense_ShowUser(int Socket, const char *Username)
1779 int responseCode, ret;
1781 sendf(Socket, "USER_INFO %s\n", Username);
1782 buf = ReadLine(Socket);
1784 responseCode = atoi(buf);
1786 switch(responseCode)
1789 _PrintUserLine(buf);
1794 printf("Unknown user '%s'\n", Username);
1799 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1809 void _PrintUserLine(const char *Line)
1811 regmatch_t matches[6];
1814 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1819 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1820 char username[usernameLen + 1];
1821 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1822 char flags[flagsLen + 1];
1824 memcpy(username, Line + matches[3].rm_so, usernameLen);
1825 username[usernameLen] = '\0';
1826 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1827 flags[flagsLen] = '\0';
1829 bal = atoi(Line + matches[4].rm_so);
1830 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1834 int Dispense_AddUser(int Socket, const char *Username)
1837 int responseCode, ret;
1839 // Check for a dry run
1841 printf("Dry Run - No action\n");
1845 sendf(Socket, "USER_ADD %s\n", Username);
1847 buf = ReadLine(Socket);
1848 responseCode = atoi(buf);
1850 switch(responseCode)
1853 printf("User '%s' added\n", Username);
1858 printf("Only wheel can add users\n");
1863 printf("User '%s' already exists\n", Username);
1868 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1878 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1881 int responseCode, ret;
1883 // Check for a dry run
1885 printf("Dry Run - No action\n");
1889 // TODO: Pre-validate the string
1891 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1893 buf = ReadLine(Socket);
1894 responseCode = atoi(buf);
1896 switch(responseCode)
1899 printf("User '%s' updated\n", Username);
1904 printf("Only wheel can modify users\n");
1909 printf("User '%s' does not exist\n", Username);
1914 printf("Flag string is invalid\n");
1919 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1932 char *ReadLine(int Socket)
1934 static char buf[BUFSIZ];
1935 static int bufPos = 0;
1936 static int bufValid = 0;
1938 char *newline = NULL;
1940 char *ret = malloc(10);
1942 #if DEBUG_TRACE_SERVER
1943 printf("ReadLine: ");
1955 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1956 buf[bufPos+len] = '\0';
1959 newline = strchr( buf+bufPos, '\n' );
1964 retLen += strlen(buf+bufPos);
1965 ret = realloc(ret, retLen + 1);
1966 strcat( ret, buf+bufPos );
1969 int newLen = newline - (buf+bufPos) + 1;
1970 bufValid = len - newLen;
1973 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1976 #if DEBUG_TRACE_SERVER
1977 printf("%i '%s'\n", retLen, ret);
1983 int sendf(int Socket, const char *Format, ...)
1988 va_start(args, Format);
1989 len = vsnprintf(NULL, 0, Format, args);
1994 va_start(args, Format);
1995 vsnprintf(buf, len+1, Format, args);
1998 #if DEBUG_TRACE_SERVER
1999 printf("sendf: %s", buf);
2002 return send(Socket, buf, len, 0);
2006 char *trim(char *string)
2010 while( isspace(*string) )
2013 for( i = strlen(string); i--; )
2015 if( isspace(string[i]) )
2024 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
2028 ret = regexec(regex, string, nMatches, matches, 0);
2029 if( ret && errorMessage ) {
2030 size_t len = regerror(ret, regex, NULL, 0);
2032 regerror(ret, regex, errorStr, len);
2033 printf("string = '%s'\n", string);
2034 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
2041 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2043 int ret = regcomp(regex, pattern, flags);
2045 size_t len = regerror(ret, regex, NULL, 0);
2047 regerror(ret, regex, errorStr, len);
2048 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);