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
186 if( text_argc + 1 == MAX_TXT_ARGS )
188 fprintf(stderr, "ERROR: Too many arguments\n");
191 text_args[text_argc++] = argv[i];
198 if( text_argc + 1 == MAX_TXT_ARGS )
200 fprintf(stderr, "ERROR: Too many arguments\n");
204 text_args[text_argc++] = argv[i];
211 if( strcmp(text_args[0], "acct") == 0 )
214 sock = OpenConnection(gsDispenseServer, giDispensePort);
215 if( sock < 0 ) return -1;
217 if( text_argc == 1 ) {
218 ret = Dispense_EnumUsers(sock);
223 // text_args[1]: Username
228 // Authentication required
229 if( Authenticate(sock) )
232 // text_args[1]: Username
233 // text_args[2]: Ammount
234 // text_args[3]: Reason
236 if( text_args[2][0] == '=' ) {
238 if( text_args[2][1] != '0' && atoi(text_args[2]+1) == 0 ) {
239 fprintf(stderr, "Error: Invalid balance to be set\n");
243 ret = Dispense_SetBalance(sock, text_args[1], atoi(text_args[2]+1), text_args[3]);
247 ret = Dispense_AlterBalance(sock, text_args[1], atoi(text_args[2]), text_args[3]);
250 // TODO: Preserve ret if non-zero
252 // Show user information
253 ret = Dispense_ShowUser(sock, text_args[1]);
260 // - "Here, have some money."
261 if( strcmp(text_args[0], "give") == 0 )
263 if( text_argc != 4 ) {
264 fprintf(stderr, "`dispense give` takes three arguments\n");
269 // text_args[1]: Destination
270 // text_args[2]: Ammount
271 // text_args[3]: Reason
274 sock = OpenConnection(gsDispenseServer, giDispensePort);
275 if( sock < 0 ) return -1;
278 if( Authenticate(sock) )
281 ret = Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
289 // - User administration (Admin Only)
290 if( strcmp(text_args[0], "user") == 0 )
292 // Check argument count
293 if( text_argc == 1 ) {
294 fprintf(stderr, "Error: `dispense user` requires arguments\n");
300 sock = OpenConnection(gsDispenseServer, giDispensePort);
301 if( sock < 0 ) return -1;
303 // Attempt authentication
304 if( Authenticate(sock) )
308 if( strcmp(text_args[1], "add") == 0 )
310 if( text_argc != 3 ) {
311 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
316 ret = Dispense_AddUser(sock, text_args[2]);
319 else if( strcmp(text_args[1], "type") == 0 || strcmp(text_args[1], "flags") == 0 )
321 if( text_argc != 4 ) {
322 fprintf(stderr, "Error: `dispense user flags` requires two arguments\n");
327 ret = Dispense_SetUserType(sock, text_args[2], text_args[3]);
331 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
339 else if( strcmp(text_args[0], "donate") == 0 )
341 // Check argument count
342 if( text_argc != 3 ) {
343 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
349 sock = OpenConnection(gsDispenseServer, giDispensePort);
350 if( sock < 0 ) return -1;
352 // Attempt authentication
353 if( Authenticate(sock) )
357 ret =Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
363 // Query an item price
364 else if( strcmp(text_args[0], "iteminfo") == 0 )
366 regmatch_t matches[3];
369 // Check argument count
370 if( text_argc != 2 ) {
371 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
376 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
377 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
380 type = text_args[1] + matches[1].rm_so;
381 text_args[1][ matches[1].rm_eo ] = '\0';
382 id = atoi( text_args[1] + matches[2].rm_so );
384 sock = OpenConnection(gsDispenseServer, giDispensePort);
385 if( sock < 0 ) return -1;
386 ret = Dispense_ItemInfo(sock, type, id);
390 // Item name / pattern
392 gsItemPattern = text_args[0];
396 sock = OpenConnection(gsDispenseServer, giDispensePort);
397 if( sock < 0 ) return -1;
399 // Get the user's balance
400 GetUserBalance(sock);
403 PopulateItemList(sock);
405 // Disconnect from server
408 if( gsItemPattern && gsItemPattern[0] )
410 regmatch_t matches[3];
412 if( strcmp(gsItemPattern, "door") == 0 )
414 // Connect, Authenticate, dispense and close
415 sock = OpenConnection(gsDispenseServer, giDispensePort);
416 if( sock < 0 ) return -1;
418 ret = DispenseItem(sock, "door", 0);
422 // Item id (<type>:<num>)
423 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
428 // Get and finish ident
429 ident = gsItemPattern + matches[1].rm_so;
430 gsItemPattern[matches[1].rm_eo] = '\0';
432 id = atoi( gsItemPattern + matches[2].rm_so );
434 // Connect, Authenticate, dispense and close
435 sock = OpenConnection(gsDispenseServer, giDispensePort);
436 if( sock < 0 ) return -1;
438 Dispense_ItemInfo(sock, ident, id);
441 ret = DispenseItem(sock, ident, id);
445 // Item number (6 = coke)
446 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
448 i = atoi(gsItemPattern);
455 for( i = 0; i < giNumItems; i ++ )
457 // Prefix match (with case-insensitive match)
458 for( j = 0; gsItemPattern[j]; j ++ )
460 if( gaItems[i].Desc[j] == gsItemPattern[j] )
462 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
466 // Check if the prefix matched
467 if( gsItemPattern[j] != '\0' )
471 if( gaItems[i].Desc[j] == '\0' ) {
476 // Only one match allowed
481 // TODO: Allow ambiguous matches?
482 // or just print a wanrning
483 printf("Warning - Ambiguous pattern, stopping\n");
488 // Was a match found?
491 fprintf(stderr, "No item matches the passed string\n");
498 else if( giUIMode != UI_MODE_BASIC )
504 // Very basic dispense interface
505 for( i = 0; i < giNumItems; i ++ ) {
507 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
510 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
511 gaItems[i].Price, gaItems[i].Desc);
520 fgets(buffer, BUFSIZ, stdin);
524 if( buf[0] == 'q' ) break;
528 if( i != 0 || buf[0] == '0' )
530 if( i < 0 || i >= giNumItems ) {
531 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
540 // Check for a valid item ID
543 // Connect, Authenticate, dispense and close
544 sock = OpenConnection(gsDispenseServer, giDispensePort);
545 if( sock < 0 ) return -1;
547 Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
550 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
563 " Show interactive list\n"
564 " dispense <name>|<index>|<itemid>\n"
565 " Dispense named item (<name> matches if it is a unique prefix)\n"
566 " dispense give <user> <ammount> \"<reason>\"\n"
567 " Give money to another user\n"
568 " dispense donate <ammount> \"<reason>\"\n"
569 " Donate to the club\n"
570 " dispense iteminfo <type>:<id>\n"
571 " Get the name and price for an item\n"
572 " == Coke members == \n"
573 " dispense acct [<user>]\n"
574 " Show user balances\n"
575 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
576 " Alter a account value\n"
577 " == Dispense administrators ==\n"
578 " dispense acct <user> =<ammount> \"<reason>\"\n"
579 " Set an account balance\n"
580 " dispense user add <user>\n"
581 " Create new coke account (Admins only)\n"
582 " dispense user type <user> <flags>\n"
583 " Alter a user's flags\n"
584 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
585 " Flags are removed by preceding the name with '-' or '!'\n"
589 " Set a different user (Coke members only)\n"
593 " Use alternate GUI\n"
594 " -m <min balance>\n"
595 " -M <max balance>\n"
596 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
600 // -------------------
601 // --- NCurses GUI ---
602 // -------------------
604 * \brief Render the NCurses UI
606 int ShowNCursesUI(void)
608 // TODO: ncurses interface (with separation between item classes)
609 // - Hmm... that would require standardising the item ID to be <class>:<index>
614 const int displayMinWidth = 40;
615 char *titleString = "Dispense";
620 int ret = -2; // -2: Used for marking "no return yet"
622 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
629 if( gsEffectiveUser )
630 username = gsEffectiveUser;
632 pwd = getpwuid( getuid() );
633 username = pwd->pw_name;
636 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, giUserBalance%100);
643 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
644 // Get item count per screen
645 // - 6: randomly chosen (Need at least 3)
646 itemCount = LINES - 6;
647 if( itemCount > maxItemIndex )
648 itemCount = maxItemIndex;
651 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
656 height = itemCount + 3;
657 width = displayMinWidth;
660 xBase = COLS/2 - width/2;
661 yBase = LINES/2 - height/2;
666 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
669 for( i = 0; i < itemCount; i ++ )
673 move( yBase + 1 + i, xBase );
678 // Check for the '...' row
679 // - Oh god, magic numbers!
680 if( (i == 0 && itemBase > 0)
681 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
683 printw(" ..."); pos += 8;
684 times = (width - pos) - 1;
685 while(times--) addch(' ');
690 yBase + 1 + i, xBase + pos, // Position
691 (width - pos) - 3, // Width
692 itemBase + i, // Index
693 !!(currentItem == itemBase + i) // Hilighted
698 // Scrollbar (if needed)
699 if( maxItemIndex > itemCount ) {
703 else if( i == itemCount - 1 ) {
707 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
708 if( i-1 == percentage*(itemCount-3)/100 ) {
722 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
725 // - Username, balance, flags
726 PrintAlign(yBase+height-1, xBase+1, width-2,
727 username, ' ', balance_str, ' ', gsUserFlags);
743 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
746 if( currentItem >= maxItemIndex ) {
749 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
756 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
759 if( currentItem < 0 ) {
760 currentItem = maxItemIndex - 1;
762 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
772 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
773 itemBase = currentItem - 2;
774 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
775 itemBase = currentItem - itemCount + 2;
781 ret = ShowItemAt(0, 0, 0, currentItem, 0);
784 ret = -1; // -1: Return with no dispense
788 // Check if the return value was changed
789 if( ret != -2 ) break;
801 * \brief Show item \a Index at (\a Col, \a Row)
802 * \return Dispense index of item
803 * \note Part of the NCurses UI
805 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
815 // - This assumes that
816 case UI_MODE_STANDARD:
818 // Index = -1, request limit
819 if( Index < 0 || Index >= giNumItems+2 )
825 name = "Coke Machine";
826 Index = -1; // -1 indicates a label
833 name = gaItems[Index].Desc;
834 price = gaItems[Index].Price;
835 status = gaItems[Index].Status;
843 name = "Electronic Payment System";
844 Index = -1; // -1 indicates a label
849 name = gaItems[Index].Desc;
850 price = gaItems[Index].Price;
851 status = gaItems[Index].Status;
857 // Width = 0, don't print
864 // Show hilight and status
885 getyx(stdscr, _y, _x);
886 // Assumes max 4 digit prices
887 times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
888 while(times--) addch(' ');
890 printw(" %4i", price);
894 printw("-- %s", name);
895 getyx(stdscr, _y, _x);
896 times = Width - 4 - (_x - Col);
897 while(times--) addch(' ');
902 // If the item isn't availiable for sale, return -1 (so it's skipped)
910 * \brief Print a three-part string at the specified position (formatted)
911 * \note NCurses UI Helper
913 * Prints \a Left on the left of the area, \a Right on the righthand side
914 * and \a Mid in the middle of the area. These are padded with \a Pad1
915 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
917 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
918 * and the arguments to these are read in that order.
920 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
921 const char *Mid, char Pad2, const char *Right, ...)
923 int lLen, mLen, rLen;
928 // Get the length of the strings
929 va_start(args, Right);
930 lLen = vsnprintf(NULL, 0, Left, args);
931 mLen = vsnprintf(NULL, 0, Mid, args);
932 rLen = vsnprintf(NULL, 0, Right, args);
936 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
937 return ; // TODO: What to do?
943 va_start(args, Right);
947 vsnprintf(tmp, lLen+1, Left, args);
951 times = (Width - mLen)/2 - lLen;
952 while(times--) addch(Pad1);
956 vsnprintf(tmp, mLen+1, Mid, args);
960 times = (Width - mLen)/2 - rLen;
961 if( (Width - mLen) % 2 ) times ++;
962 while(times--) addch(Pad2);
966 vsnprintf(tmp, rLen+1, Right, args);
971 // ---------------------
972 // --- Coke Protocol ---
973 // ---------------------
974 int OpenConnection(const char *Host, int Port)
976 struct hostent *host;
977 struct sockaddr_in serverAddr;
980 host = gethostbyname(Host);
982 fprintf(stderr, "Unable to look up '%s'\n", Host);
986 memset(&serverAddr, 0, sizeof(serverAddr));
988 serverAddr.sin_family = AF_INET; // IPv4
989 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
990 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
991 serverAddr.sin_port = htons(Port);
993 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
995 fprintf(stderr, "Failed to create socket\n");
999 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1001 if( geteuid() == 0 || getuid() == 0 )
1004 struct sockaddr_in localAddr;
1005 memset(&localAddr, 0, sizeof(localAddr));
1006 localAddr.sin_family = AF_INET; // IPv4
1008 // Loop through all the top ports until one is avaliable
1009 for( i = 512; i < 1024; i ++)
1011 localAddr.sin_port = htons(i); // IPv4
1012 // Attempt to bind to low port for autoauth
1013 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1017 printf("Warning: AUTOAUTH unavaliable\n");
1019 // printf("Bound to 0.0.0.0:%i\n", i);
1022 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1023 fprintf(stderr, "Failed to connect to server\n");
1031 * \brief Authenticate with the server
1032 * \return Boolean Failure
1034 int Authenticate(int Socket)
1041 regmatch_t matches[4];
1043 if( gbIsAuthenticated ) return 0;
1046 pwd = getpwuid( getuid() );
1048 // Attempt automatic authentication
1049 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1051 // Check if it worked
1052 buf = ReadLine(Socket);
1054 responseCode = atoi(buf);
1055 switch( responseCode )
1057 case 200: // Autoauth succeeded, return
1061 case 401: // Untrusted, attempt password authentication
1064 sendf(Socket, "USER %s\n", pwd->pw_name);
1065 printf("Using username %s\n", pwd->pw_name);
1067 buf = ReadLine(Socket);
1070 // Expected format: 100 SALT <something> ...
1071 // OR : 100 User Set
1072 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1073 responseCode = atoi(buf);
1074 if( responseCode != 100 ) {
1075 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1081 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1082 // Store it for later
1083 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1084 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1088 // Give three attempts
1089 for( i = 0; i < 3; i ++ )
1091 int ofs = strlen(pwd->pw_name)+strlen(salt);
1094 char *pass = getpass("Password: ");
1097 // Create hash string
1098 // <username><salt><hash>
1099 strcpy(tmp, pwd->pw_name);
1101 SHA1( (unsigned char*)pass, strlen(pass), h );
1102 memcpy(tmp+ofs, h, 20);
1105 SHA1( (unsigned char*)tmp, ofs+20, h );
1106 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1107 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1108 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1112 sendf(Socket, "PASS %s\n", tmpBuf);
1113 buf = ReadLine(Socket);
1115 responseCode = atoi(buf);
1117 if( responseCode == 200 ) break;
1118 // Bad username/password
1119 if( responseCode == 401 ) continue;
1121 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1127 return 2; // 2 = Bad Password
1130 case 404: // Bad Username
1131 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1136 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1137 printf("%s\n", buf);
1142 // Set effective user
1143 if( gsEffectiveUser ) {
1144 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1146 buf = ReadLine(Socket);
1147 responseCode = atoi(buf);
1149 switch(responseCode)
1152 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1156 printf("Only coke members can use `dispense -u`\n");
1161 printf("Invalid user selected\n");
1166 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1167 printf("%s\n", buf);
1175 gbIsAuthenticated = 1;
1180 int GetUserBalance(int Socket)
1182 regmatch_t matches[6];
1189 if( gsEffectiveUser ) {
1190 gsUserName = gsEffectiveUser;
1193 pwd = getpwuid( getuid() );
1194 gsUserName = strdup(pwd->pw_name);
1198 sendf(Socket, "USER_INFO %s\n", gsUserName);
1199 buf = ReadLine(Socket);
1200 responseCode = atoi(buf);
1201 switch(responseCode)
1203 case 202: break; // Ok
1206 printf("Invalid user? (USER_INFO failed)\n");
1211 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1212 printf("%s\n", buf);
1217 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1219 giUserBalance = atoi( buf + matches[4].rm_so );
1220 gsUserFlags = strdup( buf + matches[5].rm_so );
1228 * \brief Read an item info response from the server
1229 * \param Dest Destination for the read item (strings will be on the heap)
1231 int ReadItemInfo(int Socket, tItem *Dest)
1236 regmatch_t matches[8];
1240 buf = ReadLine(Socket);
1241 responseCode = atoi(buf);
1243 switch(responseCode)
1248 printf("Bad item name\n");
1253 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1257 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1259 buf[ matches[3].rm_eo ] = '\0';
1260 buf[ matches[5].rm_eo ] = '\0';
1261 buf[ matches[7].rm_eo ] = '\0';
1263 statusStr = &buf[ matches[5].rm_so ];
1265 Dest->ID = atoi( buf + matches[4].rm_so );
1267 if( strcmp(statusStr, "avail") == 0 )
1269 else if( strcmp(statusStr, "sold") == 0 )
1271 else if( strcmp(statusStr, "error") == 0 )
1274 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1278 Dest->Price = atoi( buf + matches[6].rm_so );
1280 // Hack a little to reduce heap fragmentation
1282 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1283 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1284 strcpy(tmpType, buf + matches[3].rm_so);
1285 strcpy(tmpDesc, buf + matches[7].rm_so);
1287 Dest->Type = strdup( tmpType );
1288 Dest->Desc = strdup( tmpDesc );
1295 * \brief Fill the item information structure
1296 * \return Boolean Failure
1298 void PopulateItemList(int Socket)
1303 char *itemType, *itemStart;
1305 regmatch_t matches[4];
1307 // Ask server for stock list
1308 send(Socket, "ENUM_ITEMS\n", 11, 0);
1309 buf = ReadLine(Socket);
1311 //printf("Output: %s\n", buf);
1313 responseCode = atoi(buf);
1314 if( responseCode != 201 ) {
1315 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1319 // - Get item list -
1322 // 201 Items <count>
1324 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1326 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1327 count = atoi( &buf[ matches[3].rm_so ] );
1330 if( strcmp(itemType, "Items") != 0 ) {
1332 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1337 itemStart = &buf[ matches[3].rm_eo ];
1342 gaItems = malloc( giNumItems * sizeof(tItem) );
1344 // Fetch item information
1345 for( i = 0; i < giNumItems; i ++ )
1347 ReadItemInfo( Socket, &gaItems[i] );
1351 buf = ReadLine(Socket);
1352 responseCode = atoi(buf);
1354 if( responseCode != 200 ) {
1355 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1366 * \brief Get information on an item
1367 * \return Boolean Failure
1369 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1374 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1376 if( ReadItemInfo(Socket, &item) )
1381 printf("%8s:%-2i %2i.%02i %s\n",
1383 item.Price/100, item.Price%100,
1393 * \brief Dispense an item
1394 * \return Boolean Failure
1396 int DispenseItem(int Socket, const char *Type, int ID)
1398 int ret, responseCode;
1401 // Check for a dry run
1403 printf("Dry Run - No action\n");
1408 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1409 buf = ReadLine(Socket);
1411 responseCode = atoi(buf);
1412 switch( responseCode )
1415 printf("Dispense OK\n");
1419 printf("Not authenticated\n");
1423 printf("Insufficient balance\n");
1427 printf("Bad item name\n");
1431 printf("Item failed to dispense, is the slot empty?\n");
1435 printf("Dispense not possible (slot empty/permissions)\n");
1439 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1449 * \brief Alter a user's balance
1451 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1456 // Check for a dry run
1458 printf("Dry Run - No action\n");
1462 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1463 buf = ReadLine(Socket);
1465 responseCode = atoi(buf);
1468 switch(responseCode)
1470 case 200: return 0; // OK
1472 fprintf(stderr, "Insufficient balance\n");
1474 case 403: // Not in coke
1475 fprintf(stderr, "You are not in coke (sucker)\n");
1477 case 404: // Unknown user
1478 fprintf(stderr, "Unknown user '%s'\n", Username);
1481 fprintf(stderr, "Unknown response code %i\n", responseCode);
1489 * \brief Set a user's balance
1490 * \note Only avaliable to dispense admins
1492 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1497 // Check for a dry run
1499 printf("Dry Run - No action\n");
1503 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1504 buf = ReadLine(Socket);
1506 responseCode = atoi(buf);
1509 switch(responseCode)
1511 case 200: return 0; // OK
1512 case 403: // Not in coke
1513 fprintf(stderr, "You are not an admin\n");
1515 case 404: // Unknown user
1516 fprintf(stderr, "Unknown user '%s'\n", Username);
1519 fprintf(stderr, "Unknown response code %i\n", responseCode);
1527 * \brief Give money to another user
1529 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1535 printf("Sorry, you can only give, you can't take.\n");
1539 // Fast return on zero
1540 if( Ammount == 0 ) {
1541 printf("Are you actually going to give any?\n");
1545 // Check for a dry run
1547 printf("Dry Run - No action\n");
1551 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1552 buf = ReadLine(Socket);
1554 responseCode = atoi(buf);
1557 switch(responseCode)
1560 printf("Give succeeded\n");
1564 fprintf(stderr, "Insufficient balance\n");
1567 case 404: // Unknown user
1568 fprintf(stderr, "Unknown user '%s'\n", Username);
1572 fprintf(stderr, "Unknown response code %i\n", responseCode);
1581 * \brief Donate money to the club
1583 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1589 printf("Sorry, you can only give, you can't take.\n");
1593 // Fast return on zero
1594 if( Ammount == 0 ) {
1595 printf("Are you actually going to give any?\n");
1599 // Check for a dry run
1601 printf("Dry Run - No action\n");
1605 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1606 buf = ReadLine(Socket);
1608 responseCode = atoi(buf);
1611 switch(responseCode)
1613 case 200: return 0; // OK
1616 fprintf(stderr, "Insufficient balance\n");
1620 fprintf(stderr, "Unknown response code %i\n", responseCode);
1628 * \brief Enumerate users
1630 int Dispense_EnumUsers(int Socket)
1635 regmatch_t matches[4];
1637 if( giMinimumBalance != INT_MIN ) {
1638 if( giMaximumBalance != INT_MAX ) {
1639 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1642 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1646 if( giMaximumBalance != INT_MAX ) {
1647 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1650 sendf(Socket, "ENUM_USERS\n");
1653 buf = ReadLine(Socket);
1654 responseCode = atoi(buf);
1656 switch(responseCode)
1658 case 201: break; // Ok, length follows
1661 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1666 // Get count (not actually used)
1667 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1668 nUsers = atoi( buf + matches[3].rm_so );
1669 printf("%i users returned\n", nUsers);
1674 // Read returned users
1676 buf = ReadLine(Socket);
1677 responseCode = atoi(buf);
1679 if( responseCode != 202 ) break;
1681 _PrintUserLine(buf);
1683 } while(responseCode == 202);
1685 // Check final response
1686 if( responseCode != 200 ) {
1687 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1697 int Dispense_ShowUser(int Socket, const char *Username)
1700 int responseCode, ret;
1702 sendf(Socket, "USER_INFO %s\n", Username);
1703 buf = ReadLine(Socket);
1705 responseCode = atoi(buf);
1707 switch(responseCode)
1710 _PrintUserLine(buf);
1715 printf("Unknown user '%s'\n", Username);
1720 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1730 void _PrintUserLine(const char *Line)
1732 regmatch_t matches[6];
1735 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1740 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1741 char username[usernameLen + 1];
1742 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1743 char flags[flagsLen + 1];
1745 memcpy(username, Line + matches[3].rm_so, usernameLen);
1746 username[usernameLen] = '\0';
1747 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1748 flags[flagsLen] = '\0';
1750 bal = atoi(Line + matches[4].rm_so);
1751 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1755 int Dispense_AddUser(int Socket, const char *Username)
1758 int responseCode, ret;
1760 // Check for a dry run
1762 printf("Dry Run - No action\n");
1766 sendf(Socket, "USER_ADD %s\n", Username);
1768 buf = ReadLine(Socket);
1769 responseCode = atoi(buf);
1771 switch(responseCode)
1774 printf("User '%s' added\n", Username);
1779 printf("Only wheel can add users\n");
1784 printf("User '%s' already exists\n", Username);
1789 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1799 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1802 int responseCode, ret;
1804 // Check for a dry run
1806 printf("Dry Run - No action\n");
1810 // TODO: Pre-validate the string
1812 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1814 buf = ReadLine(Socket);
1815 responseCode = atoi(buf);
1817 switch(responseCode)
1820 printf("User '%s' updated\n", Username);
1825 printf("Only wheel can modify users\n");
1830 printf("User '%s' does not exist\n", Username);
1835 printf("Flag string is invalid\n");
1840 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1853 char *ReadLine(int Socket)
1855 static char buf[BUFSIZ];
1856 static int bufPos = 0;
1857 static int bufValid = 0;
1859 char *newline = NULL;
1861 char *ret = malloc(10);
1863 #if DEBUG_TRACE_SERVER
1864 printf("ReadLine: ");
1876 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1877 buf[bufPos+len] = '\0';
1880 newline = strchr( buf+bufPos, '\n' );
1885 retLen += strlen(buf+bufPos);
1886 ret = realloc(ret, retLen + 1);
1887 strcat( ret, buf+bufPos );
1890 int newLen = newline - (buf+bufPos) + 1;
1891 bufValid = len - newLen;
1894 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1897 #if DEBUG_TRACE_SERVER
1898 printf("%i '%s'\n", retLen, ret);
1904 int sendf(int Socket, const char *Format, ...)
1909 va_start(args, Format);
1910 len = vsnprintf(NULL, 0, Format, args);
1915 va_start(args, Format);
1916 vsnprintf(buf, len+1, Format, args);
1919 #if DEBUG_TRACE_SERVER
1920 printf("sendf: %s", buf);
1923 return send(Socket, buf, len, 0);
1927 char *trim(char *string)
1931 while( isspace(*string) )
1934 for( i = strlen(string); i--; )
1936 if( isspace(string[i]) )
1945 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1949 ret = regexec(regex, string, nMatches, matches, 0);
1950 if( ret && errorMessage ) {
1951 size_t len = regerror(ret, regex, NULL, 0);
1953 regerror(ret, regex, errorStr, len);
1954 printf("string = '%s'\n", string);
1955 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1962 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1964 int ret = regcomp(regex, pattern, flags);
1966 size_t len = regerror(ret, regex, NULL, 0);
1968 regerror(ret, regex, errorStr, len);
1969 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);