3 * client.c -- connect to a server
7 * This code is Copyright (c) 2002, by the authors of nmh. See the
8 * COPYRIGHT file in the root directory of the nmh distribution for
9 * complete copyright information.
16 #include <sys/socket.h>
17 #include <netinet/in.h>
20 #ifdef HAVE_ARPA_INET_H
21 # include <arpa/inet.h>
33 /* client's own static version of several nmh subroutines */
34 static char **client_brkstring (char *, char *, char *);
35 static int client_brkany (char, char *);
36 static char **client_copyip (char **, char **, int);
37 static char *client_getcpy (char *);
38 static void client_freelist(char **);
42 client (char *args, char *service, char *response, int len_response, int debug)
45 char **ap, *arguments[MAXARGS];
46 struct addrinfo hints, *res, *ai;
49 if (args != NULL && *args != 0) {
50 ap = client_copyip (client_brkstring (client_getcpy (args), " ", "\n"),
53 if (servers != NULL && *servers != 0)
54 ap = client_copyip (client_brkstring (client_getcpy (servers), " ", "\n"),
57 if (ap == arguments) {
58 *ap++ = client_getcpy ("localhost");
62 memset(&hints, 0, sizeof(hints));
63 hints.ai_flags = AI_ADDRCONFIG;
64 hints.ai_family = PF_UNSPEC;
65 hints.ai_socktype = SOCK_STREAM;
67 for (ap = arguments; *ap; ap++) {
70 fprintf(stderr, "Trying to connect to \"%s\" ...\n", *ap);
73 rc = getaddrinfo(*ap, service, &hints, &res);
77 fprintf(stderr, "Lookup of \"%s\" failed: %s\n", *ap,
83 for (ai = res; ai != NULL; ai = ai->ai_next) {
85 char address[NI_MAXHOST];
87 rc = getnameinfo(ai->ai_addr, ai->ai_addrlen, address,
88 sizeof(address), NULL, NULL, NI_NUMERICHOST);
90 fprintf(stderr, "Connecting to %s...\n",
91 rc ? "unknown" : address);
94 sd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
98 fprintf(stderr, "socket() failed: %s\n", strerror(errno));
102 if (connect(sd, ai->ai_addr, ai->ai_addrlen) == 0) {
109 fprintf(stderr, "Connection failed: %s\n", strerror(errno));
119 strncpy (response, "no servers available", len_response);
125 * Free a list of strings
129 client_freelist(char **list)
131 while (*list++ != NULL)
137 * static copies of three nmh subroutines
140 static char *broken[MAXARGS + 1];
143 client_brkstring (char *strg, char *brksep, char *brkterm)
146 register char c, *sp;
150 for (bi = 0; bi < MAXARGS; bi++) {
151 while (client_brkany (c = *sp, brksep))
153 if (!c || client_brkany (c, brkterm)) {
160 while ((c = *++sp) && !client_brkany (c, brksep) && !client_brkany (c, brkterm))
170 * returns 1 if chr in strg, 0 otherwise
173 client_brkany (char chr, char *strg)
178 for (sp = strg; *sp; sp++)
186 * copy a string array and return pointer to end
189 client_copyip (char **p, char **q, int len_q)
191 while (*p && --len_q > 0)
201 client_getcpy (char *str)
206 len = strlen(str) + 1;
207 cp = mh_xmalloc(len);
209 memcpy (cp, str, len);