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 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
445 gaItems[i].Price, gaItems[i].Desc);
454 fgets(buffer, BUFSIZ, stdin);
458 if( buf[0] == 'q' ) break;
462 if( i != 0 || buf[0] == '0' )
464 if( i < 0 || i >= giNumItems ) {
465 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
474 // Check for a valid item ID
477 // Connect, Authenticate, dispense and close
478 sock = OpenConnection(gsDispenseServer, giDispensePort);
479 if( sock < 0 ) return -1;
481 Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
484 DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
497 " Show interactive list\n"
499 " Dispense named item\n"
500 " dispense give <user> <ammount> \"<reason>\"\n"
501 " Give money to another user\n"
502 " dispense donate <ammount> \"<reason>\"\n"
503 " Donate to the club\n"
504 " == Coke members == \n"
505 " dispense acct [<user>]\n"
506 " Show user balances\n"
507 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
508 " Alter a account value\n"
509 " == Dispense administrators ==\n"
510 " dispense acct <user> =<ammount> \"<reason>\"\n"
511 " Set an account balance\n"
512 " dispense user add <user>\n"
513 " Create new coke account (Admins only)\n"
514 " dispense user type <user> <flags>\n"
515 " Alter a user's flags\n"
516 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
517 " Flags are removed by preceding the name with '-' or '!'\n"
521 " Set a different user (Coke members only)\n"
525 " Use alternate GUI\n"
526 " -m <min balance>\n"
527 " -M <max balance>\n"
528 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
532 // -------------------
533 // --- NCurses GUI ---
534 // -------------------
536 * \brief Render the NCurses UI
538 int ShowNCursesUI(void)
540 // TODO: ncurses interface (with separation between item classes)
541 // - Hmm... that would require standardising the item ID to be <class>:<index>
546 const int displayMinWidth = 40;
547 const int displayMinItems = 8;
548 char *titleString = "Dispense";
549 int itemCount = displayMinItems;
552 int ret = -2; // -2: Used for marking "no return yet"
554 char balance_str[5+1+2+1]; // If $9999.99 is too little, something's wrong
561 if( gsEffectiveUser )
562 username = gsEffectiveUser;
564 pwd = getpwuid( getuid() );
565 username = pwd->pw_name;
568 snprintf(balance_str, sizeof balance_str, "$%i.%02i", giUserBalance/100, giUserBalance%100);
575 // - 6: randomly chosen (Need at least 3)
576 itemCount = LINES - 6;
577 if( itemCount > giNumItems )
578 itemCount = giNumItems;
581 height = itemCount + 3;
582 width = displayMinWidth;
585 xBase = COLS/2 - width/2;
586 yBase = LINES/2 - height/2;
591 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
594 for( i = 0; i < itemCount; i ++ )
596 move( yBase + 1 + i, xBase );
598 if( currentItem == itemBase + i ) {
606 // - Oh god, magic numbers!
607 if( i == 0 && itemBase > 0 ) {
609 times = width-1 - 8 - 3;
610 while(times--) addch(' ');
612 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
614 times = width-1 - 8 - 3;
615 while(times--) addch(' ');
619 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
623 // Scrollbar (if needed)
624 if( giNumItems > itemCount ) {
628 else if( i == itemCount - 1 ) {
632 int percentage = itemBase * 100 / (giNumItems-itemCount);
633 if( i-1 == percentage*(itemCount-3)/100 ) {
647 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
650 // - Username, balance, flags
651 PrintAlign(yBase+height-1, xBase+1, width-2,
652 username, ' ', balance_str, ' ', gsUserFlags);
666 //if( itemBase < giNumItems - (itemCount) )
668 if( currentItem < giNumItems - 1 )
670 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
676 if( currentItem > 0 )
678 if( itemBase + 1 > currentItem && itemBase > 0 )
694 ret = -1; // -1: Return with no dispense
698 // Check if the return value was changed
699 if( ret != -2 ) break;
711 * \brief Show item \a Index at (\a Col, \a Row)
712 * \note Part of the NCurses UI
714 void ShowItemAt(int Row, int Col, int Width, int Index)
722 if( Index < 0 || Index >= giNumItems ) {
727 name = gaItems[Index].Desc;
728 price = gaItems[Index].Price;
731 printw("%02i %s", Index, name);
733 getyx(stdscr, _y, _x);
734 // Assumes max 4 digit prices
735 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
736 while(times--) addch(' ');
737 printw("%4i", price);
741 * \brief Print a three-part string at the specified position (formatted)
742 * \note NCurses UI Helper
744 * Prints \a Left on the left of the area, \a Right on the righthand side
745 * and \a Mid in the middle of the area. These are padded with \a Pad1
746 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
748 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
749 * and the arguments to these are read in that order.
751 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
752 const char *Mid, char Pad2, const char *Right, ...)
754 int lLen, mLen, rLen;
759 // Get the length of the strings
760 va_start(args, Right);
761 lLen = vsnprintf(NULL, 0, Left, args);
762 mLen = vsnprintf(NULL, 0, Mid, args);
763 rLen = vsnprintf(NULL, 0, Right, args);
767 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
768 return ; // TODO: What to do?
774 va_start(args, Right);
778 vsnprintf(tmp, lLen+1, Left, args);
782 times = (Width - mLen)/2 - lLen;
783 while(times--) addch(Pad1);
787 vsnprintf(tmp, mLen+1, Mid, args);
791 times = (Width - mLen)/2 - rLen;
792 if( (Width - mLen) % 2 ) times ++;
793 while(times--) addch(Pad2);
797 vsnprintf(tmp, rLen+1, Right, args);
802 // ---------------------
803 // --- Coke Protocol ---
804 // ---------------------
805 int OpenConnection(const char *Host, int Port)
807 struct hostent *host;
808 struct sockaddr_in serverAddr;
811 host = gethostbyname(Host);
813 fprintf(stderr, "Unable to look up '%s'\n", Host);
817 memset(&serverAddr, 0, sizeof(serverAddr));
819 serverAddr.sin_family = AF_INET; // IPv4
820 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
821 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
822 serverAddr.sin_port = htons(Port);
824 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
826 fprintf(stderr, "Failed to create socket\n");
833 struct sockaddr_in localAddr;
834 memset(&localAddr, 0, sizeof(localAddr));
835 localAddr.sin_family = AF_INET; // IPv4
837 // Loop through all the top ports until one is avaliable
838 for( i = 1001; i < 1024; i ++)
840 localAddr.sin_port = htons(i); // IPv4
841 // Attempt to bind to low port for autoauth
842 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
846 printf("Warning: AUTOAUTH unavaliable\n");
849 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
850 fprintf(stderr, "Failed to connect to server\n");
858 * \brief Authenticate with the server
859 * \return Boolean Failure
861 int Authenticate(int Socket)
868 regmatch_t matches[4];
870 if( gbIsAuthenticated ) return 0;
873 pwd = getpwuid( getuid() );
875 // Attempt automatic authentication
876 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
878 // Check if it worked
879 buf = ReadLine(Socket);
881 responseCode = atoi(buf);
882 switch( responseCode )
884 case 200: // Autoauth succeeded, return
888 case 401: // Untrusted, attempt password authentication
891 sendf(Socket, "USER %s\n", pwd->pw_name);
892 printf("Using username %s\n", pwd->pw_name);
894 buf = ReadLine(Socket);
897 // Expected format: 100 SALT <something> ...
899 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
900 responseCode = atoi(buf);
901 if( responseCode != 100 ) {
902 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
908 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
909 // Store it for later
910 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
911 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
915 // Give three attempts
916 for( i = 0; i < 3; i ++ )
918 int ofs = strlen(pwd->pw_name)+strlen(salt);
921 char *pass = getpass("Password: ");
924 // Create hash string
925 // <username><salt><hash>
926 strcpy(tmp, pwd->pw_name);
928 SHA1( (unsigned char*)pass, strlen(pass), h );
929 memcpy(tmp+ofs, h, 20);
932 SHA1( (unsigned char*)tmp, ofs+20, h );
933 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
934 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
935 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
939 sendf(Socket, "PASS %s\n", tmpBuf);
940 buf = ReadLine(Socket);
942 responseCode = atoi(buf);
944 if( responseCode == 200 ) break;
945 // Bad username/password
946 if( responseCode == 401 ) continue;
948 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
954 return 2; // 2 = Bad Password
957 case 404: // Bad Username
958 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
963 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
969 // Set effective user
970 if( gsEffectiveUser ) {
971 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
973 buf = ReadLine(Socket);
974 responseCode = atoi(buf);
979 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
983 printf("Only coke members can use `dispense -u`\n");
988 printf("Invalid user selected\n");
993 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1002 gbIsAuthenticated = 1;
1007 int GetUserBalance(int Socket)
1009 regmatch_t matches[6];
1016 if( gsEffectiveUser ) {
1017 gsUserName = gsEffectiveUser;
1020 pwd = getpwuid( getuid() );
1021 gsUserName = strdup(pwd->pw_name);
1025 sendf(Socket, "USER_INFO %s\n", gsUserName);
1026 buf = ReadLine(Socket);
1027 responseCode = atoi(buf);
1028 switch(responseCode)
1030 case 202: break; // Ok
1033 printf("Invalid user? (USER_INFO failed)\n");
1038 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
1039 printf("%s\n", buf);
1044 RunRegex(&gUserInfoRegex, buf, 6, matches, "Malformed server response");
1046 giUserBalance = atoi( buf + matches[4].rm_so );
1047 gsUserFlags = strdup( buf + matches[5].rm_so );
1056 * \brief Fill the item information structure
1057 * \return Boolean Failure
1059 void PopulateItemList(int Socket)
1064 char *itemType, *itemStart;
1066 regmatch_t matches[4];
1068 // Ask server for stock list
1069 send(Socket, "ENUM_ITEMS\n", 11, 0);
1070 buf = ReadLine(Socket);
1072 //printf("Output: %s\n", buf);
1074 responseCode = atoi(buf);
1075 if( responseCode != 201 ) {
1076 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1080 // - Get item list -
1083 // 201 Items <count>
1085 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1087 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1088 count = atoi( &buf[ matches[3].rm_so ] );
1091 if( strcmp(itemType, "Items") != 0 ) {
1093 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1098 itemStart = &buf[ matches[3].rm_eo ];
1103 gaItems = malloc( giNumItems * sizeof(tItem) );
1105 // Fetch item information
1106 for( i = 0; i < giNumItems; i ++ )
1108 regmatch_t matches[7];
1111 buf = ReadLine(Socket);
1112 responseCode = atoi(buf);
1114 if( responseCode != 202 ) {
1115 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1119 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
1121 buf[ matches[3].rm_eo ] = '\0';
1123 gaItems[i].Type = strdup( buf + matches[3].rm_so );
1124 gaItems[i].ID = atoi( buf + matches[4].rm_so );
1125 gaItems[i].Price = atoi( buf + matches[5].rm_so );
1126 gaItems[i].Desc = strdup( buf + matches[6].rm_so );
1132 buf = ReadLine(Socket);
1133 responseCode = atoi(buf);
1135 if( responseCode != 200 ) {
1136 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1147 * \brief Get information on an item
1148 * \return Boolean Failure
1150 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1154 regmatch_t matches[7];
1159 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1160 buf = ReadLine(Socket);
1162 responseCode = atoi(buf);
1163 switch( responseCode )
1169 printf("Bad item name\n");
1174 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1180 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
1182 buf[ matches[3].rm_eo ] = '\0';
1184 type = buf + matches[3].rm_so; buf[matches[3].rm_eo] = '\0';
1185 id = atoi( buf + matches[4].rm_so );
1186 price = atoi( buf + matches[5].rm_so );
1187 desc = buf + matches[6].rm_so; buf[matches[6].rm_eo] = '\0';
1189 printf("%8s:%-2i %2i.%02i %s\n", type, id, price/100, price%100, desc);
1197 * \brief Dispense an item
1198 * \return Boolean Failure
1200 int DispenseItem(int Socket, const char *Type, int ID)
1202 int ret, responseCode;
1205 // Check for a dry run
1207 printf("Dry Run - No action\n");
1212 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1213 buf = ReadLine(Socket);
1215 responseCode = atoi(buf);
1216 switch( responseCode )
1219 printf("Dispense OK\n");
1223 printf("Not authenticated\n");
1227 printf("Insufficient balance\n");
1231 printf("Bad item name\n");
1235 printf("Item failed to dispense, is the slot empty?\n");
1239 printf("Dispense not possible (slot empty/permissions)\n");
1243 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1253 * \brief Alter a user's balance
1255 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1260 // Check for a dry run
1262 printf("Dry Run - No action\n");
1266 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1267 buf = ReadLine(Socket);
1269 responseCode = atoi(buf);
1272 switch(responseCode)
1274 case 200: return 0; // OK
1276 fprintf(stderr, "Insufficient balance\n");
1278 case 403: // Not in coke
1279 fprintf(stderr, "You are not in coke (sucker)\n");
1281 case 404: // Unknown user
1282 fprintf(stderr, "Unknown user '%s'\n", Username);
1285 fprintf(stderr, "Unknown response code %i\n", responseCode);
1293 * \brief Set a user's balance
1294 * \note Only avaliable to dispense admins
1296 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1301 // Check for a dry run
1303 printf("Dry Run - No action\n");
1307 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1308 buf = ReadLine(Socket);
1310 responseCode = atoi(buf);
1313 switch(responseCode)
1315 case 200: return 0; // OK
1316 case 403: // Not in coke
1317 fprintf(stderr, "You are not an admin\n");
1319 case 404: // Unknown user
1320 fprintf(stderr, "Unknown user '%s'\n", Username);
1323 fprintf(stderr, "Unknown response code %i\n", responseCode);
1331 * \brief Give money to another user
1333 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1339 printf("Sorry, you can only give, you can't take.\n");
1343 // Fast return on zero
1344 if( Ammount == 0 ) {
1345 printf("Are you actually going to give any?\n");
1349 // Check for a dry run
1351 printf("Dry Run - No action\n");
1355 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1356 buf = ReadLine(Socket);
1358 responseCode = atoi(buf);
1361 switch(responseCode)
1363 case 200: return 0; // OK
1366 fprintf(stderr, "Insufficient balance\n");
1369 case 404: // Unknown user
1370 fprintf(stderr, "Unknown user '%s'\n", Username);
1374 fprintf(stderr, "Unknown response code %i\n", responseCode);
1383 * \brief Donate money to the club
1385 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1391 printf("Sorry, you can only give, you can't take.\n");
1395 // Fast return on zero
1396 if( Ammount == 0 ) {
1397 printf("Are you actually going to give any?\n");
1401 // Check for a dry run
1403 printf("Dry Run - No action\n");
1407 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1408 buf = ReadLine(Socket);
1410 responseCode = atoi(buf);
1413 switch(responseCode)
1415 case 200: return 0; // OK
1418 fprintf(stderr, "Insufficient balance\n");
1422 fprintf(stderr, "Unknown response code %i\n", responseCode);
1430 * \brief Enumerate users
1432 int Dispense_EnumUsers(int Socket)
1437 regmatch_t matches[4];
1439 if( giMinimumBalance != INT_MIN ) {
1440 if( giMaximumBalance != INT_MAX ) {
1441 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1444 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1448 if( giMaximumBalance != INT_MAX ) {
1449 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1452 sendf(Socket, "ENUM_USERS\n");
1455 buf = ReadLine(Socket);
1456 responseCode = atoi(buf);
1458 switch(responseCode)
1460 case 201: break; // Ok, length follows
1463 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1468 // Get count (not actually used)
1469 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1470 nUsers = atoi( buf + matches[3].rm_so );
1471 printf("%i users returned\n", nUsers);
1476 // Read returned users
1478 buf = ReadLine(Socket);
1479 responseCode = atoi(buf);
1481 if( responseCode != 202 ) break;
1483 _PrintUserLine(buf);
1485 } while(responseCode == 202);
1487 // Check final response
1488 if( responseCode != 200 ) {
1489 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1499 int Dispense_ShowUser(int Socket, const char *Username)
1502 int responseCode, ret;
1504 sendf(Socket, "USER_INFO %s\n", Username);
1505 buf = ReadLine(Socket);
1507 responseCode = atoi(buf);
1509 switch(responseCode)
1512 _PrintUserLine(buf);
1517 printf("Unknown user '%s'\n", Username);
1522 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1532 void _PrintUserLine(const char *Line)
1534 regmatch_t matches[6];
1537 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1542 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1543 char username[usernameLen + 1];
1544 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1545 char flags[flagsLen + 1];
1547 memcpy(username, Line + matches[3].rm_so, usernameLen);
1548 username[usernameLen] = '\0';
1549 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1550 flags[flagsLen] = '\0';
1552 bal = atoi(Line + matches[4].rm_so);
1553 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1557 int Dispense_AddUser(int Socket, const char *Username)
1560 int responseCode, ret;
1562 // Check for a dry run
1564 printf("Dry Run - No action\n");
1568 sendf(Socket, "USER_ADD %s\n", Username);
1570 buf = ReadLine(Socket);
1571 responseCode = atoi(buf);
1573 switch(responseCode)
1576 printf("User '%s' added\n", Username);
1581 printf("Only wheel can add users\n");
1586 printf("User '%s' already exists\n", Username);
1591 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1601 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1604 int responseCode, ret;
1606 // Check for a dry run
1608 printf("Dry Run - No action\n");
1612 // TODO: Pre-validate the string
1614 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1616 buf = ReadLine(Socket);
1617 responseCode = atoi(buf);
1619 switch(responseCode)
1622 printf("User '%s' updated\n", Username);
1627 printf("Only wheel can modify users\n");
1632 printf("User '%s' does not exist\n", Username);
1637 printf("Flag string is invalid\n");
1642 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1655 char *ReadLine(int Socket)
1657 static char buf[BUFSIZ];
1658 static int bufPos = 0;
1659 static int bufValid = 0;
1661 char *newline = NULL;
1663 char *ret = malloc(10);
1665 #if DEBUG_TRACE_SERVER
1666 printf("ReadLine: ");
1678 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1679 buf[bufPos+len] = '\0';
1682 newline = strchr( buf+bufPos, '\n' );
1687 retLen += strlen(buf+bufPos);
1688 ret = realloc(ret, retLen + 1);
1689 strcat( ret, buf+bufPos );
1692 int newLen = newline - (buf+bufPos) + 1;
1693 bufValid = len - newLen;
1696 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1699 #if DEBUG_TRACE_SERVER
1700 printf("%i '%s'\n", retLen, ret);
1706 int sendf(int Socket, const char *Format, ...)
1711 va_start(args, Format);
1712 len = vsnprintf(NULL, 0, Format, args);
1717 va_start(args, Format);
1718 vsnprintf(buf, len+1, Format, args);
1721 #if DEBUG_TRACE_SERVER
1722 printf("sendf: %s", buf);
1725 return send(Socket, buf, len, 0);
1729 char *trim(char *string)
1733 while( isspace(*string) )
1736 for( i = strlen(string); i--; )
1738 if( isspace(string[i]) )
1747 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1751 ret = regexec(regex, string, nMatches, matches, 0);
1752 if( ret && errorMessage ) {
1753 size_t len = regerror(ret, regex, NULL, 0);
1755 regerror(ret, regex, errorStr, len);
1756 printf("string = '%s'\n", string);
1757 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1764 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1766 int ret = regcomp(regex, pattern, flags);
1768 size_t len = regerror(ret, regex, NULL, 0);
1770 regerror(ret, regex, errorStr, len);
1771 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);