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 {
45 int Status; // 0: Availiable, 1: Sold out, -1: Error
51 int main(int argc, char *argv[]);
54 int ShowNCursesUI(void);
55 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted);
56 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
57 // --- Coke Server Communication ---
58 int OpenConnection(const char *Host, int Port);
59 int Authenticate(int Socket);
60 int GetUserBalance(int Socket);
61 void PopulateItemList(int Socket);
62 int Dispense_ItemInfo(int Socket, const char *Type, int ID);
63 int DispenseItem(int Socket, const char *Type, int ID);
64 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
65 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
66 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
67 int Dispense_Donate(int Socket, int Ammount, const char *Reason);
68 int Dispense_EnumUsers(int Socket);
69 int Dispense_ShowUser(int Socket, const char *Username);
70 void _PrintUserLine(const char *Line);
71 int Dispense_AddUser(int Socket, const char *Username);
72 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
74 char *ReadLine(int Socket);
75 int sendf(int Socket, const char *Format, ...);
76 char *trim(char *string);
77 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
78 void CompileRegex(regex_t *regex, const char *pattern, int flags);
81 char *gsDispenseServer = "heathred";
82 int giDispensePort = 11020;
86 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
87 int gbIsAuthenticated = 0;
89 char *gsItemPattern; //!< Item pattern
90 char *gsEffectiveUser; //!< '-u' Dispense as another user
91 int giUIMode = UI_MODE_STANDARD;
92 int gbDryRun = 0; //!< '-n' Read-only
93 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
94 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
95 char *gsUserName; //!< User that dispense will happen as
96 char *gsUserFlags; //!< User's flag set
97 int giUserBalance=-1; //!< User balance (set by Authenticate)
100 int main(int argc, char *argv[])
106 // -- Create regular expressions
107 // > Code Type Count ...
108 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
109 // > Code Type Ident Status Price Desc
110 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);
111 // > Code 'SALT' salt
112 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
113 // > Code 'User' Username Balance Flags
114 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
116 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
119 for( i = 1; i < argc; i ++ )
132 case 'm': // Minimum balance
133 if( i + 1 >= argc ) {
134 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
137 giMinimumBalance = atoi(argv[++i]);
139 case 'M': // Maximum balance
140 if( i + 1 >= argc ) {
141 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
144 giMaximumBalance = atoi(argv[++i]);
147 case 'u': // Override User
148 if( i + 1 >= argc ) {
149 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
152 gsEffectiveUser = argv[++i];
155 case 'H': // Override remote host
156 if( i + 1 >= argc ) {
157 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
160 gsDispenseServer = argv[++i];
162 case 'P': // Override remote port
163 if( i + 1 >= argc ) {
164 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
167 giDispensePort = atoi(argv[++i]);
170 case 'G': // Don't use GUI
171 giUIMode = UI_MODE_BASIC;
173 case 'D': // Drinks only
174 giUIMode = UI_MODE_DRINKSONLY;
176 case 'n': // Dry Run / read-only
187 if( strcmp(arg, "acct") == 0 )
190 sock = OpenConnection(gsDispenseServer, giDispensePort);
191 if( sock < 0 ) return -1;
194 if( i + 1 == argc ) {
195 Dispense_EnumUsers(sock);
199 // argv[i+1]: Username
204 if( i + 3 >= argc ) {
205 fprintf(stderr, "Error: `dispense acct' needs a reason\n");
209 // Authentication required
210 if( Authenticate(sock) )
213 // argv[i+1]: Username
214 // argv[i+2]: Ammount
217 if( argv[i+2][0] == '=' ) {
219 if( argv[i+2][1] != '0' && atoi(&argv[i+2][1]) == 0 ) {
220 fprintf(stderr, "Error: Invalid balance to be set\n");
224 Dispense_SetBalance(sock, argv[i+1], atoi(argv[i+2]+1), argv[i+3]);
228 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
232 // Show user information
233 Dispense_ShowUser(sock, argv[i+1]);
240 // - "Here, have some money."
241 if( strcmp(arg, "give") == 0 )
243 if( i + 3 >= argc ) {
244 fprintf(stderr, "`dispense give` takes three arguments\n");
249 // argv[i+1]: Destination
250 // argv[i+2]: Ammount
254 sock = OpenConnection(gsDispenseServer, giDispensePort);
255 if( sock < 0 ) return -1;
258 if( Authenticate(sock) )
261 Dispense_Give(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
266 // - User administration (Admin Only)
267 if( strcmp(arg, "user") == 0 )
269 // Check argument count
270 if( i + 1 >= argc ) {
271 fprintf(stderr, "Error: `dispense user` requires arguments\n");
277 sock = OpenConnection(gsDispenseServer, giDispensePort);
278 if( sock < 0 ) return -1;
280 // Attempt authentication
281 if( Authenticate(sock) )
285 if( strcmp(argv[i+1], "add") == 0 )
287 if( i + 2 >= argc ) {
288 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
293 Dispense_AddUser(sock, argv[i+2]);
296 else if( strcmp(argv[i+1], "type") == 0 )
298 if( i + 3 >= argc ) {
299 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
304 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
308 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
316 if( strcmp(arg, "donate") == 0 )
318 // Check argument count
319 if( i + 2 >= argc ) {
320 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
326 sock = OpenConnection(gsDispenseServer, giDispensePort);
327 if( sock < 0 ) return -1;
329 // Attempt authentication
330 if( Authenticate(sock) )
334 Dispense_Donate(sock, atoi(argv[i+1]), argv[i+1]);
340 // Item name / pattern
347 sock = OpenConnection(gsDispenseServer, giDispensePort);
348 if( sock < 0 ) return -1;
350 // Get the user's balance
351 GetUserBalance(sock);
354 PopulateItemList(sock);
356 // Disconnect from server
361 regmatch_t matches[3];
363 if( strcmp(gsItemPattern, "door") == 0 )
365 // Connect, Authenticate, dispense and close
366 sock = OpenConnection(gsDispenseServer, giDispensePort);
367 if( sock < 0 ) return -1;
369 DispenseItem(sock, "door", 0);
373 // Item id (<type>:<num>)
374 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
379 // Get and finish ident
380 ident = gsItemPattern + matches[1].rm_so;
381 gsItemPattern[matches[1].rm_eo] = '\0';
383 id = atoi( gsItemPattern + matches[2].rm_so );
385 // Connect, Authenticate, dispense and close
386 sock = OpenConnection(gsDispenseServer, giDispensePort);
387 if( sock < 0 ) return -1;
389 Dispense_ItemInfo(sock, ident, id);
392 DispenseItem(sock, ident, id);
396 // Item number (6 = coke)
397 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
399 i = atoi(gsItemPattern);
406 for( i = 0; i < giNumItems; i ++ )
408 // Prefix match (with case-insensitive match)
409 for( j = 0; gsItemPattern[j]; j ++ )
411 if( gaItems[i].Desc[j] == gsItemPattern[j] )
413 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
417 // Check if the prefix matched
418 if( gsItemPattern[j] != '\0' )
422 if( gaItems[i].Desc[j] == '\0' ) {
427 // Only one match allowed
432 // TODO: Allow ambiguous matches?
433 // or just print a wanrning
434 printf("Warning - Ambiguous pattern, stopping\n");
439 // Was a match found?
442 fprintf(stderr, "No item matches the passed string\n");
449 else if( giUIMode != UI_MODE_BASIC )
455 // Very basic dispense interface
456 for( i = 0; i < giNumItems; i ++ ) {
458 if( i && strcmp(gaItems[i].Type, gaItems[i-1].Type) != 0 )
461 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
462 gaItems[i].Price, gaItems[i].Desc);
471 fgets(buffer, BUFSIZ, stdin);
475 if( buf[0] == 'q' ) break;
479 if( i != 0 || buf[0] == '0' )
481 if( i < 0 || i >= giNumItems ) {
482 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
491 // Check for a valid item ID
494 // Connect, Authenticate, dispense and close
495 sock = OpenConnection(gsDispenseServer, giDispensePort);
496 if( sock < 0 ) return -1;
498 Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
501 DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
514 " Show interactive list\n"
516 " Dispense named item\n"
517 " dispense give <user> <ammount> \"<reason>\"\n"
518 " Give money to another user\n"
519 " dispense donate <ammount> \"<reason>\"\n"
520 " Donate to the club\n"
521 " == Coke members == \n"
522 " dispense acct [<user>]\n"
523 " Show user balances\n"
524 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
525 " Alter a account value\n"
526 " == Dispense administrators ==\n"
527 " dispense acct <user> =<ammount> \"<reason>\"\n"
528 " Set an account balance\n"
529 " dispense user add <user>\n"
530 " Create new coke account (Admins only)\n"
531 " dispense user type <user> <flags>\n"
532 " Alter a user's flags\n"
533 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
534 " Flags are removed by preceding the name with '-' or '!'\n"
538 " Set a different user (Coke members only)\n"
542 " Use alternate GUI\n"
543 " -m <min balance>\n"
544 " -M <max balance>\n"
545 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
549 // -------------------
550 // --- NCurses GUI ---
551 // -------------------
553 * \brief Render the NCurses UI
555 int ShowNCursesUI(void)
557 // TODO: ncurses interface (with separation between item classes)
558 // - Hmm... that would require standardising the item ID to be <class>:<index>
563 const int displayMinWidth = 40;
564 char *titleString = "Dispense";
569 int ret = -2; // -2: Used for marking "no return yet"
571 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
578 if( gsEffectiveUser )
579 username = gsEffectiveUser;
581 pwd = getpwuid( getuid() );
582 username = pwd->pw_name;
585 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, giUserBalance%100);
592 maxItemIndex = ShowItemAt(0, 0, 0, -1, 0);
593 // Get item count per screen
594 // - 6: randomly chosen (Need at least 3)
595 itemCount = LINES - 6;
596 if( itemCount > maxItemIndex )
597 itemCount = maxItemIndex;
600 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
605 height = itemCount + 3;
606 width = displayMinWidth;
609 xBase = COLS/2 - width/2;
610 yBase = LINES/2 - height/2;
615 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
618 for( i = 0; i < itemCount; i ++ )
622 move( yBase + 1 + i, xBase );
627 // Check for the '...' row
628 // - Oh god, magic numbers!
629 if( (i == 0 && itemBase > 0)
630 || (i == itemCount - 1 && itemBase < maxItemIndex - itemCount) )
632 printw(" ..."); pos += 8;
633 times = (width - pos) - 1;
634 while(times--) addch(' ');
639 yBase + 1 + i, xBase + pos, // Position
640 (width - pos) - 3, // Width
641 itemBase + i, // Index
642 !!(currentItem == itemBase + i) // Hilighted
647 // Scrollbar (if needed)
648 if( maxItemIndex > itemCount ) {
652 else if( i == itemCount - 1 ) {
656 int percentage = itemBase * 100 / (maxItemIndex-itemCount);
657 if( i-1 == percentage*(itemCount-3)/100 ) {
671 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
674 // - Username, balance, flags
675 PrintAlign(yBase+height-1, xBase+1, width-2,
676 username, ' ', balance_str, ' ', gsUserFlags);
692 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
695 if( currentItem >= maxItemIndex ) {
698 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
705 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
708 if( currentItem < 0 ) {
709 currentItem = maxItemIndex - 1;
711 while( ShowItemAt(0, 0, 0, currentItem, 0) == -1 )
721 if( itemCount > maxItemIndex && currentItem < itemBase + 2 && itemBase > 0 )
722 itemBase = currentItem - 2;
723 if( itemCount > maxItemIndex && currentItem > itemBase + itemCount - 2 && itemBase < maxItemIndex-1 )
724 itemBase = currentItem - itemCount + 2;
730 ret = ShowItemAt(0, 0, 0, currentItem, 0);
733 ret = -1; // -1: Return with no dispense
737 // Check if the return value was changed
738 if( ret != -2 ) break;
750 * \brief Show item \a Index at (\a Col, \a Row)
751 * \return Dispense index of item
752 * \note Part of the NCurses UI
754 int ShowItemAt(int Row, int Col, int Width, int Index, int bHilighted)
764 // - This assumes that
765 case UI_MODE_STANDARD:
767 // Index = -1, request limit
768 if( Index < 0 || Index >= giNumItems+2 )
774 name = "Coke Machine";
775 Index = -1; // -1 indicates a label
782 name = gaItems[Index].Desc;
783 price = gaItems[Index].Price;
784 status = gaItems[Index].Status;
792 name = "Electronic Payment System";
793 Index = -1; // -1 indicates a label
798 name = gaItems[Index].Desc;
799 price = gaItems[Index].Price;
800 status = gaItems[Index].Status;
806 // Width = 0, don't print
813 // Show hilight and status
834 getyx(stdscr, _y, _x);
835 // Assumes max 4 digit prices
836 times = Width - 5 - (_x - Col); // TODO: Better handling for large prices
837 while(times--) addch(' ');
839 printw(" %4i", price);
843 printw("-- %s", name);
844 getyx(stdscr, _y, _x);
845 times = Width - 4 - (_x - Col);
846 while(times--) addch(' ');
851 // If the item isn't availiable for sale, return -1 (so it's skipped)
859 * \brief Print a three-part string at the specified position (formatted)
860 * \note NCurses UI Helper
862 * Prints \a Left on the left of the area, \a Right on the righthand side
863 * and \a Mid in the middle of the area. These are padded with \a Pad1
864 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
866 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
867 * and the arguments to these are read in that order.
869 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
870 const char *Mid, char Pad2, const char *Right, ...)
872 int lLen, mLen, rLen;
877 // Get the length of the strings
878 va_start(args, Right);
879 lLen = vsnprintf(NULL, 0, Left, args);
880 mLen = vsnprintf(NULL, 0, Mid, args);
881 rLen = vsnprintf(NULL, 0, Right, args);
885 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
886 return ; // TODO: What to do?
892 va_start(args, Right);
896 vsnprintf(tmp, lLen+1, Left, args);
900 times = (Width - mLen)/2 - lLen;
901 while(times--) addch(Pad1);
905 vsnprintf(tmp, mLen+1, Mid, args);
909 times = (Width - mLen)/2 - rLen;
910 if( (Width - mLen) % 2 ) times ++;
911 while(times--) addch(Pad2);
915 vsnprintf(tmp, rLen+1, Right, args);
920 // ---------------------
921 // --- Coke Protocol ---
922 // ---------------------
923 int OpenConnection(const char *Host, int Port)
925 struct hostent *host;
926 struct sockaddr_in serverAddr;
929 host = gethostbyname(Host);
931 fprintf(stderr, "Unable to look up '%s'\n", Host);
935 memset(&serverAddr, 0, sizeof(serverAddr));
937 serverAddr.sin_family = AF_INET; // IPv4
938 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
939 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
940 serverAddr.sin_port = htons(Port);
942 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
944 fprintf(stderr, "Failed to create socket\n");
951 struct sockaddr_in localAddr;
952 memset(&localAddr, 0, sizeof(localAddr));
953 localAddr.sin_family = AF_INET; // IPv4
955 // Loop through all the top ports until one is avaliable
956 for( i = 1001; i < 1024; i ++)
958 localAddr.sin_port = htons(i); // IPv4
959 // Attempt to bind to low port for autoauth
960 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
964 printf("Warning: AUTOAUTH unavaliable\n");
967 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
968 fprintf(stderr, "Failed to connect to server\n");
976 * \brief Authenticate with the server
977 * \return Boolean Failure
979 int Authenticate(int Socket)
986 regmatch_t matches[4];
988 if( gbIsAuthenticated ) return 0;
991 pwd = getpwuid( getuid() );
993 // Attempt automatic authentication
994 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
996 // Check if it worked
997 buf = ReadLine(Socket);
999 responseCode = atoi(buf);
1000 switch( responseCode )
1002 case 200: // Autoauth succeeded, return
1006 case 401: // Untrusted, attempt password authentication
1009 sendf(Socket, "USER %s\n", pwd->pw_name);
1010 printf("Using username %s\n", pwd->pw_name);
1012 buf = ReadLine(Socket);
1015 // Expected format: 100 SALT <something> ...
1016 // OR : 100 User Set
1017 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
1018 responseCode = atoi(buf);
1019 if( responseCode != 100 ) {
1020 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1026 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
1027 // Store it for later
1028 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
1029 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
1033 // Give three attempts
1034 for( i = 0; i < 3; i ++ )
1036 int ofs = strlen(pwd->pw_name)+strlen(salt);
1039 char *pass = getpass("Password: ");
1042 // Create hash string
1043 // <username><salt><hash>
1044 strcpy(tmp, pwd->pw_name);
1046 SHA1( (unsigned char*)pass, strlen(pass), h );
1047 memcpy(tmp+ofs, h, 20);
1050 SHA1( (unsigned char*)tmp, ofs+20, h );
1051 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1052 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
1053 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
1057 sendf(Socket, "PASS %s\n", tmpBuf);
1058 buf = ReadLine(Socket);
1060 responseCode = atoi(buf);
1062 if( responseCode == 200 ) break;
1063 // Bad username/password
1064 if( responseCode == 401 ) continue;
1066 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
1072 return 2; // 2 = Bad Password
1075 case 404: // Bad Username
1076 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
1081 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1082 printf("%s\n", buf);
1087 // Set effective user
1088 if( gsEffectiveUser ) {
1089 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
1091 buf = ReadLine(Socket);
1092 responseCode = atoi(buf);
1094 switch(responseCode)
1097 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1101 printf("Only coke members can use `dispense -u`\n");
1106 printf("Invalid user selected\n");
1111 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1112 printf("%s\n", buf);
1120 gbIsAuthenticated = 1;
1125 int GetUserBalance(int Socket)
1127 regmatch_t matches[6];
1134 if( gsEffectiveUser ) {
1135 gsUserName = gsEffectiveUser;
1138 pwd = getpwuid( getuid() );
1139 gsUserName = strdup(pwd->pw_name);
1143 sendf(Socket, "USER_INFO %s\n", gsUserName);
1144 buf = ReadLine(Socket);
1145 responseCode = atoi(buf);
1146 switch(responseCode)
1148 case 202: break; // Ok
1151 printf("Invalid user? (USER_INFO failed)\n");
1156 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1157 printf("%s\n", buf);
1162 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1164 giUserBalance = atoi( buf + matches[4].rm_so );
1165 gsUserFlags = strdup( buf + matches[5].rm_so );
1173 * \brief Read an item info response from the server
1174 * \param Dest Destination for the read item (strings will be on the heap)
1176 int ReadItemInfo(int Socket, tItem *Dest)
1181 regmatch_t matches[8];
1185 buf = ReadLine(Socket);
1186 responseCode = atoi(buf);
1188 switch(responseCode)
1193 printf("Bad item name\n");
1198 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n%s", responseCode, buf);
1202 RunRegex(&gItemRegex, buf, 8, matches, "Malformed server response");
1204 buf[ matches[3].rm_eo ] = '\0';
1205 buf[ matches[5].rm_eo ] = '\0';
1206 buf[ matches[7].rm_eo ] = '\0';
1208 statusStr = &buf[ matches[5].rm_so ];
1210 Dest->ID = atoi( buf + matches[4].rm_so );
1212 if( strcmp(statusStr, "avail") == 0 )
1214 else if( strcmp(statusStr, "sold") == 0 )
1216 else if( strcmp(statusStr, "error") == 0 )
1219 fprintf(stderr, "Unknown response from dispense server (status '%s')\n",
1223 Dest->Price = atoi( buf + matches[6].rm_so );
1225 // Hack a little to reduce heap fragmentation
1227 char tmpType[strlen(buf + matches[3].rm_so) + 1];
1228 char tmpDesc[strlen(buf + matches[7].rm_so) + 1];
1229 strcpy(tmpType, buf + matches[3].rm_so);
1230 strcpy(tmpDesc, buf + matches[7].rm_so);
1232 Dest->Type = strdup( tmpType );
1233 Dest->Desc = strdup( tmpDesc );
1240 * \brief Fill the item information structure
1241 * \return Boolean Failure
1243 void PopulateItemList(int Socket)
1248 char *itemType, *itemStart;
1250 regmatch_t matches[4];
1252 // Ask server for stock list
1253 send(Socket, "ENUM_ITEMS\n", 11, 0);
1254 buf = ReadLine(Socket);
1256 //printf("Output: %s\n", buf);
1258 responseCode = atoi(buf);
1259 if( responseCode != 201 ) {
1260 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1264 // - Get item list -
1267 // 201 Items <count>
1269 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1271 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1272 count = atoi( &buf[ matches[3].rm_so ] );
1275 if( strcmp(itemType, "Items") != 0 ) {
1277 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1282 itemStart = &buf[ matches[3].rm_eo ];
1287 gaItems = malloc( giNumItems * sizeof(tItem) );
1289 // Fetch item information
1290 for( i = 0; i < giNumItems; i ++ )
1292 ReadItemInfo( Socket, &gaItems[i] );
1296 buf = ReadLine(Socket);
1297 responseCode = atoi(buf);
1299 if( responseCode != 200 ) {
1300 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1311 * \brief Get information on an item
1312 * \return Boolean Failure
1314 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1319 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1321 if( ReadItemInfo(Socket, &item) )
1326 printf("%8s:%-2i %2i.%02i %s\n",
1328 item.Price/100, item.Price%100,
1338 * \brief Dispense an item
1339 * \return Boolean Failure
1341 int DispenseItem(int Socket, const char *Type, int ID)
1343 int ret, responseCode;
1346 // Check for a dry run
1348 printf("Dry Run - No action\n");
1353 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1354 buf = ReadLine(Socket);
1356 responseCode = atoi(buf);
1357 switch( responseCode )
1360 printf("Dispense OK\n");
1364 printf("Not authenticated\n");
1368 printf("Insufficient balance\n");
1372 printf("Bad item name\n");
1376 printf("Item failed to dispense, is the slot empty?\n");
1380 printf("Dispense not possible (slot empty/permissions)\n");
1384 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1394 * \brief Alter a user's balance
1396 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1401 // Check for a dry run
1403 printf("Dry Run - No action\n");
1407 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1408 buf = ReadLine(Socket);
1410 responseCode = atoi(buf);
1413 switch(responseCode)
1415 case 200: return 0; // OK
1417 fprintf(stderr, "Insufficient balance\n");
1419 case 403: // Not in coke
1420 fprintf(stderr, "You are not in coke (sucker)\n");
1422 case 404: // Unknown user
1423 fprintf(stderr, "Unknown user '%s'\n", Username);
1426 fprintf(stderr, "Unknown response code %i\n", responseCode);
1434 * \brief Set a user's balance
1435 * \note Only avaliable to dispense admins
1437 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1442 // Check for a dry run
1444 printf("Dry Run - No action\n");
1448 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1449 buf = ReadLine(Socket);
1451 responseCode = atoi(buf);
1454 switch(responseCode)
1456 case 200: return 0; // OK
1457 case 403: // Not in coke
1458 fprintf(stderr, "You are not an admin\n");
1460 case 404: // Unknown user
1461 fprintf(stderr, "Unknown user '%s'\n", Username);
1464 fprintf(stderr, "Unknown response code %i\n", responseCode);
1472 * \brief Give money to another user
1474 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1480 printf("Sorry, you can only give, you can't take.\n");
1484 // Fast return on zero
1485 if( Ammount == 0 ) {
1486 printf("Are you actually going to give any?\n");
1490 // Check for a dry run
1492 printf("Dry Run - No action\n");
1496 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1497 buf = ReadLine(Socket);
1499 responseCode = atoi(buf);
1502 switch(responseCode)
1504 case 200: return 0; // OK
1507 fprintf(stderr, "Insufficient balance\n");
1510 case 404: // Unknown user
1511 fprintf(stderr, "Unknown user '%s'\n", Username);
1515 fprintf(stderr, "Unknown response code %i\n", responseCode);
1524 * \brief Donate money to the club
1526 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1532 printf("Sorry, you can only give, you can't take.\n");
1536 // Fast return on zero
1537 if( Ammount == 0 ) {
1538 printf("Are you actually going to give any?\n");
1542 // Check for a dry run
1544 printf("Dry Run - No action\n");
1548 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1549 buf = ReadLine(Socket);
1551 responseCode = atoi(buf);
1554 switch(responseCode)
1556 case 200: return 0; // OK
1559 fprintf(stderr, "Insufficient balance\n");
1563 fprintf(stderr, "Unknown response code %i\n", responseCode);
1571 * \brief Enumerate users
1573 int Dispense_EnumUsers(int Socket)
1578 regmatch_t matches[4];
1580 if( giMinimumBalance != INT_MIN ) {
1581 if( giMaximumBalance != INT_MAX ) {
1582 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1585 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1589 if( giMaximumBalance != INT_MAX ) {
1590 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1593 sendf(Socket, "ENUM_USERS\n");
1596 buf = ReadLine(Socket);
1597 responseCode = atoi(buf);
1599 switch(responseCode)
1601 case 201: break; // Ok, length follows
1604 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1609 // Get count (not actually used)
1610 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1611 nUsers = atoi( buf + matches[3].rm_so );
1612 printf("%i users returned\n", nUsers);
1617 // Read returned users
1619 buf = ReadLine(Socket);
1620 responseCode = atoi(buf);
1622 if( responseCode != 202 ) break;
1624 _PrintUserLine(buf);
1626 } while(responseCode == 202);
1628 // Check final response
1629 if( responseCode != 200 ) {
1630 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1640 int Dispense_ShowUser(int Socket, const char *Username)
1643 int responseCode, ret;
1645 sendf(Socket, "USER_INFO %s\n", Username);
1646 buf = ReadLine(Socket);
1648 responseCode = atoi(buf);
1650 switch(responseCode)
1653 _PrintUserLine(buf);
1658 printf("Unknown user '%s'\n", Username);
1663 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1673 void _PrintUserLine(const char *Line)
1675 regmatch_t matches[6];
1678 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1683 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1684 char username[usernameLen + 1];
1685 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1686 char flags[flagsLen + 1];
1688 memcpy(username, Line + matches[3].rm_so, usernameLen);
1689 username[usernameLen] = '\0';
1690 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1691 flags[flagsLen] = '\0';
1693 bal = atoi(Line + matches[4].rm_so);
1694 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1698 int Dispense_AddUser(int Socket, const char *Username)
1701 int responseCode, ret;
1703 // Check for a dry run
1705 printf("Dry Run - No action\n");
1709 sendf(Socket, "USER_ADD %s\n", Username);
1711 buf = ReadLine(Socket);
1712 responseCode = atoi(buf);
1714 switch(responseCode)
1717 printf("User '%s' added\n", Username);
1722 printf("Only wheel can add users\n");
1727 printf("User '%s' already exists\n", Username);
1732 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1742 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1745 int responseCode, ret;
1747 // Check for a dry run
1749 printf("Dry Run - No action\n");
1753 // TODO: Pre-validate the string
1755 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1757 buf = ReadLine(Socket);
1758 responseCode = atoi(buf);
1760 switch(responseCode)
1763 printf("User '%s' updated\n", Username);
1768 printf("Only wheel can modify users\n");
1773 printf("User '%s' does not exist\n", Username);
1778 printf("Flag string is invalid\n");
1783 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1796 char *ReadLine(int Socket)
1798 static char buf[BUFSIZ];
1799 static int bufPos = 0;
1800 static int bufValid = 0;
1802 char *newline = NULL;
1804 char *ret = malloc(10);
1806 #if DEBUG_TRACE_SERVER
1807 printf("ReadLine: ");
1819 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1820 buf[bufPos+len] = '\0';
1823 newline = strchr( buf+bufPos, '\n' );
1828 retLen += strlen(buf+bufPos);
1829 ret = realloc(ret, retLen + 1);
1830 strcat( ret, buf+bufPos );
1833 int newLen = newline - (buf+bufPos) + 1;
1834 bufValid = len - newLen;
1837 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1840 #if DEBUG_TRACE_SERVER
1841 printf("%i '%s'\n", retLen, ret);
1847 int sendf(int Socket, const char *Format, ...)
1852 va_start(args, Format);
1853 len = vsnprintf(NULL, 0, Format, args);
1858 va_start(args, Format);
1859 vsnprintf(buf, len+1, Format, args);
1862 #if DEBUG_TRACE_SERVER
1863 printf("sendf: %s", buf);
1866 return send(Socket, buf, len, 0);
1870 char *trim(char *string)
1874 while( isspace(*string) )
1877 for( i = strlen(string); i--; )
1879 if( isspace(string[i]) )
1888 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1892 ret = regexec(regex, string, nMatches, matches, 0);
1893 if( ret && errorMessage ) {
1894 size_t len = regerror(ret, regex, NULL, 0);
1896 regerror(ret, regex, errorStr, len);
1897 printf("string = '%s'\n", string);
1898 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1905 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1907 int ret = regcomp(regex, pattern, flags);
1909 size_t len = regerror(ret, regex, NULL, 0);
1911 regerror(ret, regex, errorStr, len);
1912 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);