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 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 Dispense_SetBalance(sock, text_args[1], atoi(text_args[2]+1), text_args[3]);
251 Dispense_AlterBalance(sock, text_args[1], atoi(text_args[2]), text_args[3]);
255 // Show user information
256 Dispense_ShowUser(sock, text_args[1]);
263 // - "Here, have some money."
264 if( strcmp(text_args[0], "give") == 0 )
266 if( text_argc != 4 ) {
267 fprintf(stderr, "`dispense give` takes three arguments\n");
272 // text_args[1]: Destination
273 // text_args[2]: Ammount
274 // text_args[3]: Reason
277 sock = OpenConnection(gsDispenseServer, giDispensePort);
278 if( sock < 0 ) return -1;
281 if( Authenticate(sock) )
284 Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
292 // - User administration (Admin Only)
293 if( strcmp(text_args[0], "user") == 0 )
295 // Check argument count
296 if( text_argc == 1 ) {
297 fprintf(stderr, "Error: `dispense user` requires arguments\n");
303 sock = OpenConnection(gsDispenseServer, giDispensePort);
304 if( sock < 0 ) return -1;
306 // Attempt authentication
307 if( Authenticate(sock) )
311 if( strcmp(text_args[1], "add") == 0 )
313 if( text_argc != 3 ) {
314 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
319 Dispense_AddUser(sock, text_args[2]);
322 else if( strcmp(text_args[1], "type") == 0 || strcmp(text_args[1], "flags") == 0 )
324 if( text_argc != 4 ) {
325 fprintf(stderr, "Error: `dispense user flags` requires two arguments\n");
330 Dispense_SetUserType(sock, text_args[2], text_args[3]);
334 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
342 else if( strcmp(text_args[0], "donate") == 0 )
344 // Check argument count
345 if( text_argc != 3 ) {
346 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
352 sock = OpenConnection(gsDispenseServer, giDispensePort);
353 if( sock < 0 ) return -1;
355 // Attempt authentication
356 if( Authenticate(sock) )
360 Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
366 // Query an item price
367 else if( strcmp(text_args[0], "iteminfo") == 0 )
369 regmatch_t matches[3];
372 // Check argument count
373 if( text_argc != 2 ) {
374 fprintf(stderr, "Error: `dispense iteminfo` requires an argument\n");
379 if( RunRegex(&gUserItemIdentRegex, text_args[1], 3, matches, NULL) != 0 ) {
380 fprintf(stderr, "Error: Invalid item ID passed (<type>:<id> expected)\n");
383 type = text_args[1] + matches[1].rm_so;
384 text_args[1][ matches[1].rm_eo ] = '\0';
385 id = atoi( text_args[1] + matches[2].rm_so );
387 sock = OpenConnection(gsDispenseServer, giDispensePort);
388 if( sock < 0 ) return -1;
389 Dispense_ItemInfo(sock, type, id);
393 // Item name / pattern
395 gsItemPattern = text_args[0];
399 sock = OpenConnection(gsDispenseServer, giDispensePort);
400 if( sock < 0 ) return -1;
402 // Get the user's balance
403 GetUserBalance(sock);
406 PopulateItemList(sock);
408 // Disconnect from server
411 if( gsItemPattern && gsItemPattern[0] )
413 regmatch_t matches[3];
415 if( strcmp(gsItemPattern, "door") == 0 )
417 // Connect, Authenticate, dispense and close
418 sock = OpenConnection(gsDispenseServer, giDispensePort);
419 if( sock < 0 ) return -1;
421 DispenseItem(sock, "door", 0);
425 // Item id (<type>:<num>)
426 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
431 // Get and finish ident
432 ident = gsItemPattern + matches[1].rm_so;
433 gsItemPattern[matches[1].rm_eo] = '\0';
435 id = atoi( gsItemPattern + matches[2].rm_so );
437 // Connect, Authenticate, dispense and close
438 sock = OpenConnection(gsDispenseServer, giDispensePort);
439 if( sock < 0 ) return -1;
441 Dispense_ItemInfo(sock, ident, id);
444 DispenseItem(sock, ident, id);
448 // Item number (6 = coke)
449 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
451 i = atoi(gsItemPattern);
458 for( i = 0; i < giNumItems; i ++ )
460 // Prefix match (with case-insensitive match)
461 for( j = 0; gsItemPattern[j]; j ++ )
463 if( gaItems[i].Desc[j] == gsItemPattern[j] )
465 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
469 // Check if the prefix matched
470 if( gsItemPattern[j] != '\0' )
474 if( gaItems[i].Desc[j] == '\0' ) {
479 // Only one match allowed
484 // TODO: Allow ambiguous matches?
485 // or just print a wanrning
486 printf("Warning - Ambiguous pattern, stopping\n");
491 // Was a match found?
494 fprintf(stderr, "No item matches the passed string\n");
501 else if( giUIMode != UI_MODE_BASIC )
507 // Very basic dispense interface
508 for( i = 0; i < giNumItems; i ++ ) {
510 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
513 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
514 gaItems[i].Price, gaItems[i].Desc);
523 fgets(buffer, BUFSIZ, stdin);
527 if( buf[0] == 'q' ) break;
531 if( i != 0 || buf[0] == '0' )
533 if( i < 0 || i >= giNumItems ) {
534 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
543 // Check for a valid item ID
546 // Connect, Authenticate, dispense and close
547 sock = OpenConnection(gsDispenseServer, giDispensePort);
548 if( sock < 0 ) return -1;
550 Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
553 ret = DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
566 " Show interactive list\n"
567 " dispense <name>|<index>|<itemid>\n"
568 " Dispense named item (<name> matches if it is a unique prefix)\n"
569 " dispense give <user> <ammount> \"<reason>\"\n"
570 " Give money to another user\n"
571 " dispense donate <ammount> \"<reason>\"\n"
572 " Donate to the club\n"
573 " dispense iteminfo <type>:<id>\n"
574 " Get the name and price for an item\n"
575 " == Coke members == \n"
576 " dispense acct [<user>]\n"
577 " Show user balances\n"
578 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
579 " Alter a account value\n"
580 " == Dispense administrators ==\n"
581 " dispense acct <user> =<ammount> \"<reason>\"\n"
582 " Set an account balance\n"
583 " dispense user add <user>\n"
584 " Create new coke account (Admins only)\n"
585 " dispense user type <user> <flags>\n"
586 " Alter a user's flags\n"
587 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
588 " Flags are removed by preceding the name with '-' or '!'\n"
592 " Set a different user (Coke members only)\n"
596 " Use alternate GUI\n"
597 " -m <min balance>\n"
598 " -M <max balance>\n"
599 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
603 // -------------------
604 // --- NCurses GUI ---
605 // -------------------
607 * \brief Render the NCurses UI
609 int ShowNCursesUI(void)
611 // TODO: ncurses interface (with separation between item classes)
612 // - Hmm... that would require standardising the item ID to be <class>:<index>
617 const int displayMinWidth = 40;
618 char *titleString = "Dispense";
623 int ret = -2; // -2: Used for marking "no return yet"
625 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
632 if( gsEffectiveUser )
633 username = gsEffectiveUser;
635 pwd = getpwuid( getuid() );
636 username = pwd->pw_name;
639 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, giUserBalance%100);
646 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
647 // Get item count per screen
648 // - 6: randomly chosen (Need at least 3)
649 itemCount = LINES - 6;
650 if( itemCount > maxItemIndex )
651 itemCount = maxItemIndex;
654 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
659 height = itemCount + 3;
660 width = displayMinWidth;
663 xBase = COLS/2 - width/2;
664 yBase = LINES/2 - height/2;
669 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
672 for( i = 0; i < itemCount; i ++ )
676 move( yBase + 1 + i, xBase );
681 // Check for the '...' row
682 // - Oh god, magic numbers!
683 if( (i == 0 && itemBase > 0)
684 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
686 printw(" ..."); pos += 8;
687 times = (width - pos) - 1;
688 while(times--) addch(' ');
693 yBase + 1 + i, xBase + pos, // Position
694 (width - pos) - 3, // Width
695 itemBase + i, // Index
696 !!(currentItem == itemBase + i) // Hilighted
701 // Scrollbar (if needed)
702 if( maxItemIndex > itemCount ) {
706 else if( i == itemCount - 1 ) {
710 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
711 if( i-1 == percentage*(itemCount-3)/100 ) {
725 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
728 // - Username, balance, flags
729 PrintAlign(yBase+height-1, xBase+1, width-2,
730 username, ' ', balance_str, ' ', gsUserFlags);
746 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
749 if( currentItem >= maxItemIndex ) {
752 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
759 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
762 if( currentItem < 0 ) {
763 currentItem = maxItemIndex - 1;
765 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
775 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
776 itemBase = currentItem - 2;
777 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
778 itemBase = currentItem - itemCount + 2;
784 ret = ShowItemAt(0, 0, 0, currentItem, 0);
787 ret = -1; // -1: Return with no dispense
791 // Check if the return value was changed
792 if( ret != -2 ) break;
804 * \brief Show item \a Index at (\a Col, \a Row)
805 * \return Dispense index of item
806 * \note Part of the NCurses UI
808 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
818 // - This assumes that
819 case UI_MODE_STANDARD:
821 // Index = -1, request limit
822 if( Index < 0 || Index >= giNumItems+2 )
828 name = "Coke Machine";
829 Index = -1; // -1 indicates a label
836 name = gaItems[Index].Desc;
837 price = gaItems[Index].Price;
838 status = gaItems[Index].Status;
846 name = "Electronic Payment System";
847 Index = -1; // -1 indicates a label
852 name = gaItems[Index].Desc;
853 price = gaItems[Index].Price;
854 status = gaItems[Index].Status;
860 // Width = 0, don't print
867 // Show hilight and status
888 getyx(stdscr, _y, _x);
889 // Assumes max 4 digit prices
890 times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
891 while(times--) addch(' ');
893 printw(" %4i", price);
897 printw("-- %s", name);
898 getyx(stdscr, _y, _x);
899 times = Width - 4 - (_x - Col);
900 while(times--) addch(' ');
905 // If the item isn't availiable for sale, return -1 (so it's skipped)
913 * \brief Print a three-part string at the specified position (formatted)
914 * \note NCurses UI Helper
916 * Prints \a Left on the left of the area, \a Right on the righthand side
917 * and \a Mid in the middle of the area. These are padded with \a Pad1
918 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
920 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
921 * and the arguments to these are read in that order.
923 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
924 const char *Mid, char Pad2, const char *Right, ...)
926 int lLen, mLen, rLen;
931 // Get the length of the strings
932 va_start(args, Right);
933 lLen = vsnprintf(NULL, 0, Left, args);
934 mLen = vsnprintf(NULL, 0, Mid, args);
935 rLen = vsnprintf(NULL, 0, Right, args);
939 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
940 return ; // TODO: What to do?
946 va_start(args, Right);
950 vsnprintf(tmp, lLen+1, Left, args);
954 times = (Width - mLen)/2 - lLen;
955 while(times--) addch(Pad1);
959 vsnprintf(tmp, mLen+1, Mid, args);
963 times = (Width - mLen)/2 - rLen;
964 if( (Width - mLen) % 2 ) times ++;
965 while(times--) addch(Pad2);
969 vsnprintf(tmp, rLen+1, Right, args);
974 // ---------------------
975 // --- Coke Protocol ---
976 // ---------------------
977 int OpenConnection(const char *Host, int Port)
979 struct hostent *host;
980 struct sockaddr_in serverAddr;
983 host = gethostbyname(Host);
985 fprintf(stderr, "Unable to look up '%s'\n", Host);
989 memset(&serverAddr, 0, sizeof(serverAddr));
991 serverAddr.sin_family = AF_INET; // IPv4
992 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
993 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
994 serverAddr.sin_port = htons(Port);
996 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
998 fprintf(stderr, "Failed to create socket\n");
1002 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
1004 if( geteuid() == 0 || getuid() == 0 )
1007 struct sockaddr_in localAddr;
1008 memset(&localAddr, 0, sizeof(localAddr));
1009 localAddr.sin_family = AF_INET; // IPv4
1011 // Loop through all the top ports until one is avaliable
1012 for( i = 512; i < 1024; i ++)
1014 localAddr.sin_port = htons(i); // IPv4
1015 // Attempt to bind to low port for autoauth
1016 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
1020 printf("Warning: AUTOAUTH unavaliable\n");
1022 // printf("Bound to 0.0.0.0:%i\n", i);
1025 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
1026 fprintf(stderr, "Failed to connect to server\n");
1034 * \brief Authenticate with the server
1035 * \return Boolean Failure
1037 int Authenticate(int Socket)
1044 regmatch_t matches[4];
1046 if( gbIsAuthenticated ) return 0;
1049 pwd = getpwuid( getuid() );
1051 // Attempt automatic authentication
1052 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1054 // Check if it worked
1055 buf = ReadLine(Socket);
1057 responseCode = atoi(buf);
1058 switch( responseCode )
1060 case 200: // Autoauth succeeded, return
1064 case 401: // Untrusted, attempt password authentication
1067 sendf(Socket, "USER %s\n", pwd->pw_name);
1068 printf("Using username %s\n", pwd->pw_name);
1070 buf = ReadLine(Socket);
1073 // Expected format: 100 SALT <something> ...
1074 // OR : 100 User Set
1075 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1076 responseCode = atoi(buf);
1077 if( responseCode != 100 ) {
1078 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1084 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1085 // Store it for later
1086 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1087 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1091 // Give three attempts
1092 for( i = 0; i < 3; i ++ )
1094 int ofs = strlen(pwd->pw_name)+strlen(salt);
1097 char *pass = getpass("Password: ");
1100 // Create hash string
1101 // <username><salt><hash>
1102 strcpy(tmp, pwd->pw_name);
1104 SHA1( (unsigned char*)pass, strlen(pass), h );
1105 memcpy(tmp+ofs, h, 20);
1108 SHA1( (unsigned char*)tmp, ofs+20, h );
1109 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1110 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1111 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1115 sendf(Socket, "PASS %s\n", tmpBuf);
1116 buf = ReadLine(Socket);
1118 responseCode = atoi(buf);
1120 if( responseCode == 200 ) break;
1121 // Bad username/password
1122 if( responseCode == 401 ) continue;
1124 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1130 return 2; // 2 = Bad Password
1133 case 404: // Bad Username
1134 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1139 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1140 printf("%s\n", buf);
1145 // Set effective user
1146 if( gsEffectiveUser ) {
1147 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1149 buf = ReadLine(Socket);
1150 responseCode = atoi(buf);
1152 switch(responseCode)
1155 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1159 printf("Only coke members can use `dispense -u`\n");
1164 printf("Invalid user selected\n");
1169 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1170 printf("%s\n", buf);
1178 gbIsAuthenticated = 1;
1183 int GetUserBalance(int Socket)
1185 regmatch_t matches[6];
1192 if( gsEffectiveUser ) {
1193 gsUserName = gsEffectiveUser;
1196 pwd = getpwuid( getuid() );
1197 gsUserName = strdup(pwd->pw_name);
1201 sendf(Socket, "USER_INFO %s\n", gsUserName);
1202 buf = ReadLine(Socket);
1203 responseCode = atoi(buf);
1204 switch(responseCode)
1206 case 202: break; // Ok
1209 printf("Invalid user? (USER_INFO failed)\n");
1214 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1215 printf("%s\n", buf);
1220 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1222 giUserBalance = atoi( buf + matches[4].rm_so );
1223 gsUserFlags = strdup( buf + matches[5].rm_so );
1231 * \brief Read an item info response from the server
1232 * \param Dest Destination for the read item (strings will be on the heap)
1234 int ReadItemInfo(int Socket, tItem *Dest)
1239 regmatch_t matches[8];
1243 buf = ReadLine(Socket);
1244 responseCode = atoi(buf);
1246 switch(responseCode)
1251 printf("Bad item name\n");
1256 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1260 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1262 buf[ matches[3].rm_eo ] = '\0';
1263 buf[ matches[5].rm_eo ] = '\0';
1264 buf[ matches[7].rm_eo ] = '\0';
1266 statusStr = &buf[ matches[5].rm_so ];
1268 Dest->ID = atoi( buf + matches[4].rm_so );
1270 if( strcmp(statusStr, "avail") == 0 )
1272 else if( strcmp(statusStr, "sold") == 0 )
1274 else if( strcmp(statusStr, "error") == 0 )
1277 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1281 Dest->Price = atoi( buf + matches[6].rm_so );
1283 // Hack a little to reduce heap fragmentation
1285 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1286 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1287 strcpy(tmpType, buf + matches[3].rm_so);
1288 strcpy(tmpDesc, buf + matches[7].rm_so);
1290 Dest->Type = strdup( tmpType );
1291 Dest->Desc = strdup( tmpDesc );
1298 * \brief Fill the item information structure
1299 * \return Boolean Failure
1301 void PopulateItemList(int Socket)
1306 char *itemType, *itemStart;
1308 regmatch_t matches[4];
1310 // Ask server for stock list
1311 send(Socket, "ENUM_ITEMS\n", 11, 0);
1312 buf = ReadLine(Socket);
1314 //printf("Output: %s\n", buf);
1316 responseCode = atoi(buf);
1317 if( responseCode != 201 ) {
1318 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1322 // - Get item list -
1325 // 201 Items <count>
1327 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1329 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1330 count = atoi( &buf[ matches[3].rm_so ] );
1333 if( strcmp(itemType, "Items") != 0 ) {
1335 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1340 itemStart = &buf[ matches[3].rm_eo ];
1345 gaItems = malloc( giNumItems * sizeof(tItem) );
1347 // Fetch item information
1348 for( i = 0; i < giNumItems; i ++ )
1350 ReadItemInfo( Socket, &gaItems[i] );
1354 buf = ReadLine(Socket);
1355 responseCode = atoi(buf);
1357 if( responseCode != 200 ) {
1358 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1369 * \brief Get information on an item
1370 * \return Boolean Failure
1372 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1377 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1379 if( ReadItemInfo(Socket, &item) )
1384 printf("%8s:%-2i %2i.%02i %s\n",
1386 item.Price/100, item.Price%100,
1396 * \brief Dispense an item
1397 * \return Boolean Failure
1399 int DispenseItem(int Socket, const char *Type, int ID)
1401 int ret, responseCode;
1404 // Check for a dry run
1406 printf("Dry Run - No action\n");
1411 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1412 buf = ReadLine(Socket);
1414 responseCode = atoi(buf);
1415 switch( responseCode )
1418 printf("Dispense OK\n");
1422 printf("Not authenticated\n");
1426 printf("Insufficient balance\n");
1430 printf("Bad item name\n");
1434 printf("Item failed to dispense, is the slot empty?\n");
1438 printf("Dispense not possible (slot empty/permissions)\n");
1442 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1452 * \brief Alter a user's balance
1454 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1459 // Check for a dry run
1461 printf("Dry Run - No action\n");
1465 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1466 buf = ReadLine(Socket);
1468 responseCode = atoi(buf);
1471 switch(responseCode)
1473 case 200: return 0; // OK
1475 fprintf(stderr, "Insufficient balance\n");
1477 case 403: // Not in coke
1478 fprintf(stderr, "You are not in coke (sucker)\n");
1480 case 404: // Unknown user
1481 fprintf(stderr, "Unknown user '%s'\n", Username);
1484 fprintf(stderr, "Unknown response code %i\n", responseCode);
1492 * \brief Set a user's balance
1493 * \note Only avaliable to dispense admins
1495 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1500 // Check for a dry run
1502 printf("Dry Run - No action\n");
1506 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1507 buf = ReadLine(Socket);
1509 responseCode = atoi(buf);
1512 switch(responseCode)
1514 case 200: return 0; // OK
1515 case 403: // Not in coke
1516 fprintf(stderr, "You are not an admin\n");
1518 case 404: // Unknown user
1519 fprintf(stderr, "Unknown user '%s'\n", Username);
1522 fprintf(stderr, "Unknown response code %i\n", responseCode);
1530 * \brief Give money to another user
1532 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1538 printf("Sorry, you can only give, you can't take.\n");
1542 // Fast return on zero
1543 if( Ammount == 0 ) {
1544 printf("Are you actually going to give any?\n");
1548 // Check for a dry run
1550 printf("Dry Run - No action\n");
1554 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1555 buf = ReadLine(Socket);
1557 responseCode = atoi(buf);
1560 switch(responseCode)
1563 printf("Give succeeded\n");
1567 fprintf(stderr, "Insufficient balance\n");
1570 case 404: // Unknown user
1571 fprintf(stderr, "Unknown user '%s'\n", Username);
1575 fprintf(stderr, "Unknown response code %i\n", responseCode);
1584 * \brief Donate money to the club
1586 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1592 printf("Sorry, you can only give, you can't take.\n");
1596 // Fast return on zero
1597 if( Ammount == 0 ) {
1598 printf("Are you actually going to give any?\n");
1602 // Check for a dry run
1604 printf("Dry Run - No action\n");
1608 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1609 buf = ReadLine(Socket);
1611 responseCode = atoi(buf);
1614 switch(responseCode)
1616 case 200: return 0; // OK
1619 fprintf(stderr, "Insufficient balance\n");
1623 fprintf(stderr, "Unknown response code %i\n", responseCode);
1631 * \brief Enumerate users
1633 int Dispense_EnumUsers(int Socket)
1638 regmatch_t matches[4];
1640 if( giMinimumBalance != INT_MIN ) {
1641 if( giMaximumBalance != INT_MAX ) {
1642 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1645 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1649 if( giMaximumBalance != INT_MAX ) {
1650 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1653 sendf(Socket, "ENUM_USERS\n");
1656 buf = ReadLine(Socket);
1657 responseCode = atoi(buf);
1659 switch(responseCode)
1661 case 201: break; // Ok, length follows
1664 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1669 // Get count (not actually used)
1670 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1671 nUsers = atoi( buf + matches[3].rm_so );
1672 printf("%i users returned\n", nUsers);
1677 // Read returned users
1679 buf = ReadLine(Socket);
1680 responseCode = atoi(buf);
1682 if( responseCode != 202 ) break;
1684 _PrintUserLine(buf);
1686 } while(responseCode == 202);
1688 // Check final response
1689 if( responseCode != 200 ) {
1690 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1700 int Dispense_ShowUser(int Socket, const char *Username)
1703 int responseCode, ret;
1705 sendf(Socket, "USER_INFO %s\n", Username);
1706 buf = ReadLine(Socket);
1708 responseCode = atoi(buf);
1710 switch(responseCode)
1713 _PrintUserLine(buf);
1718 printf("Unknown user '%s'\n", Username);
1723 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1733 void _PrintUserLine(const char *Line)
1735 regmatch_t matches[6];
1738 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1743 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1744 char username[usernameLen + 1];
1745 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1746 char flags[flagsLen + 1];
1748 memcpy(username, Line + matches[3].rm_so, usernameLen);
1749 username[usernameLen] = '\0';
1750 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1751 flags[flagsLen] = '\0';
1753 bal = atoi(Line + matches[4].rm_so);
1754 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1758 int Dispense_AddUser(int Socket, const char *Username)
1761 int responseCode, ret;
1763 // Check for a dry run
1765 printf("Dry Run - No action\n");
1769 sendf(Socket, "USER_ADD %s\n", Username);
1771 buf = ReadLine(Socket);
1772 responseCode = atoi(buf);
1774 switch(responseCode)
1777 printf("User '%s' added\n", Username);
1782 printf("Only wheel can add users\n");
1787 printf("User '%s' already exists\n", Username);
1792 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1802 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1805 int responseCode, ret;
1807 // Check for a dry run
1809 printf("Dry Run - No action\n");
1813 // TODO: Pre-validate the string
1815 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1817 buf = ReadLine(Socket);
1818 responseCode = atoi(buf);
1820 switch(responseCode)
1823 printf("User '%s' updated\n", Username);
1828 printf("Only wheel can modify users\n");
1833 printf("User '%s' does not exist\n", Username);
1838 printf("Flag string is invalid\n");
1843 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1856 char *ReadLine(int Socket)
1858 static char buf[BUFSIZ];
1859 static int bufPos = 0;
1860 static int bufValid = 0;
1862 char *newline = NULL;
1864 char *ret = malloc(10);
1866 #if DEBUG_TRACE_SERVER
1867 printf("ReadLine: ");
1879 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1880 buf[bufPos+len] = '\0';
1883 newline = strchr( buf+bufPos, '\n' );
1888 retLen += strlen(buf+bufPos);
1889 ret = realloc(ret, retLen + 1);
1890 strcat( ret, buf+bufPos );
1893 int newLen = newline - (buf+bufPos) + 1;
1894 bufValid = len - newLen;
1897 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1900 #if DEBUG_TRACE_SERVER
1901 printf("%i '%s'\n", retLen, ret);
1907 int sendf(int Socket, const char *Format, ...)
1912 va_start(args, Format);
1913 len = vsnprintf(NULL, 0, Format, args);
1918 va_start(args, Format);
1919 vsnprintf(buf, len+1, Format, args);
1922 #if DEBUG_TRACE_SERVER
1923 printf("sendf: %s", buf);
1926 return send(Socket, buf, len, 0);
1930 char *trim(char *string)
1934 while( isspace(*string) )
1937 for( i = strlen(string); i--; )
1939 if( isspace(string[i]) )
1948 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1952 ret = regexec(regex, string, nMatches, matches, 0);
1953 if( ret && errorMessage ) {
1954 size_t len = regerror(ret, regex, NULL, 0);
1956 regerror(ret, regex, errorStr, len);
1957 printf("string = '%s'\n", string);
1958 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1965 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1967 int ret = regcomp(regex, pattern, flags);
1969 size_t len = regerror(ret, regex, NULL, 0);
1971 regerror(ret, regex, errorStr, len);
1972 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);