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
32 typedef struct sItem {
40 int main(int argc, char *argv[]);
43 int ShowNCursesUI(void);
44 void ShowItemAt(int Row, int Col, int Width, int Index);
45 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1, const char *Mid, char Pad2, const char *Right, ...);
46 // --- Coke Server Communication ---
47 int OpenConnection(const char *Host, int Port);
48 int Authenticate(int Socket);
49 void PopulateItemList(int Socket);
50 int DispenseItem(int Socket, int ItemID);
51 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
52 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
53 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
54 int Dispense_Donate(int Socket, int Ammount, const char *Reason);
55 int Dispense_EnumUsers(int Socket);
56 int Dispense_ShowUser(int Socket, const char *Username);
57 void _PrintUserLine(const char *Line);
58 int Dispense_AddUser(int Socket, const char *Username);
59 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
61 char *ReadLine(int Socket);
62 int sendf(int Socket, const char *Format, ...);
63 char *trim(char *string);
64 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
65 void CompileRegex(regex_t *regex, const char *pattern, int flags);
68 char *gsDispenseServer = "localhost";
69 int giDispensePort = 11020;
73 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex;
74 int gbIsAuthenticated = 0;
76 char *gsItemPattern; //!< Item pattern
77 char *gsEffectiveUser; //!< '-u' Dispense as another user
78 int gbUseNCurses = 0; //!< '-G' Use the NCurses GUI?
79 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
80 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
83 int main(int argc, char *argv[])
89 // -- Create regular expressions
90 // > Code Type Count ...
91 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
92 // > Code Type Ident Price Desc
93 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z]+):([0-9]+)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
95 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
96 // > Code 'User' Username Balance Flags
97 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
100 for( i = 1; i < argc; i ++ )
113 case 'm': // Minimum balance
114 giMinimumBalance = atoi(argv[++i]);
116 case 'M': // Maximum balance
117 giMaximumBalance = atoi(argv[++i]);
120 case 'u': // Override User
121 gsEffectiveUser = argv[++i];
135 if( strcmp(arg, "acct") == 0 )
138 sock = OpenConnection(gsDispenseServer, giDispensePort);
139 if( sock < 0 ) return -1;
142 if( i + 1 == argc ) {
143 Dispense_EnumUsers(sock);
147 // argv[i+1]: Username
152 if( i + 3 >= argc ) {
153 fprintf(stderr, "Error: `dispense acct' needs a reason\n");
157 // Authentication required
158 if( Authenticate(sock) )
161 // argv[i+1]: Username
162 // argv[i+2]: Ammount
165 if( argv[i+2][0] == '=' ) {
167 if( argv[i+2][1] != '0' && atoi(&argv[i+2][1]) == 0 ) {
168 fprintf(stderr, "Error: Invalid balance to be set\n");
172 Dispense_SetBalance(sock, argv[i+1], atoi(argv[i+2]+1), argv[i+3]);
176 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
180 // Show user information
181 Dispense_ShowUser(sock, argv[i+1]);
188 // - "Here, have some money."
189 if( strcmp(arg, "give") == 0 )
191 if( i + 3 >= argc ) {
192 fprintf(stderr, "`dispense give` takes three arguments\n");
196 // TODO: `dispense give`
198 // argv[i+1]: Destination
199 // argv[i+2]: Ammount
203 sock = OpenConnection(gsDispenseServer, giDispensePort);
204 if( sock < 0 ) return -1;
207 if( Authenticate(sock) )
210 Dispense_Give(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
215 // - User administration (Admin Only)
216 if( strcmp(arg, "user") == 0 )
218 // Check argument count
219 if( i + 1 >= argc ) {
220 fprintf(stderr, "Error: `dispense user` requires arguments\n");
226 sock = OpenConnection(gsDispenseServer, giDispensePort);
227 if( sock < 0 ) return -1;
229 // Attempt authentication
230 if( Authenticate(sock) )
234 if( strcmp(argv[i+1], "add") == 0 )
236 if( i + 2 >= argc ) {
237 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
242 Dispense_AddUser(sock, argv[i+2]);
245 else if( strcmp(argv[i+1], "type") == 0 )
247 if( i + 3 >= argc ) {
248 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
253 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
257 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
265 if( strcmp(arg, "donate") == 0 )
267 // Check argument count
268 if( i + 2 >= argc ) {
269 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
275 sock = OpenConnection(gsDispenseServer, giDispensePort);
276 if( sock < 0 ) return -1;
278 // Attempt authentication
279 if( Authenticate(sock) )
283 Dispense_Donate(sock, atoi(argv[i+1]), argv[i+1]);
289 // Item name / pattern
296 sock = OpenConnection(gsDispenseServer, giDispensePort);
297 if( sock < 0 ) return -1;
300 PopulateItemList(sock);
302 // Disconnect from server
307 // TODO: Implement `dispense <name>`
308 printf("TODO: Implement `dispense <name>`\n");
311 else if( gbUseNCurses )
317 // Very basic dispense interface
318 for( i = 0; i < giNumItems; i ++ ) {
319 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
320 gaItems[i].Price, gaItems[i].Desc);
329 fgets(buffer, BUFSIZ, stdin);
333 if( buf[0] == 'q' ) break;
337 if( i != 0 || buf[0] == '0' )
339 if( i < 0 || i >= giNumItems ) {
340 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
349 // Connect to server again
350 sock = OpenConnection(gsDispenseServer, giDispensePort);
351 if( sock < 0 ) return -1;
356 // Check for a valid item ID
358 DispenseItem(sock, i);
371 " Show interactive list\n"
373 " Dispense named item\n"
374 " dispense give <user> <ammount> \"<reason>\"\n"
375 " Give money to another user\n"
376 " dispense donate <ammount> \"<reason>\"\n"
377 " Donate to the club\n"
378 " == Coke members == \n"
379 " dispense acct [<user>]\n"
380 " Show user balances\n"
381 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
382 " Alter a account value\n"
383 " == Dispense administrators ==\n"
384 " dispense acct <user> =<ammount> \"<reason>\"\n"
385 " Set an account balance\n"
386 " dispense user add <user>\n"
387 " Create new coke account (Admins only)\n"
388 " dispense user type <user> <flags>\n"
389 " Alter a user's flags\n"
390 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
391 " Flags are removed by preceding the name with '-' or '!'\n"
395 " Set a different user (Coke members only)\n"
399 " Use alternate GUI\n"
400 " -m <min balance>\n"
401 " -M <max balance>\n"
402 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
406 // -------------------
407 // --- NCurses GUI ---
408 // -------------------
410 * \brief Render the NCurses UI
412 int ShowNCursesUI(void)
414 // TODO: ncurses interface (with separation between item classes)
415 // - Hmm... that would require standardising the item ID to be <class>:<index>
420 const int displayMinWidth = 40;
421 const int displayMinItems = 8;
422 char *titleString = "Dispense";
423 int itemCount = displayMinItems;
426 int ret = -2; // -2: Used for marking "no return yet"
435 // - 6: randomly chosen (Need at least 3)
436 itemCount = LINES - 6;
437 if( itemCount > giNumItems )
438 itemCount = giNumItems;
441 height = itemCount + 3;
442 width = displayMinWidth;
445 xBase = COLS/2 - width/2;
446 yBase = LINES/2 - height/2;
451 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
454 for( i = 0; i < itemCount; i ++ )
456 move( yBase + 1 + i, xBase );
458 if( currentItem == itemBase + i ) {
466 // - Oh god, magic numbers!
467 if( i == 0 && itemBase > 0 ) {
469 times = width-1 - 8 - 3;
470 while(times--) addch(' ');
472 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
474 times = width-1 - 8 - 3;
475 while(times--) addch(' ');
479 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
483 // Scrollbar (if needed)
484 if( giNumItems > itemCount ) {
488 else if( i == itemCount - 1 ) {
492 int percentage = itemBase * 100 / (giNumItems-itemCount);
493 if( i-1 == percentage*(itemCount-3)/100 ) {
507 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
520 //if( itemBase < giNumItems - (itemCount) )
522 if( currentItem < giNumItems - 1 )
524 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
530 if( currentItem > 0 )
532 if( itemBase + 1 > currentItem && itemBase > 0 )
548 ret = -1; // -1: Return with no dispense
552 // Check if the return value was changed
553 if( ret != -2 ) break;
565 * \brief Show item \a Index at (\a Col, \a Row)
566 * \note Part of the NCurses UI
568 void ShowItemAt(int Row, int Col, int Width, int Index)
576 if( Index < 0 || Index >= giNumItems ) {
581 name = gaItems[Index].Desc;
582 price = gaItems[Index].Price;
585 printw("%02i %s", Index, name);
587 getyx(stdscr, _y, _x);
588 // Assumes max 4 digit prices
589 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
590 while(times--) addch(' ');
591 printw("%4i", price);
595 * \brief Print a three-part string at the specified position (formatted)
596 * \note NCurses UI Helper
598 * Prints \a Left on the left of the area, \a Right on the righthand side
599 * and \a Mid in the middle of the area. These are padded with \a Pad1
600 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
602 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
603 * and the arguments to these are read in that order.
605 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
606 const char *Mid, char Pad2, const char *Right, ...)
608 int lLen, mLen, rLen;
613 // Get the length of the strings
614 va_start(args, Right);
615 lLen = vsnprintf(NULL, 0, Left, args);
616 mLen = vsnprintf(NULL, 0, Mid, args);
617 rLen = vsnprintf(NULL, 0, Right, args);
621 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
622 return ; // TODO: What to do?
628 va_start(args, Right);
632 vsnprintf(tmp, lLen+1, Left, args);
636 times = Width/2 - mLen/2 - lLen;
637 while(times--) addch(Pad1);
641 vsnprintf(tmp, mLen+1, Mid, args);
645 times = Width/2 - mLen/2 - rLen;
646 while(times--) addch(Pad2);
650 vsnprintf(tmp, rLen+1, Right, args);
655 // ---------------------
656 // --- Coke Protocol ---
657 // ---------------------
658 int OpenConnection(const char *Host, int Port)
660 struct hostent *host;
661 struct sockaddr_in serverAddr;
664 host = gethostbyname(Host);
666 fprintf(stderr, "Unable to look up '%s'\n", Host);
670 memset(&serverAddr, 0, sizeof(serverAddr));
672 serverAddr.sin_family = AF_INET; // IPv4
673 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
674 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
675 serverAddr.sin_port = htons(Port);
677 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
679 fprintf(stderr, "Failed to create socket\n");
685 struct sockaddr_in localAddr;
686 memset(&localAddr, 0, sizeof(localAddr));
687 localAddr.sin_family = AF_INET; // IPv4
688 localAddr.sin_port = 1023; // IPv4
689 // Attempt to bind to low port for autoauth
690 bind(sock, &localAddr, sizeof(localAddr));
694 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
695 fprintf(stderr, "Failed to connect to server\n");
703 * \brief Authenticate with the server
704 * \return Boolean Failure
706 int Authenticate(int Socket)
713 regmatch_t matches[4];
715 if( gbIsAuthenticated ) return 0;
718 pwd = getpwuid( getuid() );
720 // Attempt automatic authentication
721 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
723 // Check if it worked
724 buf = ReadLine(Socket);
726 responseCode = atoi(buf);
727 switch( responseCode )
729 case 200: // Autoauth succeeded, return
733 case 401: // Untrusted, attempt password authentication
736 sendf(Socket, "USER %s\n", pwd->pw_name);
737 printf("Using username %s\n", pwd->pw_name);
739 buf = ReadLine(Socket);
742 // Expected format: 100 SALT <something> ...
744 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
745 responseCode = atoi(buf);
746 if( responseCode != 100 ) {
747 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
753 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
754 // Store it for later
755 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
756 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
760 // Give three attempts
761 for( i = 0; i < 3; i ++ )
763 int ofs = strlen(pwd->pw_name)+strlen(salt);
766 char *pass = getpass("Password: ");
769 // Create hash string
770 // <username><salt><hash>
771 strcpy(tmp, pwd->pw_name);
773 SHA1( (unsigned char*)pass, strlen(pass), h );
774 memcpy(tmp+ofs, h, 20);
777 SHA1( (unsigned char*)tmp, ofs+20, h );
778 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
779 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
780 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
784 sendf(Socket, "PASS %s\n", tmpBuf);
785 buf = ReadLine(Socket);
787 responseCode = atoi(buf);
789 if( responseCode == 200 ) break;
790 // Bad username/password
791 if( responseCode == 401 ) continue;
793 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
799 return 2; // 2 = Bad Password
802 case 404: // Bad Username
803 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
808 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
814 // Set effective user
815 if( gsEffectiveUser ) {
816 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
818 buf = ReadLine(Socket);
819 responseCode = atoi(buf);
824 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
828 printf("Only coke members can use `dispense -u`\n");
833 printf("Invalid user selected\n");
838 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
847 gbIsAuthenticated = 1;
854 * \brief Fill the item information structure
855 * \return Boolean Failure
857 void PopulateItemList(int Socket)
862 char *itemType, *itemStart;
864 regmatch_t matches[4];
866 // Ask server for stock list
867 send(Socket, "ENUM_ITEMS\n", 11, 0);
868 buf = ReadLine(Socket);
870 //printf("Output: %s\n", buf);
872 responseCode = atoi(buf);
873 if( responseCode != 201 ) {
874 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
883 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
885 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
886 count = atoi( &buf[ matches[3].rm_so ] );
889 if( strcmp(itemType, "Items") != 0 ) {
891 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
896 itemStart = &buf[ matches[3].rm_eo ];
901 gaItems = malloc( giNumItems * sizeof(tItem) );
903 // Fetch item information
904 for( i = 0; i < giNumItems; i ++ )
906 regmatch_t matches[7];
909 buf = ReadLine(Socket);
910 responseCode = atoi(buf);
912 if( responseCode != 202 ) {
913 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
917 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
919 buf[ matches[3].rm_eo ] = '\0';
921 gaItems[i].Type = strdup( buf + matches[3].rm_so );
922 gaItems[i].ID = atoi( buf + matches[4].rm_so );
923 gaItems[i].Price = atoi( buf + matches[5].rm_so );
924 gaItems[i].Desc = strdup( buf + matches[6].rm_so );
930 buf = ReadLine(Socket);
931 responseCode = atoi(buf);
933 if( responseCode != 200 ) {
934 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
944 * \brief Dispense an item
945 * \return Boolean Failure
947 int DispenseItem(int Socket, int ItemID)
949 int ret, responseCode;
952 if( ItemID < 0 || ItemID > giNumItems ) return -1;
955 sendf(Socket, "DISPENSE %s:%i\n", gaItems[ItemID].Type, gaItems[ItemID].ID);
956 buf = ReadLine(Socket);
958 responseCode = atoi(buf);
959 switch( responseCode )
962 printf("Dispense OK\n");
966 printf("Not authenticated\n");
970 printf("Insufficient balance\n");
974 printf("Bad item name, bug report\n");
978 printf("Item failed to dispense, is the slot empty?\n");
982 printf("Dispense not possible (slot empty/permissions)\n");
986 printf("Unknown response code %i ('%s')\n", responseCode, buf);
996 * \brief Alter a user's balance
998 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1003 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1004 buf = ReadLine(Socket);
1006 responseCode = atoi(buf);
1009 switch(responseCode)
1011 case 200: return 0; // OK
1013 fprintf(stderr, "Insufficient balance\n");
1015 case 403: // Not in coke
1016 fprintf(stderr, "You are not in coke (sucker)\n");
1018 case 404: // Unknown user
1019 fprintf(stderr, "Unknown user '%s'\n", Username);
1022 fprintf(stderr, "Unknown response code %i\n", responseCode);
1030 * \brief Set a user's balance
1031 * \note Only avaliable to dispense admins
1033 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1038 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1039 buf = ReadLine(Socket);
1041 responseCode = atoi(buf);
1044 switch(responseCode)
1046 case 200: return 0; // OK
1047 case 403: // Not in coke
1048 fprintf(stderr, "You are not an admin\n");
1050 case 404: // Unknown user
1051 fprintf(stderr, "Unknown user '%s'\n", Username);
1054 fprintf(stderr, "Unknown response code %i\n", responseCode);
1062 * \brief Give money to another user
1064 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1070 printf("Sorry, you can only give, you can't take.\n");
1074 // Fast return on zero
1075 if( Ammount == 0 ) {
1076 printf("Are you actually going to give any?\n");
1080 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1081 buf = ReadLine(Socket);
1083 responseCode = atoi(buf);
1086 switch(responseCode)
1088 case 200: return 0; // OK
1091 fprintf(stderr, "Insufficient balance\n");
1094 case 404: // Unknown user
1095 fprintf(stderr, "Unknown user '%s'\n", Username);
1099 fprintf(stderr, "Unknown response code %i\n", responseCode);
1108 * \brief Donate money to the club
1110 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1116 printf("Sorry, you can only give, you can't take.\n");
1120 // Fast return on zero
1121 if( Ammount == 0 ) {
1122 printf("Are you actually going to give any?\n");
1126 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1127 buf = ReadLine(Socket);
1129 responseCode = atoi(buf);
1132 switch(responseCode)
1134 case 200: return 0; // OK
1137 fprintf(stderr, "Insufficient balance\n");
1141 fprintf(stderr, "Unknown response code %i\n", responseCode);
1149 * \brief Enumerate users
1151 int Dispense_EnumUsers(int Socket)
1156 regmatch_t matches[4];
1158 if( giMinimumBalance != INT_MIN ) {
1159 if( giMaximumBalance != INT_MAX ) {
1160 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1163 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1167 if( giMaximumBalance != INT_MAX ) {
1168 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1171 sendf(Socket, "ENUM_USERS\n");
1174 buf = ReadLine(Socket);
1175 responseCode = atoi(buf);
1177 switch(responseCode)
1179 case 201: break; // Ok, length follows
1182 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1187 // Get count (not actually used)
1188 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1189 nUsers = atoi( buf + matches[3].rm_so );
1190 printf("%i users returned\n", nUsers);
1195 // Read returned users
1197 buf = ReadLine(Socket);
1198 responseCode = atoi(buf);
1200 if( responseCode != 202 ) break;
1202 _PrintUserLine(buf);
1204 } while(responseCode == 202);
1206 // Check final response
1207 if( responseCode != 200 ) {
1208 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1218 int Dispense_ShowUser(int Socket, const char *Username)
1221 int responseCode, ret;
1223 sendf(Socket, "USER_INFO %s\n", Username);
1224 buf = ReadLine(Socket);
1226 responseCode = atoi(buf);
1228 switch(responseCode)
1231 _PrintUserLine(buf);
1236 printf("Unknown user '%s'\n", Username);
1241 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1251 void _PrintUserLine(const char *Line)
1253 regmatch_t matches[6];
1256 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1261 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1262 char username[usernameLen + 1];
1263 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1264 char flags[flagsLen + 1];
1266 memcpy(username, Line + matches[3].rm_so, usernameLen);
1267 username[usernameLen] = '\0';
1268 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1269 flags[flagsLen] = '\0';
1271 bal = atoi(Line + matches[4].rm_so);
1272 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1276 int Dispense_AddUser(int Socket, const char *Username)
1279 int responseCode, ret;
1281 sendf(Socket, "USER_ADD %s\n", Username);
1283 buf = ReadLine(Socket);
1284 responseCode = atoi(buf);
1286 switch(responseCode)
1289 printf("User '%s' added\n", Username);
1294 printf("Only wheel can add users\n");
1299 printf("User '%s' already exists\n", Username);
1304 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1314 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1317 int responseCode, ret;
1319 // TODO: Pre-validate the string
1321 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1323 buf = ReadLine(Socket);
1324 responseCode = atoi(buf);
1326 switch(responseCode)
1329 printf("User '%s' updated\n", Username);
1334 printf("Only wheel can modify users\n");
1339 printf("User '%s' does not exist\n", Username);
1344 printf("Flag string is invalid\n");
1349 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1362 char *ReadLine(int Socket)
1364 static char buf[BUFSIZ];
1365 static int bufPos = 0;
1366 static int bufValid = 0;
1368 char *newline = NULL;
1370 char *ret = malloc(10);
1372 #if DEBUG_TRACE_SERVER
1373 printf("ReadLine: ");
1385 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1386 buf[bufPos+len] = '\0';
1389 newline = strchr( buf+bufPos, '\n' );
1394 retLen += strlen(buf+bufPos);
1395 ret = realloc(ret, retLen + 1);
1396 strcat( ret, buf+bufPos );
1399 int newLen = newline - (buf+bufPos) + 1;
1400 bufValid = len - newLen;
1403 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1406 #if DEBUG_TRACE_SERVER
1407 printf("%i '%s'\n", retLen, ret);
1413 int sendf(int Socket, const char *Format, ...)
1418 va_start(args, Format);
1419 len = vsnprintf(NULL, 0, Format, args);
1424 va_start(args, Format);
1425 vsnprintf(buf, len+1, Format, args);
1428 #if DEBUG_TRACE_SERVER
1429 printf("sendf: %s", buf);
1432 return send(Socket, buf, len, 0);
1436 char *trim(char *string)
1440 while( isspace(*string) )
1443 for( i = strlen(string); i--; )
1445 if( isspace(string[i]) )
1454 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1458 ret = regexec(regex, string, nMatches, matches, 0);
1460 size_t len = regerror(ret, regex, NULL, 0);
1462 regerror(ret, regex, errorStr, len);
1463 printf("string = '%s'\n", string);
1464 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1471 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1473 int ret = regcomp(regex, pattern, flags);
1475 size_t len = regerror(ret, regex, NULL, 0);
1477 regerror(ret, regex, errorStr, len);
1478 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);