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 // Check for a valid item ID
352 // Connect, Authenticate, dispense and close
353 sock = OpenConnection(gsDispenseServer, giDispensePort);
354 if( sock < 0 ) return -1;
356 DispenseItem(sock, i);
369 " Show interactive list\n"
371 " Dispense named item\n"
372 " dispense give <user> <ammount> \"<reason>\"\n"
373 " Give money to another user\n"
374 " dispense donate <ammount> \"<reason>\"\n"
375 " Donate to the club\n"
376 " == Coke members == \n"
377 " dispense acct [<user>]\n"
378 " Show user balances\n"
379 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
380 " Alter a account value\n"
381 " == Dispense administrators ==\n"
382 " dispense acct <user> =<ammount> \"<reason>\"\n"
383 " Set an account balance\n"
384 " dispense user add <user>\n"
385 " Create new coke account (Admins only)\n"
386 " dispense user type <user> <flags>\n"
387 " Alter a user's flags\n"
388 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
389 " Flags are removed by preceding the name with '-' or '!'\n"
393 " Set a different user (Coke members only)\n"
397 " Use alternate GUI\n"
398 " -m <min balance>\n"
399 " -M <max balance>\n"
400 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
404 // -------------------
405 // --- NCurses GUI ---
406 // -------------------
408 * \brief Render the NCurses UI
410 int ShowNCursesUI(void)
412 // TODO: ncurses interface (with separation between item classes)
413 // - Hmm... that would require standardising the item ID to be <class>:<index>
418 const int displayMinWidth = 40;
419 const int displayMinItems = 8;
420 char *titleString = "Dispense";
421 int itemCount = displayMinItems;
424 int ret = -2; // -2: Used for marking "no return yet"
433 // - 6: randomly chosen (Need at least 3)
434 itemCount = LINES - 6;
435 if( itemCount > giNumItems )
436 itemCount = giNumItems;
439 height = itemCount + 3;
440 width = displayMinWidth;
443 xBase = COLS/2 - width/2;
444 yBase = LINES/2 - height/2;
449 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
452 for( i = 0; i < itemCount; i ++ )
454 move( yBase + 1 + i, xBase );
456 if( currentItem == itemBase + i ) {
464 // - Oh god, magic numbers!
465 if( i == 0 && itemBase > 0 ) {
467 times = width-1 - 8 - 3;
468 while(times--) addch(' ');
470 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
472 times = width-1 - 8 - 3;
473 while(times--) addch(' ');
477 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
481 // Scrollbar (if needed)
482 if( giNumItems > itemCount ) {
486 else if( i == itemCount - 1 ) {
490 int percentage = itemBase * 100 / (giNumItems-itemCount);
491 if( i-1 == percentage*(itemCount-3)/100 ) {
505 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
518 //if( itemBase < giNumItems - (itemCount) )
520 if( currentItem < giNumItems - 1 )
522 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
528 if( currentItem > 0 )
530 if( itemBase + 1 > currentItem && itemBase > 0 )
546 ret = -1; // -1: Return with no dispense
550 // Check if the return value was changed
551 if( ret != -2 ) break;
563 * \brief Show item \a Index at (\a Col, \a Row)
564 * \note Part of the NCurses UI
566 void ShowItemAt(int Row, int Col, int Width, int Index)
574 if( Index < 0 || Index >= giNumItems ) {
579 name = gaItems[Index].Desc;
580 price = gaItems[Index].Price;
583 printw("%02i %s", Index, name);
585 getyx(stdscr, _y, _x);
586 // Assumes max 4 digit prices
587 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
588 while(times--) addch(' ');
589 printw("%4i", price);
593 * \brief Print a three-part string at the specified position (formatted)
594 * \note NCurses UI Helper
596 * Prints \a Left on the left of the area, \a Right on the righthand side
597 * and \a Mid in the middle of the area. These are padded with \a Pad1
598 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
600 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
601 * and the arguments to these are read in that order.
603 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
604 const char *Mid, char Pad2, const char *Right, ...)
606 int lLen, mLen, rLen;
611 // Get the length of the strings
612 va_start(args, Right);
613 lLen = vsnprintf(NULL, 0, Left, args);
614 mLen = vsnprintf(NULL, 0, Mid, args);
615 rLen = vsnprintf(NULL, 0, Right, args);
619 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
620 return ; // TODO: What to do?
626 va_start(args, Right);
630 vsnprintf(tmp, lLen+1, Left, args);
634 times = Width/2 - mLen/2 - lLen;
635 while(times--) addch(Pad1);
639 vsnprintf(tmp, mLen+1, Mid, args);
643 times = Width/2 - mLen/2 - rLen;
644 while(times--) addch(Pad2);
648 vsnprintf(tmp, rLen+1, Right, args);
653 // ---------------------
654 // --- Coke Protocol ---
655 // ---------------------
656 int OpenConnection(const char *Host, int Port)
658 struct hostent *host;
659 struct sockaddr_in serverAddr;
662 host = gethostbyname(Host);
664 fprintf(stderr, "Unable to look up '%s'\n", Host);
668 memset(&serverAddr, 0, sizeof(serverAddr));
670 serverAddr.sin_family = AF_INET; // IPv4
671 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
672 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
673 serverAddr.sin_port = htons(Port);
675 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
677 fprintf(stderr, "Failed to create socket\n");
683 struct sockaddr_in localAddr;
684 memset(&localAddr, 0, sizeof(localAddr));
685 localAddr.sin_family = AF_INET; // IPv4
686 localAddr.sin_port = 1023; // IPv4
687 // Attempt to bind to low port for autoauth
688 bind(sock, &localAddr, sizeof(localAddr));
692 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
693 fprintf(stderr, "Failed to connect to server\n");
701 * \brief Authenticate with the server
702 * \return Boolean Failure
704 int Authenticate(int Socket)
711 regmatch_t matches[4];
713 if( gbIsAuthenticated ) return 0;
716 pwd = getpwuid( getuid() );
718 // Attempt automatic authentication
719 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
721 // Check if it worked
722 buf = ReadLine(Socket);
724 responseCode = atoi(buf);
725 switch( responseCode )
727 case 200: // Autoauth succeeded, return
731 case 401: // Untrusted, attempt password authentication
734 sendf(Socket, "USER %s\n", pwd->pw_name);
735 printf("Using username %s\n", pwd->pw_name);
737 buf = ReadLine(Socket);
740 // Expected format: 100 SALT <something> ...
742 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
743 responseCode = atoi(buf);
744 if( responseCode != 100 ) {
745 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
751 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
752 // Store it for later
753 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
754 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
758 // Give three attempts
759 for( i = 0; i < 3; i ++ )
761 int ofs = strlen(pwd->pw_name)+strlen(salt);
764 char *pass = getpass("Password: ");
767 // Create hash string
768 // <username><salt><hash>
769 strcpy(tmp, pwd->pw_name);
771 SHA1( (unsigned char*)pass, strlen(pass), h );
772 memcpy(tmp+ofs, h, 20);
775 SHA1( (unsigned char*)tmp, ofs+20, h );
776 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
777 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
778 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
782 sendf(Socket, "PASS %s\n", tmpBuf);
783 buf = ReadLine(Socket);
785 responseCode = atoi(buf);
787 if( responseCode == 200 ) break;
788 // Bad username/password
789 if( responseCode == 401 ) continue;
791 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
797 return 2; // 2 = Bad Password
800 case 404: // Bad Username
801 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
806 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
812 // Set effective user
813 if( gsEffectiveUser ) {
814 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
816 buf = ReadLine(Socket);
817 responseCode = atoi(buf);
822 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
826 printf("Only coke members can use `dispense -u`\n");
831 printf("Invalid user selected\n");
836 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
845 gbIsAuthenticated = 1;
852 * \brief Fill the item information structure
853 * \return Boolean Failure
855 void PopulateItemList(int Socket)
860 char *itemType, *itemStart;
862 regmatch_t matches[4];
864 // Ask server for stock list
865 send(Socket, "ENUM_ITEMS\n", 11, 0);
866 buf = ReadLine(Socket);
868 //printf("Output: %s\n", buf);
870 responseCode = atoi(buf);
871 if( responseCode != 201 ) {
872 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
881 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
883 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
884 count = atoi( &buf[ matches[3].rm_so ] );
887 if( strcmp(itemType, "Items") != 0 ) {
889 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
894 itemStart = &buf[ matches[3].rm_eo ];
899 gaItems = malloc( giNumItems * sizeof(tItem) );
901 // Fetch item information
902 for( i = 0; i < giNumItems; i ++ )
904 regmatch_t matches[7];
907 buf = ReadLine(Socket);
908 responseCode = atoi(buf);
910 if( responseCode != 202 ) {
911 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
915 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
917 buf[ matches[3].rm_eo ] = '\0';
919 gaItems[i].Type = strdup( buf + matches[3].rm_so );
920 gaItems[i].ID = atoi( buf + matches[4].rm_so );
921 gaItems[i].Price = atoi( buf + matches[5].rm_so );
922 gaItems[i].Desc = strdup( buf + matches[6].rm_so );
928 buf = ReadLine(Socket);
929 responseCode = atoi(buf);
931 if( responseCode != 200 ) {
932 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
942 * \brief Dispense an item
943 * \return Boolean Failure
945 int DispenseItem(int Socket, int ItemID)
947 int ret, responseCode;
950 if( ItemID < 0 || ItemID > giNumItems ) return -1;
953 sendf(Socket, "DISPENSE %s:%i\n", gaItems[ItemID].Type, gaItems[ItemID].ID);
954 buf = ReadLine(Socket);
956 responseCode = atoi(buf);
957 switch( responseCode )
960 printf("Dispense OK\n");
964 printf("Not authenticated\n");
968 printf("Insufficient balance\n");
972 printf("Bad item name, bug report\n");
976 printf("Item failed to dispense, is the slot empty?\n");
980 printf("Dispense not possible (slot empty/permissions)\n");
984 printf("Unknown response code %i ('%s')\n", responseCode, buf);
994 * \brief Alter a user's balance
996 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1001 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1002 buf = ReadLine(Socket);
1004 responseCode = atoi(buf);
1007 switch(responseCode)
1009 case 200: return 0; // OK
1011 fprintf(stderr, "Insufficient balance\n");
1013 case 403: // Not in coke
1014 fprintf(stderr, "You are not in coke (sucker)\n");
1016 case 404: // Unknown user
1017 fprintf(stderr, "Unknown user '%s'\n", Username);
1020 fprintf(stderr, "Unknown response code %i\n", responseCode);
1028 * \brief Set a user's balance
1029 * \note Only avaliable to dispense admins
1031 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1036 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1037 buf = ReadLine(Socket);
1039 responseCode = atoi(buf);
1042 switch(responseCode)
1044 case 200: return 0; // OK
1045 case 403: // Not in coke
1046 fprintf(stderr, "You are not an admin\n");
1048 case 404: // Unknown user
1049 fprintf(stderr, "Unknown user '%s'\n", Username);
1052 fprintf(stderr, "Unknown response code %i\n", responseCode);
1060 * \brief Give money to another user
1062 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1068 printf("Sorry, you can only give, you can't take.\n");
1072 // Fast return on zero
1073 if( Ammount == 0 ) {
1074 printf("Are you actually going to give any?\n");
1078 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1079 buf = ReadLine(Socket);
1081 responseCode = atoi(buf);
1084 switch(responseCode)
1086 case 200: return 0; // OK
1089 fprintf(stderr, "Insufficient balance\n");
1092 case 404: // Unknown user
1093 fprintf(stderr, "Unknown user '%s'\n", Username);
1097 fprintf(stderr, "Unknown response code %i\n", responseCode);
1106 * \brief Donate money to the club
1108 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1114 printf("Sorry, you can only give, you can't take.\n");
1118 // Fast return on zero
1119 if( Ammount == 0 ) {
1120 printf("Are you actually going to give any?\n");
1124 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1125 buf = ReadLine(Socket);
1127 responseCode = atoi(buf);
1130 switch(responseCode)
1132 case 200: return 0; // OK
1135 fprintf(stderr, "Insufficient balance\n");
1139 fprintf(stderr, "Unknown response code %i\n", responseCode);
1147 * \brief Enumerate users
1149 int Dispense_EnumUsers(int Socket)
1154 regmatch_t matches[4];
1156 if( giMinimumBalance != INT_MIN ) {
1157 if( giMaximumBalance != INT_MAX ) {
1158 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1161 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1165 if( giMaximumBalance != INT_MAX ) {
1166 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1169 sendf(Socket, "ENUM_USERS\n");
1172 buf = ReadLine(Socket);
1173 responseCode = atoi(buf);
1175 switch(responseCode)
1177 case 201: break; // Ok, length follows
1180 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1185 // Get count (not actually used)
1186 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1187 nUsers = atoi( buf + matches[3].rm_so );
1188 printf("%i users returned\n", nUsers);
1193 // Read returned users
1195 buf = ReadLine(Socket);
1196 responseCode = atoi(buf);
1198 if( responseCode != 202 ) break;
1200 _PrintUserLine(buf);
1202 } while(responseCode == 202);
1204 // Check final response
1205 if( responseCode != 200 ) {
1206 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1216 int Dispense_ShowUser(int Socket, const char *Username)
1219 int responseCode, ret;
1221 sendf(Socket, "USER_INFO %s\n", Username);
1222 buf = ReadLine(Socket);
1224 responseCode = atoi(buf);
1226 switch(responseCode)
1229 _PrintUserLine(buf);
1234 printf("Unknown user '%s'\n", Username);
1239 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1249 void _PrintUserLine(const char *Line)
1251 regmatch_t matches[6];
1254 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1259 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1260 char username[usernameLen + 1];
1261 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1262 char flags[flagsLen + 1];
1264 memcpy(username, Line + matches[3].rm_so, usernameLen);
1265 username[usernameLen] = '\0';
1266 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1267 flags[flagsLen] = '\0';
1269 bal = atoi(Line + matches[4].rm_so);
1270 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1274 int Dispense_AddUser(int Socket, const char *Username)
1277 int responseCode, ret;
1279 sendf(Socket, "USER_ADD %s\n", Username);
1281 buf = ReadLine(Socket);
1282 responseCode = atoi(buf);
1284 switch(responseCode)
1287 printf("User '%s' added\n", Username);
1292 printf("Only wheel can add users\n");
1297 printf("User '%s' already exists\n", Username);
1302 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1312 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1315 int responseCode, ret;
1317 // TODO: Pre-validate the string
1319 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1321 buf = ReadLine(Socket);
1322 responseCode = atoi(buf);
1324 switch(responseCode)
1327 printf("User '%s' updated\n", Username);
1332 printf("Only wheel can modify users\n");
1337 printf("User '%s' does not exist\n", Username);
1342 printf("Flag string is invalid\n");
1347 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1360 char *ReadLine(int Socket)
1362 static char buf[BUFSIZ];
1363 static int bufPos = 0;
1364 static int bufValid = 0;
1366 char *newline = NULL;
1368 char *ret = malloc(10);
1370 #if DEBUG_TRACE_SERVER
1371 printf("ReadLine: ");
1383 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1384 buf[bufPos+len] = '\0';
1387 newline = strchr( buf+bufPos, '\n' );
1392 retLen += strlen(buf+bufPos);
1393 ret = realloc(ret, retLen + 1);
1394 strcat( ret, buf+bufPos );
1397 int newLen = newline - (buf+bufPos) + 1;
1398 bufValid = len - newLen;
1401 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1404 #if DEBUG_TRACE_SERVER
1405 printf("%i '%s'\n", retLen, ret);
1411 int sendf(int Socket, const char *Format, ...)
1416 va_start(args, Format);
1417 len = vsnprintf(NULL, 0, Format, args);
1422 va_start(args, Format);
1423 vsnprintf(buf, len+1, Format, args);
1426 #if DEBUG_TRACE_SERVER
1427 printf("sendf: %s", buf);
1430 return send(Socket, buf, len, 0);
1434 char *trim(char *string)
1438 while( isspace(*string) )
1441 for( i = strlen(string); i--; )
1443 if( isspace(string[i]) )
1452 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1456 ret = regexec(regex, string, nMatches, matches, 0);
1458 size_t len = regerror(ret, regex, NULL, 0);
1460 regerror(ret, regex, errorStr, len);
1461 printf("string = '%s'\n", string);
1462 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1469 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1471 int ret = regcomp(regex, pattern, flags);
1473 size_t len = regerror(ret, regex, NULL, 0);
1475 regerror(ret, regex, errorStr, len);
1476 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);