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, 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
892 // Show hilight and status
913 getyx(stdscr, _y, _x);
914 // Assumes max 4 digit prices
915 times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
916 while(times--) addch(' ');
918 printw(" %4i", price);
922 printw("-- %s", name);
923 getyx(stdscr, _y, _x);
924 times = Width - 4 - (_x - Col);
925 while(times--) addch(' ');
930 // If the item isn't availiable for sale, return -1 (so it's skipped)
938 * \brief Print a three-part string at the specified position (formatted)
939 * \note NCurses UI Helper
941 * Prints \a Left on the left of the area, \a Right on the righthand side
942 * and \a Mid in the middle of the area. These are padded with \a Pad1
943 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
945 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
946 * and the arguments to these are read in that order.
948 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
949 const char *Mid, char Pad2, const char *Right, ...)
951 int lLen, mLen, rLen;
956 // Get the length of the strings
957 va_start(args, Right);
958 lLen = vsnprintf(NULL, 0, Left, args);
959 mLen = vsnprintf(NULL, 0, Mid, args);
960 rLen = vsnprintf(NULL, 0, Right, args);
964 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
965 return ; // TODO: What to do?
971 va_start(args, Right);
975 vsnprintf(tmp, lLen+1, Left, args);
979 times = (Width - mLen)/2 - lLen;
980 while(times--) addch(Pad1);
984 vsnprintf(tmp, mLen+1, Mid, args);
988 times = (Width - mLen)/2 - rLen;
989 if( (Width - mLen) % 2 ) times ++;
990 while(times--) addch(Pad2);
994 vsnprintf(tmp, rLen+1, Right, args);
999 // ---------------------
1000 // --- Coke Protocol ---
1001 // ---------------------
1002 int OpenConnection(const char *Host, int Port)
1004 struct hostent *host;
1005 struct sockaddr_in serverAddr;
1008 host = gethostbyname(Host);
1010 fprintf(stderr, "Unable to look up '%s'\n", Host);
1014 memset(&serverAddr, 0, sizeof(serverAddr));
1016 serverAddr.sin_family = AF_INET; // IPv4
1017 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
1018 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
1019 serverAddr.sin_port = htons(Port);
1021 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1023 fprintf(stderr, "Failed to create socket\n");
1027 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1029 if( geteuid() == 0 || getuid() == 0 )
1032 struct sockaddr_in localAddr;
1033 memset(&localAddr, 0, sizeof(localAddr));
1034 localAddr.sin_family = AF_INET; // IPv4
1036 // Loop through all the top ports until one is avaliable
1037 for( i = 512; i < 1024; i ++)
1039 localAddr.sin_port = htons(i); // IPv4
1040 // Attempt to bind to low port for autoauth
1041 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1045 printf("Warning: AUTOAUTH unavaliable\n");
1047 // printf("Bound to 0.0.0.0:%i\n", i);
1050 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1051 fprintf(stderr, "Failed to connect to server\n");
1059 * \brief Authenticate with the server
1060 * \return Boolean Failure
1062 int Authenticate(int Socket)
1069 regmatch_t matches[4];
1071 if( gbIsAuthenticated ) return 0;
1074 pwd = getpwuid( getuid() );
1076 // Attempt automatic authentication
1077 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1079 // Check if it worked
1080 buf = ReadLine(Socket);
1082 responseCode = atoi(buf);
1083 switch( responseCode )
1085 case 200: // Autoauth succeeded, return
1089 case 401: // Untrusted, attempt password authentication
1092 sendf(Socket, "USER %s\n", pwd->pw_name);
1093 printf("Using username %s\n", pwd->pw_name);
1095 buf = ReadLine(Socket);
1098 // Expected format: 100 SALT <something> ...
1099 // OR : 100 User Set
1100 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1101 responseCode = atoi(buf);
1102 if( responseCode != 100 ) {
1103 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1109 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1110 // Store it for later
1111 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1112 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1116 // Give three attempts
1117 for( i = 0; i < 3; i ++ )
1119 int ofs = strlen(pwd->pw_name)+strlen(salt);
1122 char *pass = getpass("Password: ");
1125 // Create hash string
1126 // <username><salt><hash>
1127 strcpy(tmp, pwd->pw_name);
1129 SHA1( (unsigned char*)pass, strlen(pass), h );
1130 memcpy(tmp+ofs, h, 20);
1133 SHA1( (unsigned char*)tmp, ofs+20, h );
1134 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1135 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1136 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1140 sendf(Socket, "PASS %s\n", tmpBuf);
1141 buf = ReadLine(Socket);
1143 responseCode = atoi(buf);
1145 if( responseCode == 200 ) break;
1146 // Bad username/password
1147 if( responseCode == 401 ) continue;
1149 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1155 return 2; // 2 = Bad Password
1158 case 404: // Bad Username
1159 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1164 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1165 printf("%s\n", buf);
1170 // Set effective user
1171 if( gsEffectiveUser ) {
1172 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1174 buf = ReadLine(Socket);
1175 responseCode = atoi(buf);
1177 switch(responseCode)
1180 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1184 printf("Only coke members can use `dispense -u`\n");
1189 printf("Invalid user selected\n");
1194 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1195 printf("%s\n", buf);
1203 gbIsAuthenticated = 1;
1208 int GetUserBalance(int Socket)
1210 regmatch_t matches[6];
1217 if( gsEffectiveUser ) {
1218 gsUserName = gsEffectiveUser;
1221 pwd = getpwuid( getuid() );
1222 gsUserName = strdup(pwd->pw_name);
1226 sendf(Socket, "USER_INFO %s\n", gsUserName);
1227 buf = ReadLine(Socket);
1228 responseCode = atoi(buf);
1229 switch(responseCode)
1231 case 202: break; // Ok
1234 printf("Invalid user? (USER_INFO failed)\n");
1239 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1240 printf("%s\n", buf);
1245 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1247 giUserBalance = atoi( buf + matches[4].rm_so );
1248 gsUserFlags = strdup( buf + matches[5].rm_so );
1256 * \brief Read an item info response from the server
1257 * \param Dest Destination for the read item (strings will be on the heap)
1259 int ReadItemInfo(int Socket, tItem *Dest)
1264 regmatch_t matches[8];
1268 buf = ReadLine(Socket);
1269 responseCode = atoi(buf);
1271 switch(responseCode)
1276 printf("Bad item name\n");
1281 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1285 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1287 buf[ matches[3].rm_eo ] = '\0';
1288 buf[ matches[5].rm_eo ] = '\0';
1289 buf[ matches[7].rm_eo ] = '\0';
1291 statusStr = &buf[ matches[5].rm_so ];
1293 Dest->ID = atoi( buf + matches[4].rm_so );
1295 if( strcmp(statusStr, "avail") == 0 )
1297 else if( strcmp(statusStr, "sold") == 0 )
1299 else if( strcmp(statusStr, "error") == 0 )
1302 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1306 Dest->Price = atoi( buf + matches[6].rm_so );
1308 // Hack a little to reduce heap fragmentation
1310 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1311 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1312 strcpy(tmpType, buf + matches[3].rm_so);
1313 strcpy(tmpDesc, buf + matches[7].rm_so);
1315 Dest->Type = strdup( tmpType );
1316 Dest->Desc = strdup( tmpDesc );
1323 * \brief Fill the item information structure
1324 * \return Boolean Failure
1326 void PopulateItemList(int Socket)
1331 char *itemType, *itemStart;
1333 regmatch_t matches[4];
1335 // Ask server for stock list
1336 send(Socket, "ENUM_ITEMS\n", 11, 0);
1337 buf = ReadLine(Socket);
1339 //printf("Output: %s\n", buf);
1341 responseCode = atoi(buf);
1342 if( responseCode != 201 ) {
1343 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1347 // - Get item list -
1350 // 201 Items <count>
1352 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1354 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1355 count = atoi( &buf[ matches[3].rm_so ] );
1358 if( strcmp(itemType, "Items") != 0 ) {
1360 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1365 itemStart = &buf[ matches[3].rm_eo ];
1370 gaItems = malloc( giNumItems * sizeof(tItem) );
1372 // Fetch item information
1373 for( i = 0; i < giNumItems; i ++ )
1375 ReadItemInfo( Socket, &gaItems[i] );
1379 buf = ReadLine(Socket);
1380 responseCode = atoi(buf);
1382 if( responseCode != 200 ) {
1383 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1394 * \brief Get information on an item
1395 * \return Boolean Failure
1397 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1402 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1404 if( ReadItemInfo(Socket, &item) )
1409 printf("%8s:%-2i %2i.%02i %s\n",
1411 item.Price/100, item.Price%100,
1421 * \brief Dispense an item
1422 * \return Boolean Failure
1424 int DispenseItem(int Socket, const char *Type, int ID)
1426 int ret, responseCode;
1429 // Check for a dry run
1431 printf("Dry Run - No action\n");
1436 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1437 buf = ReadLine(Socket);
1439 responseCode = atoi(buf);
1440 switch( responseCode )
1443 printf("Dispense OK\n");
1447 printf("Not authenticated\n");
1451 printf("Insufficient balance\n");
1455 printf("Bad item name\n");
1459 printf("Item failed to dispense, is the slot empty?\n");
1463 printf("Dispense not possible (slot empty/permissions)\n");
1467 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1477 * \brief Alter a user's balance
1479 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1484 // Check for a dry run
1486 printf("Dry Run - No action\n");
1490 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1491 buf = ReadLine(Socket);
1493 responseCode = atoi(buf);
1496 switch(responseCode)
1498 case 200: return 0; // OK
1500 fprintf(stderr, "Insufficient balance\n");
1502 case 403: // Not in coke
1503 fprintf(stderr, "You are not in coke (sucker)\n");
1505 case 404: // Unknown user
1506 fprintf(stderr, "Unknown user '%s'\n", Username);
1509 fprintf(stderr, "Unknown response code %i\n", responseCode);
1517 * \brief Set a user's balance
1518 * \note Only avaliable to dispense admins
1520 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1525 // Check for a dry run
1527 printf("Dry Run - No action\n");
1531 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1532 buf = ReadLine(Socket);
1534 responseCode = atoi(buf);
1537 switch(responseCode)
1539 case 200: return 0; // OK
1540 case 403: // Not in coke
1541 fprintf(stderr, "You are not an admin\n");
1543 case 404: // Unknown user
1544 fprintf(stderr, "Unknown user '%s'\n", Username);
1547 fprintf(stderr, "Unknown response code %i\n", responseCode);
1555 * \brief Give money to another user
1557 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1563 printf("Sorry, you can only give, you can't take.\n");
1567 // Fast return on zero
1568 if( Ammount == 0 ) {
1569 printf("Are you actually going to give any?\n");
1573 // Check for a dry run
1575 printf("Dry Run - No action\n");
1579 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1580 buf = ReadLine(Socket);
1582 responseCode = atoi(buf);
1585 switch(responseCode)
1588 printf("Give succeeded\n");
1592 fprintf(stderr, "Insufficient balance\n");
1595 case 404: // Unknown user
1596 fprintf(stderr, "Unknown user '%s'\n", Username);
1600 fprintf(stderr, "Unknown response code %i\n", responseCode);
1609 * \brief Donate money to the club
1611 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1617 printf("Sorry, you can only give, you can't take.\n");
1621 // Fast return on zero
1622 if( Ammount == 0 ) {
1623 printf("Are you actually going to give any?\n");
1627 // Check for a dry run
1629 printf("Dry Run - No action\n");
1633 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1634 buf = ReadLine(Socket);
1636 responseCode = atoi(buf);
1639 switch(responseCode)
1641 case 200: return 0; // OK
1644 fprintf(stderr, "Insufficient balance\n");
1648 fprintf(stderr, "Unknown response code %i\n", responseCode);
1656 * \brief Enumerate users
1658 int Dispense_EnumUsers(int Socket)
1663 regmatch_t matches[4];
1665 if( giMinimumBalance != INT_MIN ) {
1666 if( giMaximumBalance != INT_MAX ) {
1667 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1670 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1674 if( giMaximumBalance != INT_MAX ) {
1675 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1678 sendf(Socket, "ENUM_USERS\n");
1681 buf = ReadLine(Socket);
1682 responseCode = atoi(buf);
1684 switch(responseCode)
1686 case 201: break; // Ok, length follows
1689 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1694 // Get count (not actually used)
1695 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1696 nUsers = atoi( buf + matches[3].rm_so );
1697 printf("%i users returned\n", nUsers);
1702 // Read returned users
1704 buf = ReadLine(Socket);
1705 responseCode = atoi(buf);
1707 if( responseCode != 202 ) break;
1709 _PrintUserLine(buf);
1711 } while(responseCode == 202);
1713 // Check final response
1714 if( responseCode != 200 ) {
1715 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1725 int Dispense_ShowUser(int Socket, const char *Username)
1728 int responseCode, ret;
1730 sendf(Socket, "USER_INFO %s\n", Username);
1731 buf = ReadLine(Socket);
1733 responseCode = atoi(buf);
1735 switch(responseCode)
1738 _PrintUserLine(buf);
1743 printf("Unknown user '%s'\n", Username);
1748 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1758 void _PrintUserLine(const char *Line)
1760 regmatch_t matches[6];
1763 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1768 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1769 char username[usernameLen + 1];
1770 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1771 char flags[flagsLen + 1];
1773 memcpy(username, Line + matches[3].rm_so, usernameLen);
1774 username[usernameLen] = '\0';
1775 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1776 flags[flagsLen] = '\0';
1778 bal = atoi(Line + matches[4].rm_so);
1779 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1783 int Dispense_AddUser(int Socket, const char *Username)
1786 int responseCode, ret;
1788 // Check for a dry run
1790 printf("Dry Run - No action\n");
1794 sendf(Socket, "USER_ADD %s\n", Username);
1796 buf = ReadLine(Socket);
1797 responseCode = atoi(buf);
1799 switch(responseCode)
1802 printf("User '%s' added\n", Username);
1807 printf("Only wheel can add users\n");
1812 printf("User '%s' already exists\n", Username);
1817 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1827 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1830 int responseCode, ret;
1832 // Check for a dry run
1834 printf("Dry Run - No action\n");
1838 // TODO: Pre-validate the string
1840 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1842 buf = ReadLine(Socket);
1843 responseCode = atoi(buf);
1845 switch(responseCode)
1848 printf("User '%s' updated\n", Username);
1853 printf("Only wheel can modify users\n");
1858 printf("User '%s' does not exist\n", Username);
1863 printf("Flag string is invalid\n");
1868 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1881 char *ReadLine(int Socket)
1883 static char buf[BUFSIZ];
1884 static int bufPos = 0;
1885 static int bufValid = 0;
1887 char *newline = NULL;
1889 char *ret = malloc(10);
1891 #if DEBUG_TRACE_SERVER
1892 printf("ReadLine: ");
1904 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1905 buf[bufPos+len] = '\0';
1908 newline = strchr( buf+bufPos, '\n' );
1913 retLen += strlen(buf+bufPos);
1914 ret = realloc(ret, retLen + 1);
1915 strcat( ret, buf+bufPos );
1918 int newLen = newline - (buf+bufPos) + 1;
1919 bufValid = len - newLen;
1922 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1925 #if DEBUG_TRACE_SERVER
1926 printf("%i '%s'\n", retLen, ret);
1932 int sendf(int Socket, const char *Format, ...)
1937 va_start(args, Format);
1938 len = vsnprintf(NULL, 0, Format, args);
1943 va_start(args, Format);
1944 vsnprintf(buf, len+1, Format, args);
1947 #if DEBUG_TRACE_SERVER
1948 printf("sendf: %s", buf);
1951 return send(Socket, buf, len, 0);
1955 char *trim(char *string)
1959 while( isspace(*string) )
1962 for( i = strlen(string); i--; )
1964 if( isspace(string[i]) )
1973 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1977 ret = regexec(regex, string, nMatches, matches, 0);
1978 if( ret && errorMessage ) {
1979 size_t len = regerror(ret, regex, NULL, 0);
1981 regerror(ret, regex, errorStr, len);
1982 printf("string = '%s'\n", string);
1983 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1990 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1992 int ret = regcomp(regex, pattern, flags);
1994 size_t len = regerror(ret, regex, NULL, 0);
1996 regerror(ret, regex, errorStr, len);
1997 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);