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 DispenseItem(int Socket, int ItemID);
52 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason);
53 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason);
54 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason);
55 int Dispense_Donate(int Socket, int Ammount, const char *Reason);
56 int Dispense_EnumUsers(int Socket);
57 int Dispense_ShowUser(int Socket, const char *Username);
58 void _PrintUserLine(const char *Line);
59 int Dispense_AddUser(int Socket, const char *Username);
60 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString);
62 char *ReadLine(int Socket);
63 int sendf(int Socket, const char *Format, ...);
64 char *trim(char *string);
65 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage);
66 void CompileRegex(regex_t *regex, const char *pattern, int flags);
69 char *gsDispenseServer = "heathred";
70 int giDispensePort = 11020;
74 regex_t gArrayRegex, gItemRegex, gSaltRegex, gUserInfoRegex;
75 int gbIsAuthenticated = 0;
77 char *gsItemPattern; //!< Item pattern
78 char *gsEffectiveUser; //!< '-u' Dispense as another user
79 int gbUseNCurses = 0; //!< '-G' Use the NCurses GUI?
80 int giMinimumBalance = INT_MIN; //!< '-m' Minumum balance for `dispense acct`
81 int giMaximumBalance = INT_MAX; //!< '-M' Maximum balance for `dispense acct`
84 int main(int argc, char *argv[])
90 // -- Create regular expressions
91 // > Code Type Count ...
92 CompileRegex(&gArrayRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([0-9]+)", REG_EXTENDED); //
93 // > Code Type Ident Price Desc
94 CompileRegex(&gItemRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([A-Za-z]+):([0-9]+)\\s+([0-9]+)\\s+(.+)$", REG_EXTENDED);
96 CompileRegex(&gSaltRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+(.+)$", REG_EXTENDED);
97 // > Code 'User' Username Balance Flags
98 CompileRegex(&gUserInfoRegex, "^([0-9]{3})\\s+([A-Za-z]+)\\s+([^ ]+)\\s+(-?[0-9]+)\\s+(.+)$", REG_EXTENDED);
101 for( i = 1; i < argc; i ++ )
114 case 'm': // Minimum balance
115 giMinimumBalance = atoi(argv[++i]);
117 case 'M': // Maximum balance
118 giMaximumBalance = atoi(argv[++i]);
121 case 'u': // Override User
122 gsEffectiveUser = argv[++i];
136 if( strcmp(arg, "acct") == 0 )
139 sock = OpenConnection(gsDispenseServer, giDispensePort);
140 if( sock < 0 ) return -1;
143 if( i + 1 == argc ) {
144 Dispense_EnumUsers(sock);
148 // argv[i+1]: Username
153 if( i + 3 >= argc ) {
154 fprintf(stderr, "Error: `dispense acct' needs a reason\n");
158 // Authentication required
159 if( Authenticate(sock) )
162 // argv[i+1]: Username
163 // argv[i+2]: Ammount
166 if( argv[i+2][0] == '=' ) {
168 if( argv[i+2][1] != '0' && atoi(&argv[i+2][1]) == 0 ) {
169 fprintf(stderr, "Error: Invalid balance to be set\n");
173 Dispense_SetBalance(sock, argv[i+1], atoi(argv[i+2]+1), argv[i+3]);
177 Dispense_AlterBalance(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
181 // Show user information
182 Dispense_ShowUser(sock, argv[i+1]);
189 // - "Here, have some money."
190 if( strcmp(arg, "give") == 0 )
192 if( i + 3 >= argc ) {
193 fprintf(stderr, "`dispense give` takes three arguments\n");
197 // TODO: `dispense give`
199 // argv[i+1]: Destination
200 // argv[i+2]: Ammount
204 sock = OpenConnection(gsDispenseServer, giDispensePort);
205 if( sock < 0 ) return -1;
208 if( Authenticate(sock) )
211 Dispense_Give(sock, argv[i+1], atoi(argv[i+2]), argv[i+3]);
216 // - User administration (Admin Only)
217 if( strcmp(arg, "user") == 0 )
219 // Check argument count
220 if( i + 1 >= argc ) {
221 fprintf(stderr, "Error: `dispense user` requires arguments\n");
227 sock = OpenConnection(gsDispenseServer, giDispensePort);
228 if( sock < 0 ) return -1;
230 // Attempt authentication
231 if( Authenticate(sock) )
235 if( strcmp(argv[i+1], "add") == 0 )
237 if( i + 2 >= argc ) {
238 fprintf(stderr, "Error: `dispense user add` requires an argument\n");
243 Dispense_AddUser(sock, argv[i+2]);
246 else if( strcmp(argv[i+1], "type") == 0 )
248 if( i + 3 >= argc ) {
249 fprintf(stderr, "Error: `dispense user type` requires two arguments\n");
254 Dispense_SetUserType(sock, argv[i+2], argv[i+3]);
258 fprintf(stderr, "Error: Unknown sub-command for `dispense user`\n");
266 if( strcmp(arg, "donate") == 0 )
268 // Check argument count
269 if( i + 2 >= argc ) {
270 fprintf(stderr, "Error: `dispense donate` requires two arguments\n");
276 sock = OpenConnection(gsDispenseServer, giDispensePort);
277 if( sock < 0 ) return -1;
279 // Attempt authentication
280 if( Authenticate(sock) )
284 Dispense_Donate(sock, atoi(argv[i+1]), argv[i+1]);
290 // Item name / pattern
297 sock = OpenConnection(gsDispenseServer, giDispensePort);
298 if( sock < 0 ) return -1;
301 PopulateItemList(sock);
303 // Disconnect from server
308 // TODO: Implement `dispense <name>`
309 printf("TODO: Implement `dispense <name>`\n");
312 else if( gbUseNCurses )
318 // Very basic dispense interface
319 for( i = 0; i < giNumItems; i ++ ) {
320 printf("%2i %s:%i\t%3i %s\n", i, gaItems[i].Type, gaItems[i].ID,
321 gaItems[i].Price, gaItems[i].Desc);
330 fgets(buffer, BUFSIZ, stdin);
334 if( buf[0] == 'q' ) break;
338 if( i != 0 || buf[0] == '0' )
340 if( i < 0 || i >= giNumItems ) {
341 printf("Bad item %i (should be between 0 and %i)\n", i, giNumItems);
350 // Check for a valid item ID
353 // Connect, Authenticate, dispense and close
354 sock = OpenConnection(gsDispenseServer, giDispensePort);
355 if( sock < 0 ) return -1;
357 DispenseItem(sock, i);
370 " Show interactive list\n"
372 " Dispense named item\n"
373 " dispense give <user> <ammount> \"<reason>\"\n"
374 " Give money to another user\n"
375 " dispense donate <ammount> \"<reason>\"\n"
376 " Donate to the club\n"
377 " == Coke members == \n"
378 " dispense acct [<user>]\n"
379 " Show user balances\n"
380 " dispense acct <user> [+-]<ammount> \"<reason>\"\n"
381 " Alter a account value\n"
382 " == Dispense administrators ==\n"
383 " dispense acct <user> =<ammount> \"<reason>\"\n"
384 " Set an account balance\n"
385 " dispense user add <user>\n"
386 " Create new coke account (Admins only)\n"
387 " dispense user type <user> <flags>\n"
388 " Alter a user's flags\n"
389 " <flags> is a comma-separated list of user, coke, admin or disabled\n"
390 " Flags are removed by preceding the name with '-' or '!'\n"
394 " Set a different user (Coke members only)\n"
398 " Use alternate GUI\n"
399 " -m <min balance>\n"
400 " -M <max balance>\n"
401 " Set the Maximum/Minimum balances shown in `dispense acct`\n"
405 // -------------------
406 // --- NCurses GUI ---
407 // -------------------
409 * \brief Render the NCurses UI
411 int ShowNCursesUI(void)
413 // TODO: ncurses interface (with separation between item classes)
414 // - Hmm... that would require standardising the item ID to be <class>:<index>
419 const int displayMinWidth = 40;
420 const int displayMinItems = 8;
421 char *titleString = "Dispense";
422 int itemCount = displayMinItems;
425 int ret = -2; // -2: Used for marking "no return yet"
434 // - 6: randomly chosen (Need at least 3)
435 itemCount = LINES - 6;
436 if( itemCount > giNumItems )
437 itemCount = giNumItems;
440 height = itemCount + 3;
441 width = displayMinWidth;
444 xBase = COLS/2 - width/2;
445 yBase = LINES/2 - height/2;
450 PrintAlign(yBase, xBase, width, "/", '-', titleString, '-', "\\");
453 for( i = 0; i < itemCount; i ++ )
455 move( yBase + 1 + i, xBase );
457 if( currentItem == itemBase + i ) {
465 // - Oh god, magic numbers!
466 if( i == 0 && itemBase > 0 ) {
468 times = width-1 - 8 - 3;
469 while(times--) addch(' ');
471 else if( i == itemCount - 1 && itemBase < giNumItems - itemCount ) {
473 times = width-1 - 8 - 3;
474 while(times--) addch(' ');
478 ShowItemAt( yBase + 1 + i, xBase + 5, width - 7, itemBase + i);
482 // Scrollbar (if needed)
483 if( giNumItems > itemCount ) {
487 else if( i == itemCount - 1 ) {
491 int percentage = itemBase * 100 / (giNumItems-itemCount);
492 if( i-1 == percentage*(itemCount-3)/100 ) {
506 PrintAlign(yBase+height-2, xBase, width, "\\", '-', "", '-', "/");
519 //if( itemBase < giNumItems - (itemCount) )
521 if( currentItem < giNumItems - 1 )
523 if( itemBase + itemCount - 1 <= currentItem && itemBase + itemCount < giNumItems )
529 if( currentItem > 0 )
531 if( itemBase + 1 > currentItem && itemBase > 0 )
547 ret = -1; // -1: Return with no dispense
551 // Check if the return value was changed
552 if( ret != -2 ) break;
564 * \brief Show item \a Index at (\a Col, \a Row)
565 * \note Part of the NCurses UI
567 void ShowItemAt(int Row, int Col, int Width, int Index)
575 if( Index < 0 || Index >= giNumItems ) {
580 name = gaItems[Index].Desc;
581 price = gaItems[Index].Price;
584 printw("%02i %s", Index, name);
586 getyx(stdscr, _y, _x);
587 // Assumes max 4 digit prices
588 times = Width - 4 - (_x - Col); // TODO: Better handling for large prices
589 while(times--) addch(' ');
590 printw("%4i", price);
594 * \brief Print a three-part string at the specified position (formatted)
595 * \note NCurses UI Helper
597 * Prints \a Left on the left of the area, \a Right on the righthand side
598 * and \a Mid in the middle of the area. These are padded with \a Pad1
599 * between \a Left and \a Mid, and \a Pad2 between \a Mid and \a Right.
601 * ::printf style format codes are allowed in \a Left, \a Mid and \a Right,
602 * and the arguments to these are read in that order.
604 void PrintAlign(int Row, int Col, int Width, const char *Left, char Pad1,
605 const char *Mid, char Pad2, const char *Right, ...)
607 int lLen, mLen, rLen;
612 // Get the length of the strings
613 va_start(args, Right);
614 lLen = vsnprintf(NULL, 0, Left, args);
615 mLen = vsnprintf(NULL, 0, Mid, args);
616 rLen = vsnprintf(NULL, 0, Right, args);
620 if( lLen + mLen/2 > Width/2 || mLen/2 + rLen > Width/2 ) {
621 return ; // TODO: What to do?
627 va_start(args, Right);
631 vsnprintf(tmp, lLen+1, Left, args);
635 times = Width/2 - mLen/2 - lLen;
636 while(times--) addch(Pad1);
640 vsnprintf(tmp, mLen+1, Mid, args);
644 times = Width/2 - mLen/2 - rLen;
645 while(times--) addch(Pad2);
649 vsnprintf(tmp, rLen+1, Right, args);
654 // ---------------------
655 // --- Coke Protocol ---
656 // ---------------------
657 int OpenConnection(const char *Host, int Port)
659 struct hostent *host;
660 struct sockaddr_in serverAddr;
663 host = gethostbyname(Host);
665 fprintf(stderr, "Unable to look up '%s'\n", Host);
669 memset(&serverAddr, 0, sizeof(serverAddr));
671 serverAddr.sin_family = AF_INET; // IPv4
672 // NOTE: I have a suspicion that IPv6 will play sillybuggers with this :)
673 serverAddr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
674 serverAddr.sin_port = htons(Port);
676 sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
678 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
689 // Loop through all the top ports until one is avaliable
690 for( i = 1001; i < 1024; i ++)
692 localAddr.sin_port = htons(i); // IPv4
693 // Attempt to bind to low port for autoauth
694 if( bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0 )
698 printf("Warning: AUTOAUTH unavaliable\n");
701 if( connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0 ) {
702 fprintf(stderr, "Failed to connect to server\n");
710 * \brief Authenticate with the server
711 * \return Boolean Failure
713 int Authenticate(int Socket)
720 regmatch_t matches[4];
722 if( gbIsAuthenticated ) return 0;
725 pwd = getpwuid( getuid() );
727 // Attempt automatic authentication
728 sendf(Socket, "AUTOAUTH %s\n", pwd->pw_name);
730 // Check if it worked
731 buf = ReadLine(Socket);
733 responseCode = atoi(buf);
734 switch( responseCode )
736 case 200: // Autoauth succeeded, return
740 case 401: // Untrusted, attempt password authentication
743 sendf(Socket, "USER %s\n", pwd->pw_name);
744 printf("Using username %s\n", pwd->pw_name);
746 buf = ReadLine(Socket);
749 // Expected format: 100 SALT <something> ...
751 RunRegex(&gSaltRegex, buf, 4, matches, "Malformed server response");
752 responseCode = atoi(buf);
753 if( responseCode != 100 ) {
754 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
760 if( memcmp( buf+matches[2].rm_so, "SALT", matches[2].rm_eo - matches[2].rm_so) == 0) {
761 // Store it for later
762 memcpy( salt, buf + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so );
763 salt[ matches[3].rm_eo - matches[3].rm_so ] = 0;
767 // Give three attempts
768 for( i = 0; i < 3; i ++ )
770 int ofs = strlen(pwd->pw_name)+strlen(salt);
773 char *pass = getpass("Password: ");
776 // Create hash string
777 // <username><salt><hash>
778 strcpy(tmp, pwd->pw_name);
780 SHA1( (unsigned char*)pass, strlen(pass), h );
781 memcpy(tmp+ofs, h, 20);
784 SHA1( (unsigned char*)tmp, ofs+20, h );
785 sprintf(tmpBuf, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
786 h[ 0], h[ 1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[ 8], h[ 9],
787 h[10], h[11], h[12], h[13], h[14], h[15], h[16], h[17], h[18], h[19]
791 sendf(Socket, "PASS %s\n", tmpBuf);
792 buf = ReadLine(Socket);
794 responseCode = atoi(buf);
796 if( responseCode == 200 ) break;
797 // Bad username/password
798 if( responseCode == 401 ) continue;
800 fprintf(stderr, "Unknown repsonse code %i from server\n%s\n", responseCode, buf);
806 return 2; // 2 = Bad Password
809 case 404: // Bad Username
810 fprintf(stderr, "Bad Username '%s'\n", pwd->pw_name);
815 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
821 // Set effective user
822 if( gsEffectiveUser ) {
823 sendf(Socket, "SETEUSER %s\n", gsEffectiveUser);
825 buf = ReadLine(Socket);
826 responseCode = atoi(buf);
831 printf("Running as '%s' by '%s'\n", gsEffectiveUser, pwd->pw_name);
835 printf("Only coke members can use `dispense -u`\n");
840 printf("Invalid user selected\n");
845 fprintf(stderr, "Unkown response code %i from server\n", responseCode);
854 gbIsAuthenticated = 1;
861 * \brief Fill the item information structure
862 * \return Boolean Failure
864 void PopulateItemList(int Socket)
869 char *itemType, *itemStart;
871 regmatch_t matches[4];
873 // Ask server for stock list
874 send(Socket, "ENUM_ITEMS\n", 11, 0);
875 buf = ReadLine(Socket);
877 //printf("Output: %s\n", buf);
879 responseCode = atoi(buf);
880 if( responseCode != 201 ) {
881 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
890 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
892 itemType = &buf[ matches[2].rm_so ]; buf[ matches[2].rm_eo ] = '\0';
893 count = atoi( &buf[ matches[3].rm_so ] );
896 if( strcmp(itemType, "Items") != 0 ) {
898 fprintf(stderr, "Unexpected array type, expected 'Items', got '%s'\n",
903 itemStart = &buf[ matches[3].rm_eo ];
908 gaItems = malloc( giNumItems * sizeof(tItem) );
910 // Fetch item information
911 for( i = 0; i < giNumItems; i ++ )
913 regmatch_t matches[7];
916 buf = ReadLine(Socket);
917 responseCode = atoi(buf);
919 if( responseCode != 202 ) {
920 fprintf(stderr, "Unknown response from dispense server (Response Code %i)\n", responseCode);
924 RunRegex(&gItemRegex, buf, 7, matches, "Malformed server response");
926 buf[ matches[3].rm_eo ] = '\0';
928 gaItems[i].Type = strdup( buf + matches[3].rm_so );
929 gaItems[i].ID = atoi( buf + matches[4].rm_so );
930 gaItems[i].Price = atoi( buf + matches[5].rm_so );
931 gaItems[i].Desc = strdup( buf + matches[6].rm_so );
937 buf = ReadLine(Socket);
938 responseCode = atoi(buf);
940 if( responseCode != 200 ) {
941 fprintf(stderr, "Unknown response from dispense server %i\n'%s'",
951 * \brief Dispense an item
952 * \return Boolean Failure
954 int DispenseItem(int Socket, int ItemID)
956 int ret, responseCode;
959 if( ItemID < 0 || ItemID > giNumItems ) return -1;
962 sendf(Socket, "DISPENSE %s:%i\n", gaItems[ItemID].Type, gaItems[ItemID].ID);
963 buf = ReadLine(Socket);
965 responseCode = atoi(buf);
966 switch( responseCode )
969 printf("Dispense OK\n");
973 printf("Not authenticated\n");
977 printf("Insufficient balance\n");
981 printf("Bad item name, bug report\n");
985 printf("Item failed to dispense, is the slot empty?\n");
989 printf("Dispense not possible (slot empty/permissions)\n");
993 printf("Unknown response code %i ('%s')\n", responseCode, buf);
1003 * \brief Alter a user's balance
1005 int Dispense_AlterBalance(int Socket, const char *Username, int Ammount, const char *Reason)
1010 sendf(Socket, "ADD %s %i %s\n", Username, Ammount, Reason);
1011 buf = ReadLine(Socket);
1013 responseCode = atoi(buf);
1016 switch(responseCode)
1018 case 200: return 0; // OK
1020 fprintf(stderr, "Insufficient balance\n");
1022 case 403: // Not in coke
1023 fprintf(stderr, "You are not in coke (sucker)\n");
1025 case 404: // Unknown user
1026 fprintf(stderr, "Unknown user '%s'\n", Username);
1029 fprintf(stderr, "Unknown response code %i\n", responseCode);
1037 * \brief Set a user's balance
1038 * \note Only avaliable to dispense admins
1040 int Dispense_SetBalance(int Socket, const char *Username, int Balance, const char *Reason)
1045 sendf(Socket, "SET %s %i %s\n", Username, Balance, Reason);
1046 buf = ReadLine(Socket);
1048 responseCode = atoi(buf);
1051 switch(responseCode)
1053 case 200: return 0; // OK
1054 case 403: // Not in coke
1055 fprintf(stderr, "You are not an admin\n");
1057 case 404: // Unknown user
1058 fprintf(stderr, "Unknown user '%s'\n", Username);
1061 fprintf(stderr, "Unknown response code %i\n", responseCode);
1069 * \brief Give money to another user
1071 int Dispense_Give(int Socket, const char *Username, int Ammount, const char *Reason)
1077 printf("Sorry, you can only give, you can't take.\n");
1081 // Fast return on zero
1082 if( Ammount == 0 ) {
1083 printf("Are you actually going to give any?\n");
1087 sendf(Socket, "GIVE %s %i %s\n", Username, Ammount, Reason);
1088 buf = ReadLine(Socket);
1090 responseCode = atoi(buf);
1093 switch(responseCode)
1095 case 200: return 0; // OK
1098 fprintf(stderr, "Insufficient balance\n");
1101 case 404: // Unknown user
1102 fprintf(stderr, "Unknown user '%s'\n", Username);
1106 fprintf(stderr, "Unknown response code %i\n", responseCode);
1115 * \brief Donate money to the club
1117 int Dispense_Donate(int Socket, int Ammount, const char *Reason)
1123 printf("Sorry, you can only give, you can't take.\n");
1127 // Fast return on zero
1128 if( Ammount == 0 ) {
1129 printf("Are you actually going to give any?\n");
1133 sendf(Socket, "DONATE %i %s\n", Ammount, Reason);
1134 buf = ReadLine(Socket);
1136 responseCode = atoi(buf);
1139 switch(responseCode)
1141 case 200: return 0; // OK
1144 fprintf(stderr, "Insufficient balance\n");
1148 fprintf(stderr, "Unknown response code %i\n", responseCode);
1156 * \brief Enumerate users
1158 int Dispense_EnumUsers(int Socket)
1163 regmatch_t matches[4];
1165 if( giMinimumBalance != INT_MIN ) {
1166 if( giMaximumBalance != INT_MAX ) {
1167 sendf(Socket, "ENUM_USERS min_balance:%i max_balance:%i\n", giMinimumBalance, giMaximumBalance);
1170 sendf(Socket, "ENUM_USERS min_balance:%i\n", giMinimumBalance);
1174 if( giMaximumBalance != INT_MAX ) {
1175 sendf(Socket, "ENUM_USERS max_balance:%i\n", giMaximumBalance);
1178 sendf(Socket, "ENUM_USERS\n");
1181 buf = ReadLine(Socket);
1182 responseCode = atoi(buf);
1184 switch(responseCode)
1186 case 201: break; // Ok, length follows
1189 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1194 // Get count (not actually used)
1195 RunRegex(&gArrayRegex, buf, 4, matches, "Malformed server response");
1196 nUsers = atoi( buf + matches[3].rm_so );
1197 printf("%i users returned\n", nUsers);
1202 // Read returned users
1204 buf = ReadLine(Socket);
1205 responseCode = atoi(buf);
1207 if( responseCode != 202 ) break;
1209 _PrintUserLine(buf);
1211 } while(responseCode == 202);
1213 // Check final response
1214 if( responseCode != 200 ) {
1215 fprintf(stderr, "Unknown response code %i\n%s\n", responseCode, buf);
1225 int Dispense_ShowUser(int Socket, const char *Username)
1228 int responseCode, ret;
1230 sendf(Socket, "USER_INFO %s\n", Username);
1231 buf = ReadLine(Socket);
1233 responseCode = atoi(buf);
1235 switch(responseCode)
1238 _PrintUserLine(buf);
1243 printf("Unknown user '%s'\n", Username);
1248 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1258 void _PrintUserLine(const char *Line)
1260 regmatch_t matches[6];
1263 RunRegex(&gUserInfoRegex, Line, 6, matches, "Malformed server response");
1268 int usernameLen = matches[3].rm_eo - matches[3].rm_so;
1269 char username[usernameLen + 1];
1270 int flagsLen = matches[5].rm_eo - matches[5].rm_so;
1271 char flags[flagsLen + 1];
1273 memcpy(username, Line + matches[3].rm_so, usernameLen);
1274 username[usernameLen] = '\0';
1275 memcpy(flags, Line + matches[5].rm_so, flagsLen);
1276 flags[flagsLen] = '\0';
1278 bal = atoi(Line + matches[4].rm_so);
1279 printf("%-15s: $%4i.%02i (%s)\n", username, bal/100, abs(bal)%100, flags);
1283 int Dispense_AddUser(int Socket, const char *Username)
1286 int responseCode, ret;
1288 sendf(Socket, "USER_ADD %s\n", Username);
1290 buf = ReadLine(Socket);
1291 responseCode = atoi(buf);
1293 switch(responseCode)
1296 printf("User '%s' added\n", Username);
1301 printf("Only wheel can add users\n");
1306 printf("User '%s' already exists\n", Username);
1311 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1321 int Dispense_SetUserType(int Socket, const char *Username, const char *TypeString)
1324 int responseCode, ret;
1326 // TODO: Pre-validate the string
1328 sendf(Socket, "USER_FLAGS %s %s\n", Username, TypeString);
1330 buf = ReadLine(Socket);
1331 responseCode = atoi(buf);
1333 switch(responseCode)
1336 printf("User '%s' updated\n", Username);
1341 printf("Only wheel can modify users\n");
1346 printf("User '%s' does not exist\n", Username);
1351 printf("Flag string is invalid\n");
1356 fprintf(stderr, "Unknown response code %i '%s'\n", responseCode, buf);
1369 char *ReadLine(int Socket)
1371 static char buf[BUFSIZ];
1372 static int bufPos = 0;
1373 static int bufValid = 0;
1375 char *newline = NULL;
1377 char *ret = malloc(10);
1379 #if DEBUG_TRACE_SERVER
1380 printf("ReadLine: ");
1392 len = recv(Socket, buf+bufPos, BUFSIZ-1-bufPos, 0);
1393 buf[bufPos+len] = '\0';
1396 newline = strchr( buf+bufPos, '\n' );
1401 retLen += strlen(buf+bufPos);
1402 ret = realloc(ret, retLen + 1);
1403 strcat( ret, buf+bufPos );
1406 int newLen = newline - (buf+bufPos) + 1;
1407 bufValid = len - newLen;
1410 if( len + bufPos == BUFSIZ - 1 ) bufPos = 0;
1413 #if DEBUG_TRACE_SERVER
1414 printf("%i '%s'\n", retLen, ret);
1420 int sendf(int Socket, const char *Format, ...)
1425 va_start(args, Format);
1426 len = vsnprintf(NULL, 0, Format, args);
1431 va_start(args, Format);
1432 vsnprintf(buf, len+1, Format, args);
1435 #if DEBUG_TRACE_SERVER
1436 printf("sendf: %s", buf);
1439 return send(Socket, buf, len, 0);
1443 char *trim(char *string)
1447 while( isspace(*string) )
1450 for( i = strlen(string); i--; )
1452 if( isspace(string[i]) )
1461 int RunRegex(regex_t *regex, const char *string, int nMatches, regmatch_t *matches, const char *errorMessage)
1465 ret = regexec(regex, string, nMatches, matches, 0);
1467 size_t len = regerror(ret, regex, NULL, 0);
1469 regerror(ret, regex, errorStr, len);
1470 printf("string = '%s'\n", string);
1471 fprintf(stderr, "%s\n%s", errorMessage, errorStr);
1478 void CompileRegex(regex_t *regex, const char *pattern, int flags)
1480 int ret = regcomp(regex, pattern, flags);
1482 size_t len = regerror(ret, regex, NULL, 0);
1484 regerror(ret, regex, errorStr, len);
1485 fprintf(stderr, "Regex compilation failed - %s\n", errorStr);