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 4 // 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);
226 // text_args[1]: Username
231 // Authentication required
232 if( Authenticate(sock) )
235 // text_args[1]: Username
236 // text_args[2]: Ammount
237 // text_args[3]: Reason
239 if( text_args[2][0] == '=' ) {
241 if( text_args[2][1] != '0' && atoi(text_args[2]+1) == 0 ) {
242 fprintf(stderr, "Error: Invalid balance to be set\n");
246 Dispense_SetBalance(sock, text_args[1], atoi(text_args[2]+1), text_args[3]);
250 Dispense_AlterBalance(sock, text_args[1], atoi(text_args[2]), text_args[3]);
254 // Show user information
255 Dispense_ShowUser(sock, text_args[1]);
262 // - "Here, have some money."
263 if( strcmp(text_args[0], "give") == 0 )
265 if( text_argc != 3 ) {
266 fprintf(stderr, "`dispense give` takes three arguments\n");
271 // text_args[1]: Destination
272 // text_args[2]: Ammount
273 // text_args[3]: Reason
276 sock = OpenConnection(gsDispenseServer, giDispensePort);
277 if( sock < 0 ) return -1;
280 if( Authenticate(sock) )
283 Dispense_Give(sock, text_args[1], atoi(text_args[2]), text_args[3]);
288 // - User administration (Admin Only)
289 if( strcmp(text_args[0], "user") == 0 )
291 // Check argument count
292 if( text_argc == 1 ) {
293 fprintf(stderr, "Error: `dispense user` requires arguments\n");
299 sock = OpenConnection(gsDispenseServer, giDispensePort);
300 if( sock < 0 ) return -1;
302 // Attempt authentication
303 if( Authenticate(sock) )
307 if( strcmp(text_args[1], "add") == 0 )
309 if( text_argc != 2 ) {
310 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
315 Dispense_AddUser(sock, text_args[2]);
318 else if( strcmp(text_args[1], "type") == 0 )
320 if( text_argc != 3 ) {
321 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
326 Dispense_SetUserType(sock, text_args[2], text_args[3]);
330 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
338 if( strcmp(text_args[0], "donate") == 0 )
340 // Check argument count
341 if( text_argc != 2 ) {
342 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
348 sock = OpenConnection(gsDispenseServer, giDispensePort);
349 if( sock < 0 ) return -1;
351 // Attempt authentication
352 if( Authenticate(sock) )
356 Dispense_Donate(sock, atoi(text_args[1]), text_args[2]);
361 // Item name / pattern
362 gsItemPattern = text_args[0];
366 sock = OpenConnection(gsDispenseServer, giDispensePort);
367 if( sock < 0 ) return -1;
369 // Get the user's balance
370 GetUserBalance(sock);
373 PopulateItemList(sock);
375 // Disconnect from server
378 if( gsItemPattern && gsItemPattern[0] )
380 regmatch_t matches[3];
382 if( strcmp(gsItemPattern, "door") == 0 )
384 // Connect, Authenticate, dispense and close
385 sock = OpenConnection(gsDispenseServer, giDispensePort);
386 if( sock < 0 ) return -1;
388 DispenseItem(sock, "door", 0);
392 // Item id (<type>:<num>)
393 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
398 // Get and finish ident
399 ident = gsItemPattern + matches[1].rm_so;
400 gsItemPattern[matches[1].rm_eo] = '\0';
402 id = atoi( gsItemPattern + matches[2].rm_so );
404 // Connect, Authenticate, dispense and close
405 sock = OpenConnection(gsDispenseServer, giDispensePort);
406 if( sock < 0 ) return -1;
408 Dispense_ItemInfo(sock, ident, id);
411 DispenseItem(sock, ident, id);
415 // Item number (6 = coke)
416 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
418 i = atoi(gsItemPattern);
425 for( i = 0; i < giNumItems; i ++ )
427 // Prefix match (with case-insensitive match)
428 for( j = 0; gsItemPattern[j]; j ++ )
430 if( gaItems[i].Desc[j] == gsItemPattern[j] )
432 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
436 // Check if the prefix matched
437 if( gsItemPattern[j] != '\0' )
441 if( gaItems[i].Desc[j] == '\0' ) {
446 // Only one match allowed
451 // TODO: Allow ambiguous matches?
452 // or just print a wanrning
453 printf("Warning - Ambiguous pattern, stopping\n");
458 // Was a match found?
461 fprintf(stderr, "No item matches the passed string\n");
468 else if( giUIMode != UI_MODE_BASIC )
474 // Very basic dispense interface
475 for( i = 0; i < giNumItems; i ++ ) {
477 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
480 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
481 gaItems[i].Price, gaItems[i].Desc);
490 fgets(buffer, BUFSIZ, stdin);
494 if( buf[0] == 'q' ) break;
498 if( i != 0 || buf[0] == '0' )
500 if( i < 0 || i >= giNumItems ) {
501 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
510 // Check for a valid item ID
513 // Connect, Authenticate, dispense and close
514 sock = OpenConnection(gsDispenseServer, giDispensePort);
515 if( sock < 0 ) return -1;
517 Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
520 DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
533 " Show interactive list\n"
535 " Dispense named item\n"
536 " dispense give <user> <ammount> \"<reason>\"\n"
537 " Give money to another user\n"
538 " dispense donate <ammount> \"<reason>\"\n"
539 " Donate to the club\n"
540 " == Coke members == \n"
541 " dispense acct [<user>]\n"
542 " Show user balances\n"
543 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
544 " Alter a account value\n"
545 " == Dispense administrators ==\n"
546 " dispense acct <user> =<ammount> \"<reason>\"\n"
547 " Set an account balance\n"
548 " dispense user add <user>\n"
549 " Create new coke account (Admins only)\n"
550 " dispense user type <user> <flags>\n"
551 " Alter a user's flags\n"
552 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
553 " Flags are removed by preceding the name with '-' or '!'\n"
557 " Set a different user (Coke members only)\n"
561 " Use alternate GUI\n"
562 " -m <min balance>\n"
563 " -M <max balance>\n"
564 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
568 // -------------------
569 // --- NCurses GUI ---
570 // -------------------
572 * \brief Render the NCurses UI
574 int ShowNCursesUI(void)
576 // TODO: ncurses interface (with separation between item classes)
577 // - Hmm... that would require standardising the item ID to be <class>:<index>
582 const int displayMinWidth = 40;
583 char *titleString = "Dispense";
588 int ret = -2; // -2: Used for marking "no return yet"
590 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
597 if( gsEffectiveUser )
598 username = gsEffectiveUser;
600 pwd = getpwuid( getuid() );
601 username = pwd->pw_name;
604 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, giUserBalance%100);
611 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
612 // Get item count per screen
613 // - 6: randomly chosen (Need at least 3)
614 itemCount = LINES - 6;
615 if( itemCount > maxItemIndex )
616 itemCount = maxItemIndex;
619 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
624 height = itemCount + 3;
625 width = displayMinWidth;
628 xBase = COLS/2 - width/2;
629 yBase = LINES/2 - height/2;
634 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
637 for( i = 0; i < itemCount; i ++ )
641 move( yBase + 1 + i, xBase );
646 // Check for the '...' row
647 // - Oh god, magic numbers!
648 if( (i == 0 && itemBase > 0)
649 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
651 printw(" ..."); pos += 8;
652 times = (width - pos) - 1;
653 while(times--) addch(' ');
658 yBase + 1 + i, xBase + pos, // Position
659 (width - pos) - 3, // Width
660 itemBase + i, // Index
661 !!(currentItem == itemBase + i) // Hilighted
666 // Scrollbar (if needed)
667 if( maxItemIndex > itemCount ) {
671 else if( i == itemCount - 1 ) {
675 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
676 if( i-1 == percentage*(itemCount-3)/100 ) {
690 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
693 // - Username, balance, flags
694 PrintAlign(yBase+height-1, xBase+1, width-2,
695 username, ' ', balance_str, ' ', gsUserFlags);
711 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
714 if( currentItem >= maxItemIndex ) {
717 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
724 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
727 if( currentItem < 0 ) {
728 currentItem = maxItemIndex - 1;
730 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
740 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
741 itemBase = currentItem - 2;
742 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
743 itemBase = currentItem - itemCount + 2;
749 ret = ShowItemAt(0, 0, 0, currentItem, 0);
752 ret = -1; // -1: Return with no dispense
756 // Check if the return value was changed
757 if( ret != -2 ) break;
769 * \brief Show item \a Index at (\a Col, \a Row)
770 * \return Dispense index of item
771 * \note Part of the NCurses UI
773 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
783 // - This assumes that
784 case UI_MODE_STANDARD:
786 // Index = -1, request limit
787 if( Index < 0 || Index >= giNumItems+2 )
793 name = "Coke Machine";
794 Index = -1; // -1 indicates a label
801 name = gaItems[Index].Desc;
802 price = gaItems[Index].Price;
803 status = gaItems[Index].Status;
811 name = "Electronic Payment System";
812 Index = -1; // -1 indicates a label
817 name = gaItems[Index].Desc;
818 price = gaItems[Index].Price;
819 status = gaItems[Index].Status;
825 // Width = 0, don't print
832 // Show hilight and status
853 getyx(stdscr, _y, _x);
854 // Assumes max 4 digit prices
855 times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
856 while(times--) addch(' ');
858 printw(" %4i", price);
862 printw("-- %s", name);
863 getyx(stdscr, _y, _x);
864 times = Width - 4 - (_x - Col);
865 while(times--) addch(' ');
870 // If the item isn't availiable for sale, return -1 (so it's skipped)
878 * \brief Print a three-part string at the specified position (formatted)
879 * \note NCurses UI Helper
881 * Prints \a Left on the left of the area, \a Right on the righthand side
882 * and \a Mid in the middle of the area. These are padded with \a Pad1
883 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
885 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
886 * and the arguments to these are read in that order.
888 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
889 const char *Mid, char Pad2, const char *Right, ...)
891 int lLen, mLen, rLen;
896 // Get the length of the strings
897 va_start(args, Right);
898 lLen = vsnprintf(NULL, 0, Left, args);
899 mLen = vsnprintf(NULL, 0, Mid, args);
900 rLen = vsnprintf(NULL, 0, Right, args);
904 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
905 return ; // TODO: What to do?
911 va_start(args, Right);
915 vsnprintf(tmp, lLen+1, Left, args);
919 times = (Width - mLen)/2 - lLen;
920 while(times--) addch(Pad1);
924 vsnprintf(tmp, mLen+1, Mid, args);
928 times = (Width - mLen)/2 - rLen;
929 if( (Width - mLen) % 2 ) times ++;
930 while(times--) addch(Pad2);
934 vsnprintf(tmp, rLen+1, Right, args);
939 // ---------------------
940 // --- Coke Protocol ---
941 // ---------------------
942 int OpenConnection(const char *Host, int Port)
944 struct hostent *host;
945 struct sockaddr_in serverAddr;
948 host = gethostbyname(Host);
950 fprintf(stderr, "Unable to look up '%s'\n", Host);
954 memset(&serverAddr, 0, sizeof(serverAddr));
956 serverAddr.sin_family = AF_INET; // IPv4
957 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
958 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
959 serverAddr.sin_port = htons(Port);
961 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
963 fprintf(stderr, "Failed to create socket\n");
970 struct sockaddr_in localAddr;
971 memset(&localAddr, 0, sizeof(localAddr));
972 localAddr.sin_family = AF_INET; // IPv4
974 // Loop through all the top ports until one is avaliable
975 for( i = 1001; i < 1024; i ++)
977 localAddr.sin_port = htons(i); // IPv4
978 // Attempt to bind to low port for autoauth
979 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
983 printf("Warning: AUTOAUTH unavaliable\n");
986 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
987 fprintf(stderr, "Failed to connect to server\n");
995 * \brief Authenticate with the server
996 * \return Boolean Failure
998 int Authenticate(int Socket)
1005 regmatch_t matches[4];
1007 if( gbIsAuthenticated ) return 0;
1010 pwd = getpwuid( getuid() );
1012 // Attempt automatic authentication
1013 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1015 // Check if it worked
1016 buf = ReadLine(Socket);
1018 responseCode = atoi(buf);
1019 switch( responseCode )
1021 case 200: // Autoauth succeeded, return
1025 case 401: // Untrusted, attempt password authentication
1028 sendf(Socket, "USER %s\n", pwd->pw_name);
1029 printf("Using username %s\n", pwd->pw_name);
1031 buf = ReadLine(Socket);
1034 // Expected format: 100 SALT <something> ...
1035 // OR : 100 User Set
1036 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1037 responseCode = atoi(buf);
1038 if( responseCode != 100 ) {
1039 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1045 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1046 // Store it for later
1047 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1048 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1052 // Give three attempts
1053 for( i = 0; i < 3; i ++ )
1055 int ofs = strlen(pwd->pw_name)+strlen(salt);
1058 char *pass = getpass("Password: ");
1061 // Create hash string
1062 // <username><salt><hash>
1063 strcpy(tmp, pwd->pw_name);
1065 SHA1( (unsigned char*)pass, strlen(pass), h );
1066 memcpy(tmp+ofs, h, 20);
1069 SHA1( (unsigned char*)tmp, ofs+20, h );
1070 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1071 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1072 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1076 sendf(Socket, "PASS %s\n", tmpBuf);
1077 buf = ReadLine(Socket);
1079 responseCode = atoi(buf);
1081 if( responseCode == 200 ) break;
1082 // Bad username/password
1083 if( responseCode == 401 ) continue;
1085 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1091 return 2; // 2 = Bad Password
1094 case 404: // Bad Username
1095 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1100 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1101 printf("%s\n", buf);
1106 // Set effective user
1107 if( gsEffectiveUser ) {
1108 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1110 buf = ReadLine(Socket);
1111 responseCode = atoi(buf);
1113 switch(responseCode)
1116 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1120 printf("Only coke members can use `dispense -u`\n");
1125 printf("Invalid user selected\n");
1130 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1131 printf("%s\n", buf);
1139 gbIsAuthenticated = 1;
1144 int GetUserBalance(int Socket)
1146 regmatch_t matches[6];
1153 if( gsEffectiveUser ) {
1154 gsUserName = gsEffectiveUser;
1157 pwd = getpwuid( getuid() );
1158 gsUserName = strdup(pwd->pw_name);
1162 sendf(Socket, "USER_INFO %s\n", gsUserName);
1163 buf = ReadLine(Socket);
1164 responseCode = atoi(buf);
1165 switch(responseCode)
1167 case 202: break; // Ok
1170 printf("Invalid user? (USER_INFO failed)\n");
1175 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1176 printf("%s\n", buf);
1181 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1183 giUserBalance = atoi( buf + matches[4].rm_so );
1184 gsUserFlags = strdup( buf + matches[5].rm_so );
1192 * \brief Read an item info response from the server
1193 * \param Dest Destination for the read item (strings will be on the heap)
1195 int ReadItemInfo(int Socket, tItem *Dest)
1200 regmatch_t matches[8];
1204 buf = ReadLine(Socket);
1205 responseCode = atoi(buf);
1207 switch(responseCode)
1212 printf("Bad item name\n");
1217 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1221 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1223 buf[ matches[3].rm_eo ] = '\0';
1224 buf[ matches[5].rm_eo ] = '\0';
1225 buf[ matches[7].rm_eo ] = '\0';
1227 statusStr = &buf[ matches[5].rm_so ];
1229 Dest->ID = atoi( buf + matches[4].rm_so );
1231 if( strcmp(statusStr, "avail") == 0 )
1233 else if( strcmp(statusStr, "sold") == 0 )
1235 else if( strcmp(statusStr, "error") == 0 )
1238 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1242 Dest->Price = atoi( buf + matches[6].rm_so );
1244 // Hack a little to reduce heap fragmentation
1246 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1247 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1248 strcpy(tmpType, buf + matches[3].rm_so);
1249 strcpy(tmpDesc, buf + matches[7].rm_so);
1251 Dest->Type = strdup( tmpType );
1252 Dest->Desc = strdup( tmpDesc );
1259 * \brief Fill the item information structure
1260 * \return Boolean Failure
1262 void PopulateItemList(int Socket)
1267 char *itemType, *itemStart;
1269 regmatch_t matches[4];
1271 // Ask server for stock list
1272 send(Socket, "ENUM_ITEMS\n", 11, 0);
1273 buf = ReadLine(Socket);
1275 //printf("Output: %s\n", buf);
1277 responseCode = atoi(buf);
1278 if( responseCode != 201 ) {
1279 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1283 // - Get item list -
1286 // 201 Items <count>
1288 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1290 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1291 count = atoi( &buf[ matches[3].rm_so ] );
1294 if( strcmp(itemType, "Items") != 0 ) {
1296 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1301 itemStart = &buf[ matches[3].rm_eo ];
1306 gaItems = malloc( giNumItems * sizeof(tItem) );
1308 // Fetch item information
1309 for( i = 0; i < giNumItems; i ++ )
1311 ReadItemInfo( Socket, &gaItems[i] );
1315 buf = ReadLine(Socket);
1316 responseCode = atoi(buf);
1318 if( responseCode != 200 ) {
1319 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1330 * \brief Get information on an item
1331 * \return Boolean Failure
1333 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1338 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1340 if( ReadItemInfo(Socket, &item) )
1345 printf("%8s:%-2i %2i.%02i %s\n",
1347 item.Price/100, item.Price%100,
1357 * \brief Dispense an item
1358 * \return Boolean Failure
1360 int DispenseItem(int Socket, const char *Type, int ID)
1362 int ret, responseCode;
1365 // Check for a dry run
1367 printf("Dry Run - No action\n");
1372 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1373 buf = ReadLine(Socket);
1375 responseCode = atoi(buf);
1376 switch( responseCode )
1379 printf("Dispense OK\n");
1383 printf("Not authenticated\n");
1387 printf("Insufficient balance\n");
1391 printf("Bad item name\n");
1395 printf("Item failed to dispense, is the slot empty?\n");
1399 printf("Dispense not possible (slot empty/permissions)\n");
1403 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1413 * \brief Alter a user's balance
1415 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1420 // Check for a dry run
1422 printf("Dry Run - No action\n");
1426 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1427 buf = ReadLine(Socket);
1429 responseCode = atoi(buf);
1432 switch(responseCode)
1434 case 200: return 0; // OK
1436 fprintf(stderr, "Insufficient balance\n");
1438 case 403: // Not in coke
1439 fprintf(stderr, "You are not in coke (sucker)\n");
1441 case 404: // Unknown user
1442 fprintf(stderr, "Unknown user '%s'\n", Username);
1445 fprintf(stderr, "Unknown response code %i\n", responseCode);
1453 * \brief Set a user's balance
1454 * \note Only avaliable to dispense admins
1456 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1461 // Check for a dry run
1463 printf("Dry Run - No action\n");
1467 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1468 buf = ReadLine(Socket);
1470 responseCode = atoi(buf);
1473 switch(responseCode)
1475 case 200: return 0; // OK
1476 case 403: // Not in coke
1477 fprintf(stderr, "You are not an admin\n");
1479 case 404: // Unknown user
1480 fprintf(stderr, "Unknown user '%s'\n", Username);
1483 fprintf(stderr, "Unknown response code %i\n", responseCode);
1491 * \brief Give money to another user
1493 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1499 printf("Sorry, you can only give, you can't take.\n");
1503 // Fast return on zero
1504 if( Ammount == 0 ) {
1505 printf("Are you actually going to give any?\n");
1509 // Check for a dry run
1511 printf("Dry Run - No action\n");
1515 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1516 buf = ReadLine(Socket);
1518 responseCode = atoi(buf);
1521 switch(responseCode)
1523 case 200: return 0; // OK
1526 fprintf(stderr, "Insufficient balance\n");
1529 case 404: // Unknown user
1530 fprintf(stderr, "Unknown user '%s'\n", Username);
1534 fprintf(stderr, "Unknown response code %i\n", responseCode);
1543 * \brief Donate money to the club
1545 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1551 printf("Sorry, you can only give, you can't take.\n");
1555 // Fast return on zero
1556 if( Ammount == 0 ) {
1557 printf("Are you actually going to give any?\n");
1561 // Check for a dry run
1563 printf("Dry Run - No action\n");
1567 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1568 buf = ReadLine(Socket);
1570 responseCode = atoi(buf);
1573 switch(responseCode)
1575 case 200: return 0; // OK
1578 fprintf(stderr, "Insufficient balance\n");
1582 fprintf(stderr, "Unknown response code %i\n", responseCode);
1590 * \brief Enumerate users
1592 int Dispense_EnumUsers(int Socket)
1597 regmatch_t matches[4];
1599 if( giMinimumBalance != INT_MIN ) {
1600 if( giMaximumBalance != INT_MAX ) {
1601 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1604 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1608 if( giMaximumBalance != INT_MAX ) {
1609 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1612 sendf(Socket, "ENUM_USERS\n");
1615 buf = ReadLine(Socket);
1616 responseCode = atoi(buf);
1618 switch(responseCode)
1620 case 201: break; // Ok, length follows
1623 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1628 // Get count (not actually used)
1629 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1630 nUsers = atoi( buf + matches[3].rm_so );
1631 printf("%i users returned\n", nUsers);
1636 // Read returned users
1638 buf = ReadLine(Socket);
1639 responseCode = atoi(buf);
1641 if( responseCode != 202 ) break;
1643 _PrintUserLine(buf);
1645 } while(responseCode == 202);
1647 // Check final response
1648 if( responseCode != 200 ) {
1649 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1659 int Dispense_ShowUser(int Socket, const char *Username)
1662 int responseCode, ret;
1664 sendf(Socket, "USER_INFO %s\n", Username);
1665 buf = ReadLine(Socket);
1667 responseCode = atoi(buf);
1669 switch(responseCode)
1672 _PrintUserLine(buf);
1677 printf("Unknown user '%s'\n", Username);
1682 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1692 void _PrintUserLine(const char *Line)
1694 regmatch_t matches[6];
1697 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1702 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1703 char username[usernameLen + 1];
1704 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1705 char flags[flagsLen + 1];
1707 memcpy(username, Line + matches[3].rm_so, usernameLen);
1708 username[usernameLen] = '\0';
1709 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1710 flags[flagsLen] = '\0';
1712 bal = atoi(Line + matches[4].rm_so);
1713 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1717 int Dispense_AddUser(int Socket, const char *Username)
1720 int responseCode, ret;
1722 // Check for a dry run
1724 printf("Dry Run - No action\n");
1728 sendf(Socket, "USER_ADD %s\n", Username);
1730 buf = ReadLine(Socket);
1731 responseCode = atoi(buf);
1733 switch(responseCode)
1736 printf("User '%s' added\n", Username);
1741 printf("Only wheel can add users\n");
1746 printf("User '%s' already exists\n", Username);
1751 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1761 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1764 int responseCode, ret;
1766 // Check for a dry run
1768 printf("Dry Run - No action\n");
1772 // TODO: Pre-validate the string
1774 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1776 buf = ReadLine(Socket);
1777 responseCode = atoi(buf);
1779 switch(responseCode)
1782 printf("User '%s' updated\n", Username);
1787 printf("Only wheel can modify users\n");
1792 printf("User '%s' does not exist\n", Username);
1797 printf("Flag string is invalid\n");
1802 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1815 char *ReadLine(int Socket)
1817 static char buf[BUFSIZ];
1818 static int bufPos = 0;
1819 static int bufValid = 0;
1821 char *newline = NULL;
1823 char *ret = malloc(10);
1825 #if DEBUG_TRACE_SERVER
1826 printf("ReadLine: ");
1838 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1839 buf[bufPos+len] = '\0';
1842 newline = strchr( buf+bufPos, '\n' );
1847 retLen += strlen(buf+bufPos);
1848 ret = realloc(ret, retLen + 1);
1849 strcat( ret, buf+bufPos );
1852 int newLen = newline - (buf+bufPos) + 1;
1853 bufValid = len - newLen;
1856 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1859 #if DEBUG_TRACE_SERVER
1860 printf("%i '%s'\n", retLen, ret);
1866 int sendf(int Socket, const char *Format, ...)
1871 va_start(args, Format);
1872 len = vsnprintf(NULL, 0, Format, args);
1877 va_start(args, Format);
1878 vsnprintf(buf, len+1, Format, args);
1881 #if DEBUG_TRACE_SERVER
1882 printf("sendf: %s", buf);
1885 return send(Socket, buf, len, 0);
1889 char *trim(char *string)
1893 while( isspace(*string) )
1896 for( i = strlen(string); i--; )
1898 if( isspace(string[i]) )
1907 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1911 ret = regexec(regex, string, nMatches, matches, 0);
1912 if( ret && errorMessage ) {
1913 size_t len = regerror(ret, regex, NULL, 0);
1915 regerror(ret, regex, errorStr, len);
1916 printf("string = '%s'\n", string);
1917 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1924 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1926 int ret = regcomp(regex, pattern, flags);
1928 size_t len = regerror(ret, regex, NULL, 0);
1930 regerror(ret, regex, errorStr, len);
1931 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);