finger

finger fortune@hhvn.uk
Log | Files | Refs | LICENSE

commit 6e5b03e929e5342fdd68cad71611c102dc36f6b0
parent caba10978888df9b472b2369f9c4ba76266cf634
Author: hhvn <dev@hhvn.uk>
Date:   Sun, 11 Jul 2021 18:17:05 +0100

finger.c: redesign argument parsing

Diffstat:
Mfinger.c | 64+++++++++++++++++++++++-----------------------------------------
1 file changed, 23 insertions(+), 41 deletions(-)

diff --git a/finger.c b/finger.c @@ -13,15 +13,14 @@ #include "arg.h" #define EXIT_USAGE 2 -#define USER_DFLT "" -#define HOST_DFLT "localhost" -#define PORT_DFLT "79" - #ifndef __OpenBSD__ #define pledge(a,b) 0 #endif enum { ISUSER, ISHOST, ISPORT }; +char *user_dflt = ""; +char *host_dflt = "localhost"; +char *port_dflt = "79"; char *argv0; int verbose = 0; @@ -72,7 +71,7 @@ finger(char *user, char *host, char *port, int w) { hints.ai_socktype = SOCK_STREAM; if ((sret = getaddrinfo(host, port, &hints, &ai)) != 0 || ai == NULL) - die(1, "%s%s\n", verbose ? "getaddrinfo(): " : "", gai_strerror(sret)); + die(1, "%s%s: %s:%s\n", verbose ? "getaddrinfo(): " : "", gai_strerror(sret), host, port); if ((sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == 1) die(1, "%s%s\n", verbose ? "socket(): " : "", strerror(errno)); if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) @@ -95,9 +94,9 @@ finger(char *user, char *host, char *port, int w) { int main(int argc, char *argv[]) { - char user[128], - host[128], - port[128]; + char *user, + *host, + *port; int sendw = 0; int segment; int i, j, k; @@ -120,42 +119,25 @@ main(int argc, char *argv[]) { die(1, "no targets specified\n"); for (i=0; i < argc; i++) { + user = user_dflt; + host = host_dflt; + port = port_dflt; + segment = ISUSER; - for (j=k=0; argv[i] && argv[i][k]; j++, k++) { - switch (segment) { - case ISUSER: - if (argv[i][k] == '@') { - if (argv[i][k+1] == '\0' || argv[i][k+1] == ':') - die(1, "missing hostname in: %s\n", argv[i]); - user[j] = '\0'; - segment++; - j = -1; - } else { - user[j] = argv[i][k]; - } - break; - case ISHOST: - if (argv[i][k] == ':') { - if (argv[i][k+1] == '\0') - die(1, "missing port in: %s\n", argv[i]); - host[j] = '\0'; - segment++; - j = -1; - } else { - host[j] = argv[i][k]; - } - break; - case ISPORT: - port[j] = argv[i][k]; + user = argv[i]; + for (; argv[i] && *argv[i]; argv[i]++) { + if (segment == ISUSER && *argv[i] == '@') { + *argv[i] = '\0'; + host = argv[i]+1; + segment = ISHOST; + } + if (segment == ISHOST && *argv[i] == ':') { + *argv[i] = '\0'; + port = argv[i]+1; + segment = ISPORT; } } - - /* set defaults */ - switch (segment) { - case ISUSER: strlcpy(host, HOST_DFLT, sizeof(host)); - case ISHOST: strlcpy(port, PORT_DFLT, sizeof(port)); - } - + printf("user: %s | host: %s | port: %s\n", user, host, port); finger(user, host, port, sendw); }