예제 #1
0
END_TEST
#endif

START_TEST (test_fildes_many)
{
    const char idsession[] = "zIDSESSION";
    int dummyfd, i, killed = 0;
    conn_setup();
    dummyfd = open(SCANFILE, O_RDONLY);
    fail_unless_fmt(dummyfd != -1, "failed to open %s: %s\n", SCANFILE, strerror(errno));

    fail_unless_fmt(send(sockd, idsession, sizeof(idsession), 0) == sizeof(idsession), "send IDSESSION failed\n");
    for (i=0;i<1024;i++) {
	if (sendmsg_fd(sockd, "zFILDES", sizeof("zFILDES"), dummyfd, 1) == -1) {
	    killed = 1;
	    break;
	}
    }
    close(dummyfd);
    if (send(sockd, "zEND", sizeof("zEND"), 0) == -1) {
	killed = 1;
    }
    conn_teardown();

    conn_setup();
    test_command("zPING", sizeof("zPING"), NULL, "PONG", 5);
    conn_teardown();
}
예제 #2
0
END_TEST
#endif

#define EXPECT_INSTREAM "stream: ClamAV-Test-File.UNOFFICIAL FOUND\n"
#define EXPECT_INSTREAM0 "stream: ClamAV-Test-File.UNOFFICIAL FOUND"

#define STATS_REPLY "POOLS: 1\n\nSTATE: VALID PRIMARY\n"
START_TEST (test_stats)
{
    char *recvdata;
    size_t len = strlen("nSTATS\n");
    int rc;

    conn_setup();
    rc = send(sockd, "nSTATS\n", len, 0);
    fail_unless_fmt((size_t)rc == len, "Unable to send(): %s\n", strerror(errno));

    recvdata = recvfull(sockd, &len);

    fail_unless_fmt(len > strlen(STATS_REPLY), "Reply has wrong size: %lu, minimum %lu, reply: %s\n",
		    len, strlen(STATS_REPLY), recvdata);

    if (len > strlen(STATS_REPLY))
	len = strlen(STATS_REPLY);
    rc = strncmp(recvdata, STATS_REPLY, len);

    fail_unless_fmt(rc == 0, "Wrong reply: %s\n", recvdata);
    free(recvdata);
    conn_teardown();
}
예제 #3
0
/**
 * [Client only]
 * Setup the configuration for the server this client is connecting to:
 *   - Get server host and port.
 *   - Get address of server.
 *
 * server: Of the form server_host:server_port. The server to connect to.
 *         If no port is specified, defaults to port 80.
 * returns: 0 on success, -1 otherwise.
 */
int do_config_server(char *server) { ASSERT_CLIENT_ONLY;
  /* Parse server into its hostname and port. */
  char *host, *server_port_str, *_server = server;
  int server_port;
  host = strsep(&server, ":");
  if (server == NULL) {
    fprintf(stderr, "[ERROR] No port specified for server %s\n", host);
    return -1;
  }
  server_port_str = strsep(&server, ":");
  server_port = atoi(server_port_str);
  config->sconn = calloc(sizeof(conn_t), 1);
  conn_add(config->sconn);

  /* Get IP address of server. See if this is a server on the same machine. */
  in_addr_t dst_ip = ip_from_hostname(_server);
  if (dst_ip == 0)
    return -1;
  else if (dst_ip != LOCALHOST)
    unix_socket = false;

  /* Set up connection details. */
  int port = server_port == 0 ? DEFAULT_PORT : server_port;
  conn_setup(config->sconn, dst_ip, port, unix_socket);

  return 0;
}
예제 #4
0
/**
 * [Server only]
 * Handle a new connection from a client. Set up connection details and
 * initialize sequence numbers.
 *
 * pkt: The SYN segment from the client.
 * returns: The conn_t associated with the new connection.
 */
conn_t *tcp_new_connection(char *pkt) { ASSERT_SERVER_ONLY;
  /* Ignore if too many clients are connected. */
  if (num_connected >= MAX_NUM_CLIENTS) {
    fprintf(stderr, "[ERROR] Maximum number of clients (%d) reached\n",
            MAX_NUM_CLIENTS);
    return NULL;
  }
  num_connected++;

  iphdr_t *ip_hdr = (iphdr_t *) pkt;
  tcphdr_t *syn = (tcphdr_t *) (pkt + IP_HDR_SIZE);

  /* Set up connection details and add to list of connections. */
  conn_t *conn = calloc(sizeof(conn_t), 1);
  conn_setup(conn, ntohl(ip_hdr->saddr), ntohs(syn->th_sport), unix_socket);
  conn->their_init_seqno = ntohl(syn->th_seq);
  conn->ackno = conn->their_init_seqno + 1;
  conn_add(conn);

  /* Send a SYN-ACK to the client. */
  send_synack(conn);

  /* Get window size of the client. */
  ctcp_cfg->send_window = ntohs(syn->window);
  ctcp_config_t *config_copy = calloc(sizeof(ctcp_config_t), 1);
  memcpy(config_copy, ctcp_cfg, sizeof(ctcp_config_t));

  /* Student code. */
  ctcp_state_t *state = ctcp_init(conn, config_copy);
  conn->state = state;

  fprintf(stderr, "[INFO] Client connected\n");
  return conn;
}
예제 #5
0
static void tst_fildes(const char *cmd, size_t len, int fd,
			const char *expect, size_t expect_len, int closefd, int singlemsg)
{
    char *recvdata, *p;
    int rc;

    conn_setup();
    fail_unless_fmt(sendmsg_fd(sockd, cmd, len, fd, singlemsg) != -1,
		     "Failed to sendmsg: %s\n", strerror(errno));

    if (closefd)
	close(fd);

    recvdata = recvfull(sockd, &len);
    p = strchr(recvdata, ':');

    fail_unless_fmt(!!p, "Reply doesn't contain ':' : %s\n", recvdata);
    *p++ = '\0';

    fail_unless_fmt(sscanf(recvdata, "fd[%u]", &rc) == 1, "Reply doesn't contain fd: %s\n", recvdata);

    len -= p - recvdata;
    fail_unless_fmt(len == expect_len, "Reply has wrong size: %lu, expected %lu, reply: %s, expected: %s\n",
		    len, expect_len, p, expect);

    rc = memcmp(p, expect, expect_len);
    fail_unless_fmt(!rc, "Wrong reply for command %s: |%s|, expected: |%s|\n", cmd, p, expect);
    free(recvdata);
    conn_teardown();
}
예제 #6
0
파일: axel.c 프로젝트: ghuntley/axel
/* Thread used to set up a connection					*/
void *setup_thread( void *c )
{
	conn_t *conn = c;
	int oldstate;
	
	/* Allow this thread to be killed at any time.			*/
	pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, &oldstate );
	pthread_setcanceltype( PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate );
	
	if( conn_setup( conn ) )
	{
		conn->last_transfer = gettime();
		if( conn_exec( conn ) )
		{
			conn->last_transfer = gettime();
			conn->enabled = 1;
			conn->state = 0;
			return( NULL );
		}
	}
	
	conn_disconnect( conn );
	conn->state = 0;
	return( NULL );
}
예제 #7
0
END_TEST

START_TEST (test_idsession_stress)
{
    char buf[BUFSIZ];
    size_t i;
    char *data, *p;
    size_t len;

    conn_setup();

    fail_unless_fmt(send(sockd, "zIDSESSION", sizeof("zIDSESSION"), 0) == sizeof("zIDSESSION"),
		    "send() failed: %s\n", strerror(errno));
    for (i=0;i < 1024; i++) {
	snprintf(buf, sizeof(buf), "%u", (unsigned)(i+1));
	fail_unless(send(sockd, "zVERSION", sizeof("zVERSION"), 0) == sizeof("zVERSION"),
		    "send failed: %s\n",strerror(errno));
	data = recvpartial(sockd, &len, 1);
	p = strchr(data, ':');
	fail_unless_fmt(!!p, "wrong VERSION reply (%u): %s\n", i, data);
	*p++ = '\0';
	fail_unless_fmt(*p == ' ', "wrong VERSION reply (%u): %s\n", i, p);
	*p++  = '\0';

	fail_unless_fmt(!strcmp(p, VERSION_REPLY), "wrong VERSION reply: %s\n", data);
	fail_unless_fmt(!strcmp(data, buf), "wrong IDSESSION id: %s\n", data);

	free(data);
    }

    conn_teardown();
}
예제 #8
0
static int
_conn_sync_connect(connectionObject *self)
{
    PGconn *pgconn;
    int green;

    /* store this value to prevent inconsistencies due to a change
     * in the middle of the function. */
    green = psyco_green();
    if (!green) {
        Py_BEGIN_ALLOW_THREADS;
        self->pgconn = pgconn = PQconnectdb(self->dsn);
        Py_END_ALLOW_THREADS;
        Dprintf("conn_connect: new postgresql connection at %p", pgconn);
    }
    else {
        Py_BEGIN_ALLOW_THREADS;
        self->pgconn = pgconn = PQconnectStart(self->dsn);
        Py_END_ALLOW_THREADS;
        Dprintf("conn_connect: new green postgresql connection at %p", pgconn);
    }

    if (pgconn == NULL)
    {
        Dprintf("conn_connect: PQconnectdb(%s) FAILED", self->dsn);
        PyErr_SetString(OperationalError, "PQconnectdb() failed");
        return -1;
    }
    else if (PQstatus(pgconn) == CONNECTION_BAD)
    {
        Dprintf("conn_connect: PQconnectdb(%s) returned BAD", self->dsn);
        PyErr_SetString(OperationalError, PQerrorMessage(pgconn));
        return -1;
    }

    PQsetNoticeProcessor(pgconn, conn_notice_callback, (void*)self);

    /* if the connection is green, wait to finish connection */
    if (green) {
        if (0 > pq_set_non_blocking(self, 1)) {
            return -1;
        }
        if (0 != psyco_wait(self)) {
            return -1;
        }
    }

    /* From here the connection is considered ready: with the new status,
     * poll() will use PQisBusy instead of PQconnectPoll.
     */
    self->status = CONN_STATUS_READY;

    if (conn_setup(self, self->pgconn) == -1) {
        return -1;
    }

    return 0;
}
예제 #9
0
END_TEST

START_TEST (test_compat_commands)
{
    /* test sending the command the "old way" */
    struct basic_test *test = &basic_tests[_i];
    char nsend[BUFSIZ], nreply[BUFSIZ];

    if (test->skiproot && isroot)
	return;

    if (!test->support_old) {
	snprintf(nreply, sizeof(nreply), "UNKNOWN COMMAND\n");
	test->extra = NULL;
    } else {
	snprintf(nreply, sizeof(nreply), "%s\n", test->reply);
    }
    /* one command = one packet, no delimiter */
    if (!test->extra) {
	conn_setup();
	test_command(test->command, strlen(test->command), test->extra, nreply, strlen(nreply));
	conn_teardown();
    }

    /* one packet, \n delimited command, followed by "extra" if needed */
    snprintf(nsend, sizeof(nsend), "%s\n", test->command);
    conn_setup();
    test_command(nsend, strlen(nsend), test->extra, nreply, strlen(nreply));
    conn_teardown();

    if (!test->extra) {
	/* FILDES won't support this, because it expects
	 * strlen("FILDES\n") characters, then 1 character and the FD. */
	/* one packet, \r\n delimited command, followed by "extra" if needed */
	snprintf(nsend, sizeof(nsend), "%s\r\n", test->command);
	conn_setup();
	test_command(nsend, strlen(nsend), test->extra, nreply, strlen(nreply));
	conn_teardown();
    }
}
예제 #10
0
static PyObject *
psyco_conn_reset(connectionObject *self)
{
    int res;

    EXC_IF_CONN_CLOSED(self);
    EXC_IF_CONN_ASYNC(self, reset);

    if (pq_reset(self) < 0)
        return NULL;

    res = conn_setup(self, self->pgconn);
    if (res < 0)
        return NULL;

    Py_RETURN_NONE;
}
예제 #11
0
static PyObject *
psyco_conn_reset(connectionObject *self, PyObject *args)
{
    int res;

    EXC_IF_CONN_CLOSED(self);
    EXC_IF_CONN_ASYNC(self, reset);

    if (pq_reset(self) < 0)
        return NULL;

    res = conn_setup(self, self->pgconn);
    if (res < 0)
        return NULL;

    Py_INCREF(Py_None);
    return Py_None;
}
예제 #12
0
END_TEST

START_TEST (test_stream)
{
    char buf[BUFSIZ];
    char *recvdata;
    size_t len;
    unsigned port;
    int streamsd, infd, nread;

    infd = open(SCANFILE, O_RDONLY);

    fail_unless_fmt(infd != -1, "open failed: %s\n", strerror(errno));
    conn_setup();
    fail_unless_fmt(
	send(sockd, "zSTREAM", sizeof("zSTREAM"), 0) == sizeof("zSTREAM"),
	"send failed: %s\n", strerror(errno));
    recvdata = recvpartial(sockd, &len, 1);
    fail_unless_fmt (sscanf(recvdata, "PORT %u\n", &port) == 1,
		     "Wrong stream reply: %s\n", recvdata);

    free(recvdata);
    streamsd = conn_tcp(port);

    do {
	nread = read(infd, buf, sizeof(buf));
	if (nread > 0)
	    fail_unless_fmt(send(streamsd, buf, nread, 0) == nread,
			    "send failed: %s\n", strerror(errno));
    } while (nread > 0 || (nread == -1 && errno == EINTR));
    fail_unless_fmt(nread != -1, "read failed: %s\n", strerror(errno));
    close(infd);
    close(streamsd);

    recvdata = recvfull(sockd, &len);
    fail_unless_fmt(!strcmp(recvdata,"stream: ClamAV-Test-File.UNOFFICIAL FOUND"),
		    "Wrong reply: %s\n", recvdata);
    free(recvdata);

    conn_teardown();
}
예제 #13
0
/**
 * Send resets to previous connections, if they exist. We can tell if there are
 * lots of RSTs or ACKs being sent to us.
 */
void *send_resets(void *args) {
  fprintf(stderr, "[INFO] Cleaning up old connections... ");
  char buf[MAX_PACKET_SIZE];
  memset(buf, 0, MAX_PACKET_SIZE);
  int r;

  /* See if there are leftover packets. If so, send resets to them. */
  r = recv(config->socket, buf, MAX_PACKET_SIZE, 0);
  while (r > 0) {
    handling_resets = true;

    iphdr_t *ip_hdr = (iphdr_t *) buf;
    tcphdr_t *tcp_hdr = (tcphdr_t *) (buf + IP_HDR_SIZE);
    char *rst = create_tcp_rst(ip_hdr->saddr, tcp_hdr->th_dport,
                               tcp_hdr->th_sport, tcp_hdr->th_ack);

    /* Create connection object to send resets to. */
    conn_t conn;
    memset((void *) &conn, 0, sizeof(conn_t));
    conn_setup(&conn, ip_hdr->saddr, ntohs(tcp_hdr->th_sport), false);

    int s = sendto(config->socket, rst, FULL_HDR_SIZE, 0,
                   (struct sockaddr *) &conn.saddr, sizeof(conn.saddr));
    memset(buf, 0, MAX_PACKET_SIZE);
    free(rst);

    /* Could not send resets. Give up. */
    if (s < 0)
      break;

    /* Continue checking for more packets to send resets to. */
    handling_resets = false;
    r = recv(config->socket, buf, MAX_PACKET_SIZE, 0);
  }

  handling_resets = false;
  return NULL;
}
예제 #14
0
END_TEST

START_TEST (test_fildes_unwanted)
{
    char *recvdata;
    size_t len;
    int dummyfd;
    conn_setup();
    dummyfd = open(SCANFILE, O_RDONLY);

    /* send a 'zVERSION\0' including the ancillary data.
     * The \0 is from the extra char needed when sending ancillary data */
    fail_unless_fmt(sendmsg_fd(sockd, "zIDSESSION", strlen("zIDSESSION"), dummyfd, 1) != -1,
		    "sendmsg failed: %s\n", strerror(errno));

    recvdata = recvfull(sockd, &len);

    fail_unless_fmt(!strcmp(recvdata,"1: PROTOCOL ERROR: ancillary data sent without FILDES. ERROR"),
		    "Wrong reply: %s\n", recvdata);

    free(recvdata);
    close(dummyfd);
    conn_teardown();
}
예제 #15
0
파일: axel.c 프로젝트: 3rdexp/xsandbox
void *setup_thread_cb( void *c )
#endif
{
	conn_t *conn = c;
	int oldstate;
	
	/* Allow this thread to be killed at any time.			*/
#if !WIN32
	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldstate);
#endif
	
	if (conn_setup(conn))
	{
		conn->last_transfer = gettime();
		if (conn_exec(conn))
		{
			conn->last_transfer = gettime();
			conn->enabled = 1;
			conn->state = 0;
#if WIN32
			return 0;
#else
			return NULL;
#endif
		}
	}
	
	conn_disconnect(conn);
	conn->state = 0;
#if WIN32
	return 0;
#else
	return NULL;
#endif
}
예제 #16
0
template <> void
GncDbiBackend<DbType::DBI_SQLITE>::session_begin(QofSession* session,
                                                 const char* book_id,
                                                 bool ignore_lock,
                                                 bool create, bool force)
{
    gboolean file_exists;
    PairVec options;

    g_return_if_fail (session != nullptr);
    g_return_if_fail (book_id != nullptr);

    ENTER (" ");

    /* Remove uri type if present */
    auto path = gnc_uri_get_path (book_id);
    std::string filepath{path};
    g_free(path);
    GFileTest ftest = static_cast<decltype (ftest)> (
        G_FILE_TEST_IS_REGULAR | G_FILE_TEST_EXISTS) ;
    file_exists = g_file_test (filepath.c_str(), ftest);
    if (!create && !file_exists)
    {
        set_error (ERR_FILEIO_FILE_NOT_FOUND);
        std::string msg{"Sqlite3 file "};
        set_message (msg + filepath + " not found");
        PWARN ("Sqlite3 file %s not found", filepath.c_str());
        LEAVE("Error");
	return;
    }

    if (create && !force && file_exists)
    {
        set_error (ERR_BACKEND_STORE_EXISTS);
        auto msg = "Might clobber, no force";
        PWARN ("%s", msg);
        LEAVE("Error");
	return;
    }

    connect(nullptr);
    /* dbi-sqlite3 documentation says that sqlite3 doesn't take a "host" option */
    options.push_back(std::make_pair("host", "localhost"));
    auto dirname = g_path_get_dirname (filepath.c_str());
    auto basename = g_path_get_basename (filepath.c_str());
    options.push_back(std::make_pair("dbname", basename));
    options.push_back(std::make_pair("sqlite3_dbdir", dirname));
    if (basename != nullptr) g_free (basename);
    if (dirname != nullptr) g_free (dirname);
    UriStrings uri;
    auto conn = conn_setup(options, uri);
    if (conn == nullptr)
    {
        LEAVE("Error");
        return;
    }

    auto result = dbi_conn_connect (conn);

    if (result < 0)
    {
        dbi_conn_close(conn);
        PERR ("Unable to connect to %s: %d\n", book_id, result);
        set_error (ERR_BACKEND_BAD_URL);
        LEAVE("Error");
	return;
    }

    if (!conn_test_dbi_library(conn))
    {
        if (create && !file_exists)
        {
         /* File didn't exist before, but it does now, and we don't want to
          * leave it lying around.
          */
            dbi_conn_close (conn);
            conn = nullptr;
            g_unlink (filepath.c_str());
        }
        dbi_conn_close(conn);
        LEAVE("Bad DBI Library");
        return;
    }

    try
    {
        connect(new GncDbiSqlConnection(DbType::DBI_SQLITE,
                                            this, conn, ignore_lock));
    }
    catch (std::runtime_error& err)
    {
        return;
    }

    /* We should now have a proper session set up.
     * Let's start logging */
    xaccLogSetBaseName (filepath.c_str());
    PINFO ("logpath=%s", filepath.c_str() ? filepath.c_str() : "(null)");

    LEAVE ("");
}
예제 #17
0
END_TEST

#define TIMEOUT_REPLY "TIMED OUT WAITING FOR COMMAND\n"

START_TEST (test_connections)
{
    int rc;
    int i;
    struct rlimit rlim;
    int *sock;
    int nf, maxfd=0;
    fail_unless_fmt(getrlimit(RLIMIT_NOFILE, &rlim) != -1,
		    "Failed to get RLIMIT_NOFILE: %s\n", strerror(errno));
    nf = rlim.rlim_cur - 5;
    sock = malloc(sizeof(int)*nf);

    fail_unless(!!sock, "malloc failed\n");

    for (i=0;i<nf;i++) {
	/* just open connections, and let them time out */
	conn_setup_mayfail(1);
	if (sockd == -1) {
	    nf = i;
	    break;
	}
	sock[i] = sockd;
	if (sockd > maxfd)
	    maxfd = sockd;
    }
    rc = fork();
    fail_unless(rc != -1, "fork() failed: %s\n", strerror(errno));
    if (rc == 0) {
	char dummy;
	int ret;
	fd_set rfds;
	FD_ZERO(&rfds);
	for (i=0;i<nf;i++) {
	    FD_SET(sock[i], &rfds);
	}
	while (1) {
	    ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
	    if (ret < 0)
		break;
	    for (i=0;i<nf;i++) {
		if (FD_ISSET(sock[i], &rfds)) {
		    if (recv(sock[i], &dummy, 1, 0) == 0) {
			close(sock[i]);
			FD_CLR(sock[i], &rfds);
		    }
		}
	    }
	}
	free(sock);
	exit(0);
    } else {
	for (i=0;i<nf;i++) {
	    close(sock[i]);
	}
	free(sock);
	/* now see if clamd is able to do anything else */
	for (i=0;i<10;i++) {
	    conn_setup();
	    test_command("RELOAD", sizeof("RELOAD")-1, NULL, "RELOADING\n", sizeof("RELOADING\n")-1);
	    conn_teardown();
	}
    }
}
예제 #18
0
파일: main.c 프로젝트: Zabrane/SPOCP
int
main(int argc, char **argv)
{
	int             debug = 0, conftest = 0, nodaemon = 0;
	int             i = 0;
	unsigned int    clilen;
	struct sockaddr_in cliaddr;
	struct timeval  start, end;
	char           *cnfg = DEF_CNFG;
	char		localhost[MAXNAMLEN + 1], path[MAXNAMLEN + 1];
	FILE           *pidfp;
	octet_t         oct;
	ruleset_t      *rs;

	/*
	 * Who am I running as ? 
	 */

	uname(&myname);

	/*
	 * spocp_err = 0 ;
	 */

	memset(&srv, 0, sizeof(srv_t));

	pthread_mutex_init(&(srv.mutex), NULL);
	pthread_mutex_init(&(srv.mlock), NULL);

	gethostname(localhost, MAXNAMLEN);
#ifdef HAVE_GETDOMAINNAME
	getdomainname(path, MAXNAMLEN);
#else
	{
		char *pos;
		if(pos = strstr(localhost, ".")) strncpy(path, pos+1, MAXNAMLEN);
		else strcpy(path, "");
	}
#endif

	if (0)
		printf("Domain: %s\n", path);

	srv.hostname = Strdup(localhost);

	/*
	 * truncating input strings to reasonable length
	 */
	for (i = 0; i < argc; i++)
		if (strlen(argv[i]) > 512)
			argv[i][512] = '\0';

	while ((i = getopt(argc, argv, "Dhrtf:d:")) != EOF) {
		switch (i) {

		case 'D':
			nodaemon = 1;
			break;

		case 'f':
			cnfg = Strdup(optarg);
			break;

		case 'd':
			debug = atoi(optarg);
			if (debug < 0)
				debug = 0;
			break;

		case 't':
			conftest = 1;
			break;

		case 'r':
			srv.readonly = 1;

		case 'h':
		default:
			fprintf(stderr, "Usage: %s [-t] ", argv[0]);
			fprintf(stderr, "[-f configfile] ");
			fprintf(stderr, "[-D] [-d debuglevel]\n");
			exit(0);
		}
	}

	srv.root = ruleset_new(0);

	if (srv_init(&srv, cnfg) < 0)
		exit(1);

	if (srv.port && srv.uds) {
		fprintf(stderr,
			"Sorry are not allowed to listen on both a unix domain socket and a port\n");
		exit(1);
	}

	if (srv.logfile)
		spocp_open_log(srv.logfile, debug);
	else if (debug)
		spocp_open_log(0, debug);

	if (srv.name){
		localcontext = (char *) Calloc(strlen(srv.name) + strlen("//") + 1,
				       sizeof(char));

		/* Flawfinder: ignore */
		sprintf(localcontext, "//%s", srv.name);		
	}
	else {
		localcontext = (char *) Calloc(strlen(localhost) + strlen("//") + 1,
				       sizeof(char));

		/* Flawfinder: ignore */
		sprintf(localcontext, "//%s", localhost);
	}

	/*
	 * where I put the access rules for access to this server and its
	 * rules 
	 */
	snprintf(path, MAXNAMLEN, "%s/server", localcontext);
	oct_assign(&oct, path);
	if ((rs = ruleset_create(&oct, srv.root)) == 0)
		exit(1);

	rs->db = db_new();

	/*
	 * access rules for operations 
	 */
	snprintf(path, MAXNAMLEN, "%s/operation", localcontext);
	oct_assign(&oct, path);
	if ((rs = ruleset_create(&oct, srv.root)) == 0)
		exit(1);

	rs->db = db_new();


	LOG(SPOCP_INFO) {
		traceLog(LOG_INFO, "Local context: \"%s\"", localcontext);
		traceLog(LOG_INFO, "initializing backends");
		if (srv.root->db)
			plugin_display(srv.plugin);
	}

	if (srv.plugin) {
		run_plugin_init(&srv);
	}

	if ( get_rules( &srv ) != SPOCP_SUCCESS ) 
		exit(1);

	/*ruleset_tree( srv.root, 0);*/

	/* If only testing configuration and rulefile this is as far as I go */
	if (conftest) {
		traceLog(LOG_INFO,"Configuration was OK");
		exit(0);
	}

	gettimeofday(&start, NULL);

	if (srv.port || srv.uds) {

		/*
		 * stdin and stdout will not be used from here on, close to
		 * save file descriptors 
		 */

		fclose(stdin);
		fclose(stdout);

#ifdef HAVE_SSL
		/*
		 * ---------------------------------------------------------- 
		 */
		/*
		 * build our SSL context, whether it will ever be used or not 
		 */

		/*
		 * mutex'es for openSSL to use 
		 */
		THREAD_setup();

		if (srv.certificateFile && srv.privateKey && srv.caList) {
			traceLog(LOG_INFO,"Initializing the TLS/SSL environment");
			if (!(srv.ctx = tls_init(&srv))) {
				return FALSE;
			}
		}

		/*
		 * ---------------------------------------------------------- 
		 */
#endif

#ifdef HAVE_SASL
		{
			int             r = sasl_server_init(sasl_cb, "spocp");
			if (r != SASL_OK) {
				traceLog( LOG_ERR,
				    "Unable to initialized SASL library: %s",
				     sasl_errstring(r, NULL, NULL));
				return FALSE;
			}
		}
#endif

		saci_init();
		if( nodaemon == 0 ) { 
#ifdef HAVE_DAEMON
			if (daemon(1, 1) < 0) {
				fprintf(stderr, "couldn't go daemon\n");
				exit(1);
			}
#else
			daemon_init("spocp", 0);
#endif
		}

		if (srv.pidfile) {
			/*
			 * Write the PID file. 
			 */
			pidfp = fopen(srv.pidfile, "w");

			if (pidfp == (FILE *) 0) {
				fprintf(stderr,
					"Couldn't open pidfile \"%s\"\n",
					srv.pidfile);
				exit(1);
			}
			fprintf(pidfp, "%d\n", (int) getpid());
			fclose(pidfp);
		}

		if (srv.port) {
			LOG(SPOCP_INFO) traceLog( LOG_INFO,
				"Asked to listen on port %d", srv.port);

			if ((srv.listen_fd =
			     spocp_stream_socket(srv.port)) < 0)
				exit(1);

			srv.id = (char *) Malloc(16);
			sprintf(srv.id, "spocp-%d", srv.port);

			srv.type = AF_INET;
		} else {
			LOG(SPOCP_INFO)
			    traceLog(LOG_INFO,"Asked to listen on unix domain socket");
			if ((srv.listen_fd =
			     spocp_unix_domain_socket(srv.uds)) < 0)
				exit(1);

			srv.id = (char *) Malloc(7 + strlen(srv.uds));
			/* Flawfinder: ignore */
			sprintf(srv.id, "spocp-%s", srv.uds);

			srv.type = AF_UNIX;
		}

		xsignal(SIGCHLD, sig_chld);
		xsignal(SIGPIPE, sig_pipe);
		xsignal(SIGINT, sig_int);
		xsignal(SIGTERM, sig_term);
		xsignal(SIGUSR1, sig_usr1);

		clilen = sizeof(cliaddr);

		DEBUG(SPOCP_DSRV) traceLog(LOG_DEBUG,"Creating threads");
		/*
		 * returns the pool the threads are picking work from 
		 */
		srv.work = tpool_init(srv.threads, 64, 1);

		spocp_srv_run(&srv);

	} else {
		conn_t         *conn;

		saci_init();
		DEBUG(SPOCP_DSRV) traceLog(LOG_DEBUG,"---->");

		LOG(SPOCP_INFO) traceLog(LOG_INFO,"Reading STDIN");

		/*
		 * If I want to use this I have to do init_server() first
		 * conn = spocp_open_connection( STDIN_FILENO, &srv ) ; 
		 */
		/*
		 * this is much simpler 
		 */
		conn = conn_new();
		conn_setup(conn, &srv, STDIN_FILENO, "localhost", "127.0.0.1");

		LOG(SPOCP_INFO) traceLog(LOG_INFO,"Running server");

		spocp_server((void *) conn);

		gettimeofday(&end, NULL);

		print_elapsed("query time:", start, end);

		conn_free( conn );
	}

	srv_free( &srv );
	if (cnfg != DEF_CNFG)
		Free( cnfg );

	exit(0);
}
예제 #19
0
파일: conn.c 프로젝트: FiloSottile/axel
/* Get file size and other information					*/
int conn_info( conn_t *conn )
{
	/* It's all a bit messed up.. But it works.			*/
	if( conn->proto == PROTO_FTP && !conn->proxy )
	{
		ftp_command( conn->ftp, "REST %lld", 1 );
		if( ftp_wait( conn->ftp ) / 100 == 3 ||
		    conn->ftp->status / 100 == 2 )
		{
			conn->supported = 1;
			ftp_command( conn->ftp, "REST %lld", 0 );
			ftp_wait( conn->ftp );
		}
		else
		{
			conn->supported = 0;
		}
		
		if( !ftp_cwd( conn->ftp, conn->dir ) )
			return( 0 );
		conn->size = ftp_size( conn->ftp, conn->file, MAX_REDIR );
		if( conn->size < 0 )
			conn->supported = 0;
		if( conn->size == -1 )
			return( 0 );
		else if( conn->size == -2 )
			conn->size = INT_MAX;
	}
	else
	{
		char s[MAX_STRING], *t;
		long long int i = 0;
		
		do
		{
			conn->currentbyte = 1;
			if( !conn_setup( conn ) )
				return( 0 );
			conn_exec( conn );
			conn_disconnect( conn );
			/* Code 3xx == redirect				*/
			if( conn->http->status / 100 != 3 )
				break;
			if( ( t = http_header( conn->http, "location:" ) ) == NULL )
				return( 0 );
			sscanf( t, "%1023s", s );  // Warning: truncating to MAX_STRING
			if( strstr( s, "://" ) == NULL)
			{
				sprintf( conn->http->headers, "%s%s",
					conn_url( conn ), s );
				strncpy( s, conn->http->headers, MAX_STRING );
			}
			else if( s[0] == '/' )
			{
				sprintf( conn->http->headers, "http://%s:%i%s",
					conn->host, conn->port, s );
				strncpy( s, conn->http->headers, MAX_STRING );
			}
			conn_set( conn, s );
			i ++;
		}
		while( conn->http->status / 100 == 3 && i < MAX_REDIR );
		
		if( i == MAX_REDIR )
		{
			sprintf( conn->message, _("Too many redirects.\n") );
			return( 0 );
		}
		
		conn->size = http_size( conn->http );
		if( conn->http->status == 206 && conn->size >= 0 )
		{
			conn->supported = 1;
			conn->size ++;
		}
		else if( conn->http->status == 200 || conn->http->status == 206 )
		{
			conn->supported = 0;
			conn->size = INT_MAX;
		}
		else
		{
			t = strchr( conn->message, '\n' );
			if( t == NULL )
				sprintf( conn->message, _("Unknown HTTP error.\n") );
			else
				*t = 0;
			return( 0 );
		}
	}
	
	return( 1 );
}
예제 #20
0
template <DbType Type> void
GncDbiBackend<Type>::session_begin (QofSession* session, const char* book_id,
                                    bool ignore_lock, bool create, bool force)
{
    GncDbiTestResult dbi_test_result = GNC_DBI_PASS;
    PairVec options;

    g_return_if_fail (session != nullptr);
    g_return_if_fail (book_id != nullptr);

    ENTER (" ");

    /* Split the book-id
     * Format is protocol://username:password@hostname:port/dbname
     where username, password and port are optional) */
    UriStrings uri(book_id);

    if (Type == DbType::DBI_PGSQL)
    {
        if (uri.m_portnum == 0)
            uri.m_portnum = PGSQL_DEFAULT_PORT;
        /* Postgres's SQL interface coerces identifiers to lower case, but the
         * C interface is case-sensitive. This results in a mixed-case dbname
         * being created (with a lower case name) but then dbi can't conect to
         * it. To work around this, coerce the name to lowercase first. */
        auto lcname = g_utf8_strdown (uri.dbname(), -1);
        uri.m_dbname = std::string{lcname};
        g_free(lcname);
    }
    connect(nullptr);

    auto conn = conn_setup(options, uri);
    if (conn == nullptr)
    {
        LEAVE("Error");
        return;
    }

    m_exists = true; //May be unset in the error handler.
    auto result = dbi_conn_connect (conn);
    if (result == 0)
    {
        if (Type == DbType::DBI_MYSQL)
            adjust_sql_options (conn);
        if(!conn_test_dbi_library(conn))
        {
            dbi_conn_close(conn);
            LEAVE("Error");
            return;
        }
        if (create && !force && save_may_clobber_data (conn,
                                                       uri.quote_dbname(Type)))
        {
            set_error (ERR_BACKEND_STORE_EXISTS);
            PWARN ("Databse already exists, Might clobber it.");
            dbi_conn_close(conn);
            LEAVE("Error");
            return;
        }

    }
    else
    {

        if (m_exists)
        {
            PERR ("Unable to connect to database '%s'\n", uri.dbname());
            set_error (ERR_BACKEND_SERVER_ERR);
            dbi_conn_close(conn);
            LEAVE("Error");
            return;
        }

        if (create)
        {
            if (!create_database(conn, uri.quote_dbname(Type).c_str()))
            {
                dbi_conn_close(conn);
                LEAVE("Error");
                return;
            }
            conn = conn_setup(options, uri);
            result = dbi_conn_connect (conn);
            if (result < 0)
            {
                PERR ("Unable to create database '%s'\n", uri.dbname());
                set_error (ERR_BACKEND_SERVER_ERR);
                dbi_conn_close(conn);
                LEAVE("Error");
                return;
            }
            if (Type == DbType::DBI_MYSQL)
                adjust_sql_options (conn);
            if (!conn_test_dbi_library(conn))
            {
                if (Type == DbType::DBI_PGSQL)
                    dbi_conn_select_db (conn, "template1");
                dbi_conn_queryf (conn, "DROP DATABASE %s",
                                 uri.quote_dbname(Type).c_str());
                dbi_conn_close(conn);
                return;
            }
        }
        else
        {
            set_error(ERR_BACKEND_NO_SUCH_DB);
            std::string msg{"Database "};
            set_message(msg + uri.dbname() + " not found");
        }
    }

    connect(nullptr);
    try
    {
        connect(new GncDbiSqlConnection(Type, this, conn, ignore_lock));
    }
    catch (std::runtime_error& err)
    {
        return;
    }
    /* We should now have a proper session set up.
     * Let's start logging */
    auto translog_path = gnc_build_translog_path (uri.basename().c_str());
    xaccLogSetBaseName (translog_path);
    PINFO ("logpath=%s", translog_path ? translog_path : "(null)");
    g_free (translog_path);

    LEAVE (" ");
}
예제 #21
0
파일: search.c 프로젝트: Krusca/axeldroid
int search_makelist( search_t *results, char *url )
{
	int i, size = 8192, j = 0;
	char *s, *s1, *s2, *s3;
	conn_t conn[1];
	double t;
	
	memset( conn, 0, sizeof( conn_t ) );
	
	conn->conf = results->conf;
	t = gettime();
	if( !conn_set( conn, url ) )
		return( -1 );
	if( !conn_init( conn ) )
		return( -1 );
	if( !conn_info( conn ) )
		return( -1 );
	
	strcpy( results[0].url, url );
	results[0].speed = 1 + 1000 * ( gettime() - t );
	results[0].size = conn->size;
	
	s = malloc( size );
	
	sprintf( s, "http://www.filesearching.com/cgi-bin/s?q=%s&w=a&l=en&"
		"t=f&e=on&m=%i&o=n&s1=%lld&s2=%lld&x=15&y=15",
		conn->file, results->conf->search_amount,
		conn->size, conn->size );
	
	conn_disconnect( conn );
	memset( conn, 0, sizeof( conn_t ) );
	conn->conf = results->conf;
	
	if( !conn_set( conn, s ) )
	{
		free( s );
		return( 1 );
	}
	if( !conn_setup( conn ) )
	{
		free( s );
		return( 1 );
	}
	if( !conn_exec( conn ) )
	{
		free( s );
		return( 1 );
	}
	
	while( ( i = read( conn->fd, s + j, size - j ) ) > 0 )
	{
		j += i;
		if( j + 10 >= size )
		{
			size *= 2;
			s = realloc( s, size );
			memset( s + size / 2, 0, size / 2 );
		}
	}

	conn_disconnect( conn );
	
	s1 = strstr( s, "<pre class=list" );
	s1 = strchr( s1, '\n' ) + 1;
	if( strstr( s1, "</pre>" ) == NULL )
	{
		/* Incomplete list					*/
		free( s );
		return( 1 );
	}
	for( i = 1; strncmp( s1, "</pre>", 6 ) && i < results->conf->search_amount && *s1; i ++ )
	{
		s3 = strchr( s1, '\n' ); *s3 = 0;
		s2 = strrstr( s1, "<a href=" ) + 8;
		*s3 = '\n';
		s3 = strchr( s2, ' ' ); *s3 = 0;
		if( strcmp( results[0].url, s2 ) )
		{
			strncpy( results[i].url, s2, MAX_STRING );
			results[i].size = results[0].size;
			results[i].conf = results->conf;
		}
		else
		{
			/* The original URL might show up		*/
			i --;
		}
		for( s1 = s3; *s1 != '\n'; s1 ++ );
		s1 ++;
	}
	
	free( s );
	
	return( i );
}
예제 #22
0
static int 
redir_handle_url(struct redir_t *redir, 
		 struct redir_conn_t *conn, 
		 struct redir_httpreq_t *httpreq,
		 struct redir_socket_t *socket,
		 struct sockaddr_in *peer, 
		 redir_request *req) {
  int port = 80;
  int matches = 1;
  int i = -1;
  char *p = 0;

#ifdef ENABLE_REDIRINJECT
  char hasInject = 0;
  if (conn->s_params.flags & UAM_INJECT_URL) {
    safe_strncpy((char *) req->inject_url,
		 (char *) conn->s_params.url,
		 REDIRINJECT_MAX);
    hasInject = 1;
  } else if (_options.inject && *_options.inject) { 
    safe_strncpy((char *) req->inject_url,
		 (char *) _options.inject,
		 REDIRINJECT_MAX);
    hasInject = 1;
  } else {
#endif
    for (i=0; i < MAX_REGEX_PASS_THROUGHS; i++) {
      
      if ( ! _options.regex_pass_throughs[i].inuse )
	break;
      
      /*
	if ( ! _options.regex_pass_throughs[i].regex_host[0] &&
	! _options.regex_pass_throughs[i].regex_path[0] &&
	! _options.regex_pass_throughs[i].regex_qs[0] )
	break;
      */
      
#if(_debug_)
      log_dbg("REGEX host=[%s] path=[%s] qs=[%s]",
	      _options.regex_pass_throughs[i].regex_host,
	      _options.regex_pass_throughs[i].regex_path,
	      _options.regex_pass_throughs[i].regex_qs);
      
      log_dbg("Host %s", httpreq->host);
#endif
      
      if (_options.regex_pass_throughs[i].regex_host[0]) {
	switch(check_regex(&_options.regex_pass_throughs[i].re_host, 
			   _options.regex_pass_throughs[i].regex_host, 
			   httpreq->host)) {
	case -1: return -1;  
	case 1: matches = _options.regex_pass_throughs[i].neg_host; break;
	case 0: matches = !_options.regex_pass_throughs[i].neg_host; break;
	}
      }
      
      if (matches && _options.regex_pass_throughs[i].regex_path[0]) {
	switch(check_regex(&_options.regex_pass_throughs[i].re_path, 
			   _options.regex_pass_throughs[i].regex_path, 
			   httpreq->path)) {
	case -1: return -1;  
	case 1: matches = _options.regex_pass_throughs[i].neg_path; break;
	case 0: matches = !_options.regex_pass_throughs[i].neg_path; break;
	}
      }
      
      if (matches && _options.regex_pass_throughs[i].regex_qs[0]) {
	switch(check_regex(&_options.regex_pass_throughs[i].re_qs, 
			   _options.regex_pass_throughs[i].regex_qs, 
			   httpreq->qs)) {
	case -1: return -1;  
	case 1: matches = _options.regex_pass_throughs[i].neg_qs; break;
	case 0: matches = !_options.regex_pass_throughs[i].neg_qs; break;
	}
      }
      
      if (matches) break;
    }
#ifdef ENABLE_REDIRINJECT
  }
#endif

  if (i == 0)
    matches = 0;
    
  if (matches) {
    log_dbg("Matched for Host %s", httpreq->host);
    
    req->proxy = 1;
    
#ifdef ENABLE_REDIRINJECT
    /* XXX */
    /* Check for headers we wish to filter out */
    if (hasInject) {
      bstring newhdr = bfromcstr("");
      char *hdr = (char *)req->wbuf->data;

      if (_options.inject_wispr)
	(void) inject_fmt(req, conn);
      
      while (hdr && *hdr) {
	char *p = strstr(hdr, "\r\n");
	int skip = 0;
	int l;
	
	if (p) {
	  l = (p - hdr);
	} else {
	  l = req->wbuf->slen - (hdr - (char*)req->wbuf->data);
	}
	
	if (!strncasecmp(hdr, "accept-encoding:", 16)) {
	  bcatcstr(newhdr, "Accept-Encoding: identity\r\n");
	  skip = 1;
	} else if (!strncasecmp(hdr, "connection:", 11)) {
	  bcatcstr(newhdr, "Connection: close\r\n");
	  skip = 1;
	} else if (!strncasecmp(hdr, "keep-alive:", 11)) {
	  skip = 1;
	}
	
	if (!skip)
	  bcatblk(newhdr, hdr, l);
	
	if (p) {
	  if (!skip)
	    bcatblk(newhdr, p, 2);
	  hdr = p + 2;
	} else { 
	  hdr = 0;
	}
      }
      
      if (req->wbuf->slen != newhdr->slen) {
	log_dbg("Changed HTTP Headers");
      }
      
      bassign(req->wbuf, newhdr);
      bdestroy(newhdr);
    }
    /* XXX */
#endif

    if ((p = strchr(httpreq->host, ':'))) {
      *p++ = 0;
      port = atoi(p);
    }

    if (conn_setup(&req->conn, httpreq->host, port, 
		   req->wbuf, req->dbuf)) {
      log_err(errno, "conn_setup()");
      return -1;
    }
    
    req->state |= REDIR_CONN_FD;
    net_select_addfd(&sctx, req->conn.sock, SELECT_READ);
    
    return 0;
  }
  
  return 1;
}