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 void PopulateItemList(int Socket);
51 int Dispense_ItemInfo(int Socket, const char *Type, int ID);
52 int DispenseItem(int Socket, const char *Type, int ID);
53 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
54 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
55 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
56 int Dispense_Donate(int Socket, int Ammount, const char *Reason);
57 int Dispense_EnumUsers(int Socket);
58 int Dispense_ShowUser(int Socket, const char *Username);
59 void _PrintUserLine(const char *Line);
60 int Dispense_AddUser(int Socket, const char *Username);
61 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
63 char *ReadLine(int Socket);
64 int sendf(int Socket, const char *Format, ...);
65 char *trim(char *string);
66 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
67 void CompileRegex(regex_t *regex, const char *pattern, int flags);
70 char *gsDispenseServer = "heathred";
71 int giDispensePort = 11020;
75 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex, gUserItemIdentRegex;
76 int gbIsAuthenticated = 0;
78 char *gsItemPattern; //!< Item pattern
79 char *gsEffectiveUser; //!< '-u' Dispense as another user
80 int gbUseNCurses = 0; //!< '-G' Use the NCurses GUI?
81 int gbDryRun = 0; //!< '-n' Read-only
82 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
83 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
86 int main(int argc, char *argv[])
92 // -- Create regular expressions
93 // > Code Type Count ...
94 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
95 // > Code Type Ident Price Desc
96 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z]+):([0-9]+)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
98 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
99 // > Code 'User' Username Balance Flags
100 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
102 CompileRegex(&gUserItemIdentRegex, "^([A-Za-z]+):([0-9]+)$", REG_EXTENDED);
105 for( i = 1; i < argc; i ++ )
118 case 'm': // Minimum balance
119 if( i + 1 >= argc ) {
120 fprintf(stderr, "%s: -m takes an argument\n", argv[0]);
123 giMinimumBalance = atoi(argv[++i]);
125 case 'M': // Maximum balance
126 if( i + 1 >= argc ) {
127 fprintf(stderr, "%s: -M takes an argument\n", argv[0]);
130 giMaximumBalance = atoi(argv[++i]);
133 case 'u': // Override User
134 if( i + 1 >= argc ) {
135 fprintf(stderr, "%s: -u takes an argument\n", argv[0]);
138 gsEffectiveUser = argv[++i];
141 case 'H': // Override remote host
142 if( i + 1 >= argc ) {
143 fprintf(stderr, "%s: -H takes an argument\n", argv[0]);
146 gsDispenseServer = argv[++i];
148 case 'P': // Override remote port
149 if( i + 1 >= argc ) {
150 fprintf(stderr, "%s: -P takes an argument\n", argv[0]);
153 giDispensePort = atoi(argv[++i]);
159 case 'n': // Dry Run / read-only
170 if( strcmp(arg, "acct") == 0 )
173 sock = OpenConnection(gsDispenseServer, giDispensePort);
174 if( sock < 0 ) return -1;
177 if( i + 1 == argc ) {
178 Dispense_EnumUsers(sock);
182 // argv[i+1]: Username
187 if( i + 3 >= argc ) {
188 fprintf(stderr, "Error: `dispense acct' needs a reason\n");
192 // Authentication required
193 if( Authenticate(sock) )
196 // argv[i+1]: Username
197 // argv[i+2]: Ammount
200 if( argv[i+2][0] == '=' ) {
202 if( argv[i+2][1] != '0' && atoi(&argv[i+2][1]) == 0 ) {
203 fprintf(stderr, "Error: Invalid balance to be set\n");
207 Dispense_SetBalance(sock, argv[i+1], atoi(argv[i+2]+1), argv[i+3]);
211 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
215 // Show user information
216 Dispense_ShowUser(sock, argv[i+1]);
223 // - "Here, have some money."
224 if( strcmp(arg, "give") == 0 )
226 if( i + 3 >= argc ) {
227 fprintf(stderr, "`dispense give` takes three arguments\n");
232 // argv[i+1]: Destination
233 // argv[i+2]: Ammount
237 sock = OpenConnection(gsDispenseServer, giDispensePort);
238 if( sock < 0 ) return -1;
241 if( Authenticate(sock) )
244 Dispense_Give(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
249 // - User administration (Admin Only)
250 if( strcmp(arg, "user") == 0 )
252 // Check argument count
253 if( i + 1 >= argc ) {
254 fprintf(stderr, "Error: `dispense user` requires arguments\n");
260 sock = OpenConnection(gsDispenseServer, giDispensePort);
261 if( sock < 0 ) return -1;
263 // Attempt authentication
264 if( Authenticate(sock) )
268 if( strcmp(argv[i+1], "add") == 0 )
270 if( i + 2 >= argc ) {
271 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
276 Dispense_AddUser(sock, argv[i+2]);
279 else if( strcmp(argv[i+1], "type") == 0 )
281 if( i + 3 >= argc ) {
282 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
287 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
291 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
299 if( strcmp(arg, "donate") == 0 )
301 // Check argument count
302 if( i + 2 >= argc ) {
303 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
309 sock = OpenConnection(gsDispenseServer, giDispensePort);
310 if( sock < 0 ) return -1;
312 // Attempt authentication
313 if( Authenticate(sock) )
317 Dispense_Donate(sock, atoi(argv[i+1]), argv[i+1]);
323 // Item name / pattern
330 sock = OpenConnection(gsDispenseServer, giDispensePort);
331 if( sock < 0 ) return -1;
334 PopulateItemList(sock);
336 // Disconnect from server
341 regmatch_t matches[3];
343 if( strcmp(gsItemPattern, "door") == 0 )
345 // Connect, Authenticate, dispense and close
346 sock = OpenConnection(gsDispenseServer, giDispensePort);
347 if( sock < 0 ) return -1;
349 DispenseItem(sock, "door", 0);
353 // Item id (<type>:<num>)
354 else if( RunRegex(&gUserItemIdentRegex, gsItemPattern, 3, matches, NULL) == 0 )
359 // Get and finish ident
360 ident = gsItemPattern + matches[1].rm_so;
361 gsItemPattern[matches[1].rm_eo] = '\0';
363 id = atoi( gsItemPattern + matches[2].rm_so );
365 // Connect, Authenticate, dispense and close
366 sock = OpenConnection(gsDispenseServer, giDispensePort);
367 if( sock < 0 ) return -1;
369 Dispense_ItemInfo(sock, ident, id);
372 DispenseItem(sock, ident, id);
376 // Item number (6 = coke)
377 else if( strcmp(gsItemPattern, "0") == 0 || atoi(gsItemPattern) > 0 )
379 i = atoi(gsItemPattern);
386 for( i = 0; i < giNumItems; i ++ )
388 // Prefix match (with case-insensitive match)
389 for( j = 0; gsItemPattern[j]; j ++ )
391 if( gaItems[i].Desc[j] == gsItemPattern[j] )
393 if( tolower(gaItems[i].Desc[j]) == tolower(gsItemPattern[j]) )
397 // Check if the prefix matched
398 if( gsItemPattern[j] != '\0' )
402 if( gaItems[i].Desc[j] == '\0' ) {
407 // Only one match allowed
412 // TODO: Allow ambiguous matches?
418 fprintf(stderr, "No item matches the passed string\n");
425 else if( gbUseNCurses )
431 // Very basic dispense interface
432 for( i = 0; i < giNumItems; i ++ ) {
433 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
434 gaItems[i].Price, gaItems[i].Desc);
443 fgets(buffer, BUFSIZ, stdin);
447 if( buf[0] == 'q' ) break;
451 if( i != 0 || buf[0] == '0' )
453 if( i < 0 || i >= giNumItems ) {
454 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
463 // Check for a valid item ID
466 // Connect, Authenticate, dispense and close
467 sock = OpenConnection(gsDispenseServer, giDispensePort);
468 if( sock < 0 ) return -1;
470 Dispense_ItemInfo(sock, gaItems[i].Type, gaItems[i].ID);
473 DispenseItem(sock, gaItems[i].Type, gaItems[i].ID);
486 " Show interactive list\n"
488 " Dispense named item\n"
489 " dispense give <user> <ammount> \"<reason>\"\n"
490 " Give money to another user\n"
491 " dispense donate <ammount> \"<reason>\"\n"
492 " Donate to the club\n"
493 " == Coke members == \n"
494 " dispense acct [<user>]\n"
495 " Show user balances\n"
496 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
497 " Alter a account value\n"
498 " == Dispense administrators ==\n"
499 " dispense acct <user> =<ammount> \"<reason>\"\n"
500 " Set an account balance\n"
501 " dispense user add <user>\n"
502 " Create new coke account (Admins only)\n"
503 " dispense user type <user> <flags>\n"
504 " Alter a user's flags\n"
505 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
506 " Flags are removed by preceding the name with '-' or '!'\n"
510 " Set a different user (Coke members only)\n"
514 " Use alternate GUI\n"
515 " -m <min balance>\n"
516 " -M <max balance>\n"
517 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
521 // -------------------
522 // --- NCurses GUI ---
523 // -------------------
525 * \brief Render the NCurses UI
527 int ShowNCursesUI(void)
529 // TODO: ncurses interface (with separation between item classes)
530 // - Hmm... that would require standardising the item ID to be <class>:<index>
535 const int displayMinWidth = 40;
536 const int displayMinItems = 8;
537 char *titleString = "Dispense";
538 int itemCount = displayMinItems;
541 int ret = -2; // -2: Used for marking "no return yet"
550 // - 6: randomly chosen (Need at least 3)
551 itemCount = LINES - 6;
552 if( itemCount > giNumItems )
553 itemCount = giNumItems;
556 height = itemCount + 3;
557 width = displayMinWidth;
560 xBase = COLS/2 - width/2;
561 yBase = LINES/2 - height/2;
566 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
569 for( i = 0; i < itemCount; i ++ )
571 move( yBase + 1 + i, xBase );
573 if( currentItem == itemBase + i ) {
581 // - Oh god, magic numbers!
582 if( i == 0 && itemBase > 0 ) {
584 times = width-1 - 8 - 3;
585 while(times--) addch(' ');
587 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
589 times = width-1 - 8 - 3;
590 while(times--) addch(' ');
594 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
598 // Scrollbar (if needed)
599 if( giNumItems > itemCount ) {
603 else if( i == itemCount - 1 ) {
607 int percentage = itemBase * 100 / (giNumItems-itemCount);
608 if( i-1 == percentage*(itemCount-3)/100 ) {
622 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
635 //if( itemBase < giNumItems - (itemCount) )
637 if( currentItem < giNumItems - 1 )
639 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
645 if( currentItem > 0 )
647 if( itemBase + 1 > currentItem && itemBase > 0 )
663 ret = -1; // -1: Return with no dispense
667 // Check if the return value was changed
668 if( ret != -2 ) break;
680 * \brief Show item \a Index at (\a Col, \a Row)
681 * \note Part of the NCurses UI
683 void ShowItemAt(int Row, int Col, int Width, int Index)
691 if( Index < 0 || Index >= giNumItems ) {
696 name = gaItems[Index].Desc;
697 price = gaItems[Index].Price;
700 printw("%02i %s", Index, name);
702 getyx(stdscr, _y, _x);
703 // Assumes max 4 digit prices
704 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
705 while(times--) addch(' ');
706 printw("%4i", price);
710 * \brief Print a three-part string at the specified position (formatted)
711 * \note NCurses UI Helper
713 * Prints \a Left on the left of the area, \a Right on the righthand side
714 * and \a Mid in the middle of the area. These are padded with \a Pad1
715 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
717 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
718 * and the arguments to these are read in that order.
720 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
721 const char *Mid, char Pad2, const char *Right, ...)
723 int lLen, mLen, rLen;
728 // Get the length of the strings
729 va_start(args, Right);
730 lLen = vsnprintf(NULL, 0, Left, args);
731 mLen = vsnprintf(NULL, 0, Mid, args);
732 rLen = vsnprintf(NULL, 0, Right, args);
736 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
737 return ; // TODO: What to do?
743 va_start(args, Right);
747 vsnprintf(tmp, lLen+1, Left, args);
751 times = Width/2 - mLen/2 - lLen;
752 while(times--) addch(Pad1);
756 vsnprintf(tmp, mLen+1, Mid, args);
760 times = Width/2 - mLen/2 - rLen;
761 while(times--) addch(Pad2);
765 vsnprintf(tmp, rLen+1, Right, args);
770 // ---------------------
771 // --- Coke Protocol ---
772 // ---------------------
773 int OpenConnection(const char *Host, int Port)
775 struct hostent *host;
776 struct sockaddr_in serverAddr;
779 host = gethostbyname(Host);
781 fprintf(stderr, "Unable to look up '%s'\n", Host);
785 memset(&serverAddr, 0, sizeof(serverAddr));
787 serverAddr.sin_family = AF_INET; // IPv4
788 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
789 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
790 serverAddr.sin_port = htons(Port);
792 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
794 fprintf(stderr, "Failed to create socket\n");
801 struct sockaddr_in localAddr;
802 memset(&localAddr, 0, sizeof(localAddr));
803 localAddr.sin_family = AF_INET; // IPv4
805 // Loop through all the top ports until one is avaliable
806 for( i = 1001; i < 1024; i ++)
808 localAddr.sin_port = htons(i); // IPv4
809 // Attempt to bind to low port for autoauth
810 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
814 printf("Warning: AUTOAUTH unavaliable\n");
817 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
818 fprintf(stderr, "Failed to connect to server\n");
826 * \brief Authenticate with the server
827 * \return Boolean Failure
829 int Authenticate(int Socket)
836 regmatch_t matches[4];
838 if( gbIsAuthenticated ) return 0;
841 pwd = getpwuid( getuid() );
843 // Attempt automatic authentication
844 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
846 // Check if it worked
847 buf = ReadLine(Socket);
849 responseCode = atoi(buf);
850 switch( responseCode )
852 case 200: // Autoauth succeeded, return
856 case 401: // Untrusted, attempt password authentication
859 sendf(Socket, "USER %s\n", pwd->pw_name);
860 printf("Using username %s\n", pwd->pw_name);
862 buf = ReadLine(Socket);
865 // Expected format: 100 SALT <something> ...
867 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
868 responseCode = atoi(buf);
869 if( responseCode != 100 ) {
870 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
876 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
877 // Store it for later
878 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
879 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
883 // Give three attempts
884 for( i = 0; i < 3; i ++ )
886 int ofs = strlen(pwd->pw_name)+strlen(salt);
889 char *pass = getpass("Password: ");
892 // Create hash string
893 // <username><salt><hash>
894 strcpy(tmp, pwd->pw_name);
896 SHA1( (unsigned char*)pass, strlen(pass), h );
897 memcpy(tmp+ofs, h, 20);
900 SHA1( (unsigned char*)tmp, ofs+20, h );
901 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
902 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
903 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
907 sendf(Socket, "PASS %s\n", tmpBuf);
908 buf = ReadLine(Socket);
910 responseCode = atoi(buf);
912 if( responseCode == 200 ) break;
913 // Bad username/password
914 if( responseCode == 401 ) continue;
916 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
922 return 2; // 2 = Bad Password
925 case 404: // Bad Username
926 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
931 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
937 // Set effective user
938 if( gsEffectiveUser ) {
939 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
941 buf = ReadLine(Socket);
942 responseCode = atoi(buf);
947 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
951 printf("Only coke members can use `dispense -u`\n");
956 printf("Invalid user selected\n");
961 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
970 gbIsAuthenticated = 1;
977 * \brief Fill the item information structure
978 * \return Boolean Failure
980 void PopulateItemList(int Socket)
985 char *itemType, *itemStart;
987 regmatch_t matches[4];
989 // Ask server for stock list
990 send(Socket, "ENUM_ITEMS\n", 11, 0);
991 buf = ReadLine(Socket);
993 //printf("Output: %s\n", buf);
995 responseCode = atoi(buf);
996 if( responseCode != 201 ) {
997 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1001 // - Get item list -
1004 // 201 Items <count>
1006 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1008 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
1009 count = atoi( &buf[ matches[3].rm_so ] );
1012 if( strcmp(itemType, "Items") != 0 ) {
1014 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
1019 itemStart = &buf[ matches[3].rm_eo ];
1024 gaItems = malloc( giNumItems * sizeof(tItem) );
1026 // Fetch item information
1027 for( i = 0; i < giNumItems; i ++ )
1029 regmatch_t matches[7];
1032 buf = ReadLine(Socket);
1033 responseCode = atoi(buf);
1035 if( responseCode != 202 ) {
1036 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
1040 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
1042 buf[ matches[3].rm_eo ] = '\0';
1044 gaItems[i].Type = strdup( buf + matches[3].rm_so );
1045 gaItems[i].ID = atoi( buf + matches[4].rm_so );
1046 gaItems[i].Price = atoi( buf + matches[5].rm_so );
1047 gaItems[i].Desc = strdup( buf + matches[6].rm_so );
1053 buf = ReadLine(Socket);
1054 responseCode = atoi(buf);
1056 if( responseCode != 200 ) {
1057 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
1068 * \brief Get information on an item
1069 * \return Boolean Failure
1071 int Dispense_ItemInfo(int Socket, const char *Type, int ID)
1075 regmatch_t matches[7];
1080 sendf(Socket, "ITEM_INFO %s:%i\n", Type, ID);
1081 buf = ReadLine(Socket);
1083 responseCode = atoi(buf);
1084 switch( responseCode )
1090 printf("Bad item name\n");
1095 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1101 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
1103 buf[ matches[3].rm_eo ] = '\0';
1105 type = buf + matches[3].rm_so; buf[matches[3].rm_eo] = '\0';
1106 id = atoi( buf + matches[4].rm_so );
1107 price = atoi( buf + matches[5].rm_so );
1108 desc = buf + matches[6].rm_so; buf[matches[6].rm_eo] = '\0';
1110 printf("%8s:%-2i %2i.%02i %s\n", type, id, price/100, price%100, desc);
1118 * \brief Dispense an item
1119 * \return Boolean Failure
1121 int DispenseItem(int Socket, const char *Type, int ID)
1123 int ret, responseCode;
1126 // Check for a dry run
1128 printf("Dry Run - No action\n");
1133 sendf(Socket, "DISPENSE %s:%i\n", Type, ID);
1134 buf = ReadLine(Socket);
1136 responseCode = atoi(buf);
1137 switch( responseCode )
1140 printf("Dispense OK\n");
1144 printf("Not authenticated\n");
1148 printf("Insufficient balance\n");
1152 printf("Bad item name\n");
1156 printf("Item failed to dispense, is the slot empty?\n");
1160 printf("Dispense not possible (slot empty/permissions)\n");
1164 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1174 * \brief Alter a user's balance
1176 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1181 // Check for a dry run
1183 printf("Dry Run - No action\n");
1187 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1188 buf = ReadLine(Socket);
1190 responseCode = atoi(buf);
1193 switch(responseCode)
1195 case 200: return 0; // OK
1197 fprintf(stderr, "Insufficient balance\n");
1199 case 403: // Not in coke
1200 fprintf(stderr, "You are not in coke (sucker)\n");
1202 case 404: // Unknown user
1203 fprintf(stderr, "Unknown user '%s'\n", Username);
1206 fprintf(stderr, "Unknown response code %i\n", responseCode);
1214 * \brief Set a user's balance
1215 * \note Only avaliable to dispense admins
1217 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1222 // Check for a dry run
1224 printf("Dry Run - No action\n");
1228 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1229 buf = ReadLine(Socket);
1231 responseCode = atoi(buf);
1234 switch(responseCode)
1236 case 200: return 0; // OK
1237 case 403: // Not in coke
1238 fprintf(stderr, "You are not an admin\n");
1240 case 404: // Unknown user
1241 fprintf(stderr, "Unknown user '%s'\n", Username);
1244 fprintf(stderr, "Unknown response code %i\n", responseCode);
1252 * \brief Give money to another user
1254 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1260 printf("Sorry, you can only give, you can't take.\n");
1264 // Fast return on zero
1265 if( Ammount == 0 ) {
1266 printf("Are you actually going to give any?\n");
1270 // Check for a dry run
1272 printf("Dry Run - No action\n");
1276 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1277 buf = ReadLine(Socket);
1279 responseCode = atoi(buf);
1282 switch(responseCode)
1284 case 200: return 0; // OK
1287 fprintf(stderr, "Insufficient balance\n");
1290 case 404: // Unknown user
1291 fprintf(stderr, "Unknown user '%s'\n", Username);
1295 fprintf(stderr, "Unknown response code %i\n", responseCode);
1304 * \brief Donate money to the club
1306 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1312 printf("Sorry, you can only give, you can't take.\n");
1316 // Fast return on zero
1317 if( Ammount == 0 ) {
1318 printf("Are you actually going to give any?\n");
1322 // Check for a dry run
1324 printf("Dry Run - No action\n");
1328 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1329 buf = ReadLine(Socket);
1331 responseCode = atoi(buf);
1334 switch(responseCode)
1336 case 200: return 0; // OK
1339 fprintf(stderr, "Insufficient balance\n");
1343 fprintf(stderr, "Unknown response code %i\n", responseCode);
1351 * \brief Enumerate users
1353 int Dispense_EnumUsers(int Socket)
1358 regmatch_t matches[4];
1360 if( giMinimumBalance != INT_MIN ) {
1361 if( giMaximumBalance != INT_MAX ) {
1362 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1365 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1369 if( giMaximumBalance != INT_MAX ) {
1370 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1373 sendf(Socket, "ENUM_USERS\n");
1376 buf = ReadLine(Socket);
1377 responseCode = atoi(buf);
1379 switch(responseCode)
1381 case 201: break; // Ok, length follows
1384 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1389 // Get count (not actually used)
1390 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1391 nUsers = atoi( buf + matches[3].rm_so );
1392 printf("%i users returned\n", nUsers);
1397 // Read returned users
1399 buf = ReadLine(Socket);
1400 responseCode = atoi(buf);
1402 if( responseCode != 202 ) break;
1404 _PrintUserLine(buf);
1406 } while(responseCode == 202);
1408 // Check final response
1409 if( responseCode != 200 ) {
1410 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1420 int Dispense_ShowUser(int Socket, const char *Username)
1423 int responseCode, ret;
1425 sendf(Socket, "USER_INFO %s\n", Username);
1426 buf = ReadLine(Socket);
1428 responseCode = atoi(buf);
1430 switch(responseCode)
1433 _PrintUserLine(buf);
1438 printf("Unknown user '%s'\n", Username);
1443 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1453 void _PrintUserLine(const char *Line)
1455 regmatch_t matches[6];
1458 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1463 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1464 char username[usernameLen + 1];
1465 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1466 char flags[flagsLen + 1];
1468 memcpy(username, Line + matches[3].rm_so, usernameLen);
1469 username[usernameLen] = '\0';
1470 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1471 flags[flagsLen] = '\0';
1473 bal = atoi(Line + matches[4].rm_so);
1474 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1478 int Dispense_AddUser(int Socket, const char *Username)
1481 int responseCode, ret;
1483 // Check for a dry run
1485 printf("Dry Run - No action\n");
1489 sendf(Socket, "USER_ADD %s\n", Username);
1491 buf = ReadLine(Socket);
1492 responseCode = atoi(buf);
1494 switch(responseCode)
1497 printf("User '%s' added\n", Username);
1502 printf("Only wheel can add users\n");
1507 printf("User '%s' already exists\n", Username);
1512 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1522 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1525 int responseCode, ret;
1527 // Check for a dry run
1529 printf("Dry Run - No action\n");
1533 // TODO: Pre-validate the string
1535 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1537 buf = ReadLine(Socket);
1538 responseCode = atoi(buf);
1540 switch(responseCode)
1543 printf("User '%s' updated\n", Username);
1548 printf("Only wheel can modify users\n");
1553 printf("User '%s' does not exist\n", Username);
1558 printf("Flag string is invalid\n");
1563 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1576 char *ReadLine(int Socket)
1578 static char buf[BUFSIZ];
1579 static int bufPos = 0;
1580 static int bufValid = 0;
1582 char *newline = NULL;
1584 char *ret = malloc(10);
1586 #if DEBUG_TRACE_SERVER
1587 printf("ReadLine: ");
1599 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1600 buf[bufPos+len] = '\0';
1603 newline = strchr( buf+bufPos, '\n' );
1608 retLen += strlen(buf+bufPos);
1609 ret = realloc(ret, retLen + 1);
1610 strcat( ret, buf+bufPos );
1613 int newLen = newline - (buf+bufPos) + 1;
1614 bufValid = len - newLen;
1617 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1620 #if DEBUG_TRACE_SERVER
1621 printf("%i '%s'\n", retLen, ret);
1627 int sendf(int Socket, const char *Format, ...)
1632 va_start(args, Format);
1633 len = vsnprintf(NULL, 0, Format, args);
1638 va_start(args, Format);
1639 vsnprintf(buf, len+1, Format, args);
1642 #if DEBUG_TRACE_SERVER
1643 printf("sendf: %s", buf);
1646 return send(Socket, buf, len, 0);
1650 char *trim(char *string)
1654 while( isspace(*string) )
1657 for( i = strlen(string); i--; )
1659 if( isspace(string[i]) )
1668 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1672 ret = regexec(regex, string, nMatches, matches, 0);
1673 if( ret && errorMessage ) {
1674 size_t len = regerror(ret, regex, NULL, 0);
1676 regerror(ret, regex, errorStr, len);
1677 printf("string = '%s'\n", string);
1678 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1685 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1687 int ret = regcomp(regex, pattern, flags);
1689 size_t len = regerror(ret, regex, NULL, 0);
1691 regerror(ret, regex, errorStr, len);
1692 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);