Example #1
0
ip_address_item *
os_common_find_running_interfaces(void)
{
struct ifaddrs *ifalist = NULL;
ip_address_item *yield = NULL;
ip_address_item *last = NULL;
ip_address_item  *next;

if (getifaddrs(&ifalist) != 0)
  log_write(0, LOG_PANIC_DIE, "Unable to call getifaddrs: %d %s",
    errno, strerror(errno));

struct ifaddrs *ifa;
for (ifa = ifalist; ifa != NULL; ifa = ifa->ifa_next)
  {
  if (ifa->ifa_addr->sa_family != AF_INET
#if HAVE_IPV6
    && ifa->ifa_addr->sa_family != AF_INET6
#endif /* HAVE_IPV6 */
    )
    continue;

  if ( !(ifa->ifa_flags & IFF_UP) ) /* Only want 'UP' interfaces */
    continue;

  /* Create a data block for the address, fill in the data, and put it on the
  chain. */

  next = store_get(sizeof(ip_address_item));
  next->next = NULL;
  next->port = 0;
  (void)host_ntoa(-1, ifa->ifa_addr, next->address, NULL);

  if (yield == NULL)
    yield = last = next;
  else
    {
    last->next = next;
    last = next;
    }

  DEBUG(D_interface) debug_printf("Actual local interface address is %s (%s)\n",
    last->address, ifa->ifa_name);
  }

/* free the list of addresses, and return the chain of data blocks. */

freeifaddrs (ifalist);
return yield;
}
Example #2
0
int
auth_cyrus_sasl_server(auth_instance *ablock, uschar *data)
{
auth_cyrus_sasl_options_block *ob =
  (auth_cyrus_sasl_options_block *)(ablock->options_block);
uschar *output, *out2, *input, *clear, *hname;
uschar *debug = NULL;   /* Stops compiler complaining */
sasl_callback_t cbs[] = {{SASL_CB_LIST_END, NULL, NULL}};
sasl_conn_t *conn;
char * realm_expanded = NULL;
int rc, firsttime = 1, clen, *negotiated_ssf_ptr = NULL, negotiated_ssf;
unsigned int inlen, outlen;

input = data;
inlen = Ustrlen(data);

HDEBUG(D_auth) debug = string_copy(data);

hname = expand_string(ob->server_hostname);
if (hname && ob->server_realm)
  realm_expanded = CS expand_string(ob->server_realm);
if (!hname  ||  !realm_expanded  && ob->server_realm)
  {
  auth_defer_msg = expand_string_message;
  return DEFER;
  }

if (inlen)
  {
  if ((clen = b64decode(input, &clear)) < 0)
    return BAD64;
  input = clear;
  inlen = clen;
  }

if ((rc = sasl_server_init(cbs, "exim")) != SASL_OK)
  {
  auth_defer_msg = US"couldn't initialise Cyrus SASL library";
  return DEFER;
  }

rc = sasl_server_new(CS ob->server_service, CS hname, realm_expanded, NULL,
  NULL, NULL, 0, &conn);

HDEBUG(D_auth)
  debug_printf("Initialised Cyrus SASL server connection; service=\"%s\" fqdn=\"%s\" realm=\"%s\"\n",
      ob->server_service, hname, realm_expanded);

if (rc != SASL_OK )
  {
  auth_defer_msg = US"couldn't initialise Cyrus SASL connection";
  sasl_done();
  return DEFER;
  }

if (tls_in.cipher)
  {
  if ((rc = sasl_setprop(conn, SASL_SSF_EXTERNAL, (sasl_ssf_t *) &tls_in.bits)) != SASL_OK)
    {
    HDEBUG(D_auth) debug_printf("Cyrus SASL EXTERNAL SSF set %d failed: %s\n",
        tls_in.bits, sasl_errstring(rc, NULL, NULL));
    auth_defer_msg = US"couldn't set Cyrus SASL EXTERNAL SSF";
    sasl_done();
    return DEFER;
    }
  else
    HDEBUG(D_auth) debug_printf("Cyrus SASL set EXTERNAL SSF to %d\n", tls_in.bits);
  }
else
  HDEBUG(D_auth) debug_printf("Cyrus SASL: no TLS, no EXTERNAL SSF set\n");

/* So sasl_setprop() documents non-shorted IPv6 addresses which is incredibly
annoying; looking at cyrus-imapd-2.3.x source, the IP address is constructed
with their iptostring() function, which just wraps
getnameinfo(..., NI_NUMERICHOST|NI_NUMERICSERV), which is equivalent to the
inet_ntop which we wrap in our host_ntoa() function.

So the docs are too strict and we shouldn't worry about :: contractions. */

/* Set properties for remote and local host-ip;port */
for (int i = 0; i < 2; ++i)
  {
  struct sockaddr_storage ss;
  int (*query)(int, struct sockaddr *, socklen_t *);
  int propnum, port;
  const uschar *label;
  uschar *address, *address_port;
  const char *s_err;
  socklen_t sslen;

  if (i)
    {
    query = &getpeername;
    propnum = SASL_IPREMOTEPORT;
    label = CUS"peer";
    }
  else
    {
    query = &getsockname;
    propnum = SASL_IPLOCALPORT;
    label = CUS"local";
    }

  sslen = sizeof(ss);
  if ((rc = query(fileno(smtp_in), (struct sockaddr *) &ss, &sslen)) < 0)
    {
    HDEBUG(D_auth)
      debug_printf("Failed to get %s address information: %s\n",
          label, strerror(errno));
    break;
    }

  address = host_ntoa(-1, &ss, NULL, &port);
  address_port = string_sprintf("%s;%d", address, port);

  if ((rc = sasl_setprop(conn, propnum, address_port)) != SASL_OK)
    {
    s_err = sasl_errdetail(conn);
    HDEBUG(D_auth)
      debug_printf("Failed to set %s SASL property: [%d] %s\n",
          label, rc, s_err ? s_err : "<unknown reason>");
    break;
    }
  HDEBUG(D_auth) debug_printf("Cyrus SASL set %s hostport to: %s\n",
      label, address_port);
  }

for (rc = SASL_CONTINUE; rc == SASL_CONTINUE; )
  {
  if (firsttime)
    {
    firsttime = 0;
    HDEBUG(D_auth) debug_printf("Calling sasl_server_start(%s,\"%s\")\n", ob->server_mech, debug);
    rc = sasl_server_start(conn, CS ob->server_mech, inlen?CS input:NULL, inlen,
           (const char **)(&output), &outlen);
    }
  else
    {
    /* make sure that we have a null-terminated string */
    out2 = string_copyn(output, outlen);

    if ((rc = auth_get_data(&input, out2, outlen)) != OK)
      {
      /* we couldn't get the data, so free up the library before
       * returning whatever error we get */
      sasl_dispose(&conn);
      sasl_done();
      return rc;
      }
    inlen = Ustrlen(input);

    HDEBUG(D_auth) debug = string_copy(input);
    if (inlen)
      {
      if ((clen = b64decode(input, &clear)) < 0)
       {
       sasl_dispose(&conn);
       sasl_done();
       return BAD64;
       }
      input = clear;
      inlen = clen;
      }

    HDEBUG(D_auth) debug_printf("Calling sasl_server_step(\"%s\")\n", debug);
    rc = sasl_server_step(conn, CS input, inlen, (const char **)(&output), &outlen);
    }

  if (rc == SASL_BADPROT)
    {
    sasl_dispose(&conn);
    sasl_done();
    return UNEXPECTED;
    }
  if (rc == SASL_CONTINUE)
    continue;

  /* Get the username and copy it into $auth1 and $1. The former is now the
  preferred variable; the latter is the original variable. */

  if ((sasl_getprop(conn, SASL_USERNAME, (const void **)(&out2))) != SASL_OK)
    {
    HDEBUG(D_auth)
      debug_printf("Cyrus SASL library will not tell us the username: %s\n",
	  sasl_errstring(rc, NULL, NULL));
    log_write(0, LOG_REJECT, "%s authenticator (%s):\n  "
       "Cyrus SASL username fetch problem: %s", ablock->name, ob->server_mech,
       sasl_errstring(rc, NULL, NULL));
    sasl_dispose(&conn);
    sasl_done();
    return FAIL;
    }
  auth_vars[0] = expand_nstring[1] = string_copy(out2);
  expand_nlength[1] = Ustrlen(out2);
  expand_nmax = 1;

  switch (rc)
    {
    case SASL_FAIL: case SASL_BUFOVER: case SASL_BADMAC: case SASL_BADAUTH:
    case SASL_NOAUTHZ: case SASL_ENCRYPT: case SASL_EXPIRED:
    case SASL_DISABLED: case SASL_NOUSER:
      /* these are considered permanent failure codes */
      HDEBUG(D_auth)
	debug_printf("Cyrus SASL permanent failure %d (%s)\n", rc, sasl_errstring(rc, NULL, NULL));
      log_write(0, LOG_REJECT, "%s authenticator (%s):\n  "
	 "Cyrus SASL permanent failure: %s", ablock->name, ob->server_mech,
	 sasl_errstring(rc, NULL, NULL));
      sasl_dispose(&conn);
      sasl_done();
      return FAIL;

    case SASL_NOMECH:
      /* this is a temporary failure, because the mechanism is not
       * available for this user. If it wasn't available at all, we
       * shouldn't have got here in the first place...
       */
      HDEBUG(D_auth)
	debug_printf("Cyrus SASL temporary failure %d (%s)\n", rc, sasl_errstring(rc, NULL, NULL));
      auth_defer_msg =
	  string_sprintf("Cyrus SASL: mechanism %s not available", ob->server_mech);
      sasl_dispose(&conn);
      sasl_done();
      return DEFER;

    case SASL_OK:
      HDEBUG(D_auth)
	debug_printf("Cyrus SASL %s authentication succeeded for %s\n",
	    ob->server_mech, auth_vars[0]);

      if ((rc = sasl_getprop(conn, SASL_SSF, (const void **)(&negotiated_ssf_ptr)))!= SASL_OK)
	{
	HDEBUG(D_auth)
	  debug_printf("Cyrus SASL library will not tell us the SSF: %s\n",
	      sasl_errstring(rc, NULL, NULL));
	log_write(0, LOG_REJECT, "%s authenticator (%s):\n  "
	    "Cyrus SASL SSF value not available: %s", ablock->name, ob->server_mech,
	    sasl_errstring(rc, NULL, NULL));
	sasl_dispose(&conn);
	sasl_done();
	return FAIL;
	}
      negotiated_ssf = *negotiated_ssf_ptr;
      HDEBUG(D_auth)
	debug_printf("Cyrus SASL %s negotiated SSF: %d\n", ob->server_mech, negotiated_ssf);
      if (negotiated_ssf > 0)
	{
	HDEBUG(D_auth)
	  debug_printf("Exim does not implement SASL wrapping (needed for SSF %d).\n", negotiated_ssf);
	log_write(0, LOG_REJECT, "%s authenticator (%s):\n  "
	    "Cyrus SASL SSF %d not supported by Exim", ablock->name, ob->server_mech, negotiated_ssf);
	sasl_dispose(&conn);
	sasl_done();
	return FAIL;
	}

      /* close down the connection, freeing up library's memory */
      sasl_dispose(&conn);
      sasl_done();

      /* Expand server_condition as an authorization check */
      return auth_check_serv_cond(ablock);

    default:
      /* Anything else is a temporary failure, and we'll let SASL print out
       * the error string for us
       */
      HDEBUG(D_auth)
	debug_printf("Cyrus SASL temporary failure %d (%s)\n", rc, sasl_errstring(rc, NULL, NULL));
      auth_defer_msg =
	  string_sprintf("Cyrus SASL: %s", sasl_errstring(rc, NULL, NULL));
      sasl_dispose(&conn);
      sasl_done();
      return DEFER;
    }
  }
/* NOTREACHED */
return 0;  /* Stop compiler complaints */
}
Example #3
0
ip_address_item *
os_common_find_running_interfaces(void)
{
struct V_ifconf ifc;
struct V_ifreq ifreq;
int vs;
ip_address_item *yield = NULL;
ip_address_item *last = NULL;
ip_address_item  *next;
char *cp;
char buf[MAX_INTERFACES*sizeof(struct V_ifreq)];
struct sockaddr *addrp;
size_t len = 0;
char addrbuf[512];

/* We have to create a socket in order to do ioctls on it to find out
what we want to know. */

if ((vs = socket(FAMILY, SOCK_DGRAM, 0)) < 0)
  {
  #if HAVE_IPV6
  DEBUG(D_interface)
    debug_printf("Unable to create IPv6 socket to find interface addresses:\n  "
      "error %d %s\nTrying for an IPv4 socket\n", errno, strerror(errno));
  vs = socket(AF_INET, SOCK_DGRAM, 0);
  if (vs < 0)
  #endif
  log_write(0, LOG_PANIC_DIE, "Unable to create IPv4 socket to find interface "
    "addresses: %d %s", errno, strerror(errno));
  }

/* Get the interface configuration. Some additional data is required when the
new structures are in use. */

ifc.V_ifc_len = sizeof(buf);
ifc.V_ifc_buf = buf;

#ifdef V_FAMILY_QUERY
ifc.V_ifc_family = V_FAMILY_QUERY;
ifc.V_ifc_flags = 0;
#endif

if (ioctl(vs, V_GIFCONF, (char *)&ifc) < 0)
  log_write(0, LOG_PANIC_DIE, "Unable to get interface configuration: %d %s",
    errno, strerror(errno));

/* If the buffer is big enough, the ioctl sets the value of ifc.V_ifc_len to
the amount actually used. If the buffer isn't big enough, at least on some
operating systems, ifc.V_ifc_len still gets set to correspond to the total
number of interfaces, even though they don't all fit in the buffer. */

if (ifc.V_ifc_len > sizeof(buf))
  {
  ifc.V_ifc_len = sizeof(buf);
  DEBUG(D_interface)
    debug_printf("more than %d interfaces found: remainder not used\n"
      "(set MAX_INTERFACES in Local/Makefile and rebuild if you want more)\n",
      MAX_INTERFACES);
  }

/* For each interface, check it is an IP interface, get its flags, and see if
it is up; if not, skip.

BSD systems differ from others in what SIOCGIFCONF returns. Other systems
return a vector of ifreq structures whose size is as defined by the structure.
BSD systems allow sockaddrs to be longer than their sizeof, which in turn makes
the ifreq structures longer than their sizeof. The code below has its origins
in amd and ifconfig; it uses the sa_len field of each sockaddr to determine
each item's length.

This is complicated by the fact that, at least on BSD systems, the data in the
buffer is not guaranteed to be aligned. Thus, we must first copy the basic
struct to some aligned memory before looking at the field in the fixed part to
find its length, and then recopy the correct length. */

for (cp = buf; cp < buf + ifc.V_ifc_len; cp += len)
  {
  memcpy((char *)&ifreq, cp, sizeof(ifreq));

  #ifndef HAVE_SA_LEN
  len = sizeof(struct V_ifreq);

  #else
  len = ((ifreq.ifr_addr.sa_len > sizeof(ifreq.ifr_addr))?
          ifreq.ifr_addr.sa_len : sizeof(ifreq.ifr_addr)) +
         sizeof(ifreq.V_ifr_name);
  if (len > sizeof(addrbuf))
    log_write(0, LOG_PANIC_DIE, "Address for %s interface is absurdly long",
        ifreq.V_ifr_name);

  #endif

  /* If not an IP interface, skip */

  if (ifreq.V_ifr_addr.V_family != AF_INET
  #if HAVE_IPV6
    && ifreq.V_ifr_addr.V_family != AF_INET6
  #endif
    ) continue;

  /* Get the interface flags, and if the interface is down, continue. Formerly,
  we treated the inability to get the flags as a panic-die error. However, it
  seems that on some OS (Solaris 9 being the case noted), it is possible to
  have an interface in this list for which this call fails because the
  interface hasn't been "plumbed" to any protocol (IPv4 or IPv6). Therefore,
  we now just treat this case as "down" as well. */

  if (ioctl(vs, V_GIFFLAGS, (char *)&ifreq) < 0)
    {
    continue;
    /*************
    log_write(0, LOG_PANIC_DIE, "Unable to get flags for %s interface: %d %s",
      ifreq.V_ifr_name, errno, strerror(errno));
    *************/
    }
  if ((ifreq.V_ifr_flags & IFF_UP) == 0) continue;

  /* On some operating systems we have to get the IP address of the interface
  by another call. On others, it's already there, but we must copy the full
  length because we only copied the basic length above, and anyway,
  GIFFLAGS may have wrecked the data. */

  #ifndef SIOCGIFCONF_GIVES_ADDR
  if (ioctl(vs, V_GIFADDR, (char *)&ifreq) < 0)
    log_write(0, LOG_PANIC_DIE, "Unable to get IP address for %s interface: "
      "%d %s", ifreq.V_ifr_name, errno, strerror(errno));
  addrp = &ifreq.V_ifr_addr;

  #else
  memcpy(addrbuf, cp + offsetof(struct V_ifreq, V_ifr_addr),
    len - sizeof(ifreq.V_ifr_name));
  addrp = (struct sockaddr *)addrbuf;
  #endif

  /* Create a data block for the address, fill in the data, and put it on the
  chain. */

  next = store_get(sizeof(ip_address_item));
  next->next = NULL;
  next->port = 0;
  (void)host_ntoa(-1, addrp, next->address, NULL);

  if (yield == NULL) yield = last = next; else
    {
    last->next = next;
    last = next;
    }

  DEBUG(D_interface) debug_printf("Actual local interface address is %s (%s)\n",
    last->address, ifreq.V_ifr_name);
  }

/* Close the socket, and return the chain of data blocks. */

(void)close(vs);
return yield;
}
Example #4
0
File: server.c Project: akissa/exim
int main(int argc, char **argv)
{
int i;
int port = 0;
int listen_socket[3] = { -1, -1, -1 };
int accept_socket;
int dup_accept_socket;
int connection_count = 1;
int count;
int on = 1;
int timeout = 5;
int initial_pause = 0;
int use_ipv4 = 1;
int use_ipv6 = 1;
int debug = 0;
int na = 1;
line *script = NULL;
line *last = NULL;
line *s;
FILE *in, *out;
int linebuf = 1;
char *pidfile = NULL;

char *sockname = NULL;
unsigned char buffer[10240];

struct sockaddr_un sockun;            /* don't use "sun" */
struct sockaddr_un sockun_accepted;
int sockun_len = sizeof(sockun_accepted);

#if HAVE_IPV6
struct sockaddr_in6 sin6;
struct sockaddr_in6 accepted;
struct in6_addr anyaddr6 =  IN6ADDR_ANY_INIT ;
#else
struct sockaddr_in accepted;
#endif

/* Always need an IPv4 structure */

struct sockaddr_in sin4;

int len = sizeof(accepted);


/* Sort out the arguments */
if (argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")))
  {
  printf("Usage: %s [options] port|socket [connection count]\n", argv[0]);
  puts("Options"
       "\n\t-d       debug"
       "\n\t-i n     n seconds initial delay"
       "\n\t-noipv4  disable ipv4"
       "\n\t-noipv6  disable ipv6"
       "\n\t-oP file write PID to file"
       "\n\t-t n     n seconds timeout"
  );
  exit(0);
  }

while (na < argc && argv[na][0] == '-')
  {
  if (strcmp(argv[na], "-d") == 0) debug = 1;
  else if (strcmp(argv[na], "-t") == 0)
    {
    if (tmo_noerror = ((timeout = atoi(argv[++na])) < 0)) timeout = -timeout;
    }
  else if (strcmp(argv[na], "-i") == 0) initial_pause = atoi(argv[++na]);
  else if (strcmp(argv[na], "-noipv4") == 0) use_ipv4 = 0;
  else if (strcmp(argv[na], "-noipv6") == 0) use_ipv6 = 0;
  else if (strcmp(argv[na], "-oP") == 0) pidfile = argv[++na];
  else
    {
    printf("server: unknown option %s, try -h or --help\n", argv[na]);
    exit(1);
    }
  na++;
  }

if (!use_ipv4 && !use_ipv6)
  {
  printf("server: -noipv4 and -noipv6 cannot both be given\n");
  exit(1);
  }

if (na >= argc)
  {
  printf("server: no port number or socket name given\n");
  exit(1);
  }

if (argv[na][0] == '/')
  {
  sockname = argv[na];
  unlink(sockname);       /* in case left lying around */
  }
else port = atoi(argv[na]);
na++;

if (na < argc) connection_count = atoi(argv[na]);


/* Initial pause (before creating listen sockets */
if (initial_pause > 0)
  {
  if (debug)
    printf("%d: Inital pause of %d seconds\n", time(NULL), initial_pause);
  else
    printf("Inital pause of %d seconds\n", initial_pause);
  while (initial_pause > 0)
    initial_pause = sleep(initial_pause);
  }

/* Create sockets */

if (port == 0)  /* Unix domain */
  {
  if (debug) printf("%d: Creating Unix domain socket\n", time(NULL));
  listen_socket[udn] = socket(PF_UNIX, SOCK_STREAM, 0);
  if (listen_socket[udn] < 0)
    {
    printf("Unix domain socket creation failed: %s\n", strerror(errno));
    exit(1);
    }
  }
else
  {
  #if HAVE_IPV6
  if (use_ipv6)
    {
    if (debug) printf("Creating IPv6 socket\n");
    listen_socket[v6n] = socket(AF_INET6, SOCK_STREAM, 0);
    if (listen_socket[v6n] < 0)
      {
      printf("IPv6 socket creation failed: %s\n", strerror(errno));
      exit(1);
      }

    /* If this is an IPv6 wildcard socket, set IPV6_V6ONLY if that option is
    available. */

    #ifdef IPV6_V6ONLY
    if (setsockopt(listen_socket[v6n], IPPROTO_IPV6, IPV6_V6ONLY, (char *)(&on),
          sizeof(on)) < 0)
      printf("Setting IPV6_V6ONLY on IPv6 wildcard "
        "socket failed (%s): carrying on without it\n", strerror(errno));
    #endif  /* IPV6_V6ONLY */
    }
  #endif  /* HAVE_IPV6 */

  /* Create an IPv4 socket if required */

  if (use_ipv4)
    {
    if (debug) printf("Creating IPv4 socket\n");
    listen_socket[v4n] = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_socket[v4n] < 0)
      {
      printf("IPv4 socket creation failed: %s\n", strerror(errno));
      exit(1);
      }
    }
  }


/* Set SO_REUSEADDR on the IP sockets so that the program can be restarted
while a connection is being handled - this can happen as old connections lie
around for a bit while crashed processes are tidied away.  Without this, a
connection will prevent reuse of the smtp port for listening. */

for (i = v6n; i <= v4n; i++)
  {
  if (listen_socket[i] >= 0 &&
      setsockopt(listen_socket[i], SOL_SOCKET, SO_REUSEADDR, (char *)(&on),
        sizeof(on)) < 0)
    {
    printf("setting SO_REUSEADDR on socket failed: %s\n", strerror(errno));
    exit(1);
    }
  }


/* Now bind the sockets to the required port or path. If a path, ensure
anyone can write to it. */

if (port == 0)
  {
  struct stat statbuf;
  sockun.sun_family = AF_UNIX;
  if (debug) printf("Binding Unix domain socket\n");
  sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1), sockname);
  if (bind(listen_socket[udn], (struct sockaddr *)&sockun, sizeof(sockun)) < 0)
    {
    printf("Unix domain socket bind() failed: %s\n", strerror(errno));
    exit(1);
    }
  (void)stat(sockname, &statbuf);
  if (debug) printf("Setting Unix domain socket mode: %0x\n",
    statbuf.st_mode | 0777);
  if (chmod(sockname, statbuf.st_mode | 0777) < 0)
    {
    printf("Unix domain socket chmod() failed: %s\n", strerror(errno));
    exit(1);
    }
  }

else
  {
  for (i = 0; i < skn; i++)
    {
    if (listen_socket[i] < 0) continue;

    /* For an IPv6 listen, use an IPv6 socket */

    #if HAVE_IPV6
    if (i == v6n)
      {
      memset(&sin6, 0, sizeof(sin6));
      sin6.sin6_family = AF_INET6;
      sin6.sin6_port = htons(port);
      sin6.sin6_addr = anyaddr6;
      if (bind(listen_socket[i], (struct sockaddr *)&sin6, sizeof(sin6)) < 0)
        {
        printf("IPv6 socket bind() failed: %s\n", strerror(errno));
        exit(1);
        }
      }
    else
    #endif

    /* For an IPv4 bind, use an IPv4 socket, even in an IPv6 world. If an IPv4
    bind fails EADDRINUSE after IPv6 success, carry on, because it means the
    IPv6 socket will handle IPv4 connections. */

      {
      memset(&sin4, 0, sizeof(sin4));
      sin4.sin_family = AF_INET;
      sin4.sin_addr.s_addr = (S_ADDR_TYPE)INADDR_ANY;
      sin4.sin_port = htons(port);
      if (bind(listen_socket[i], (struct sockaddr *)&sin4, sizeof(sin4)) < 0)
        {
        if (listen_socket[v6n] < 0 || errno != EADDRINUSE)
          {
          printf("IPv4 socket bind() failed: %s\n", strerror(errno));
          exit(1);
          }
        else
          {
          close(listen_socket[i]);
          listen_socket[i] = -1;
          }
        }
      }
    }
  }


/* Start listening. If IPv4 fails EADDRINUSE after IPv6 succeeds, ignore the
error because it means that the IPv6 socket will handle IPv4 connections. Don't
output anything, because it will mess up the test output, which will be
different for systems that do this and those that don't. */

for (i = 0; i <= skn; i++)
  {
  if (listen_socket[i] >= 0 && listen(listen_socket[i], 5) < 0)
    {
    if (i != v4n || listen_socket[v6n] < 0 || errno != EADDRINUSE)
      {
      printf("listen() failed: %s\n", strerror(errno));
      exit(1);
      }
    }
  }


if (pidfile)
  {
  FILE * p;
  if (!(p = fopen(pidfile, "w")))
    {
    fprintf(stderr, "pidfile create failed: %s\n", strerror(errno));
    exit(1);
    }
  fprintf(p, "%ld\n", (long)getpid());
  fclose(p);
  }

/* This program handles only a fixed number of connections, in sequence. Before
waiting for the first connection, read the standard input, which contains the
script of things to do. A line containing "++++" is treated as end of file.
This is so that the Perl driving script doesn't have to close the pipe -
because that would cause it to wait for this process, which it doesn't yet want
to do. The driving script adds the "++++" automatically - it doesn't actually
appear in the test script. Within lines we interpret \xNN and \\ groups */

while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
  {
  line *next;
  char * d;
  int n = (int)strlen(CS buffer);

  if (n > 1 && buffer[0] == '>' && buffer[1] == '>')
    linebuf = 0;
  while (n > 0 && isspace(buffer[n-1])) n--;
  buffer[n] = 0;
  if (strcmp(CS buffer, "++++") == 0) break;
  next = malloc(sizeof(line) + n);
  next->next = NULL;
  d = next->line;
    {
    char * s = CS buffer;
    do
      {
      char ch;
      char cl = *s;
      if (cl == '\\' && (cl = *++s) == 'x')
	{
	if ((ch = *++s - '0') > 9 && (ch -= 'A'-'9'-1) > 15) ch -= 'a'-'A';
	if ((cl = *++s - '0') > 9 && (cl -= 'A'-'9'-1) > 15) cl -= 'a'-'A';
	cl |= ch << 4;
	}
      *d++ = cl;
      }
    while (*s++);
    }
  next->len = d - next->line - 1;
  if (last == NULL) script = last = next;
    else last->next = next;
  last = next;
  }

fclose(stdin);

/* SIGALRM handler crashes out */

signal(SIGALRM, sigalrm_handler);

/* s points to the current place in the script */

s = script;

for (count = 0; count < connection_count; count++)
  {
  alarm(timeout);
  if (port <= 0)
    {
    printf("Listening on %s ... ", sockname);
    fflush(stdout);
    accept_socket = accept(listen_socket[udn],
      (struct sockaddr *)&sockun_accepted, &sockun_len);
    }

  else
    {
    int lcount;
    int max_socket = 0;
    fd_set select_listen;

    printf("Listening on port %d ... ", port);
    fflush(stdout);

    FD_ZERO(&select_listen);
    for (i = 0; i < skn; i++)
      {
      if (listen_socket[i] >= 0) FD_SET(listen_socket[i], &select_listen);
      if (listen_socket[i] > max_socket) max_socket = listen_socket[i];
      }

    lcount = select(max_socket + 1, &select_listen, NULL, NULL, NULL);
    if (lcount < 0)
      {
      printf("Select failed\n");
      fflush(stdout);
      continue;
      }

    accept_socket = -1;
    for (i = 0; i < skn; i++)
      {
      if (listen_socket[i] > 0 && FD_ISSET(listen_socket[i], &select_listen))
        {
        accept_socket = accept(listen_socket[i],
          (struct sockaddr *)&accepted, &len);
        FD_CLR(listen_socket[i], &select_listen);
        break;
        }
      }
    }
  alarm(0);

  if (accept_socket < 0)
    {
    printf("accept() failed: %s\n", strerror(errno));
    exit(1);
    }

  out = fdopen(accept_socket, "w");

  dup_accept_socket = dup(accept_socket);

  if (port > 0)
    printf("\nConnection request from [%s]\n", host_ntoa(&accepted, CS buffer));
  else
    {
    printf("\nConnection request\n");

    /* Linux supports a feature for acquiring the peer's credentials, but it
    appears to be Linux-specific. This code is untested and unused, just
    saved here for reference. */

    /**********--------------------
    struct ucred cr;
    int cl=sizeof(cr);

    if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &cl)==0) {
      printf("Peer's pid=%d, uid=%d, gid=%d\n",
              cr.pid, cr.uid, cr.gid);
    --------------*****************/
    }

  if (dup_accept_socket < 0)
    {
    printf("Couldn't dup socket descriptor\n");
    printf("421 Connection refused: %s\n", strerror(errno));
    fprintf(out, "421 Connection refused: %s\r\n", strerror(errno));
    fclose(out);
    exit(2);
    }

  in = fdopen(dup_accept_socket, "r");

  /* Loop for handling the conversation(s). For use in SMTP sessions, there are
  default rules for determining input and output lines: the latter start with
  digits. This means that the input looks like SMTP dialog. However, this
  doesn't work for other tests (e.g. ident tests) so we have explicit '<' and
  '>' flags for input and output as well as the defaults. */

  for (; s != NULL; s = s->next)
    {
    char *ss = s->line;

    /* Output lines either start with '>' or a digit. In the '>' case we can
    fudge the sending of \r\n as required. Default is \r\n, ">>" send nothing,
    ">CR>" sends \r only, and ">LF>" sends \n only. We can also force a
    connection closedown by ">*eof". */

    if (ss[0] == '>')
      {
      char *end = "\r\n";
      unsigned len = s->len;
      printit(ss++, len--);

      if (strncmp(ss, "*eof", 4) == 0)
        {
        s = s->next;
        goto END_OFF;
        }

      if (*ss == '>')
        { end = ""; ss++; len--; }
      else if (strncmp(ss, "CR>", 3) == 0)
        { end = "\r"; ss += 3; len -= 3; }
      else if (strncmp(ss, "LF>", 3) == 0)
        { end = "\n"; ss += 3; len -= 3; }

      fwrite(ss, 1, len, out);
      if (*end) fprintf(out, end);
      }

    else if (isdigit((unsigned char)ss[0]))
      {
      printf("%s\n", ss);
      fprintf(out, "%s\r\n", ss);
      }

    /* If the script line starts with "*sleep" we just sleep for a while
    before continuing. */

    else if (strncmp(ss, "*sleep ", 7) == 0)
      {
      int sleepfor = atoi(ss+7);
      printf("%s\n", ss);
      fflush(out);
      sleep(sleepfor);
      }

    /* Otherwise the script line is the start of an input line we are expecting
    from the client, or "*eof" indicating we expect the client to close the
    connection. Read command line or data lines; the latter are indicated
    by the expected line being just ".". If the line starts with '<', that
    doesn't form part of the expected input. (This allows for incoming data
    starting with a digit.) If the line starts with '<<' we operate in
    unbuffered rather than line mode and assume that a single read gets the
    entire message. */

    else
      {
      int offset;
      int data = strcmp(ss, ".") == 0;

      if (ss[0] != '<')
	offset = 0;
      else
        {
        buffer[0] = '<';
	if (ss[1] != '<')
	  offset = 1;
	else
	  {
	  buffer[1] = '<';
	  offset = 2;
	  }
        }

      fflush(out);

      if (!linebuf)
	{
	int n;
	char c;

	alarm(timeout);
	n = read(dup_accept_socket, CS buffer+offset, s->len - offset);
	if (n == 0)
	  {
	  printf("%sxpected EOF read from client\n",
	    (strncmp(ss, "*eof", 4) == 0)? "E" : "Une");
	  s = s->next;
	  goto END_OFF;
	  }
	if (offset != 2)
	  while (read(dup_accept_socket, &c, 1) == 1 && c != '\n') ;
	alarm(0);
	n += offset;

	printit(buffer, n);

	if (data) do
	  {
	  n = (read(dup_accept_socket, &c, 1) == 1 && c == '.');
	  while (c != '\n' && read(dup_accept_socket, &c, 1) == 1)
	    ;
	  } while (!n);
	else if (memcmp(ss, buffer, n) != 0)
	  {
	  printf("Comparison failed - bailing out\nExpected: ");
	  printit(ss, n);
	  break;
	  }
	}
      else
	{
	for (;;)
	  {
	  int n;
	  alarm(timeout);
	  if (fgets(CS buffer+offset, sizeof(buffer)-offset, in) == NULL)
	    {
	    printf("%sxpected EOF read from client\n",
	      (strncmp(ss, "*eof", 4) == 0)? "E" : "Une");
	    s = s->next;
	    goto END_OFF;
	    }
	  alarm(0);
	  n = (int)strlen(CS buffer);
	  while (n > 0 && isspace(buffer[n-1])) n--;
	  buffer[n] = 0;
	  printf("%s\n", buffer);
	  if (!data || strcmp(CS buffer, ".") == 0) break;
	  }

	if (strncmp(ss, CS buffer, (int)strlen(ss)) != 0)
	  {
	  printf("Comparison failed - bailing out\n");
	  printf("Expected: %s\n", ss);
	  break;
	  }
	}
      }
    }

  END_OFF:
  fclose(in);
  fclose(out);
  }

if (s == NULL) printf("End of script\n");

if (sockname != NULL) unlink(sockname);
exit(0);
}