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);
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 != 4 ) {
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 != 3 ) {
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 != 4 ) {
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 != 3 ) {
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 ret = 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");
967 // printf("geteuid() = %i, getuid() = %i\n", geteuid(), getuid());
969 if( geteuid() == 0 || getuid() == 0 )
972 struct sockaddr_in localAddr;
973 memset(&localAddr, 0, sizeof(localAddr));
974 localAddr.sin_family = AF_INET; // IPv4
976 // Loop through all the top ports until one is avaliable
977 for( i = 512; i < 1024; i ++)
979 localAddr.sin_port = htons(i); // IPv4
980 // Attempt to bind to low port for autoauth
981 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
985 printf("Warning: AUTOAUTH unavaliable\n");
987 // printf("Bound to 0.0.0.0:%i\n", i);
990 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
991 fprintf(stderr, "Failed to connect to server\n");
999 * \brief Authenticate with the server
1000 * \return Boolean Failure
1002 int Authenticate(int Socket)
1009 regmatch_t matches[4];
1011 if( gbIsAuthenticated ) return 0;
1014 pwd = getpwuid( getuid() );
1016 // Attempt automatic authentication
1017 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
1019 // Check if it worked
1020 buf = ReadLine(Socket);
1022 responseCode = atoi(buf);
1023 switch( responseCode )
1025 case 200: // Autoauth succeeded, return
1029 case 401: // Untrusted, attempt password authentication
1032 sendf(Socket, "USER %s\n", pwd->pw_name);
1033 printf("Using username %s\n", pwd->pw_name);
1035 buf = ReadLine(Socket);
1038 // Expected format: 100 SALT <something> ...
1039 // OR : 100 User Set
1040 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1041 responseCode = atoi(buf);
1042 if( responseCode != 100 ) {
1043 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1049 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1050 // Store it for later
1051 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1052 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1056 // Give three attempts
1057 for( i = 0; i < 3; i ++ )
1059 int ofs = strlen(pwd->pw_name)+strlen(salt);
1062 char *pass = getpass("Password: ");
1065 // Create hash string
1066 // <username><salt><hash>
1067 strcpy(tmp, pwd->pw_name);
1069 SHA1( (unsigned char*)pass, strlen(pass), h );
1070 memcpy(tmp+ofs, h, 20);
1073 SHA1( (unsigned char*)tmp, ofs+20, h );
1074 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1075 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1076 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1080 sendf(Socket, "PASS %s\n", tmpBuf);
1081 buf = ReadLine(Socket);
1083 responseCode = atoi(buf);
1085 if( responseCode == 200 ) break;
1086 // Bad username/password
1087 if( responseCode == 401 ) continue;
1089 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1095 return 2; // 2 = Bad Password
1098 case 404: // Bad Username
1099 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1104 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1105 printf("%s\n", buf);
1110 // Set effective user
1111 if( gsEffectiveUser ) {
1112 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1114 buf = ReadLine(Socket);
1115 responseCode = atoi(buf);
1117 switch(responseCode)
1120 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1124 printf("Only coke members can use `dispense -u`\n");
1129 printf("Invalid user selected\n");
1134 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1135 printf("%s\n", buf);
1143 gbIsAuthenticated = 1;
1148 int GetUserBalance(int Socket)
1150 regmatch_t matches[6];
1157 if( gsEffectiveUser ) {
1158 gsUserName = gsEffectiveUser;
1161 pwd = getpwuid( getuid() );
1162 gsUserName = strdup(pwd->pw_name);
1166 sendf(Socket, "USER_INFO %s\n", gsUserName);
1167 buf = ReadLine(Socket);
1168 responseCode = atoi(buf);
1169 switch(responseCode)
1171 case 202: break; // Ok
1174 printf("Invalid user? (USER_INFO failed)\n");
1179 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1180 printf("%s\n", buf);
1185 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1187 giUserBalance = atoi( buf + matches[4].rm_so );
1188 gsUserFlags = strdup( buf + matches[5].rm_so );
1196 * \brief Read an item info response from the server
1197 * \param Dest Destination for the read item (strings will be on the heap)
1199 int ReadItemInfo(int Socket, tItem *Dest)
1204 regmatch_t matches[8];
1208 buf = ReadLine(Socket);
1209 responseCode = atoi(buf);
1211 switch(responseCode)
1216 printf("Bad item name\n");
1221 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1225 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1227 buf[ matches[3].rm_eo ] = '\0';
1228 buf[ matches[5].rm_eo ] = '\0';
1229 buf[ matches[7].rm_eo ] = '\0';
1231 statusStr = &buf[ matches[5].rm_so ];
1233 Dest->ID = atoi( buf + matches[4].rm_so );
1235 if( strcmp(statusStr, "avail") == 0 )
1237 else if( strcmp(statusStr, "sold") == 0 )
1239 else if( strcmp(statusStr, "error") == 0 )
1242 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1246 Dest->Price = atoi( buf + matches[6].rm_so );
1248 // Hack a little to reduce heap fragmentation
1250 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1251 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1252 strcpy(tmpType, buf + matches[3].rm_so);
1253 strcpy(tmpDesc, buf + matches[7].rm_so);
1255 Dest->Type = strdup( tmpType );
1256 Dest->Desc = strdup( tmpDesc );
1263 * \brief Fill the item information structure
1264 * \return Boolean Failure
1266 void PopulateItemList(int Socket)
1271 char *itemType, *itemStart;
1273 regmatch_t matches[4];
1275 // Ask server for stock list
1276 send(Socket, "ENUM_ITEMS\n", 11, 0);
1277 buf = ReadLine(Socket);
1279 //printf("Output: %s\n", buf);
1281 responseCode = atoi(buf);
1282 if( responseCode != 201 ) {
1283 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1287 // - Get item list -
1290 // 201 Items <count>
1292 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1294 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1295 count = atoi( &buf[ matches[3].rm_so ] );
1298 if( strcmp(itemType, "Items") != 0 ) {
1300 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1305 itemStart = &buf[ matches[3].rm_eo ];
1310 gaItems = malloc( giNumItems * sizeof(tItem) );
1312 // Fetch item information
1313 for( i = 0; i < giNumItems; i ++ )
1315 ReadItemInfo( Socket, &gaItems[i] );
1319 buf = ReadLine(Socket);
1320 responseCode = atoi(buf);
1322 if( responseCode != 200 ) {
1323 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1334 * \brief Get information on an item
1335 * \return Boolean Failure
1337 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1342 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1344 if( ReadItemInfo(Socket, &item) )
1349 printf("%8s:%-2i %2i.%02i %s\n",
1351 item.Price/100, item.Price%100,
1361 * \brief Dispense an item
1362 * \return Boolean Failure
1364 int DispenseItem(int Socket, const char *Type, int ID)
1366 int ret, responseCode;
1369 // Check for a dry run
1371 printf("Dry Run - No action\n");
1376 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1377 buf = ReadLine(Socket);
1379 responseCode = atoi(buf);
1380 switch( responseCode )
1383 printf("Dispense OK\n");
1387 printf("Not authenticated\n");
1391 printf("Insufficient balance\n");
1395 printf("Bad item name\n");
1399 printf("Item failed to dispense, is the slot empty?\n");
1403 printf("Dispense not possible (slot empty/permissions)\n");
1407 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1417 * \brief Alter a user's balance
1419 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1424 // Check for a dry run
1426 printf("Dry Run - No action\n");
1430 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1431 buf = ReadLine(Socket);
1433 responseCode = atoi(buf);
1436 switch(responseCode)
1438 case 200: return 0; // OK
1440 fprintf(stderr, "Insufficient balance\n");
1442 case 403: // Not in coke
1443 fprintf(stderr, "You are not in coke (sucker)\n");
1445 case 404: // Unknown user
1446 fprintf(stderr, "Unknown user '%s'\n", Username);
1449 fprintf(stderr, "Unknown response code %i\n", responseCode);
1457 * \brief Set a user's balance
1458 * \note Only avaliable to dispense admins
1460 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1465 // Check for a dry run
1467 printf("Dry Run - No action\n");
1471 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1472 buf = ReadLine(Socket);
1474 responseCode = atoi(buf);
1477 switch(responseCode)
1479 case 200: return 0; // OK
1480 case 403: // Not in coke
1481 fprintf(stderr, "You are not an admin\n");
1483 case 404: // Unknown user
1484 fprintf(stderr, "Unknown user '%s'\n", Username);
1487 fprintf(stderr, "Unknown response code %i\n", responseCode);
1495 * \brief Give money to another user
1497 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1503 printf("Sorry, you can only give, you can't take.\n");
1507 // Fast return on zero
1508 if( Ammount == 0 ) {
1509 printf("Are you actually going to give any?\n");
1513 // Check for a dry run
1515 printf("Dry Run - No action\n");
1519 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1520 buf = ReadLine(Socket);
1522 responseCode = atoi(buf);
1525 switch(responseCode)
1527 case 200: return 0; // OK
1530 fprintf(stderr, "Insufficient balance\n");
1533 case 404: // Unknown user
1534 fprintf(stderr, "Unknown user '%s'\n", Username);
1538 fprintf(stderr, "Unknown response code %i\n", responseCode);
1547 * \brief Donate money to the club
1549 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1555 printf("Sorry, you can only give, you can't take.\n");
1559 // Fast return on zero
1560 if( Ammount == 0 ) {
1561 printf("Are you actually going to give any?\n");
1565 // Check for a dry run
1567 printf("Dry Run - No action\n");
1571 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1572 buf = ReadLine(Socket);
1574 responseCode = atoi(buf);
1577 switch(responseCode)
1579 case 200: return 0; // OK
1582 fprintf(stderr, "Insufficient balance\n");
1586 fprintf(stderr, "Unknown response code %i\n", responseCode);
1594 * \brief Enumerate users
1596 int Dispense_EnumUsers(int Socket)
1601 regmatch_t matches[4];
1603 if( giMinimumBalance != INT_MIN ) {
1604 if( giMaximumBalance != INT_MAX ) {
1605 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1608 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1612 if( giMaximumBalance != INT_MAX ) {
1613 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1616 sendf(Socket, "ENUM_USERS\n");
1619 buf = ReadLine(Socket);
1620 responseCode = atoi(buf);
1622 switch(responseCode)
1624 case 201: break; // Ok, length follows
1627 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1632 // Get count (not actually used)
1633 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1634 nUsers = atoi( buf + matches[3].rm_so );
1635 printf("%i users returned\n", nUsers);
1640 // Read returned users
1642 buf = ReadLine(Socket);
1643 responseCode = atoi(buf);
1645 if( responseCode != 202 ) break;
1647 _PrintUserLine(buf);
1649 } while(responseCode == 202);
1651 // Check final response
1652 if( responseCode != 200 ) {
1653 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1663 int Dispense_ShowUser(int Socket, const char *Username)
1666 int responseCode, ret;
1668 sendf(Socket, "USER_INFO %s\n", Username);
1669 buf = ReadLine(Socket);
1671 responseCode = atoi(buf);
1673 switch(responseCode)
1676 _PrintUserLine(buf);
1681 printf("Unknown user '%s'\n", Username);
1686 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1696 void _PrintUserLine(const char *Line)
1698 regmatch_t matches[6];
1701 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1706 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1707 char username[usernameLen + 1];
1708 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1709 char flags[flagsLen + 1];
1711 memcpy(username, Line + matches[3].rm_so, usernameLen);
1712 username[usernameLen] = '\0';
1713 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1714 flags[flagsLen] = '\0';
1716 bal = atoi(Line + matches[4].rm_so);
1717 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1721 int Dispense_AddUser(int Socket, const char *Username)
1724 int responseCode, ret;
1726 // Check for a dry run
1728 printf("Dry Run - No action\n");
1732 sendf(Socket, "USER_ADD %s\n", Username);
1734 buf = ReadLine(Socket);
1735 responseCode = atoi(buf);
1737 switch(responseCode)
1740 printf("User '%s' added\n", Username);
1745 printf("Only wheel can add users\n");
1750 printf("User '%s' already exists\n", Username);
1755 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1765 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1768 int responseCode, ret;
1770 // Check for a dry run
1772 printf("Dry Run - No action\n");
1776 // TODO: Pre-validate the string
1778 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1780 buf = ReadLine(Socket);
1781 responseCode = atoi(buf);
1783 switch(responseCode)
1786 printf("User '%s' updated\n", Username);
1791 printf("Only wheel can modify users\n");
1796 printf("User '%s' does not exist\n", Username);
1801 printf("Flag string is invalid\n");
1806 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1819 char *ReadLine(int Socket)
1821 static char buf[BUFSIZ];
1822 static int bufPos = 0;
1823 static int bufValid = 0;
1825 char *newline = NULL;
1827 char *ret = malloc(10);
1829 #if DEBUG_TRACE_SERVER
1830 printf("ReadLine: ");
1842 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1843 buf[bufPos+len] = '\0';
1846 newline = strchr( buf+bufPos, '\n' );
1851 retLen += strlen(buf+bufPos);
1852 ret = realloc(ret, retLen + 1);
1853 strcat( ret, buf+bufPos );
1856 int newLen = newline - (buf+bufPos) + 1;
1857 bufValid = len - newLen;
1860 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1863 #if DEBUG_TRACE_SERVER
1864 printf("%i '%s'\n", retLen, ret);
1870 int sendf(int Socket, const char *Format, ...)
1875 va_start(args, Format);
1876 len = vsnprintf(NULL, 0, Format, args);
1881 va_start(args, Format);
1882 vsnprintf(buf, len+1, Format, args);
1885 #if DEBUG_TRACE_SERVER
1886 printf("sendf: %s", buf);
1889 return send(Socket, buf, len, 0);
1893 char *trim(char *string)
1897 while( isspace(*string) )
1900 for( i = strlen(string); i--; )
1902 if( isspace(string[i]) )
1911 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1915 ret = regexec(regex, string, nMatches, matches, 0);
1916 if( ret && errorMessage ) {
1917 size_t len = regerror(ret, regex, NULL, 0);
1919 regerror(ret, regex, errorStr, len);
1920 printf("string = '%s'\n", string);
1921 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1928 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1930 int ret = regcomp(regex, pattern, flags);
1932 size_t len = regerror(ret, regex, NULL, 0);
1934 regerror(ret, regex, errorStr, len);
1935 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);