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)
36 UI_MODE_BASIC, // Non-NCurses
44 typedef struct sItem {
47 int Status; // 0: Availiable, 1: Sold out, -1: Error
53 int main(int argc, char *argv[]);
56 int ShowNCursesUI(void);
57 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted);
58 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
59 // --- Coke Server Communication ---
60 int OpenConnection(const char *Host, int Port);
61 int Authenticate(int Socket);
62 int GetUserBalance(int Socket);
63 void PopulateItemList(int Socket);
64 int Dispense_ItemInfo(int Socket, const char *Type, int ID);
65 int DispenseItem(int Socket, const char *Type, int ID);
66 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
67 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
68 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
69 int Dispense_Donate(int Socket, int Ammount, const char *Reason);
70 int Dispense_EnumUsers(int Socket);
71 int Dispense_ShowUser(int Socket, const char *Username);
72 void _PrintUserLine(const char *Line);
73 int Dispense_AddUser(int Socket, const char *Username);
74 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
76 char *ReadLine(int Socket);
77 int sendf(int Socket, const char *Format, ...);
78 char *trim(char *string);
79 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
80 void CompileRegex(regex_t *regex, const char *pattern, int flags);
83 char *gsDispenseServer = "heathred";
84 int giDispensePort = 11020;
88 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
89 int gbIsAuthenticated = 0;
91 char *gsItemPattern; //!< Item pattern
92 char *gsEffectiveUser; //!< '-u' Dispense as another user
93 int giUIMode = UI_MODE_STANDARD;
94 int gbDryRun = 0; //!< '-n' Read-only
95 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
96 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
97 char *gsUserName; //!< User that dispense will happen as
98 char *gsUserFlags; //!< User's flag set
99 int giUserBalance=-1; //!< User balance (set by Authenticate)
102 int main(int argc, char *argv[])
107 char *text_args[MAX_TXT_ARGS]; // Non-flag arguments
112 // -- Create regular expressions
113 // > Code Type Count ...
114 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
115 // > Code Type Ident Status Price Desc
116 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);
117 // > Code 'SALT' salt
118 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
119 // > Code 'User' Username Balance Flags
120 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
122 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
125 for( i = 1; i < argc; i ++ )
138 case 'm': // Minimum balance
139 if( i + 1 >= argc ) {
140 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
143 giMinimumBalance = atoi(argv[++i]);
145 case 'M': // Maximum balance
146 if( i + 1 >= argc ) {
147 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
150 giMaximumBalance = atoi(argv[++i]);
153 case 'u': // Override User
154 if( i + 1 >= argc ) {
155 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
158 gsEffectiveUser = argv[++i];
161 case 'H': // Override remote host
162 if( i + 1 >= argc ) {
163 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
166 gsDispenseServer = argv[++i];
168 case 'P': // Override remote port
169 if( i + 1 >= argc ) {
170 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
173 giDispensePort = atoi(argv[++i]);
176 case 'G': // Don't use GUI
177 giUIMode = UI_MODE_BASIC;
179 case 'D': // Drinks only
180 giUIMode = UI_MODE_DRINKSONLY;
182 case 'n': // Dry Run / read-only
190 if( text_argc + 1 == MAX_TXT_ARGS )
192 fprintf(stderr, "ERROR: Too many arguments\n");
195 text_args[text_argc++] = argv[i];
202 if( text_argc + 1 == MAX_TXT_ARGS )
204 fprintf(stderr, "ERROR: Too many arguments\n");
208 text_args[text_argc++] = argv[i];
215 if( strcmp(text_args[0], "acct") == 0 )
218 sock = OpenConnection(gsDispenseServer, giDispensePort);
219 if( sock < 0 ) return -1;
221 if( text_argc == 1 ) {
222 ret = Dispense_EnumUsers(sock);
227 // text_args[1]: Username
232 // Authentication required
233 if( Authenticate(sock) )
236 // text_args[1]: Username
237 // text_args[2]: Ammount
238 // text_args[3]: Reason
240 if( text_args[2][0] == '=' ) {
242 if( text_args[2][1] != '0' && atoi(text_args[2]+1) == 0 ) {
243 fprintf(stderr, "Error: Invalid balance to be set\n");
247 ret = Dispense_SetBalance(sock, text_args[1], atoi(text_args[2]+1), text_args[3]);
251 ret = Dispense_AlterBalance(sock, text_args[1], atoi(text_args[2]), text_args[3]);
254 // TODO: Preserve ret if non-zero
256 // Show user information
257 ret = Dispense_ShowUser(sock, text_args[1]);
264 // - "Here, have some money."
265 if( strcmp(text_args[0], "give") == 0 )
267 if( text_argc != 4 ) {
268 fprintf(stderr, "`dispense give` takes three arguments\n");
273 // text_args[1]: Destination
274 // text_args[2]: Ammount
275 // text_args[3]: Reason
278 sock = OpenConnection(gsDispenseServer, giDispensePort);
279 if( sock < 0 ) return -1;
282 if( Authenticate(sock) )
285 ret = Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
293 // - User administration (Admin Only)
294 if( strcmp(text_args[0], "user") == 0 )
296 // Check argument count
297 if( text_argc == 1 ) {
298 fprintf(stderr, "Error: `dispense user` requires arguments\n");
304 sock = OpenConnection(gsDispenseServer, giDispensePort);
305 if( sock < 0 ) return -1;
307 // Attempt authentication
308 if( Authenticate(sock) )
312 if( strcmp(text_args[1], "add") == 0 )
314 if( text_argc != 3 ) {
315 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
320 ret = Dispense_AddUser(sock, text_args[2]);
323 else if( strcmp(text_args[1], "type") == 0 || strcmp(text_args[1], "flags") == 0 )
325 if( text_argc != 4 ) {
326 fprintf(stderr, "Error: `dispense user flags` requires two arguments\n");
331 ret = Dispense_SetUserType(sock, text_args[2], text_args[3]);
335 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
343 else if( strcmp(text_args[0], "donate") == 0 )
345 // Check argument count
346 if( text_argc != 3 ) {
347 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
353 sock = OpenConnection(gsDispenseServer, giDispensePort);
354 if( sock < 0 ) return -1;
356 // Attempt authentication
357 if( Authenticate(sock) )
361 ret =Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
367 // Query an item price
368 else if( strcmp(text_args[0], "iteminfo") == 0 )
370 regmatch_t matches[3];
373 // Check argument count
374 if( text_argc != 2 ) {
375 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
380 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
381 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
384 type = text_args[1] + matches[1].rm_so;
385 text_args[1][ matches[1].rm_eo ] = '\0';
386 id = atoi( text_args[1] + matches[2].rm_so );
388 sock = OpenConnection(gsDispenseServer, giDispensePort);
389 if( sock < 0 ) return -1;
390 ret = Dispense_ItemInfo(sock, type, id);
394 // Item name / pattern
396 gsItemPattern = text_args[0];
400 sock = OpenConnection(gsDispenseServer, giDispensePort);
401 if( sock < 0 ) return -1;
403 // Get the user's balance
404 GetUserBalance(sock);
407 PopulateItemList(sock);
409 // Disconnect from server
412 if( gsItemPattern && gsItemPattern[0] )
414 regmatch_t matches[3];
416 if( strcmp(gsItemPattern, "door") == 0 )
418 // Connect, Authenticate, dispense and close
419 sock = OpenConnection(gsDispenseServer, giDispensePort);
420 if( sock < 0 ) return -1;
422 ret = DispenseItem(sock, "door", 0);
426 // Item id (<type>:<num>)
427 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
432 // Get and finish ident
433 ident = gsItemPattern + matches[1].rm_so;
434 gsItemPattern[matches[1].rm_eo] = '\0';
436 id = atoi( gsItemPattern + matches[2].rm_so );
438 // Connect, Authenticate, dispense and close
439 sock = OpenConnection(gsDispenseServer, giDispensePort);
440 if( sock < 0 ) return -1;
442 Dispense_ItemInfo(sock, ident, id);
445 ret = DispenseItem(sock, ident, id);
449 // Item number (6 = coke)
450 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
452 i = atoi(gsItemPattern);
459 for( i = 0; i < giNumItems; i ++ )
461 // Prefix match (with case-insensitive match)
462 for( j = 0; gsItemPattern[j]; j ++ )
464 if( gaItems[i].Desc[j] == gsItemPattern[j] )
466 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
470 // Check if the prefix matched
471 if( gsItemPattern[j] != '\0' )
475 if( gaItems[i].Desc[j] == '\0' ) {
480 // Only one match allowed
485 // TODO: Allow ambiguous matches?
486 // or just print a wanrning
487 printf("Warning - Ambiguous pattern, stopping\n");
492 // Was a match found?
495 fprintf(stderr, "No item matches the passed string\n");
502 else if( giUIMode != UI_MODE_BASIC )
508 // Very basic dispense interface
509 for( i = 0; i < giNumItems; i ++ ) {
511 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
514 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
515 gaItems[i].Price, gaItems[i].Desc);
524 fgets(buffer, BUFSIZ, stdin);
528 if( buf[0] == 'q' ) break;
532 if( i != 0 || buf[0] == '0' )
534 if( i < 0 || i >= giNumItems ) {
535 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
544 // Check for a valid item ID
547 // Connect, Authenticate, dispense and close
548 sock = OpenConnection(gsDispenseServer, giDispensePort);
549 if( sock < 0 ) return -1;
551 Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
554 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
567 " Show interactive list\n"
568 " dispense <name>|<index>|<itemid>\n"
569 " Dispense named item (<name> matches if it is a unique prefix)\n"
570 " dispense give <user> <ammount> \"<reason>\"\n"
571 " Give money to another user\n"
572 " dispense donate <ammount> \"<reason>\"\n"
573 " Donate to the club\n"
574 " dispense iteminfo <type>:<id>\n"
575 " Get the name and price for an item\n"
576 " == Coke members == \n"
577 " dispense acct [<user>]\n"
578 " Show user balances\n"
579 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
580 " Alter a account value\n"
581 " == Dispense administrators ==\n"
582 " dispense acct <user> =<ammount> \"<reason>\"\n"
583 " Set an account balance\n"
584 " dispense user add <user>\n"
585 " Create new coke account (Admins only)\n"
586 " dispense user type <user> <flags>\n"
587 " Alter a user's flags\n"
588 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
589 " Flags are removed by preceding the name with '-' or '!'\n"
593 " Set a different user (Coke members only)\n"
597 " Use alternate GUI\n"
598 " -m <min balance>\n"
599 " -M <max balance>\n"
600 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
604 // -------------------
605 // --- NCurses GUI ---
606 // -------------------
608 * \brief Render the NCurses UI
610 int ShowNCursesUI(void)
612 // TODO: ncurses interface (with separation between item classes)
613 // - Hmm... that would require standardising the item ID to be <class>:<index>
618 const int displayMinWidth = 40;
619 char *titleString = "Dispense";
624 int ret = -2; // -2: Used for marking "no return yet"
626 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
633 if( gsEffectiveUser )
634 username = gsEffectiveUser;
636 pwd = getpwuid( getuid() );
637 username = pwd->pw_name;
640 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, giUserBalance%100);
647 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
648 // Get item count per screen
649 // - 6: randomly chosen (Need at least 3)
650 itemCount = LINES - 6;
651 if( itemCount > maxItemIndex )
652 itemCount = maxItemIndex;
655 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
660 height = itemCount + 3;
661 width = displayMinWidth;
664 xBase = COLS/2 - width/2;
665 yBase = LINES/2 - height/2;
670 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
673 for( i = 0; i < itemCount; i ++ )
677 move( yBase + 1 + i, xBase );
682 // Check for the '...' row
683 // - Oh god, magic numbers!
684 if( (i == 0 && itemBase > 0)
685 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
687 printw(" ..."); pos += 8;
688 times = (width - pos) - 1;
689 while(times--) addch(' ');
694 yBase + 1 + i, xBase + pos, // Position
695 (width - pos) - 3, // Width
696 itemBase + i, // Index
697 !!(currentItem == itemBase + i) // Hilighted
702 // Scrollbar (if needed)
703 if( maxItemIndex > itemCount ) {
707 else if( i == itemCount - 1 ) {
711 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
712 if( i-1 == percentage*(itemCount-3)/100 ) {
726 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
729 // - Username, balance, flags
730 PrintAlign(yBase+height-1, xBase+1, width-2,
731 username, ' ', balance_str, ' ', gsUserFlags);
747 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
750 if( currentItem >= maxItemIndex ) {
753 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
760 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
763 if( currentItem < 0 ) {
764 currentItem = maxItemIndex - 1;
766 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
776 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
777 itemBase = currentItem - 2;
778 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
779 itemBase = currentItem - itemCount + 2;
785 ret = ShowItemAt(0, 0, 0, currentItem, 0);
788 ret = -1; // -1: Return with no dispense
792 // Check if the return value was changed
793 if( ret != -2 ) break;
805 * \brief Show item \a Index at (\a Col, \a Row)
806 * \return Dispense index of item
807 * \note Part of the NCurses UI
809 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
819 // - This assumes that
820 case UI_MODE_STANDARD:
822 // Index = -1, request limit
823 if( Index < 0 || Index >= giNumItems+2 )
829 name = "Coke Machine";
830 Index = -1; // -1 indicates a label
837 name = gaItems[Index].Desc;
838 price = gaItems[Index].Price;
839 status = gaItems[Index].Status;
847 name = "Electronic Payment System";
848 Index = -1; // -1 indicates a label
853 name = gaItems[Index].Desc;
854 price = gaItems[Index].Price;
855 status = gaItems[Index].Status;
861 // Width = 0, don't print
868 // Show hilight and status
889 getyx(stdscr, _y, _x);
890 // Assumes max 4 digit prices
891 times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
892 while(times--) addch(' ');
894 printw(" %4i", price);
898 printw("-- %s", name);
899 getyx(stdscr, _y, _x);
900 times = Width - 4 - (_x - Col);
901 while(times--) addch(' ');
906 // If the item isn't availiable for sale, return -1 (so it's skipped)
914 * \brief Print a three-part string at the specified position (formatted)
915 * \note NCurses UI Helper
917 * Prints \a Left on the left of the area, \a Right on the righthand side
918 * and \a Mid in the middle of the area. These are padded with \a Pad1
919 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
921 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
922 * and the arguments to these are read in that order.
924 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
925 const char *Mid, char Pad2, const char *Right, ...)
927 int lLen, mLen, rLen;
932 // Get the length of the strings
933 va_start(args, Right);
934 lLen = vsnprintf(NULL, 0, Left, args);
935 mLen = vsnprintf(NULL, 0, Mid, args);
936 rLen = vsnprintf(NULL, 0, Right, args);
940 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
941 return ; // TODO: What to do?
947 va_start(args, Right);
951 vsnprintf(tmp, lLen+1, Left, args);
955 times = (Width - mLen)/2 - lLen;
956 while(times--) addch(Pad1);
960 vsnprintf(tmp, mLen+1, Mid, args);
964 times = (Width - mLen)/2 - rLen;
965 if( (Width - mLen) % 2 ) times ++;
966 while(times--) addch(Pad2);
970 vsnprintf(tmp, rLen+1, Right, args);
975 // ---------------------
976 // --- Coke Protocol ---
977 // ---------------------
978 int OpenConnection(const char *Host, int Port)
980 struct hostent *host;
981 struct sockaddr_in serverAddr;
984 host = gethostbyname(Host);
986 fprintf(stderr, "Unable to look up '%s'\n", Host);
990 memset(&serverAddr, 0, sizeof(serverAddr));
992 serverAddr.sin_family = AF_INET; // IPv4
993 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
994 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
995 serverAddr.sin_port = htons(Port);
997 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
999 fprintf(stderr, "Failed to create socket\n");
1003 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1005 if( geteuid() == 0 || getuid() == 0 )
1008 struct sockaddr_in localAddr;
1009 memset(&localAddr, 0, sizeof(localAddr));
1010 localAddr.sin_family = AF_INET; // IPv4
1012 // Loop through all the top ports until one is avaliable
1013 for( i = 512; i < 1024; i ++)
1015 localAddr.sin_port = htons(i); // IPv4
1016 // Attempt to bind to low port for autoauth
1017 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1021 printf("Warning: AUTOAUTH unavaliable\n");
1023 // printf("Bound to 0.0.0.0:%i\n", i);
1026 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1027 fprintf(stderr, "Failed to connect to server\n");
1035 * \brief Authenticate with the server
1036 * \return Boolean Failure
1038 int Authenticate(int Socket)
1045 regmatch_t matches[4];
1047 if( gbIsAuthenticated ) return 0;
1050 pwd = getpwuid( getuid() );
1052 // Attempt automatic authentication
1053 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1055 // Check if it worked
1056 buf = ReadLine(Socket);
1058 responseCode = atoi(buf);
1059 switch( responseCode )
1061 case 200: // Autoauth succeeded, return
1065 case 401: // Untrusted, attempt password authentication
1068 sendf(Socket, "USER %s\n", pwd->pw_name);
1069 printf("Using username %s\n", pwd->pw_name);
1071 buf = ReadLine(Socket);
1074 // Expected format: 100 SALT <something> ...
1075 // OR : 100 User Set
1076 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1077 responseCode = atoi(buf);
1078 if( responseCode != 100 ) {
1079 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1085 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1086 // Store it for later
1087 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1088 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1092 // Give three attempts
1093 for( i = 0; i < 3; i ++ )
1095 int ofs = strlen(pwd->pw_name)+strlen(salt);
1098 char *pass = getpass("Password: ");
1101 // Create hash string
1102 // <username><salt><hash>
1103 strcpy(tmp, pwd->pw_name);
1105 SHA1( (unsigned char*)pass, strlen(pass), h );
1106 memcpy(tmp+ofs, h, 20);
1109 SHA1( (unsigned char*)tmp, ofs+20, h );
1110 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1111 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1112 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1116 sendf(Socket, "PASS %s\n", tmpBuf);
1117 buf = ReadLine(Socket);
1119 responseCode = atoi(buf);
1121 if( responseCode == 200 ) break;
1122 // Bad username/password
1123 if( responseCode == 401 ) continue;
1125 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1131 return 2; // 2 = Bad Password
1134 case 404: // Bad Username
1135 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1140 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1141 printf("%s\n", buf);
1146 // Set effective user
1147 if( gsEffectiveUser ) {
1148 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1150 buf = ReadLine(Socket);
1151 responseCode = atoi(buf);
1153 switch(responseCode)
1156 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1160 printf("Only coke members can use `dispense -u`\n");
1165 printf("Invalid user selected\n");
1170 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1171 printf("%s\n", buf);
1179 gbIsAuthenticated = 1;
1184 int GetUserBalance(int Socket)
1186 regmatch_t matches[6];
1193 if( gsEffectiveUser ) {
1194 gsUserName = gsEffectiveUser;
1197 pwd = getpwuid( getuid() );
1198 gsUserName = strdup(pwd->pw_name);
1202 sendf(Socket, "USER_INFO %s\n", gsUserName);
1203 buf = ReadLine(Socket);
1204 responseCode = atoi(buf);
1205 switch(responseCode)
1207 case 202: break; // Ok
1210 printf("Invalid user? (USER_INFO failed)\n");
1215 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1216 printf("%s\n", buf);
1221 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1223 giUserBalance = atoi( buf + matches[4].rm_so );
1224 gsUserFlags = strdup( buf + matches[5].rm_so );
1232 * \brief Read an item info response from the server
1233 * \param Dest Destination for the read item (strings will be on the heap)
1235 int ReadItemInfo(int Socket, tItem *Dest)
1240 regmatch_t matches[8];
1244 buf = ReadLine(Socket);
1245 responseCode = atoi(buf);
1247 switch(responseCode)
1252 printf("Bad item name\n");
1257 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1261 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1263 buf[ matches[3].rm_eo ] = '\0';
1264 buf[ matches[5].rm_eo ] = '\0';
1265 buf[ matches[7].rm_eo ] = '\0';
1267 statusStr = &buf[ matches[5].rm_so ];
1269 Dest->ID = atoi( buf + matches[4].rm_so );
1271 if( strcmp(statusStr, "avail") == 0 )
1273 else if( strcmp(statusStr, "sold") == 0 )
1275 else if( strcmp(statusStr, "error") == 0 )
1278 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1282 Dest->Price = atoi( buf + matches[6].rm_so );
1284 // Hack a little to reduce heap fragmentation
1286 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1287 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1288 strcpy(tmpType, buf + matches[3].rm_so);
1289 strcpy(tmpDesc, buf + matches[7].rm_so);
1291 Dest->Type = strdup( tmpType );
1292 Dest->Desc = strdup( tmpDesc );
1299 * \brief Fill the item information structure
1300 * \return Boolean Failure
1302 void PopulateItemList(int Socket)
1307 char *itemType, *itemStart;
1309 regmatch_t matches[4];
1311 // Ask server for stock list
1312 send(Socket, "ENUM_ITEMS\n", 11, 0);
1313 buf = ReadLine(Socket);
1315 //printf("Output: %s\n", buf);
1317 responseCode = atoi(buf);
1318 if( responseCode != 201 ) {
1319 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1323 // - Get item list -
1326 // 201 Items <count>
1328 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1330 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1331 count = atoi( &buf[ matches[3].rm_so ] );
1334 if( strcmp(itemType, "Items") != 0 ) {
1336 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1341 itemStart = &buf[ matches[3].rm_eo ];
1346 gaItems = malloc( giNumItems * sizeof(tItem) );
1348 // Fetch item information
1349 for( i = 0; i < giNumItems; i ++ )
1351 ReadItemInfo( Socket, &gaItems[i] );
1355 buf = ReadLine(Socket);
1356 responseCode = atoi(buf);
1358 if( responseCode != 200 ) {
1359 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1370 * \brief Get information on an item
1371 * \return Boolean Failure
1373 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1378 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1380 if( ReadItemInfo(Socket, &item) )
1385 printf("%8s:%-2i %2i.%02i %s\n",
1387 item.Price/100, item.Price%100,
1397 * \brief Dispense an item
1398 * \return Boolean Failure
1400 int DispenseItem(int Socket, const char *Type, int ID)
1402 int ret, responseCode;
1405 // Check for a dry run
1407 printf("Dry Run - No action\n");
1412 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1413 buf = ReadLine(Socket);
1415 responseCode = atoi(buf);
1416 switch( responseCode )
1419 printf("Dispense OK\n");
1423 printf("Not authenticated\n");
1427 printf("Insufficient balance\n");
1431 printf("Bad item name\n");
1435 printf("Item failed to dispense, is the slot empty?\n");
1439 printf("Dispense not possible (slot empty/permissions)\n");
1443 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1453 * \brief Alter a user's balance
1455 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1460 // Check for a dry run
1462 printf("Dry Run - No action\n");
1466 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1467 buf = ReadLine(Socket);
1469 responseCode = atoi(buf);
1472 switch(responseCode)
1474 case 200: return 0; // OK
1476 fprintf(stderr, "Insufficient balance\n");
1478 case 403: // Not in coke
1479 fprintf(stderr, "You are not in coke (sucker)\n");
1481 case 404: // Unknown user
1482 fprintf(stderr, "Unknown user '%s'\n", Username);
1485 fprintf(stderr, "Unknown response code %i\n", responseCode);
1493 * \brief Set a user's balance
1494 * \note Only avaliable to dispense admins
1496 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1501 // Check for a dry run
1503 printf("Dry Run - No action\n");
1507 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1508 buf = ReadLine(Socket);
1510 responseCode = atoi(buf);
1513 switch(responseCode)
1515 case 200: return 0; // OK
1516 case 403: // Not in coke
1517 fprintf(stderr, "You are not an admin\n");
1519 case 404: // Unknown user
1520 fprintf(stderr, "Unknown user '%s'\n", Username);
1523 fprintf(stderr, "Unknown response code %i\n", responseCode);
1531 * \brief Give money to another user
1533 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1539 printf("Sorry, you can only give, you can't take.\n");
1543 // Fast return on zero
1544 if( Ammount == 0 ) {
1545 printf("Are you actually going to give any?\n");
1549 // Check for a dry run
1551 printf("Dry Run - No action\n");
1555 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1556 buf = ReadLine(Socket);
1558 responseCode = atoi(buf);
1561 switch(responseCode)
1564 printf("Give succeeded\n");
1568 fprintf(stderr, "Insufficient balance\n");
1571 case 404: // Unknown user
1572 fprintf(stderr, "Unknown user '%s'\n", Username);
1576 fprintf(stderr, "Unknown response code %i\n", responseCode);
1585 * \brief Donate money to the club
1587 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1593 printf("Sorry, you can only give, you can't take.\n");
1597 // Fast return on zero
1598 if( Ammount == 0 ) {
1599 printf("Are you actually going to give any?\n");
1603 // Check for a dry run
1605 printf("Dry Run - No action\n");
1609 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1610 buf = ReadLine(Socket);
1612 responseCode = atoi(buf);
1615 switch(responseCode)
1617 case 200: return 0; // OK
1620 fprintf(stderr, "Insufficient balance\n");
1624 fprintf(stderr, "Unknown response code %i\n", responseCode);
1632 * \brief Enumerate users
1634 int Dispense_EnumUsers(int Socket)
1639 regmatch_t matches[4];
1641 if( giMinimumBalance != INT_MIN ) {
1642 if( giMaximumBalance != INT_MAX ) {
1643 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1646 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1650 if( giMaximumBalance != INT_MAX ) {
1651 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1654 sendf(Socket, "ENUM_USERS\n");
1657 buf = ReadLine(Socket);
1658 responseCode = atoi(buf);
1660 switch(responseCode)
1662 case 201: break; // Ok, length follows
1665 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1670 // Get count (not actually used)
1671 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1672 nUsers = atoi( buf + matches[3].rm_so );
1673 printf("%i users returned\n", nUsers);
1678 // Read returned users
1680 buf = ReadLine(Socket);
1681 responseCode = atoi(buf);
1683 if( responseCode != 202 ) break;
1685 _PrintUserLine(buf);
1687 } while(responseCode == 202);
1689 // Check final response
1690 if( responseCode != 200 ) {
1691 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1701 int Dispense_ShowUser(int Socket, const char *Username)
1704 int responseCode, ret;
1706 sendf(Socket, "USER_INFO %s\n", Username);
1707 buf = ReadLine(Socket);
1709 responseCode = atoi(buf);
1711 switch(responseCode)
1714 _PrintUserLine(buf);
1719 printf("Unknown user '%s'\n", Username);
1724 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1734 void _PrintUserLine(const char *Line)
1736 regmatch_t matches[6];
1739 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1744 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1745 char username[usernameLen + 1];
1746 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1747 char flags[flagsLen + 1];
1749 memcpy(username, Line + matches[3].rm_so, usernameLen);
1750 username[usernameLen] = '\0';
1751 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1752 flags[flagsLen] = '\0';
1754 bal = atoi(Line + matches[4].rm_so);
1755 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1759 int Dispense_AddUser(int Socket, const char *Username)
1762 int responseCode, ret;
1764 // Check for a dry run
1766 printf("Dry Run - No action\n");
1770 sendf(Socket, "USER_ADD %s\n", Username);
1772 buf = ReadLine(Socket);
1773 responseCode = atoi(buf);
1775 switch(responseCode)
1778 printf("User '%s' added\n", Username);
1783 printf("Only wheel can add users\n");
1788 printf("User '%s' already exists\n", Username);
1793 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1803 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1806 int responseCode, ret;
1808 // Check for a dry run
1810 printf("Dry Run - No action\n");
1814 // TODO: Pre-validate the string
1816 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1818 buf = ReadLine(Socket);
1819 responseCode = atoi(buf);
1821 switch(responseCode)
1824 printf("User '%s' updated\n", Username);
1829 printf("Only wheel can modify users\n");
1834 printf("User '%s' does not exist\n", Username);
1839 printf("Flag string is invalid\n");
1844 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1857 char *ReadLine(int Socket)
1859 static char buf[BUFSIZ];
1860 static int bufPos = 0;
1861 static int bufValid = 0;
1863 char *newline = NULL;
1865 char *ret = malloc(10);
1867 #if DEBUG_TRACE_SERVER
1868 printf("ReadLine: ");
1880 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1881 buf[bufPos+len] = '\0';
1884 newline = strchr( buf+bufPos, '\n' );
1889 retLen += strlen(buf+bufPos);
1890 ret = realloc(ret, retLen + 1);
1891 strcat( ret, buf+bufPos );
1894 int newLen = newline - (buf+bufPos) + 1;
1895 bufValid = len - newLen;
1898 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1901 #if DEBUG_TRACE_SERVER
1902 printf("%i '%s'\n", retLen, ret);
1908 int sendf(int Socket, const char *Format, ...)
1913 va_start(args, Format);
1914 len = vsnprintf(NULL, 0, Format, args);
1919 va_start(args, Format);
1920 vsnprintf(buf, len+1, Format, args);
1923 #if DEBUG_TRACE_SERVER
1924 printf("sendf: %s", buf);
1927 return send(Socket, buf, len, 0);
1931 char *trim(char *string)
1935 while( isspace(*string) )
1938 for( i = strlen(string); i--; )
1940 if( isspace(string[i]) )
1949 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1953 ret = regexec(regex, string, nMatches, matches, 0);
1954 if( ret && errorMessage ) {
1955 size_t len = regerror(ret, regex, NULL, 0);
1957 regerror(ret, regex, errorStr, len);
1958 printf("string = '%s'\n", string);
1959 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1966 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1968 int ret = regcomp(regex, pattern, flags);
1970 size_t len = regerror(ret, regex, NULL, 0);
1972 regerror(ret, regex, errorStr, len);
1973 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);