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
45 typedef struct sItem {
48 int Status; // 0: Availiable, 1: Sold out, -1: Error
54 int main(int argc, char *argv[]);
57 int ShowNCursesUI(void);
58 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted);
59 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
60 // --- Coke Server Communication ---
61 int OpenConnection(const char *Host, int Port);
62 int Authenticate(int Socket);
63 int GetUserBalance(int Socket);
64 void PopulateItemList(int Socket);
65 int Dispense_ItemInfo(int Socket, const char *Type, int ID);
66 int DispenseItem(int Socket, const char *Type, int ID);
67 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
68 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
69 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
70 int Dispense_Donate(int Socket, int Ammount, const char *Reason);
71 int Dispense_EnumUsers(int Socket);
72 int Dispense_ShowUser(int Socket, const char *Username);
73 void _PrintUserLine(const char *Line);
74 int Dispense_AddUser(int Socket, const char *Username);
75 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
77 char *ReadLine(int Socket);
78 int sendf(int Socket, const char *Format, ...);
79 char *trim(char *string);
80 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
81 void CompileRegex(regex_t *regex, const char *pattern, int flags);
84 char *gsDispenseServer = "heathred";
85 int giDispensePort = 11020;
89 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
90 int gbIsAuthenticated = 0;
92 char *gsItemPattern; //!< Item pattern
93 char *gsEffectiveUser; //!< '-u' Dispense as another user
94 int giUIMode = UI_MODE_STANDARD;
95 int gbDryRun = 0; //!< '-n' Read-only
96 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
97 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
98 char *gsUserName; //!< User that dispense will happen as
99 char *gsUserFlags; //!< User's flag set
100 int giUserBalance=-1; //!< User balance (set by Authenticate)
101 int giDispenseCount = 1; //!< Number of dispenses to do
104 int main(int argc, char *argv[])
109 char *text_args[MAX_TXT_ARGS]; // Non-flag arguments
114 // -- Create regular expressions
115 // > Code Type Count ...
116 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
117 // > Code Type Ident Status Price Desc
118 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);
119 // > Code 'SALT' salt
120 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
121 // > Code 'User' Username Balance Flags
122 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
124 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
127 for( i = 1; i < argc; i ++ )
141 if( i + 1 >= argc ) {
142 fprintf(stderr, "%s: -c takes an argument\n", argv[0]);
146 giDispenseCount = atoi(argv[++i]);
147 if( giDispenseCount < 1 || giDispenseCount > DISPENSE_MULTIPLE_MAX ) {
148 fprintf(stderr, "Sorry, only 1-20 can be passed to -c (safety)\n");
154 case 'm': // Minimum balance
155 if( i + 1 >= argc ) {
156 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
160 giMinimumBalance = atoi(argv[++i]);
162 case 'M': // Maximum balance
163 if( i + 1 >= argc ) {
164 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
168 giMaximumBalance = atoi(argv[++i]);
171 case 'u': // Override User
172 if( i + 1 >= argc ) {
173 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
177 gsEffectiveUser = argv[++i];
180 case 'H': // Override remote host
181 if( i + 1 >= argc ) {
182 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
186 gsDispenseServer = argv[++i];
188 case 'P': // Override remote port
189 if( i + 1 >= argc ) {
190 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
194 giDispensePort = atoi(argv[++i]);
197 case 'G': // Don't use GUI
198 giUIMode = UI_MODE_BASIC;
200 case 'D': // Drinks only
201 giUIMode = UI_MODE_DRINKSONLY;
203 case 'n': // Dry Run / read-only
207 if( text_argc + 1 == MAX_TXT_ARGS )
209 fprintf(stderr, "ERROR: Too many arguments\n");
212 text_args[text_argc++] = argv[i];
219 if( text_argc + 1 == MAX_TXT_ARGS )
221 fprintf(stderr, "ERROR: Too many arguments\n");
225 text_args[text_argc++] = argv[i];
232 if( strcmp(text_args[0], "acct") == 0 )
235 sock = OpenConnection(gsDispenseServer, giDispensePort);
236 if( sock < 0 ) return -1;
238 if( text_argc == 1 ) {
239 ret = Dispense_EnumUsers(sock);
244 // text_args[1]: Username
249 // Authentication required
250 if( Authenticate(sock) )
253 // text_args[1]: Username
254 // text_args[2]: Ammount
255 // text_args[3]: Reason
257 if( text_args[2][0] == '=' ) {
259 if( text_args[2][1] != '0' && atoi(text_args[2]+1) == 0 ) {
260 fprintf(stderr, "Error: Invalid balance to be set\n");
264 ret = Dispense_SetBalance(sock, text_args[1], atoi(text_args[2]+1), text_args[3]);
268 ret = Dispense_AlterBalance(sock, text_args[1], atoi(text_args[2]), text_args[3]);
271 // TODO: Preserve ret if non-zero
273 // Show user information
274 ret = Dispense_ShowUser(sock, text_args[1]);
281 // - "Here, have some money."
282 if( strcmp(text_args[0], "give") == 0 )
284 if( text_argc != 4 ) {
285 fprintf(stderr, "`dispense give` takes three arguments\n");
290 // text_args[1]: Destination
291 // text_args[2]: Ammount
292 // text_args[3]: Reason
295 sock = OpenConnection(gsDispenseServer, giDispensePort);
296 if( sock < 0 ) return -1;
299 if( Authenticate(sock) )
302 ret = Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
310 // - User administration (Admin Only)
311 if( strcmp(text_args[0], "user") == 0 )
313 // Check argument count
314 if( text_argc == 1 ) {
315 fprintf(stderr, "Error: `dispense user` requires arguments\n");
321 sock = OpenConnection(gsDispenseServer, giDispensePort);
322 if( sock < 0 ) return -1;
324 // Attempt authentication
325 if( Authenticate(sock) )
329 if( strcmp(text_args[1], "add") == 0 )
331 if( text_argc != 3 ) {
332 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
337 ret = Dispense_AddUser(sock, text_args[2]);
340 else if( strcmp(text_args[1], "type") == 0 || strcmp(text_args[1], "flags") == 0 )
342 if( text_argc != 4 ) {
343 fprintf(stderr, "Error: `dispense user flags` requires two arguments\n");
348 ret = Dispense_SetUserType(sock, text_args[2], text_args[3]);
352 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
360 else if( strcmp(text_args[0], "donate") == 0 )
362 // Check argument count
363 if( text_argc != 3 ) {
364 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
370 sock = OpenConnection(gsDispenseServer, giDispensePort);
371 if( sock < 0 ) return -1;
373 // Attempt authentication
374 if( Authenticate(sock) )
378 ret = Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
384 // Query an item price
385 else if( strcmp(text_args[0], "iteminfo") == 0 )
387 regmatch_t matches[3];
390 // Check argument count
391 if( text_argc != 2 ) {
392 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
397 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
398 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
401 type = text_args[1] + matches[1].rm_so;
402 text_args[1][ matches[1].rm_eo ] = '\0';
403 id = atoi( text_args[1] + matches[2].rm_so );
405 sock = OpenConnection(gsDispenseServer, giDispensePort);
406 if( sock < 0 ) return -1;
407 ret = Dispense_ItemInfo(sock, type, id);
411 // Item name / pattern
413 gsItemPattern = text_args[0];
417 sock = OpenConnection(gsDispenseServer, giDispensePort);
418 if( sock < 0 ) return -1;
420 // Get the user's balance
421 GetUserBalance(sock);
424 PopulateItemList(sock);
426 // Disconnect from server
429 if( gsItemPattern && gsItemPattern[0] )
431 regmatch_t matches[3];
433 if( strcmp(gsItemPattern, "door") == 0 )
435 // Connect, Authenticate, dispense and close
436 sock = OpenConnection(gsDispenseServer, giDispensePort);
437 if( sock < 0 ) return -1;
439 ret = DispenseItem(sock, "door", 0);
443 // Item id (<type>:<num>)
444 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
449 // Get and finish ident
450 ident = gsItemPattern + matches[1].rm_so;
451 gsItemPattern[matches[1].rm_eo] = '\0';
453 id = atoi( gsItemPattern + matches[2].rm_so );
455 // Connect, Authenticate, dispense and close
456 sock = OpenConnection(gsDispenseServer, giDispensePort);
457 if( sock < 0 ) return -1;
459 Dispense_ItemInfo(sock, ident, id);
462 ret = DispenseItem(sock, ident, id);
466 // Item number (6 = coke)
467 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
469 i = atoi(gsItemPattern);
476 for( i = 0; i < giNumItems; i ++ )
478 // Prefix match (with case-insensitive match)
479 for( j = 0; gsItemPattern[j]; j ++ )
481 if( gaItems[i].Desc[j] == gsItemPattern[j] )
483 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
487 // Check if the prefix matched
488 if( gsItemPattern[j] != '\0' )
492 if( gaItems[i].Desc[j] == '\0' ) {
497 // Only one match allowed
502 // TODO: Allow ambiguous matches?
503 // or just print a wanrning
504 printf("Warning - Ambiguous pattern, stopping\n");
509 // Was a match found?
512 fprintf(stderr, "No item matches the passed string\n");
519 else if( giUIMode != UI_MODE_BASIC )
525 // Very basic dispense interface
526 for( i = 0; i < giNumItems; i ++ ) {
528 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
531 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
532 gaItems[i].Price, gaItems[i].Desc);
541 fgets(buffer, BUFSIZ, stdin);
545 if( buf[0] == 'q' ) break;
549 if( i != 0 || buf[0] == '0' )
551 if( i < 0 || i >= giNumItems ) {
552 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
561 // Check for a valid item ID
565 // Connect, Authenticate, dispense and close
566 sock = OpenConnection(gsDispenseServer, giDispensePort);
567 if( sock < 0 ) return -1;
569 Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
572 for( j = 0; j < giDispenseCount; j ++ ) {
573 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
577 printf("%i items dispensed\n", j);
591 " Show interactive list\n"
592 " dispense <name>|<index>|<itemid>\n"
593 " Dispense named item (<name> matches if it is a unique prefix)\n"
594 " dispense give <user> <ammount> \"<reason>\"\n"
595 " Give money to another user\n"
596 " dispense donate <ammount> \"<reason>\"\n"
597 " Donate to the club\n"
598 " dispense iteminfo <type>:<id>\n"
599 " Get the name and price for an item\n"
600 " == Coke members == \n"
601 " dispense acct [<user>]\n"
602 " Show user balances\n"
603 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
604 " Alter a account value\n"
605 " == Dispense administrators ==\n"
606 " dispense acct <user> =<ammount> \"<reason>\"\n"
607 " Set an account balance\n"
608 " dispense user add <user>\n"
609 " Create new coke account (Admins only)\n"
610 " dispense user type <user> <flags>\n"
611 " Alter a user's flags\n"
612 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
613 " Flags are removed by preceding the name with '-' or '!'\n"
617 " Set a different user (Coke members only)\n"
621 " Use alternate GUI\n"
622 " -m <min balance>\n"
623 " -M <max balance>\n"
624 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
628 // -------------------
629 // --- NCurses GUI ---
630 // -------------------
632 * \brief Render the NCurses UI
634 int ShowNCursesUI(void)
636 // TODO: ncurses interface (with separation between item classes)
637 // - Hmm... that would require standardising the item ID to be <class>:<index>
642 const int displayMinWidth = 40;
643 char *titleString = "Dispense";
648 int ret = -2; // -2: Used for marking "no return yet"
650 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
657 if( gsEffectiveUser )
658 username = gsEffectiveUser;
660 pwd = getpwuid( getuid() );
661 username = pwd->pw_name;
664 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, abs(giUserBalance)%100);
671 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
672 // Get item count per screen
673 // - 6: randomly chosen (Need at least 3)
674 itemCount = LINES - 6;
675 if( itemCount > maxItemIndex )
676 itemCount = maxItemIndex;
679 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
684 height = itemCount + 3;
685 width = displayMinWidth;
688 xBase = COLS/2 - width/2;
689 yBase = LINES/2 - height/2;
694 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
697 for( i = 0; i < itemCount; i ++ )
701 move( yBase + 1 + i, xBase );
706 // Check for the '...' row
707 // - Oh god, magic numbers!
708 if( (i == 0 && itemBase > 0)
709 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
711 printw(" ..."); pos += 8;
712 times = (width - pos) - 1;
713 while(times--) addch(' ');
718 yBase + 1 + i, xBase + pos, // Position
719 (width - pos) - 3, // Width
720 itemBase + i, // Index
721 !!(currentItem == itemBase + i) // Hilighted
726 // Scrollbar (if needed)
727 if( maxItemIndex > itemCount ) {
731 else if( i == itemCount - 1 ) {
735 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
736 if( i-1 == percentage*(itemCount-3)/100 ) {
750 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
753 // - Username, balance, flags
754 PrintAlign(yBase+height-1, xBase+1, width-2,
755 username, ' ', balance_str, ' ', gsUserFlags);
771 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
774 if( currentItem >= maxItemIndex ) {
777 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
784 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
787 if( currentItem < 0 ) {
788 currentItem = maxItemIndex - 1;
790 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
800 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
801 itemBase = currentItem - 2;
802 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
803 itemBase = currentItem - itemCount + 2;
809 ret = ShowItemAt(0, 0, 0, currentItem, 0);
812 ret = -1; // -1: Return with no dispense
816 // Check if the return value was changed
817 if( ret != -2 ) break;
829 * \brief Show item \a Index at (\a Col, \a Row)
830 * \return Dispense index of item
831 * \note Part of the NCurses UI
833 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
843 // - This assumes that
844 case UI_MODE_STANDARD:
846 // Index = -1, request limit
847 if( Index < 0 || Index >= giNumItems+2 )
853 name = "Coke Machine";
854 Index = -1; // -1 indicates a label
861 name = gaItems[Index].Desc;
862 price = gaItems[Index].Price;
863 status = gaItems[Index].Status;
871 name = "Electronic Payment System";
872 Index = -1; // -1 indicates a label
877 name = gaItems[Index].Desc;
878 price = gaItems[Index].Price;
879 status = gaItems[Index].Status;
885 // Width = 0, don't print
888 // 4 preceding, 5 price
889 int nameWidth = Width - 4 - 5;
894 // Show hilight and status
913 printw("%-*.*s", nameWidth, nameWidth, name);
915 // getyx(stdscr, _y, _x);
916 // Assumes max 4 digit prices
917 // times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
918 // while(times--) addch(' ');
920 printw(" %4i", price);
924 printw("-- %s", name);
925 getyx(stdscr, _y, _x);
926 times = Width - 4 - (_x - Col);
927 while(times--) addch(' ');
932 // If the item isn't availiable for sale, return -1 (so it's skipped)
940 * \brief Print a three-part string at the specified position (formatted)
941 * \note NCurses UI Helper
943 * Prints \a Left on the left of the area, \a Right on the righthand side
944 * and \a Mid in the middle of the area. These are padded with \a Pad1
945 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
947 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
948 * and the arguments to these are read in that order.
950 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
951 const char *Mid, char Pad2, const char *Right, ...)
953 int lLen, mLen, rLen;
958 // Get the length of the strings
959 va_start(args, Right);
960 lLen = vsnprintf(NULL, 0, Left, args);
961 mLen = vsnprintf(NULL, 0, Mid, args);
962 rLen = vsnprintf(NULL, 0, Right, args);
966 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
967 return ; // TODO: What to do?
973 va_start(args, Right);
977 vsnprintf(tmp, lLen+1, Left, args);
981 times = (Width - mLen)/2 - lLen;
982 while(times--) addch(Pad1);
986 vsnprintf(tmp, mLen+1, Mid, args);
990 times = (Width - mLen)/2 - rLen;
991 if( (Width - mLen) % 2 ) times ++;
992 while(times--) addch(Pad2);
996 vsnprintf(tmp, rLen+1, Right, args);
1001 // ---------------------
1002 // --- Coke Protocol ---
1003 // ---------------------
1004 int OpenConnection(const char *Host, int Port)
1006 struct hostent *host;
1007 struct sockaddr_in serverAddr;
1010 host = gethostbyname(Host);
1012 fprintf(stderr, "Unable to look up '%s'\n", Host);
1016 memset(&serverAddr, 0, sizeof(serverAddr));
1018 serverAddr.sin_family = AF_INET; // IPv4
1019 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1020 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1021 serverAddr.sin_port = htons(Port);
1023 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1025 fprintf(stderr, "Failed to create socket\n");
1029 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1031 if( geteuid() == 0 || getuid() == 0 )
1034 struct sockaddr_in localAddr;
1035 memset(&localAddr, 0, sizeof(localAddr));
1036 localAddr.sin_family = AF_INET; // IPv4
1038 // Loop through all the top ports until one is avaliable
1039 for( i = 512; i < 1024; i ++)
1041 localAddr.sin_port = htons(i); // IPv4
1042 // Attempt to bind to low port for autoauth
1043 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1047 printf("Warning: AUTOAUTH unavaliable\n");
1049 // printf("Bound to 0.0.0.0:%i\n", i);
1052 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1053 fprintf(stderr, "Failed to connect to server\n");
1061 * \brief Authenticate with the server
1062 * \return Boolean Failure
1064 int Authenticate(int Socket)
1071 regmatch_t matches[4];
1073 if( gbIsAuthenticated ) return 0;
1076 pwd = getpwuid( getuid() );
1078 // Attempt automatic authentication
1079 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1081 // Check if it worked
1082 buf = ReadLine(Socket);
1084 responseCode = atoi(buf);
1085 switch( responseCode )
1087 case 200: // Autoauth succeeded, return
1091 case 401: // Untrusted, attempt password authentication
1094 sendf(Socket, "USER %s\n", pwd->pw_name);
1095 printf("Using username %s\n", pwd->pw_name);
1097 buf = ReadLine(Socket);
1100 // Expected format: 100 SALT <something> ...
1101 // OR : 100 User Set
1102 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1103 responseCode = atoi(buf);
1104 if( responseCode != 100 ) {
1105 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1111 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1112 // Store it for later
1113 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1114 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1118 // Give three attempts
1119 for( i = 0; i < 3; i ++ )
1121 int ofs = strlen(pwd->pw_name)+strlen(salt);
1124 char *pass = getpass("Password: ");
1127 // Create hash string
1128 // <username><salt><hash>
1129 strcpy(tmp, pwd->pw_name);
1131 SHA1( (unsigned char*)pass, strlen(pass), h );
1132 memcpy(tmp+ofs, h, 20);
1135 SHA1( (unsigned char*)tmp, ofs+20, h );
1136 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1137 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1138 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1142 sendf(Socket, "PASS %s\n", tmpBuf);
1143 buf = ReadLine(Socket);
1145 responseCode = atoi(buf);
1147 if( responseCode == 200 ) break;
1148 // Bad username/password
1149 if( responseCode == 401 ) continue;
1151 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1157 return 2; // 2 = Bad Password
1160 case 404: // Bad Username
1161 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1166 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1167 printf("%s\n", buf);
1172 // Set effective user
1173 if( gsEffectiveUser ) {
1174 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1176 buf = ReadLine(Socket);
1177 responseCode = atoi(buf);
1179 switch(responseCode)
1182 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1186 printf("Only coke members can use `dispense -u`\n");
1191 printf("Invalid user selected\n");
1196 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1197 printf("%s\n", buf);
1205 gbIsAuthenticated = 1;
1210 int GetUserBalance(int Socket)
1212 regmatch_t matches[6];
1219 if( gsEffectiveUser ) {
1220 gsUserName = gsEffectiveUser;
1223 pwd = getpwuid( getuid() );
1224 gsUserName = strdup(pwd->pw_name);
1228 sendf(Socket, "USER_INFO %s\n", gsUserName);
1229 buf = ReadLine(Socket);
1230 responseCode = atoi(buf);
1231 switch(responseCode)
1233 case 202: break; // Ok
1236 printf("Invalid user? (USER_INFO failed)\n");
1241 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1242 printf("%s\n", buf);
1247 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1249 giUserBalance = atoi( buf + matches[4].rm_so );
1250 gsUserFlags = strdup( buf + matches[5].rm_so );
1258 * \brief Read an item info response from the server
1259 * \param Dest Destination for the read item (strings will be on the heap)
1261 int ReadItemInfo(int Socket, tItem *Dest)
1266 regmatch_t matches[8];
1270 buf = ReadLine(Socket);
1271 responseCode = atoi(buf);
1273 switch(responseCode)
1278 printf("Bad item name\n");
1283 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1287 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1289 buf[ matches[3].rm_eo ] = '\0';
1290 buf[ matches[5].rm_eo ] = '\0';
1291 buf[ matches[7].rm_eo ] = '\0';
1293 statusStr = &buf[ matches[5].rm_so ];
1295 Dest->ID = atoi( buf + matches[4].rm_so );
1297 if( strcmp(statusStr, "avail") == 0 )
1299 else if( strcmp(statusStr, "sold") == 0 )
1301 else if( strcmp(statusStr, "error") == 0 )
1304 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1308 Dest->Price = atoi( buf + matches[6].rm_so );
1310 // Hack a little to reduce heap fragmentation
1312 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1313 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1314 strcpy(tmpType, buf + matches[3].rm_so);
1315 strcpy(tmpDesc, buf + matches[7].rm_so);
1317 Dest->Type = strdup( tmpType );
1318 Dest->Desc = strdup( tmpDesc );
1325 * \brief Fill the item information structure
1326 * \return Boolean Failure
1328 void PopulateItemList(int Socket)
1333 char *itemType, *itemStart;
1335 regmatch_t matches[4];
1337 // Ask server for stock list
1338 send(Socket, "ENUM_ITEMS\n", 11, 0);
1339 buf = ReadLine(Socket);
1341 //printf("Output: %s\n", buf);
1343 responseCode = atoi(buf);
1344 if( responseCode != 201 ) {
1345 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1349 // - Get item list -
1352 // 201 Items <count>
1354 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1356 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1357 count = atoi( &buf[ matches[3].rm_so ] );
1360 if( strcmp(itemType, "Items") != 0 ) {
1362 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1367 itemStart = &buf[ matches[3].rm_eo ];
1372 gaItems = malloc( giNumItems * sizeof(tItem) );
1374 // Fetch item information
1375 for( i = 0; i < giNumItems; i ++ )
1377 ReadItemInfo( Socket, &gaItems[i] );
1381 buf = ReadLine(Socket);
1382 responseCode = atoi(buf);
1384 if( responseCode != 200 ) {
1385 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1396 * \brief Get information on an item
1397 * \return Boolean Failure
1399 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1404 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1406 if( ReadItemInfo(Socket, &item) )
1411 printf("%8s:%-2i %2i.%02i %s\n",
1413 item.Price/100, item.Price%100,
1423 * \brief Dispense an item
1424 * \return Boolean Failure
1426 int DispenseItem(int Socket, const char *Type, int ID)
1428 int ret, responseCode;
1431 // Check for a dry run
1433 printf("Dry Run - No action\n");
1438 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1439 buf = ReadLine(Socket);
1441 responseCode = atoi(buf);
1442 switch( responseCode )
1445 printf("Dispense OK\n");
1449 printf("Not authenticated\n");
1453 printf("Insufficient balance\n");
1457 printf("Bad item name\n");
1461 printf("Item failed to dispense, is the slot empty?\n");
1465 printf("Dispense not possible (slot empty/permissions)\n");
1469 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1479 * \brief Alter a user's balance
1481 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1486 // Check for a dry run
1488 printf("Dry Run - No action\n");
1493 if( Ammount == 0 ) {
1494 printf("An ammount would be nice\n");
1498 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1499 buf = ReadLine(Socket);
1501 responseCode = atoi(buf);
1504 switch(responseCode)
1506 case 200: return 0; // OK
1508 fprintf(stderr, "Insufficient balance\n");
1510 case 403: // Not in coke
1511 fprintf(stderr, "You are not in coke (sucker)\n");
1513 case 404: // Unknown user
1514 fprintf(stderr, "Unknown user '%s'\n", Username);
1517 fprintf(stderr, "Unknown response code %i\n", responseCode);
1525 * \brief Set a user's balance
1526 * \note Only avaliable to dispense admins
1528 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1533 // Check for a dry run
1535 printf("Dry Run - No action\n");
1539 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1540 buf = ReadLine(Socket);
1542 responseCode = atoi(buf);
1545 switch(responseCode)
1547 case 200: return 0; // OK
1548 case 403: // Not in coke
1549 fprintf(stderr, "You are not an admin\n");
1551 case 404: // Unknown user
1552 fprintf(stderr, "Unknown user '%s'\n", Username);
1555 fprintf(stderr, "Unknown response code %i\n", responseCode);
1563 * \brief Give money to another user
1565 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1571 printf("Sorry, you can only give, you can't take.\n");
1575 // Fast return on zero
1576 if( Ammount == 0 ) {
1577 printf("Are you actually going to give any?\n");
1581 // Check for a dry run
1583 printf("Dry Run - No action\n");
1587 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1588 buf = ReadLine(Socket);
1590 responseCode = atoi(buf);
1593 switch(responseCode)
1596 printf("Give succeeded\n");
1600 fprintf(stderr, "Insufficient balance\n");
1603 case 404: // Unknown user
1604 fprintf(stderr, "Unknown user '%s'\n", Username);
1608 fprintf(stderr, "Unknown response code %i\n", responseCode);
1617 * \brief Donate money to the club
1619 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1625 printf("Sorry, you can only give, you can't take.\n");
1629 // Fast return on zero
1630 if( Ammount == 0 ) {
1631 printf("Are you actually going to give any?\n");
1635 // Check for a dry run
1637 printf("Dry Run - No action\n");
1641 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1642 buf = ReadLine(Socket);
1644 responseCode = atoi(buf);
1647 switch(responseCode)
1649 case 200: return 0; // OK
1652 fprintf(stderr, "Insufficient balance\n");
1656 fprintf(stderr, "Unknown response code %i\n", responseCode);
1664 * \brief Enumerate users
1666 int Dispense_EnumUsers(int Socket)
1671 regmatch_t matches[4];
1673 if( giMinimumBalance != INT_MIN ) {
1674 if( giMaximumBalance != INT_MAX ) {
1675 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1678 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1682 if( giMaximumBalance != INT_MAX ) {
1683 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1686 sendf(Socket, "ENUM_USERS\n");
1689 buf = ReadLine(Socket);
1690 responseCode = atoi(buf);
1692 switch(responseCode)
1694 case 201: break; // Ok, length follows
1697 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1702 // Get count (not actually used)
1703 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1704 nUsers = atoi( buf + matches[3].rm_so );
1705 printf("%i users returned\n", nUsers);
1710 // Read returned users
1712 buf = ReadLine(Socket);
1713 responseCode = atoi(buf);
1715 if( responseCode != 202 ) break;
1717 _PrintUserLine(buf);
1719 } while(responseCode == 202);
1721 // Check final response
1722 if( responseCode != 200 ) {
1723 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1733 int Dispense_ShowUser(int Socket, const char *Username)
1736 int responseCode, ret;
1738 sendf(Socket, "USER_INFO %s\n", Username);
1739 buf = ReadLine(Socket);
1741 responseCode = atoi(buf);
1743 switch(responseCode)
1746 _PrintUserLine(buf);
1751 printf("Unknown user '%s'\n", Username);
1756 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1766 void _PrintUserLine(const char *Line)
1768 regmatch_t matches[6];
1771 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1776 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1777 char username[usernameLen + 1];
1778 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1779 char flags[flagsLen + 1];
1781 memcpy(username, Line + matches[3].rm_so, usernameLen);
1782 username[usernameLen] = '\0';
1783 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1784 flags[flagsLen] = '\0';
1786 bal = atoi(Line + matches[4].rm_so);
1787 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1791 int Dispense_AddUser(int Socket, const char *Username)
1794 int responseCode, ret;
1796 // Check for a dry run
1798 printf("Dry Run - No action\n");
1802 sendf(Socket, "USER_ADD %s\n", Username);
1804 buf = ReadLine(Socket);
1805 responseCode = atoi(buf);
1807 switch(responseCode)
1810 printf("User '%s' added\n", Username);
1815 printf("Only wheel can add users\n");
1820 printf("User '%s' already exists\n", Username);
1825 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1835 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1838 int responseCode, ret;
1840 // Check for a dry run
1842 printf("Dry Run - No action\n");
1846 // TODO: Pre-validate the string
1848 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1850 buf = ReadLine(Socket);
1851 responseCode = atoi(buf);
1853 switch(responseCode)
1856 printf("User '%s' updated\n", Username);
1861 printf("Only wheel can modify users\n");
1866 printf("User '%s' does not exist\n", Username);
1871 printf("Flag string is invalid\n");
1876 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1889 char *ReadLine(int Socket)
1891 static char buf[BUFSIZ];
1892 static int bufPos = 0;
1893 static int bufValid = 0;
1895 char *newline = NULL;
1897 char *ret = malloc(10);
1899 #if DEBUG_TRACE_SERVER
1900 printf("ReadLine: ");
1912 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1913 buf[bufPos+len] = '\0';
1916 newline = strchr( buf+bufPos, '\n' );
1921 retLen += strlen(buf+bufPos);
1922 ret = realloc(ret, retLen + 1);
1923 strcat( ret, buf+bufPos );
1926 int newLen = newline - (buf+bufPos) + 1;
1927 bufValid = len - newLen;
1930 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1933 #if DEBUG_TRACE_SERVER
1934 printf("%i '%s'\n", retLen, ret);
1940 int sendf(int Socket, const char *Format, ...)
1945 va_start(args, Format);
1946 len = vsnprintf(NULL, 0, Format, args);
1951 va_start(args, Format);
1952 vsnprintf(buf, len+1, Format, args);
1955 #if DEBUG_TRACE_SERVER
1956 printf("sendf: %s", buf);
1959 return send(Socket, buf, len, 0);
1963 char *trim(char *string)
1967 while( isspace(*string) )
1970 for( i = strlen(string); i--; )
1972 if( isspace(string[i]) )
1981 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1985 ret = regexec(regex, string, nMatches, matches, 0);
1986 if( ret && errorMessage ) {
1987 size_t len = regerror(ret, regex, NULL, 0);
1989 regerror(ret, regex, errorStr, len);
1990 printf("string = '%s'\n", string);
1991 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1998 void CompileRegex(regex_t *regex, const char *pattern, int flags)
2000 int ret = regcomp(regex, pattern, flags);
2002 size_t len = regerror(ret, regex, NULL, 0);
2004 regerror(ret, regex, errorStr, len);
2005 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);