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
34 UI_MODE_BASIC, // Non-NCurses
42 typedef struct sItem {
50 int main(int argc, char *argv[]);
53 int ShowNCursesUI(void);
54 int ShowItemAt(int Row, int Col, int Width, int Index);
55 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
56 // --- Coke Server Communication ---
57 int OpenConnection(const char *Host, int Port);
58 int Authenticate(int Socket);
59 int GetUserBalance(int Socket);
60 void PopulateItemList(int Socket);
61 int Dispense_ItemInfo(int Socket, const char *Type, int ID);
62 int DispenseItem(int Socket, const char *Type, int ID);
63 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
64 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
65 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
66 int Dispense_Donate(int Socket, int Ammount, const char *Reason);
67 int Dispense_EnumUsers(int Socket);
68 int Dispense_ShowUser(int Socket, const char *Username);
69 void _PrintUserLine(const char *Line);
70 int Dispense_AddUser(int Socket, const char *Username);
71 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
73 char *ReadLine(int Socket);
74 int sendf(int Socket, const char *Format, ...);
75 char *trim(char *string);
76 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
77 void CompileRegex(regex_t *regex, const char *pattern, int flags);
80 char *gsDispenseServer = "heathred";
81 int giDispensePort = 11020;
85 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
86 int gbIsAuthenticated = 0;
88 char *gsItemPattern; //!< Item pattern
89 char *gsEffectiveUser; //!< '-u' Dispense as another user
90 int giUIMode = UI_MODE_STANDARD;
91 int gbDryRun = 0; //!< '-n' Read-only
92 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
93 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
94 char *gsUserName; //!< User that dispense will happen as
95 char *gsUserFlags; //!< User's flag set
96 int giUserBalance=-1; //!< User balance (set by Authenticate)
99 int main(int argc, char *argv[])
105 // -- Create regular expressions
106 // > Code Type Count ...
107 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
108 // > Code Type Ident Price Desc
109 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z]+):([0-9]+)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
110 // > Code 'SALT' salt
111 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
112 // > Code 'User' Username Balance Flags
113 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
115 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
118 for( i = 1; i < argc; i ++ )
131 case 'm': // Minimum balance
132 if( i + 1 >= argc ) {
133 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
136 giMinimumBalance = atoi(argv[++i]);
138 case 'M': // Maximum balance
139 if( i + 1 >= argc ) {
140 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
143 giMaximumBalance = atoi(argv[++i]);
146 case 'u': // Override User
147 if( i + 1 >= argc ) {
148 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
151 gsEffectiveUser = argv[++i];
154 case 'H': // Override remote host
155 if( i + 1 >= argc ) {
156 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
159 gsDispenseServer = argv[++i];
161 case 'P': // Override remote port
162 if( i + 1 >= argc ) {
163 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
166 giDispensePort = atoi(argv[++i]);
169 case 'G': // Don't use GUI
170 giUIMode = UI_MODE_BASIC;
172 case 'D': // Drinks only
173 giUIMode = UI_MODE_DRINKSONLY;
175 case 'n': // Dry Run / read-only
186 if( strcmp(arg, "acct") == 0 )
189 sock = OpenConnection(gsDispenseServer, giDispensePort);
190 if( sock < 0 ) return -1;
193 if( i + 1 == argc ) {
194 Dispense_EnumUsers(sock);
198 // argv[i+1]: Username
203 if( i + 3 >= argc ) {
204 fprintf(stderr, "Error: `dispense acct' needs a reason\n");
208 // Authentication required
209 if( Authenticate(sock) )
212 // argv[i+1]: Username
213 // argv[i+2]: Ammount
216 if( argv[i+2][0] == '=' ) {
218 if( argv[i+2][1] != '0' && atoi(&argv[i+2][1]) == 0 ) {
219 fprintf(stderr, "Error: Invalid balance to be set\n");
223 Dispense_SetBalance(sock, argv[i+1], atoi(argv[i+2]+1), argv[i+3]);
227 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
231 // Show user information
232 Dispense_ShowUser(sock, argv[i+1]);
239 // - "Here, have some money."
240 if( strcmp(arg, "give") == 0 )
242 if( i + 3 >= argc ) {
243 fprintf(stderr, "`dispense give` takes three arguments\n");
248 // argv[i+1]: Destination
249 // argv[i+2]: Ammount
253 sock = OpenConnection(gsDispenseServer, giDispensePort);
254 if( sock < 0 ) return -1;
257 if( Authenticate(sock) )
260 Dispense_Give(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
265 // - User administration (Admin Only)
266 if( strcmp(arg, "user") == 0 )
268 // Check argument count
269 if( i + 1 >= argc ) {
270 fprintf(stderr, "Error: `dispense user` requires arguments\n");
276 sock = OpenConnection(gsDispenseServer, giDispensePort);
277 if( sock < 0 ) return -1;
279 // Attempt authentication
280 if( Authenticate(sock) )
284 if( strcmp(argv[i+1], "add") == 0 )
286 if( i + 2 >= argc ) {
287 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
292 Dispense_AddUser(sock, argv[i+2]);
295 else if( strcmp(argv[i+1], "type") == 0 )
297 if( i + 3 >= argc ) {
298 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
303 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
307 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
315 if( strcmp(arg, "donate") == 0 )
317 // Check argument count
318 if( i + 2 >= argc ) {
319 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
325 sock = OpenConnection(gsDispenseServer, giDispensePort);
326 if( sock < 0 ) return -1;
328 // Attempt authentication
329 if( Authenticate(sock) )
333 Dispense_Donate(sock, atoi(argv[i+1]), argv[i+1]);
339 // Item name / pattern
346 sock = OpenConnection(gsDispenseServer, giDispensePort);
347 if( sock < 0 ) return -1;
349 // Get the user's balance
350 GetUserBalance(sock);
353 PopulateItemList(sock);
355 // Disconnect from server
360 regmatch_t matches[3];
362 if( strcmp(gsItemPattern, "door") == 0 )
364 // Connect, Authenticate, dispense and close
365 sock = OpenConnection(gsDispenseServer, giDispensePort);
366 if( sock < 0 ) return -1;
368 DispenseItem(sock, "door", 0);
372 // Item id (<type>:<num>)
373 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
378 // Get and finish ident
379 ident = gsItemPattern + matches[1].rm_so;
380 gsItemPattern[matches[1].rm_eo] = '\0';
382 id = atoi( gsItemPattern + matches[2].rm_so );
384 // Connect, Authenticate, dispense and close
385 sock = OpenConnection(gsDispenseServer, giDispensePort);
386 if( sock < 0 ) return -1;
388 Dispense_ItemInfo(sock, ident, id);
391 DispenseItem(sock, ident, id);
395 // Item number (6 = coke)
396 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
398 i = atoi(gsItemPattern);
405 for( i = 0; i < giNumItems; i ++ )
407 // Prefix match (with case-insensitive match)
408 for( j = 0; gsItemPattern[j]; j ++ )
410 if( gaItems[i].Desc[j] == gsItemPattern[j] )
412 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
416 // Check if the prefix matched
417 if( gsItemPattern[j] != '\0' )
421 if( gaItems[i].Desc[j] == '\0' ) {
426 // Only one match allowed
431 // TODO: Allow ambiguous matches?
432 // or just print a wanrning
433 printf("Warning - Ambiguous pattern, stopping\n");
438 // Was a match found?
441 fprintf(stderr, "No item matches the passed string\n");
448 else if( giUIMode != UI_MODE_BASIC )
454 // Very basic dispense interface
455 for( i = 0; i < giNumItems; i ++ ) {
457 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
460 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
461 gaItems[i].Price, gaItems[i].Desc);
470 fgets(buffer, BUFSIZ, stdin);
474 if( buf[0] == 'q' ) break;
478 if( i != 0 || buf[0] == '0' )
480 if( i < 0 || i >= giNumItems ) {
481 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
490 // Check for a valid item ID
493 // Connect, Authenticate, dispense and close
494 sock = OpenConnection(gsDispenseServer, giDispensePort);
495 if( sock < 0 ) return -1;
497 Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
500 DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
513 " Show interactive list\n"
515 " Dispense named item\n"
516 " dispense give <user> <ammount> \"<reason>\"\n"
517 " Give money to another user\n"
518 " dispense donate <ammount> \"<reason>\"\n"
519 " Donate to the club\n"
520 " == Coke members == \n"
521 " dispense acct [<user>]\n"
522 " Show user balances\n"
523 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
524 " Alter a account value\n"
525 " == Dispense administrators ==\n"
526 " dispense acct <user> =<ammount> \"<reason>\"\n"
527 " Set an account balance\n"
528 " dispense user add <user>\n"
529 " Create new coke account (Admins only)\n"
530 " dispense user type <user> <flags>\n"
531 " Alter a user's flags\n"
532 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
533 " Flags are removed by preceding the name with '-' or '!'\n"
537 " Set a different user (Coke members only)\n"
541 " Use alternate GUI\n"
542 " -m <min balance>\n"
543 " -M <max balance>\n"
544 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
548 // -------------------
549 // --- NCurses GUI ---
550 // -------------------
552 * \brief Render the NCurses UI
554 int ShowNCursesUI(void)
556 // TODO: ncurses interface (with separation between item classes)
557 // - Hmm... that would require standardising the item ID to be <class>:<index>
562 const int displayMinWidth = 40;
563 char *titleString = "Dispense";
568 int ret = -2; // -2: Used for marking "no return yet"
570 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
577 if( gsEffectiveUser )
578 username = gsEffectiveUser;
580 pwd = getpwuid( getuid() );
581 username = pwd->pw_name;
584 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, giUserBalance%100);
591 maxItemIndex = ShowItemAt(0, 0, 0, -1);
592 // Get item count per screen
593 // - 6: randomly chosen (Need at least 3)
594 itemCount = LINES - 6;
595 if( itemCount > maxItemIndex )
596 itemCount = maxItemIndex;
598 while( ShowItemAt(0, 0, 0, currentItem) == -1 )
603 height = itemCount + 3;
604 width = displayMinWidth;
607 xBase = COLS/2 - width/2;
608 yBase = LINES/2 - height/2;
613 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
616 for( i = 0; i < itemCount; i ++ )
620 move( yBase + 1 + i, xBase );
622 if( currentItem == itemBase + i ) {
630 // Check for the '...' row
631 // - Oh god, magic numbers!
632 if( (i == 0 && itemBase > 0)
633 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
635 printw(" ..."); pos += 6;
636 times = (width - pos) - 1;
637 //times = width-1 - 8 - 3;
638 while(times--) addch(' ');
642 ShowItemAt( yBase + 1 + i, xBase + pos, (width - pos) - 3, itemBase + i);
646 // Scrollbar (if needed)
647 if( maxItemIndex > itemCount ) {
651 else if( i == itemCount - 1 ) {
655 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
656 if( i-1 == percentage*(itemCount-3)/100 ) {
670 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
673 // - Username, balance, flags
674 PrintAlign(yBase+height-1, xBase+1, width-2,
675 username, ' ', balance_str, ' ', gsUserFlags);
691 while( ShowItemAt(0, 0, 0, currentItem) == -1 )
694 if( currentItem >= maxItemIndex ) {
697 while( ShowItemAt(0, 0, 0, currentItem) == -1 )
704 while( ShowItemAt(0, 0, 0, currentItem) == -1 )
707 if( currentItem < 0 ) {
708 currentItem = maxItemIndex - 1;
710 while( ShowItemAt(0, 0, 0, currentItem) == -1 )
720 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
721 itemBase = currentItem - 2;
722 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
723 itemBase = currentItem - itemCount + 2;
729 ret = ShowItemAt(0, 0, 0, currentItem);
732 ret = -1; // -1: Return with no dispense
736 // Check if the return value was changed
737 if( ret != -2 ) break;
749 * \brief Show item \a Index at (\a Col, \a Row)
750 * \return Dispense index of item
751 * \note Part of the NCurses UI
753 int ShowItemAt(int Row, int Col, int Width, int Index)
762 // - This assumes that
763 case UI_MODE_STANDARD:
765 // Index = -1, request limit
766 if( Index < 0 || Index >= giNumItems+2 )
772 name = "Coke Machine";
773 Index = -1; // -1 indicates a label
780 name = gaItems[Index].Desc;
781 price = gaItems[Index].Price;
789 name = "Electronic Payment System";
790 Index = -1; // -1 indicates a label
795 name = gaItems[Index].Desc;
796 price = gaItems[Index].Price;
802 // Width = 0, don't print
809 printw("%02i %s", Index, name);
811 getyx(stdscr, _y, _x);
812 // Assumes max 4 digit prices
813 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
814 while(times--) addch(' ');
815 printw("%4i", price);
819 printw("-- %s", name);
820 getyx(stdscr, _y, _x);
821 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
822 while(times--) addch(' ');
823 printw(" --", price);
831 * \brief Print a three-part string at the specified position (formatted)
832 * \note NCurses UI Helper
834 * Prints \a Left on the left of the area, \a Right on the righthand side
835 * and \a Mid in the middle of the area. These are padded with \a Pad1
836 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
838 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
839 * and the arguments to these are read in that order.
841 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
842 const char *Mid, char Pad2, const char *Right, ...)
844 int lLen, mLen, rLen;
849 // Get the length of the strings
850 va_start(args, Right);
851 lLen = vsnprintf(NULL, 0, Left, args);
852 mLen = vsnprintf(NULL, 0, Mid, args);
853 rLen = vsnprintf(NULL, 0, Right, args);
857 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
858 return ; // TODO: What to do?
864 va_start(args, Right);
868 vsnprintf(tmp, lLen+1, Left, args);
872 times = (Width - mLen)/2 - lLen;
873 while(times--) addch(Pad1);
877 vsnprintf(tmp, mLen+1, Mid, args);
881 times = (Width - mLen)/2 - rLen;
882 if( (Width - mLen) % 2 ) times ++;
883 while(times--) addch(Pad2);
887 vsnprintf(tmp, rLen+1, Right, args);
892 // ---------------------
893 // --- Coke Protocol ---
894 // ---------------------
895 int OpenConnection(const char *Host, int Port)
897 struct hostent *host;
898 struct sockaddr_in serverAddr;
901 host = gethostbyname(Host);
903 fprintf(stderr, "Unable to look up '%s'\n", Host);
907 memset(&serverAddr, 0, sizeof(serverAddr));
909 serverAddr.sin_family = AF_INET; // IPv4
910 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
911 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
912 serverAddr.sin_port = htons(Port);
914 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
916 fprintf(stderr, "Failed to create socket\n");
923 struct sockaddr_in localAddr;
924 memset(&localAddr, 0, sizeof(localAddr));
925 localAddr.sin_family = AF_INET; // IPv4
927 // Loop through all the top ports until one is avaliable
928 for( i = 1001; i < 1024; i ++)
930 localAddr.sin_port = htons(i); // IPv4
931 // Attempt to bind to low port for autoauth
932 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
936 printf("Warning: AUTOAUTH unavaliable\n");
939 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
940 fprintf(stderr, "Failed to connect to server\n");
948 * \brief Authenticate with the server
949 * \return Boolean Failure
951 int Authenticate(int Socket)
958 regmatch_t matches[4];
960 if( gbIsAuthenticated ) return 0;
963 pwd = getpwuid( getuid() );
965 // Attempt automatic authentication
966 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
968 // Check if it worked
969 buf = ReadLine(Socket);
971 responseCode = atoi(buf);
972 switch( responseCode )
974 case 200: // Autoauth succeeded, return
978 case 401: // Untrusted, attempt password authentication
981 sendf(Socket, "USER %s\n", pwd->pw_name);
982 printf("Using username %s\n", pwd->pw_name);
984 buf = ReadLine(Socket);
987 // Expected format: 100 SALT <something> ...
989 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
990 responseCode = atoi(buf);
991 if( responseCode != 100 ) {
992 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
998 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
999 // Store it for later
1000 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1001 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1005 // Give three attempts
1006 for( i = 0; i < 3; i ++ )
1008 int ofs = strlen(pwd->pw_name)+strlen(salt);
1011 char *pass = getpass("Password: ");
1014 // Create hash string
1015 // <username><salt><hash>
1016 strcpy(tmp, pwd->pw_name);
1018 SHA1( (unsigned char*)pass, strlen(pass), h );
1019 memcpy(tmp+ofs, h, 20);
1022 SHA1( (unsigned char*)tmp, ofs+20, h );
1023 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1024 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1025 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1029 sendf(Socket, "PASS %s\n", tmpBuf);
1030 buf = ReadLine(Socket);
1032 responseCode = atoi(buf);
1034 if( responseCode == 200 ) break;
1035 // Bad username/password
1036 if( responseCode == 401 ) continue;
1038 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1044 return 2; // 2 = Bad Password
1047 case 404: // Bad Username
1048 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1053 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1054 printf("%s\n", buf);
1059 // Set effective user
1060 if( gsEffectiveUser ) {
1061 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1063 buf = ReadLine(Socket);
1064 responseCode = atoi(buf);
1066 switch(responseCode)
1069 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1073 printf("Only coke members can use `dispense -u`\n");
1078 printf("Invalid user selected\n");
1083 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1084 printf("%s\n", buf);
1092 gbIsAuthenticated = 1;
1097 int GetUserBalance(int Socket)
1099 regmatch_t matches[6];
1106 if( gsEffectiveUser ) {
1107 gsUserName = gsEffectiveUser;
1110 pwd = getpwuid( getuid() );
1111 gsUserName = strdup(pwd->pw_name);
1115 sendf(Socket, "USER_INFO %s\n", gsUserName);
1116 buf = ReadLine(Socket);
1117 responseCode = atoi(buf);
1118 switch(responseCode)
1120 case 202: break; // Ok
1123 printf("Invalid user? (USER_INFO failed)\n");
1128 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1129 printf("%s\n", buf);
1134 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1136 giUserBalance = atoi( buf + matches[4].rm_so );
1137 gsUserFlags = strdup( buf + matches[5].rm_so );
1146 * \brief Fill the item information structure
1147 * \return Boolean Failure
1149 void PopulateItemList(int Socket)
1154 char *itemType, *itemStart;
1156 regmatch_t matches[4];
1158 // Ask server for stock list
1159 send(Socket, "ENUM_ITEMS\n", 11, 0);
1160 buf = ReadLine(Socket);
1162 //printf("Output: %s\n", buf);
1164 responseCode = atoi(buf);
1165 if( responseCode != 201 ) {
1166 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1170 // - Get item list -
1173 // 201 Items <count>
1175 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1177 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1178 count = atoi( &buf[ matches[3].rm_so ] );
1181 if( strcmp(itemType, "Items") != 0 ) {
1183 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1188 itemStart = &buf[ matches[3].rm_eo ];
1193 gaItems = malloc( giNumItems * sizeof(tItem) );
1195 // Fetch item information
1196 for( i = 0; i < giNumItems; i ++ )
1198 regmatch_t matches[7];
1201 buf = ReadLine(Socket);
1202 responseCode = atoi(buf);
1204 if( responseCode != 202 ) {
1205 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1209 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
1211 buf[ matches[3].rm_eo ] = '\0';
1213 gaItems[i].Type = strdup( buf + matches[3].rm_so );
1214 gaItems[i].ID = atoi( buf + matches[4].rm_so );
1215 gaItems[i].Price = atoi( buf + matches[5].rm_so );
1216 gaItems[i].Desc = strdup( buf + matches[6].rm_so );
1222 buf = ReadLine(Socket);
1223 responseCode = atoi(buf);
1225 if( responseCode != 200 ) {
1226 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1237 * \brief Get information on an item
1238 * \return Boolean Failure
1240 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1244 regmatch_t matches[7];
1249 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1250 buf = ReadLine(Socket);
1252 responseCode = atoi(buf);
1253 switch( responseCode )
1259 printf("Bad item name\n");
1264 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1270 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
1272 buf[ matches[3].rm_eo ] = '\0';
1274 type = buf + matches[3].rm_so; buf[matches[3].rm_eo] = '\0';
1275 id = atoi( buf + matches[4].rm_so );
1276 price = atoi( buf + matches[5].rm_so );
1277 desc = buf + matches[6].rm_so; buf[matches[6].rm_eo] = '\0';
1279 printf("%8s:%-2i %2i.%02i %s\n", type, id, price/100, price%100, desc);
1287 * \brief Dispense an item
1288 * \return Boolean Failure
1290 int DispenseItem(int Socket, const char *Type, int ID)
1292 int ret, responseCode;
1295 // Check for a dry run
1297 printf("Dry Run - No action\n");
1302 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1303 buf = ReadLine(Socket);
1305 responseCode = atoi(buf);
1306 switch( responseCode )
1309 printf("Dispense OK\n");
1313 printf("Not authenticated\n");
1317 printf("Insufficient balance\n");
1321 printf("Bad item name\n");
1325 printf("Item failed to dispense, is the slot empty?\n");
1329 printf("Dispense not possible (slot empty/permissions)\n");
1333 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1343 * \brief Alter a user's balance
1345 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1350 // Check for a dry run
1352 printf("Dry Run - No action\n");
1356 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1357 buf = ReadLine(Socket);
1359 responseCode = atoi(buf);
1362 switch(responseCode)
1364 case 200: return 0; // OK
1366 fprintf(stderr, "Insufficient balance\n");
1368 case 403: // Not in coke
1369 fprintf(stderr, "You are not in coke (sucker)\n");
1371 case 404: // Unknown user
1372 fprintf(stderr, "Unknown user '%s'\n", Username);
1375 fprintf(stderr, "Unknown response code %i\n", responseCode);
1383 * \brief Set a user's balance
1384 * \note Only avaliable to dispense admins
1386 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1391 // Check for a dry run
1393 printf("Dry Run - No action\n");
1397 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1398 buf = ReadLine(Socket);
1400 responseCode = atoi(buf);
1403 switch(responseCode)
1405 case 200: return 0; // OK
1406 case 403: // Not in coke
1407 fprintf(stderr, "You are not an admin\n");
1409 case 404: // Unknown user
1410 fprintf(stderr, "Unknown user '%s'\n", Username);
1413 fprintf(stderr, "Unknown response code %i\n", responseCode);
1421 * \brief Give money to another user
1423 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1429 printf("Sorry, you can only give, you can't take.\n");
1433 // Fast return on zero
1434 if( Ammount == 0 ) {
1435 printf("Are you actually going to give any?\n");
1439 // Check for a dry run
1441 printf("Dry Run - No action\n");
1445 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1446 buf = ReadLine(Socket);
1448 responseCode = atoi(buf);
1451 switch(responseCode)
1453 case 200: return 0; // OK
1456 fprintf(stderr, "Insufficient balance\n");
1459 case 404: // Unknown user
1460 fprintf(stderr, "Unknown user '%s'\n", Username);
1464 fprintf(stderr, "Unknown response code %i\n", responseCode);
1473 * \brief Donate money to the club
1475 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1481 printf("Sorry, you can only give, you can't take.\n");
1485 // Fast return on zero
1486 if( Ammount == 0 ) {
1487 printf("Are you actually going to give any?\n");
1491 // Check for a dry run
1493 printf("Dry Run - No action\n");
1497 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1498 buf = ReadLine(Socket);
1500 responseCode = atoi(buf);
1503 switch(responseCode)
1505 case 200: return 0; // OK
1508 fprintf(stderr, "Insufficient balance\n");
1512 fprintf(stderr, "Unknown response code %i\n", responseCode);
1520 * \brief Enumerate users
1522 int Dispense_EnumUsers(int Socket)
1527 regmatch_t matches[4];
1529 if( giMinimumBalance != INT_MIN ) {
1530 if( giMaximumBalance != INT_MAX ) {
1531 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1534 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1538 if( giMaximumBalance != INT_MAX ) {
1539 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1542 sendf(Socket, "ENUM_USERS\n");
1545 buf = ReadLine(Socket);
1546 responseCode = atoi(buf);
1548 switch(responseCode)
1550 case 201: break; // Ok, length follows
1553 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1558 // Get count (not actually used)
1559 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1560 nUsers = atoi( buf + matches[3].rm_so );
1561 printf("%i users returned\n", nUsers);
1566 // Read returned users
1568 buf = ReadLine(Socket);
1569 responseCode = atoi(buf);
1571 if( responseCode != 202 ) break;
1573 _PrintUserLine(buf);
1575 } while(responseCode == 202);
1577 // Check final response
1578 if( responseCode != 200 ) {
1579 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1589 int Dispense_ShowUser(int Socket, const char *Username)
1592 int responseCode, ret;
1594 sendf(Socket, "USER_INFO %s\n", Username);
1595 buf = ReadLine(Socket);
1597 responseCode = atoi(buf);
1599 switch(responseCode)
1602 _PrintUserLine(buf);
1607 printf("Unknown user '%s'\n", Username);
1612 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1622 void _PrintUserLine(const char *Line)
1624 regmatch_t matches[6];
1627 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1632 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1633 char username[usernameLen + 1];
1634 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1635 char flags[flagsLen + 1];
1637 memcpy(username, Line + matches[3].rm_so, usernameLen);
1638 username[usernameLen] = '\0';
1639 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1640 flags[flagsLen] = '\0';
1642 bal = atoi(Line + matches[4].rm_so);
1643 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1647 int Dispense_AddUser(int Socket, const char *Username)
1650 int responseCode, ret;
1652 // Check for a dry run
1654 printf("Dry Run - No action\n");
1658 sendf(Socket, "USER_ADD %s\n", Username);
1660 buf = ReadLine(Socket);
1661 responseCode = atoi(buf);
1663 switch(responseCode)
1666 printf("User '%s' added\n", Username);
1671 printf("Only wheel can add users\n");
1676 printf("User '%s' already exists\n", Username);
1681 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1691 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1694 int responseCode, ret;
1696 // Check for a dry run
1698 printf("Dry Run - No action\n");
1702 // TODO: Pre-validate the string
1704 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1706 buf = ReadLine(Socket);
1707 responseCode = atoi(buf);
1709 switch(responseCode)
1712 printf("User '%s' updated\n", Username);
1717 printf("Only wheel can modify users\n");
1722 printf("User '%s' does not exist\n", Username);
1727 printf("Flag string is invalid\n");
1732 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1745 char *ReadLine(int Socket)
1747 static char buf[BUFSIZ];
1748 static int bufPos = 0;
1749 static int bufValid = 0;
1751 char *newline = NULL;
1753 char *ret = malloc(10);
1755 #if DEBUG_TRACE_SERVER
1756 printf("ReadLine: ");
1768 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1769 buf[bufPos+len] = '\0';
1772 newline = strchr( buf+bufPos, '\n' );
1777 retLen += strlen(buf+bufPos);
1778 ret = realloc(ret, retLen + 1);
1779 strcat( ret, buf+bufPos );
1782 int newLen = newline - (buf+bufPos) + 1;
1783 bufValid = len - newLen;
1786 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1789 #if DEBUG_TRACE_SERVER
1790 printf("%i '%s'\n", retLen, ret);
1796 int sendf(int Socket, const char *Format, ...)
1801 va_start(args, Format);
1802 len = vsnprintf(NULL, 0, Format, args);
1807 va_start(args, Format);
1808 vsnprintf(buf, len+1, Format, args);
1811 #if DEBUG_TRACE_SERVER
1812 printf("sendf: %s", buf);
1815 return send(Socket, buf, len, 0);
1819 char *trim(char *string)
1823 while( isspace(*string) )
1826 for( i = strlen(string); i--; )
1828 if( isspace(string[i]) )
1837 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1841 ret = regexec(regex, string, nMatches, matches, 0);
1842 if( ret && errorMessage ) {
1843 size_t len = regerror(ret, regex, NULL, 0);
1845 regerror(ret, regex, errorStr, len);
1846 printf("string = '%s'\n", string);
1847 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1854 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1856 int ret = regcomp(regex, pattern, flags);
1858 size_t len = regerror(ret, regex, NULL, 0);
1860 regerror(ret, regex, errorStr, len);
1861 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);