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
33 typedef struct sItem {
41 int main(int argc, char *argv[]);
44 int ShowNCursesUI(void);
45 void ShowItemAt(int Row, int Col, int Width, int Index);
46 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
47 // --- Coke Server Communication ---
48 int OpenConnection(const char *Host, int Port);
49 int Authenticate(int Socket);
50 int GetUserBalance(int Socket);
51 void PopulateItemList(int Socket);
52 int Dispense_ItemInfo(int Socket, const char *Type, int ID);
53 int DispenseItem(int Socket, const char *Type, int ID);
54 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
55 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
56 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
57 int Dispense_Donate(int Socket, int Ammount, const char *Reason);
58 int Dispense_EnumUsers(int Socket);
59 int Dispense_ShowUser(int Socket, const char *Username);
60 void _PrintUserLine(const char *Line);
61 int Dispense_AddUser(int Socket, const char *Username);
62 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
64 char *ReadLine(int Socket);
65 int sendf(int Socket, const char *Format, ...);
66 char *trim(char *string);
67 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
68 void CompileRegex(regex_t *regex, const char *pattern, int flags);
71 char *gsDispenseServer = "heathred";
72 int giDispensePort = 11020;
76 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
77 int gbIsAuthenticated = 0;
79 char *gsItemPattern; //!< Item pattern
80 char *gsEffectiveUser; //!< '-u' Dispense as another user
81 int gbUseNCurses = 0; //!< '-G' Use the NCurses GUI?
82 int gbDryRun = 0; //!< '-n' Read-only
83 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
84 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
85 char *gsUserName; //!< User that dispense will happen as
86 char *gsUserFlags; //!< User's flag set
87 int giUserBalance=-1; //!< User balance (set by Authenticate)
90 int main(int argc, char *argv[])
96 // -- Create regular expressions
97 // > Code Type Count ...
98 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
99 // > Code Type Ident Price Desc
100 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z]+):([0-9]+)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
101 // > Code 'SALT' salt
102 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
103 // > Code 'User' Username Balance Flags
104 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
106 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
109 for( i = 1; i < argc; i ++ )
122 case 'm': // Minimum balance
123 if( i + 1 >= argc ) {
124 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
127 giMinimumBalance = atoi(argv[++i]);
129 case 'M': // Maximum balance
130 if( i + 1 >= argc ) {
131 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
134 giMaximumBalance = atoi(argv[++i]);
137 case 'u': // Override User
138 if( i + 1 >= argc ) {
139 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
142 gsEffectiveUser = argv[++i];
145 case 'H': // Override remote host
146 if( i + 1 >= argc ) {
147 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
150 gsDispenseServer = argv[++i];
152 case 'P': // Override remote port
153 if( i + 1 >= argc ) {
154 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
157 giDispensePort = atoi(argv[++i]);
163 case 'n': // Dry Run / read-only
174 if( strcmp(arg, "acct") == 0 )
177 sock = OpenConnection(gsDispenseServer, giDispensePort);
178 if( sock < 0 ) return -1;
181 if( i + 1 == argc ) {
182 Dispense_EnumUsers(sock);
186 // argv[i+1]: Username
191 if( i + 3 >= argc ) {
192 fprintf(stderr, "Error: `dispense acct' needs a reason\n");
196 // Authentication required
197 if( Authenticate(sock) )
200 // argv[i+1]: Username
201 // argv[i+2]: Ammount
204 if( argv[i+2][0] == '=' ) {
206 if( argv[i+2][1] != '0' && atoi(&argv[i+2][1]) == 0 ) {
207 fprintf(stderr, "Error: Invalid balance to be set\n");
211 Dispense_SetBalance(sock, argv[i+1], atoi(argv[i+2]+1), argv[i+3]);
215 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
219 // Show user information
220 Dispense_ShowUser(sock, argv[i+1]);
227 // - "Here, have some money."
228 if( strcmp(arg, "give") == 0 )
230 if( i + 3 >= argc ) {
231 fprintf(stderr, "`dispense give` takes three arguments\n");
236 // argv[i+1]: Destination
237 // argv[i+2]: Ammount
241 sock = OpenConnection(gsDispenseServer, giDispensePort);
242 if( sock < 0 ) return -1;
245 if( Authenticate(sock) )
248 Dispense_Give(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
253 // - User administration (Admin Only)
254 if( strcmp(arg, "user") == 0 )
256 // Check argument count
257 if( i + 1 >= argc ) {
258 fprintf(stderr, "Error: `dispense user` requires arguments\n");
264 sock = OpenConnection(gsDispenseServer, giDispensePort);
265 if( sock < 0 ) return -1;
267 // Attempt authentication
268 if( Authenticate(sock) )
272 if( strcmp(argv[i+1], "add") == 0 )
274 if( i + 2 >= argc ) {
275 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
280 Dispense_AddUser(sock, argv[i+2]);
283 else if( strcmp(argv[i+1], "type") == 0 )
285 if( i + 3 >= argc ) {
286 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
291 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
295 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
303 if( strcmp(arg, "donate") == 0 )
305 // Check argument count
306 if( i + 2 >= argc ) {
307 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
313 sock = OpenConnection(gsDispenseServer, giDispensePort);
314 if( sock < 0 ) return -1;
316 // Attempt authentication
317 if( Authenticate(sock) )
321 Dispense_Donate(sock, atoi(argv[i+1]), argv[i+1]);
327 // Item name / pattern
334 sock = OpenConnection(gsDispenseServer, giDispensePort);
335 if( sock < 0 ) return -1;
337 // Get the user's balance
338 GetUserBalance(sock);
341 PopulateItemList(sock);
343 // Disconnect from server
348 regmatch_t matches[3];
350 if( strcmp(gsItemPattern, "door") == 0 )
352 // Connect, Authenticate, dispense and close
353 sock = OpenConnection(gsDispenseServer, giDispensePort);
354 if( sock < 0 ) return -1;
356 DispenseItem(sock, "door", 0);
360 // Item id (<type>:<num>)
361 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
366 // Get and finish ident
367 ident = gsItemPattern + matches[1].rm_so;
368 gsItemPattern[matches[1].rm_eo] = '\0';
370 id = atoi( gsItemPattern + matches[2].rm_so );
372 // Connect, Authenticate, dispense and close
373 sock = OpenConnection(gsDispenseServer, giDispensePort);
374 if( sock < 0 ) return -1;
376 Dispense_ItemInfo(sock, ident, id);
379 DispenseItem(sock, ident, id);
383 // Item number (6 = coke)
384 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
386 i = atoi(gsItemPattern);
393 for( i = 0; i < giNumItems; i ++ )
395 // Prefix match (with case-insensitive match)
396 for( j = 0; gsItemPattern[j]; j ++ )
398 if( gaItems[i].Desc[j] == gsItemPattern[j] )
400 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
404 // Check if the prefix matched
405 if( gsItemPattern[j] != '\0' )
409 if( gaItems[i].Desc[j] == '\0' ) {
414 // Only one match allowed
419 // TODO: Allow ambiguous matches?
420 // or just print a wanrning
421 printf("Warning - Ambiguous pattern, stopping\n");
426 // Was a match found?
429 fprintf(stderr, "No item matches the passed string\n");
436 else if( gbUseNCurses )
442 // Very basic dispense interface
443 for( i = 0; i < giNumItems; i ++ ) {
444 if( strcmp(gaItems[i].Desc, "-") == 0 )
447 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
448 gaItems[i].Price, gaItems[i].Desc);
457 fgets(buffer, BUFSIZ, stdin);
461 if( buf[0] == 'q' ) break;
465 if( i != 0 || buf[0] == '0' )
467 if( i < 0 || i >= giNumItems ) {
468 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
477 // Check for a valid item ID
480 // Connect, Authenticate, dispense and close
481 sock = OpenConnection(gsDispenseServer, giDispensePort);
482 if( sock < 0 ) return -1;
484 Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
487 DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
500 " Show interactive list\n"
502 " Dispense named item\n"
503 " dispense give <user> <ammount> \"<reason>\"\n"
504 " Give money to another user\n"
505 " dispense donate <ammount> \"<reason>\"\n"
506 " Donate to the club\n"
507 " == Coke members == \n"
508 " dispense acct [<user>]\n"
509 " Show user balances\n"
510 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
511 " Alter a account value\n"
512 " == Dispense administrators ==\n"
513 " dispense acct <user> =<ammount> \"<reason>\"\n"
514 " Set an account balance\n"
515 " dispense user add <user>\n"
516 " Create new coke account (Admins only)\n"
517 " dispense user type <user> <flags>\n"
518 " Alter a user's flags\n"
519 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
520 " Flags are removed by preceding the name with '-' or '!'\n"
524 " Set a different user (Coke members only)\n"
528 " Use alternate GUI\n"
529 " -m <min balance>\n"
530 " -M <max balance>\n"
531 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
535 // -------------------
536 // --- NCurses GUI ---
537 // -------------------
539 * \brief Render the NCurses UI
541 int ShowNCursesUI(void)
543 // TODO: ncurses interface (with separation between item classes)
544 // - Hmm... that would require standardising the item ID to be <class>:<index>
549 const int displayMinWidth = 40;
550 const int displayMinItems = 8;
551 char *titleString = "Dispense";
552 int itemCount = displayMinItems;
555 int ret = -2; // -2: Used for marking "no return yet"
557 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
564 if( gsEffectiveUser )
565 username = gsEffectiveUser;
567 pwd = getpwuid( getuid() );
568 username = pwd->pw_name;
571 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, giUserBalance%100);
578 // - 6: randomly chosen (Need at least 3)
579 itemCount = LINES - 6;
580 if( itemCount > giNumItems )
581 itemCount = giNumItems;
584 height = itemCount + 3;
585 width = displayMinWidth;
588 xBase = COLS/2 - width/2;
589 yBase = LINES/2 - height/2;
594 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
597 for( i = 0; i < itemCount; i ++ )
599 move( yBase + 1 + i, xBase );
601 if( currentItem == itemBase + i ) {
608 // Check for the '...' row
609 // - Oh god, magic numbers!
610 if( i == 0 && itemBase > 0 ) {
612 times = width-1 - 8 - 3;
613 while(times--) addch(' ');
615 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
617 times = width-1 - 8 - 3;
618 while(times--) addch(' ');
622 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
626 // Scrollbar (if needed)
627 if( giNumItems > itemCount ) {
631 else if( i == itemCount - 1 ) {
635 int percentage = itemBase * 100 / (giNumItems-itemCount);
636 if( i-1 == percentage*(itemCount-3)/100 ) {
650 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
653 // - Username, balance, flags
654 PrintAlign(yBase+height-1, xBase+1, width-2,
655 username, ' ', balance_str, ' ', gsUserFlags);
669 //if( itemBase < giNumItems - (itemCount) )
671 if( currentItem < giNumItems - 1 )
680 if( currentItem > 0 )
683 currentItem = giNumItems - 1;
692 if( currentItem < itemBase + 1 && itemBase > 0 )
693 itemBase = currentItem - 1;
694 if( currentItem > itemBase + itemCount - 1 && itemBase < itemCount-1 )
695 itemBase = currentItem - itemCount + 1;
698 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
702 if( itemBase + 1 > currentItem && itemBase > 0 )
713 ret = -1; // -1: Return with no dispense
717 // Check if the return value was changed
718 if( ret != -2 ) break;
730 * \brief Show item \a Index at (\a Col, \a Row)
731 * \note Part of the NCurses UI
733 void ShowItemAt(int Row, int Col, int Width, int Index)
741 if( Index < 0 || Index >= giNumItems ) {
746 name = gaItems[Index].Desc;
747 price = gaItems[Index].Price;
750 // Spacer hack (Desc = "-")
751 if( gaItems[Index].Desc[0] == '-' && gaItems[Index].Desc[1] == '\0' )
756 printw("%02i %s", Index, name);
758 getyx(stdscr, _y, _x);
759 // Assumes max 4 digit prices
760 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
761 while(times--) addch(' ');
762 printw("%4i", price);
766 * \brief Print a three-part string at the specified position (formatted)
767 * \note NCurses UI Helper
769 * Prints \a Left on the left of the area, \a Right on the righthand side
770 * and \a Mid in the middle of the area. These are padded with \a Pad1
771 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
773 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
774 * and the arguments to these are read in that order.
776 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
777 const char *Mid, char Pad2, const char *Right, ...)
779 int lLen, mLen, rLen;
784 // Get the length of the strings
785 va_start(args, Right);
786 lLen = vsnprintf(NULL, 0, Left, args);
787 mLen = vsnprintf(NULL, 0, Mid, args);
788 rLen = vsnprintf(NULL, 0, Right, args);
792 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
793 return ; // TODO: What to do?
799 va_start(args, Right);
803 vsnprintf(tmp, lLen+1, Left, args);
807 times = (Width - mLen)/2 - lLen;
808 while(times--) addch(Pad1);
812 vsnprintf(tmp, mLen+1, Mid, args);
816 times = (Width - mLen)/2 - rLen;
817 if( (Width - mLen) % 2 ) times ++;
818 while(times--) addch(Pad2);
822 vsnprintf(tmp, rLen+1, Right, args);
827 // ---------------------
828 // --- Coke Protocol ---
829 // ---------------------
830 int OpenConnection(const char *Host, int Port)
832 struct hostent *host;
833 struct sockaddr_in serverAddr;
836 host = gethostbyname(Host);
838 fprintf(stderr, "Unable to look up '%s'\n", Host);
842 memset(&serverAddr, 0, sizeof(serverAddr));
844 serverAddr.sin_family = AF_INET; // IPv4
845 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
846 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
847 serverAddr.sin_port = htons(Port);
849 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
851 fprintf(stderr, "Failed to create socket\n");
858 struct sockaddr_in localAddr;
859 memset(&localAddr, 0, sizeof(localAddr));
860 localAddr.sin_family = AF_INET; // IPv4
862 // Loop through all the top ports until one is avaliable
863 for( i = 1001; i < 1024; i ++)
865 localAddr.sin_port = htons(i); // IPv4
866 // Attempt to bind to low port for autoauth
867 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
871 printf("Warning: AUTOAUTH unavaliable\n");
874 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
875 fprintf(stderr, "Failed to connect to server\n");
883 * \brief Authenticate with the server
884 * \return Boolean Failure
886 int Authenticate(int Socket)
893 regmatch_t matches[4];
895 if( gbIsAuthenticated ) return 0;
898 pwd = getpwuid( getuid() );
900 // Attempt automatic authentication
901 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
903 // Check if it worked
904 buf = ReadLine(Socket);
906 responseCode = atoi(buf);
907 switch( responseCode )
909 case 200: // Autoauth succeeded, return
913 case 401: // Untrusted, attempt password authentication
916 sendf(Socket, "USER %s\n", pwd->pw_name);
917 printf("Using username %s\n", pwd->pw_name);
919 buf = ReadLine(Socket);
922 // Expected format: 100 SALT <something> ...
924 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
925 responseCode = atoi(buf);
926 if( responseCode != 100 ) {
927 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
933 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
934 // Store it for later
935 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
936 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
940 // Give three attempts
941 for( i = 0; i < 3; i ++ )
943 int ofs = strlen(pwd->pw_name)+strlen(salt);
946 char *pass = getpass("Password: ");
949 // Create hash string
950 // <username><salt><hash>
951 strcpy(tmp, pwd->pw_name);
953 SHA1( (unsigned char*)pass, strlen(pass), h );
954 memcpy(tmp+ofs, h, 20);
957 SHA1( (unsigned char*)tmp, ofs+20, h );
958 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
959 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
960 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
964 sendf(Socket, "PASS %s\n", tmpBuf);
965 buf = ReadLine(Socket);
967 responseCode = atoi(buf);
969 if( responseCode == 200 ) break;
970 // Bad username/password
971 if( responseCode == 401 ) continue;
973 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
979 return 2; // 2 = Bad Password
982 case 404: // Bad Username
983 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
988 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
994 // Set effective user
995 if( gsEffectiveUser ) {
996 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
998 buf = ReadLine(Socket);
999 responseCode = atoi(buf);
1001 switch(responseCode)
1004 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
1008 printf("Only coke members can use `dispense -u`\n");
1013 printf("Invalid user selected\n");
1018 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1019 printf("%s\n", buf);
1027 gbIsAuthenticated = 1;
1032 int GetUserBalance(int Socket)
1034 regmatch_t matches[6];
1041 if( gsEffectiveUser ) {
1042 gsUserName = gsEffectiveUser;
1045 pwd = getpwuid( getuid() );
1046 gsUserName = strdup(pwd->pw_name);
1050 sendf(Socket, "USER_INFO %s\n", gsUserName);
1051 buf = ReadLine(Socket);
1052 responseCode = atoi(buf);
1053 switch(responseCode)
1055 case 202: break; // Ok
1058 printf("Invalid user? (USER_INFO failed)\n");
1063 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1064 printf("%s\n", buf);
1069 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1071 giUserBalance = atoi( buf + matches[4].rm_so );
1072 gsUserFlags = strdup( buf + matches[5].rm_so );
1081 * \brief Fill the item information structure
1082 * \return Boolean Failure
1084 void PopulateItemList(int Socket)
1089 char *itemType, *itemStart;
1091 regmatch_t matches[4];
1093 // Ask server for stock list
1094 send(Socket, "ENUM_ITEMS\n", 11, 0);
1095 buf = ReadLine(Socket);
1097 //printf("Output: %s\n", buf);
1099 responseCode = atoi(buf);
1100 if( responseCode != 201 ) {
1101 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1105 // - Get item list -
1108 // 201 Items <count>
1110 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1112 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1113 count = atoi( &buf[ matches[3].rm_so ] );
1116 if( strcmp(itemType, "Items") != 0 ) {
1118 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1123 itemStart = &buf[ matches[3].rm_eo ];
1128 gaItems = malloc( giNumItems * sizeof(tItem) );
1130 // Fetch item information
1131 for( i = 0; i < giNumItems; i ++ )
1133 regmatch_t matches[7];
1136 buf = ReadLine(Socket);
1137 responseCode = atoi(buf);
1139 if( responseCode != 202 ) {
1140 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1144 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
1146 buf[ matches[3].rm_eo ] = '\0';
1148 gaItems[i].Type = strdup( buf + matches[3].rm_so );
1149 gaItems[i].ID = atoi( buf + matches[4].rm_so );
1150 gaItems[i].Price = atoi( buf + matches[5].rm_so );
1151 gaItems[i].Desc = strdup( buf + matches[6].rm_so );
1157 buf = ReadLine(Socket);
1158 responseCode = atoi(buf);
1160 if( responseCode != 200 ) {
1161 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1172 * \brief Get information on an item
1173 * \return Boolean Failure
1175 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1179 regmatch_t matches[7];
1184 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1185 buf = ReadLine(Socket);
1187 responseCode = atoi(buf);
1188 switch( responseCode )
1194 printf("Bad item name\n");
1199 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1205 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
1207 buf[ matches[3].rm_eo ] = '\0';
1209 type = buf + matches[3].rm_so; buf[matches[3].rm_eo] = '\0';
1210 id = atoi( buf + matches[4].rm_so );
1211 price = atoi( buf + matches[5].rm_so );
1212 desc = buf + matches[6].rm_so; buf[matches[6].rm_eo] = '\0';
1214 printf("%8s:%-2i %2i.%02i %s\n", type, id, price/100, price%100, desc);
1222 * \brief Dispense an item
1223 * \return Boolean Failure
1225 int DispenseItem(int Socket, const char *Type, int ID)
1227 int ret, responseCode;
1230 // Check for a dry run
1232 printf("Dry Run - No action\n");
1237 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1238 buf = ReadLine(Socket);
1240 responseCode = atoi(buf);
1241 switch( responseCode )
1244 printf("Dispense OK\n");
1248 printf("Not authenticated\n");
1252 printf("Insufficient balance\n");
1256 printf("Bad item name\n");
1260 printf("Item failed to dispense, is the slot empty?\n");
1264 printf("Dispense not possible (slot empty/permissions)\n");
1268 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1278 * \brief Alter a user's balance
1280 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1285 // Check for a dry run
1287 printf("Dry Run - No action\n");
1291 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1292 buf = ReadLine(Socket);
1294 responseCode = atoi(buf);
1297 switch(responseCode)
1299 case 200: return 0; // OK
1301 fprintf(stderr, "Insufficient balance\n");
1303 case 403: // Not in coke
1304 fprintf(stderr, "You are not in coke (sucker)\n");
1306 case 404: // Unknown user
1307 fprintf(stderr, "Unknown user '%s'\n", Username);
1310 fprintf(stderr, "Unknown response code %i\n", responseCode);
1318 * \brief Set a user's balance
1319 * \note Only avaliable to dispense admins
1321 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1326 // Check for a dry run
1328 printf("Dry Run - No action\n");
1332 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1333 buf = ReadLine(Socket);
1335 responseCode = atoi(buf);
1338 switch(responseCode)
1340 case 200: return 0; // OK
1341 case 403: // Not in coke
1342 fprintf(stderr, "You are not an admin\n");
1344 case 404: // Unknown user
1345 fprintf(stderr, "Unknown user '%s'\n", Username);
1348 fprintf(stderr, "Unknown response code %i\n", responseCode);
1356 * \brief Give money to another user
1358 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1364 printf("Sorry, you can only give, you can't take.\n");
1368 // Fast return on zero
1369 if( Ammount == 0 ) {
1370 printf("Are you actually going to give any?\n");
1374 // Check for a dry run
1376 printf("Dry Run - No action\n");
1380 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1381 buf = ReadLine(Socket);
1383 responseCode = atoi(buf);
1386 switch(responseCode)
1388 case 200: return 0; // OK
1391 fprintf(stderr, "Insufficient balance\n");
1394 case 404: // Unknown user
1395 fprintf(stderr, "Unknown user '%s'\n", Username);
1399 fprintf(stderr, "Unknown response code %i\n", responseCode);
1408 * \brief Donate money to the club
1410 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1416 printf("Sorry, you can only give, you can't take.\n");
1420 // Fast return on zero
1421 if( Ammount == 0 ) {
1422 printf("Are you actually going to give any?\n");
1426 // Check for a dry run
1428 printf("Dry Run - No action\n");
1432 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1433 buf = ReadLine(Socket);
1435 responseCode = atoi(buf);
1438 switch(responseCode)
1440 case 200: return 0; // OK
1443 fprintf(stderr, "Insufficient balance\n");
1447 fprintf(stderr, "Unknown response code %i\n", responseCode);
1455 * \brief Enumerate users
1457 int Dispense_EnumUsers(int Socket)
1462 regmatch_t matches[4];
1464 if( giMinimumBalance != INT_MIN ) {
1465 if( giMaximumBalance != INT_MAX ) {
1466 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1469 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1473 if( giMaximumBalance != INT_MAX ) {
1474 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1477 sendf(Socket, "ENUM_USERS\n");
1480 buf = ReadLine(Socket);
1481 responseCode = atoi(buf);
1483 switch(responseCode)
1485 case 201: break; // Ok, length follows
1488 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1493 // Get count (not actually used)
1494 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1495 nUsers = atoi( buf + matches[3].rm_so );
1496 printf("%i users returned\n", nUsers);
1501 // Read returned users
1503 buf = ReadLine(Socket);
1504 responseCode = atoi(buf);
1506 if( responseCode != 202 ) break;
1508 _PrintUserLine(buf);
1510 } while(responseCode == 202);
1512 // Check final response
1513 if( responseCode != 200 ) {
1514 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1524 int Dispense_ShowUser(int Socket, const char *Username)
1527 int responseCode, ret;
1529 sendf(Socket, "USER_INFO %s\n", Username);
1530 buf = ReadLine(Socket);
1532 responseCode = atoi(buf);
1534 switch(responseCode)
1537 _PrintUserLine(buf);
1542 printf("Unknown user '%s'\n", Username);
1547 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1557 void _PrintUserLine(const char *Line)
1559 regmatch_t matches[6];
1562 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1567 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1568 char username[usernameLen + 1];
1569 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1570 char flags[flagsLen + 1];
1572 memcpy(username, Line + matches[3].rm_so, usernameLen);
1573 username[usernameLen] = '\0';
1574 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1575 flags[flagsLen] = '\0';
1577 bal = atoi(Line + matches[4].rm_so);
1578 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1582 int Dispense_AddUser(int Socket, const char *Username)
1585 int responseCode, ret;
1587 // Check for a dry run
1589 printf("Dry Run - No action\n");
1593 sendf(Socket, "USER_ADD %s\n", Username);
1595 buf = ReadLine(Socket);
1596 responseCode = atoi(buf);
1598 switch(responseCode)
1601 printf("User '%s' added\n", Username);
1606 printf("Only wheel can add users\n");
1611 printf("User '%s' already exists\n", Username);
1616 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1626 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1629 int responseCode, ret;
1631 // Check for a dry run
1633 printf("Dry Run - No action\n");
1637 // TODO: Pre-validate the string
1639 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1641 buf = ReadLine(Socket);
1642 responseCode = atoi(buf);
1644 switch(responseCode)
1647 printf("User '%s' updated\n", Username);
1652 printf("Only wheel can modify users\n");
1657 printf("User '%s' does not exist\n", Username);
1662 printf("Flag string is invalid\n");
1667 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1680 char *ReadLine(int Socket)
1682 static char buf[BUFSIZ];
1683 static int bufPos = 0;
1684 static int bufValid = 0;
1686 char *newline = NULL;
1688 char *ret = malloc(10);
1690 #if DEBUG_TRACE_SERVER
1691 printf("ReadLine: ");
1703 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1704 buf[bufPos+len] = '\0';
1707 newline = strchr( buf+bufPos, '\n' );
1712 retLen += strlen(buf+bufPos);
1713 ret = realloc(ret, retLen + 1);
1714 strcat( ret, buf+bufPos );
1717 int newLen = newline - (buf+bufPos) + 1;
1718 bufValid = len - newLen;
1721 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1724 #if DEBUG_TRACE_SERVER
1725 printf("%i '%s'\n", retLen, ret);
1731 int sendf(int Socket, const char *Format, ...)
1736 va_start(args, Format);
1737 len = vsnprintf(NULL, 0, Format, args);
1742 va_start(args, Format);
1743 vsnprintf(buf, len+1, Format, args);
1746 #if DEBUG_TRACE_SERVER
1747 printf("sendf: %s", buf);
1750 return send(Socket, buf, len, 0);
1754 char *trim(char *string)
1758 while( isspace(*string) )
1761 for( i = strlen(string); i--; )
1763 if( isspace(string[i]) )
1772 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1776 ret = regexec(regex, string, nMatches, matches, 0);
1777 if( ret && errorMessage ) {
1778 size_t len = regerror(ret, regex, NULL, 0);
1780 regerror(ret, regex, errorStr, len);
1781 printf("string = '%s'\n", string);
1782 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1789 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1791 int ret = regcomp(regex, pattern, flags);
1793 size_t len = regerror(ret, regex, NULL, 0);
1795 regerror(ret, regex, errorStr, len);
1796 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);