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;
303 PopulateItemList(sock);
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);
348 // Check for a valid item ID
350 DispenseItem(sock, i);
363 " Show interactive list\n"
365 " Dispense named item\n"
366 " dispense give <user> <ammount> \"<reason>\"\n"
367 " Give money to another user\n"
368 " dispense donate <ammount> \"<reason>\"\n"
369 " Donate to the club\n"
370 " == Coke members == \n"
371 " dispense acct [<user>]\n"
372 " Show user balances\n"
373 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
374 " Alter a account value\n"
375 " == Dispense administrators ==\n"
376 " dispense acct <user> =<ammount> \"<reason>\"\n"
377 " Set an account balance\n"
378 " dispense user add <user>\n"
379 " Create new coke account (Admins only)\n"
380 " dispense user type <user> <flags>\n"
381 " Alter a user's flags\n"
382 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
383 " Flags are removed by preceding the name with '-' or '!'\n"
387 " Set a different user (Coke members only)\n"
391 " Use alternate GUI\n"
392 " -m <min balance>\n"
393 " -M <max balance>\n"
394 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
398 // -------------------
399 // --- NCurses GUI ---
400 // -------------------
402 * \brief Render the NCurses UI
404 int ShowNCursesUI(void)
406 // TODO: ncurses interface (with separation between item classes)
407 // - Hmm... that would require standardising the item ID to be <class>:<index>
412 const int displayMinWidth = 40;
413 const int displayMinItems = 8;
414 char *titleString = "Dispense";
415 int itemCount = displayMinItems;
418 int ret = -2; // -2: Used for marking "no return yet"
427 // - 6: randomly chosen (Need at least 3)
428 itemCount = LINES - 6;
429 if( itemCount > giNumItems )
430 itemCount = giNumItems;
433 height = itemCount + 3;
434 width = displayMinWidth;
437 xBase = COLS/2 - width/2;
438 yBase = LINES/2 - height/2;
443 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
446 for( i = 0; i < itemCount; i ++ )
448 move( yBase + 1 + i, xBase );
450 if( currentItem == itemBase + i ) {
458 // - Oh god, magic numbers!
459 if( i == 0 && itemBase > 0 ) {
461 times = width-1 - 8 - 3;
462 while(times--) addch(' ');
464 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
466 times = width-1 - 8 - 3;
467 while(times--) addch(' ');
471 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
475 // Scrollbar (if needed)
476 if( giNumItems > itemCount ) {
480 else if( i == itemCount - 1 ) {
484 int percentage = itemBase * 100 / (giNumItems-itemCount);
485 if( i-1 == percentage*(itemCount-3)/100 ) {
499 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
512 //if( itemBase < giNumItems - (itemCount) )
514 if( currentItem < giNumItems - 1 )
516 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
522 if( currentItem > 0 )
524 if( itemBase + 1 > currentItem && itemBase > 0 )
540 ret = -1; // -1: Return with no dispense
544 // Check if the return value was changed
545 if( ret != -2 ) break;
557 * \brief Show item \a Index at (\a Col, \a Row)
558 * \note Part of the NCurses UI
560 void ShowItemAt(int Row, int Col, int Width, int Index)
568 if( Index < 0 || Index >= giNumItems ) {
573 name = gaItems[Index].Desc;
574 price = gaItems[Index].Price;
577 printw("%02i %s", Index, name);
579 getyx(stdscr, _y, _x);
580 // Assumes max 4 digit prices
581 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
582 while(times--) addch(' ');
583 printw("%4i", price);
587 * \brief Print a three-part string at the specified position (formatted)
588 * \note NCurses UI Helper
590 * Prints \a Left on the left of the area, \a Right on the righthand side
591 * and \a Mid in the middle of the area. These are padded with \a Pad1
592 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
594 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
595 * and the arguments to these are read in that order.
597 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
598 const char *Mid, char Pad2, const char *Right, ...)
600 int lLen, mLen, rLen;
605 // Get the length of the strings
606 va_start(args, Right);
607 lLen = vsnprintf(NULL, 0, Left, args);
608 mLen = vsnprintf(NULL, 0, Mid, args);
609 rLen = vsnprintf(NULL, 0, Right, args);
613 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
614 return ; // TODO: What to do?
620 va_start(args, Right);
624 vsnprintf(tmp, lLen+1, Left, args);
628 times = Width/2 - mLen/2 - lLen;
629 while(times--) addch(Pad1);
633 vsnprintf(tmp, mLen+1, Mid, args);
637 times = Width/2 - mLen/2 - rLen;
638 while(times--) addch(Pad2);
642 vsnprintf(tmp, rLen+1, Right, args);
647 // ---------------------
648 // --- Coke Protocol ---
649 // ---------------------
650 int OpenConnection(const char *Host, int Port)
652 struct hostent *host;
653 struct sockaddr_in serverAddr;
656 host = gethostbyname(Host);
658 fprintf(stderr, "Unable to look up '%s'\n", Host);
662 memset(&serverAddr, 0, sizeof(serverAddr));
664 serverAddr.sin_family = AF_INET; // IPv4
665 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
666 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
667 serverAddr.sin_port = htons(Port);
669 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
671 fprintf(stderr, "Failed to create socket\n");
677 struct sockaddr_in localAddr;
678 memset(&localAddr, 0, sizeof(localAddr));
679 localAddr.sin_family = AF_INET; // IPv4
680 localAddr.sin_port = 1023; // IPv4
681 // Attempt to bind to low port for autoauth
682 bind(sock, &localAddr, sizeof(localAddr));
686 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
687 fprintf(stderr, "Failed to connect to server\n");
695 * \brief Authenticate with the server
696 * \return Boolean Failure
698 int Authenticate(int Socket)
705 regmatch_t matches[4];
707 if( gbIsAuthenticated ) return 0;
710 pwd = getpwuid( getuid() );
712 // Attempt automatic authentication
713 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
715 // Check if it worked
716 buf = ReadLine(Socket);
718 responseCode = atoi(buf);
719 switch( responseCode )
721 case 200: // Autoauth succeeded, return
725 case 401: // Untrusted, attempt password authentication
728 sendf(Socket, "USER %s\n", pwd->pw_name);
729 printf("Using username %s\n", pwd->pw_name);
731 buf = ReadLine(Socket);
734 // Expected format: 100 SALT <something> ...
736 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
737 responseCode = atoi(buf);
738 if( responseCode != 100 ) {
739 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
745 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
746 // Store it for later
747 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
748 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
752 // Give three attempts
753 for( i = 0; i < 3; i ++ )
755 int ofs = strlen(pwd->pw_name)+strlen(salt);
758 char *pass = getpass("Password: ");
761 // Create hash string
762 // <username><salt><hash>
763 strcpy(tmp, pwd->pw_name);
765 SHA1( (unsigned char*)pass, strlen(pass), h );
766 memcpy(tmp+ofs, h, 20);
769 SHA1( (unsigned char*)tmp, ofs+20, h );
770 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
771 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
772 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
776 sendf(Socket, "PASS %s\n", tmpBuf);
777 buf = ReadLine(Socket);
779 responseCode = atoi(buf);
781 if( responseCode == 200 ) break;
782 // Bad username/password
783 if( responseCode == 401 ) continue;
785 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
791 return 2; // 2 = Bad Password
794 case 404: // Bad Username
795 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
800 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
806 // Set effective user
807 if( gsEffectiveUser ) {
808 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
810 buf = ReadLine(Socket);
811 responseCode = atoi(buf);
816 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
820 printf("Only coke members can use `dispense -u`\n");
825 printf("Invalid user selected\n");
830 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
839 gbIsAuthenticated = 1;
846 * \brief Fill the item information structure
847 * \return Boolean Failure
849 void PopulateItemList(int Socket)
854 char *itemType, *itemStart;
856 regmatch_t matches[4];
858 // Ask server for stock list
859 send(Socket, "ENUM_ITEMS\n", 11, 0);
860 buf = ReadLine(Socket);
862 //printf("Output: %s\n", buf);
864 responseCode = atoi(buf);
865 if( responseCode != 201 ) {
866 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
875 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
877 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
878 count = atoi( &buf[ matches[3].rm_so ] );
881 if( strcmp(itemType, "Items") != 0 ) {
883 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
888 itemStart = &buf[ matches[3].rm_eo ];
893 gaItems = malloc( giNumItems * sizeof(tItem) );
895 // Fetch item information
896 for( i = 0; i < giNumItems; i ++ )
898 regmatch_t matches[7];
901 buf = ReadLine(Socket);
902 responseCode = atoi(buf);
904 if( responseCode != 202 ) {
905 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
909 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
911 buf[ matches[3].rm_eo ] = '\0';
913 gaItems[i].Type = strdup( buf + matches[3].rm_so );
914 gaItems[i].ID = atoi( buf + matches[4].rm_so );
915 gaItems[i].Price = atoi( buf + matches[5].rm_so );
916 gaItems[i].Desc = strdup( buf + matches[6].rm_so );
922 buf = ReadLine(Socket);
923 responseCode = atoi(buf);
925 if( responseCode != 200 ) {
926 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
936 * \brief Dispense an item
937 * \return Boolean Failure
939 int DispenseItem(int Socket, int ItemID)
941 int ret, responseCode;
944 if( ItemID < 0 || ItemID > giNumItems ) return -1;
947 sendf(Socket, "DISPENSE %s:%i\n", gaItems[ItemID].Type, gaItems[ItemID].ID);
948 buf = ReadLine(Socket);
950 responseCode = atoi(buf);
951 switch( responseCode )
954 printf("Dispense OK\n");
958 printf("Not authenticated\n");
962 printf("Insufficient balance\n");
966 printf("Bad item name, bug report\n");
970 printf("Item failed to dispense, is the slot empty?\n");
974 printf("Dispense not possible (slot empty/permissions)\n");
978 printf("Unknown response code %i ('%s')\n", responseCode, buf);
988 * \brief Alter a user's balance
990 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
995 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
996 buf = ReadLine(Socket);
998 responseCode = atoi(buf);
1001 switch(responseCode)
1003 case 200: return 0; // OK
1005 fprintf(stderr, "Insufficient balance\n");
1007 case 403: // Not in coke
1008 fprintf(stderr, "You are not in coke (sucker)\n");
1010 case 404: // Unknown user
1011 fprintf(stderr, "Unknown user '%s'\n", Username);
1014 fprintf(stderr, "Unknown response code %i\n", responseCode);
1022 * \brief Set a user's balance
1023 * \note Only avaliable to dispense admins
1025 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1030 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1031 buf = ReadLine(Socket);
1033 responseCode = atoi(buf);
1036 switch(responseCode)
1038 case 200: return 0; // OK
1039 case 403: // Not in coke
1040 fprintf(stderr, "You are not an admin\n");
1042 case 404: // Unknown user
1043 fprintf(stderr, "Unknown user '%s'\n", Username);
1046 fprintf(stderr, "Unknown response code %i\n", responseCode);
1054 * \brief Give money to another user
1056 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1062 printf("Sorry, you can only give, you can't take.\n");
1066 // Fast return on zero
1067 if( Ammount == 0 ) {
1068 printf("Are you actually going to give any?\n");
1072 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1073 buf = ReadLine(Socket);
1075 responseCode = atoi(buf);
1078 switch(responseCode)
1080 case 200: return 0; // OK
1083 fprintf(stderr, "Insufficient balance\n");
1086 case 404: // Unknown user
1087 fprintf(stderr, "Unknown user '%s'\n", Username);
1091 fprintf(stderr, "Unknown response code %i\n", responseCode);
1100 * \brief Donate money to the club
1102 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1108 printf("Sorry, you can only give, you can't take.\n");
1112 // Fast return on zero
1113 if( Ammount == 0 ) {
1114 printf("Are you actually going to give any?\n");
1118 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1119 buf = ReadLine(Socket);
1121 responseCode = atoi(buf);
1124 switch(responseCode)
1126 case 200: return 0; // OK
1129 fprintf(stderr, "Insufficient balance\n");
1133 fprintf(stderr, "Unknown response code %i\n", responseCode);
1141 * \brief Enumerate users
1143 int Dispense_EnumUsers(int Socket)
1148 regmatch_t matches[4];
1150 if( giMinimumBalance != INT_MIN ) {
1151 if( giMaximumBalance != INT_MAX ) {
1152 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1155 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1159 if( giMaximumBalance != INT_MAX ) {
1160 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1163 sendf(Socket, "ENUM_USERS\n");
1166 buf = ReadLine(Socket);
1167 responseCode = atoi(buf);
1169 switch(responseCode)
1171 case 201: break; // Ok, length follows
1174 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1179 // Get count (not actually used)
1180 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1181 nUsers = atoi( buf + matches[3].rm_so );
1182 printf("%i users returned\n", nUsers);
1187 // Read returned users
1189 buf = ReadLine(Socket);
1190 responseCode = atoi(buf);
1192 if( responseCode != 202 ) break;
1194 _PrintUserLine(buf);
1196 } while(responseCode == 202);
1198 // Check final response
1199 if( responseCode != 200 ) {
1200 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1210 int Dispense_ShowUser(int Socket, const char *Username)
1213 int responseCode, ret;
1215 sendf(Socket, "USER_INFO %s\n", Username);
1216 buf = ReadLine(Socket);
1218 responseCode = atoi(buf);
1220 switch(responseCode)
1223 _PrintUserLine(buf);
1228 printf("Unknown user '%s'\n", Username);
1233 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1243 void _PrintUserLine(const char *Line)
1245 regmatch_t matches[6];
1248 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1253 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1254 char username[usernameLen + 1];
1255 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1256 char flags[flagsLen + 1];
1258 memcpy(username, Line + matches[3].rm_so, usernameLen);
1259 username[usernameLen] = '\0';
1260 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1261 flags[flagsLen] = '\0';
1263 bal = atoi(Line + matches[4].rm_so);
1264 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1268 int Dispense_AddUser(int Socket, const char *Username)
1271 int responseCode, ret;
1273 sendf(Socket, "USER_ADD %s\n", Username);
1275 buf = ReadLine(Socket);
1276 responseCode = atoi(buf);
1278 switch(responseCode)
1281 printf("User '%s' added\n", Username);
1286 printf("Only wheel can add users\n");
1291 printf("User '%s' already exists\n", Username);
1296 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1306 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1309 int responseCode, ret;
1311 // TODO: Pre-validate the string
1313 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1315 buf = ReadLine(Socket);
1316 responseCode = atoi(buf);
1318 switch(responseCode)
1321 printf("User '%s' updated\n", Username);
1326 printf("Only wheel can modify users\n");
1331 printf("User '%s' does not exist\n", Username);
1336 printf("Flag string is invalid\n");
1341 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1354 char *ReadLine(int Socket)
1356 static char buf[BUFSIZ];
1357 static int bufPos = 0;
1358 static int bufValid = 0;
1360 char *newline = NULL;
1362 char *ret = malloc(10);
1364 #if DEBUG_TRACE_SERVER
1365 printf("ReadLine: ");
1377 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1378 buf[bufPos+len] = '\0';
1381 newline = strchr( buf+bufPos, '\n' );
1386 retLen += strlen(buf+bufPos);
1387 ret = realloc(ret, retLen + 1);
1388 strcat( ret, buf+bufPos );
1391 int newLen = newline - (buf+bufPos) + 1;
1392 bufValid = len - newLen;
1395 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1398 #if DEBUG_TRACE_SERVER
1399 printf("%i '%s'\n", retLen, ret);
1405 int sendf(int Socket, const char *Format, ...)
1410 va_start(args, Format);
1411 len = vsnprintf(NULL, 0, Format, args);
1416 va_start(args, Format);
1417 vsnprintf(buf, len+1, Format, args);
1420 #if DEBUG_TRACE_SERVER
1421 printf("sendf: %s", buf);
1424 return send(Socket, buf, len, 0);
1428 char *trim(char *string)
1432 while( isspace(*string) )
1435 for( i = strlen(string); i--; )
1437 if( isspace(string[i]) )
1446 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1450 ret = regexec(regex, string, nMatches, matches, 0);
1452 size_t len = regerror(ret, regex, NULL, 0);
1454 regerror(ret, regex, errorStr, len);
1455 printf("string = '%s'\n", string);
1456 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1463 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1465 int ret = regcomp(regex, pattern, flags);
1467 size_t len = regerror(ret, regex, NULL, 0);
1469 regerror(ret, regex, errorStr, len);
1470 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);