Exemple #1
0
void hmsg_monitor(void)
{
	int i, maxi, listenfd, clifd, nread;
	char buf[MAXLINE];
	uid_t uid;
	struct pollfd *pollfd;

	if ((pollfd = malloc(open_max() * sizeof(struct pollfd))) == NULL)
		dlog(L_ERR, "malloc error");

	/* obtain fd to listen for client requests on */
	if ((listenfd = msg_listen(MSG_PATH)) < 0)
		dlog(L_ERR, "msg_listen error");

	client_add(listenfd, 0);    /* we use [0] for listenfd */
	pollfd[0].fd = listenfd;
	pollfd[0].events = POLLIN;
	maxi = 0;

	for ( ; ; ) {
		if (poll(pollfd, maxi + 1, -1) < 0)
			dlog(L_ERR, "poll error");

		if (pollfd[0].revents & POLLIN) {
			/* accept new client request */
			if ((clifd = serv_accept(listenfd, &uid)) < 0)
				dlog(L_ERR, "serv_accept error: %d", clifd);

			i = client_add(clifd, uid);
			pollfd[i].fd = clifd;
			pollfd[i].events = POLLIN;
			if (i > maxi)
				maxi = i;
			dlog(L_INFO, "new connection: uid %d, fd %d\n", uid, clifd);
		}

		for (i = 1; i <= maxi; i++) {
			if ((clifd = client[i].fd) < 0)
				continue;
			if (pollfd[i].revents & POLLHUP) {
				goto hungup;
			} else if (pollfd[i].revents & POLLIN) {
			/* read argument buffer from client */
				if ((nread = read(clifd, buf, MAXLINE)) < 0) {
					dlog(L_ERR, "read error on fd %d\n", clifd);
				} else if (nread == 0) {
hungup:
					dlog(L_INFO, "closed: uid %d, fd %d\n",
						client[i].uid, clifd);
					client_del(clifd);  /* client has closed conn */
					pollfd[i].fd = -1;
					close(clifd);
				} else {        /* process client's request */
					msg_parse_arg(buf, nread, clifd, client[i].uid);
				}
			}
		}
	}
}
Exemple #2
0
int main(void)
{
	int s;
	int i;
	int ret;
        fd_set fds;
	struct clients cli;

	client_init(&cli);
	s = socket_setup(SOCK_PATH);
	cli.self = s;
	client_add(&cli, s);

	for (;;) {
		fds = cli.set;
		if (select(cli.max + 1, &fds, NULL, NULL, NULL) == -1) {
		    perror("select");
		    exit(1);
		}

		for (i = 0; i <= cli.max; i++) {
			if (!FD_ISSET(i, &fds))
				continue;

			if (i == cli.self) {
				client_accept(&cli, s);
				continue;
			}
			client_handle_request(&cli, i);
		}
	}

	return 0;
}
Exemple #3
0
static int loop(int type)
{
	void (*workfn) (int ci);
	void (*deadfn) (int ci);
	int rv, i;

	rv = setup_config(type);
	if (rv < 0)
		goto fail;

	rv = setup_timer();
	if (rv < 0)
		goto fail;

	rv = setup_transport();
	if (rv < 0)
		goto fail;

	rv = setup_ticket();
	if (rv < 0)
		goto fail;

	rv = setup_listener(BOOTHC_SOCK_PATH);
	if (rv < 0)
		goto fail;
	client_add(rv, process_listener, NULL);

        while (1) {
                rv = poll(pollfd, client_maxi + 1, poll_timeout);
                if (rv == -1 && errno == EINTR)
                        continue;
                if (rv < 0) {
                        log_error("poll errno %d", errno);
			goto fail;
                }

                for (i = 0; i <= client_maxi; i++) {
                        if (client[i].fd < 0)
                                continue;
                        if (pollfd[i].revents & POLLIN) {
                                workfn = client[i].workfn;
                                if (workfn)
                                        workfn(i);
                        }
                        if (pollfd[i].revents &
			    (POLLERR | POLLHUP | POLLNVAL)) {
                                deadfn = client[i].deadfn;
                                if (deadfn)
                                        deadfn(i);
                        }
                }

		process_timerlist();
	}

	return 0;

fail:
	return -1;
}
Exemple #4
0
void client_change(char *nname, int32_t id)
{
	GtkTreeIter cur_pos;
	int32_t nid = 0;
	char found = 0;
	gtk_tree_model_get_iter_first(GTK_TREE_MODEL(client_list),&cur_pos);
	do
	{
		gtk_tree_model_get(GTK_TREE_MODEL(client_list),&cur_pos,1,&nid,-1);
		if(nid == id)
		{
			found = 1;
			break;
		}
	}
	while(gtk_tree_model_iter_next(GTK_TREE_MODEL(client_list),&cur_pos));

	if(found)
	{
		gtk_list_store_set(client_list,&cur_pos,0,nname,-1);
		if(id == -1)
		{
			char msg[128] = { 0 };
			sprintf(msg,"*** You are now known as %s\n",nname);
			chat_append(msg);
		}
	}
	else
		client_add(nname,id);
}
Exemple #5
0
static int setup(int type)
{
	int rv;

	rv = setup_config(type);
	if (rv < 0)
		goto fail;

	rv = setup_timer();
	if (rv < 0)
		goto fail;

	rv = setup_transport();
	if (rv < 0)
		goto fail;

	rv = setup_ticket();
	if (rv < 0)
		goto fail;

	rv = setup_listener(BOOTHC_SOCK_PATH);
	if (rv < 0)
		goto fail;
	client_add(rv, process_listener, NULL);

	return 0;

fail:
	return -1;
}
Exemple #6
0
void loop (void)
{
	int		i, n, maxfd, maxi, listenfd, clifd, nread;
	char	buf[MAXLINE];
	uid_t	uid;
	fd_set	rset, allset;

	FD_ZERO (&allset);

	/* obtain fd to listen for client requests on */
	if ((listenfd = serv_listen (CS_OPEN)) < 0) {
		log_sys ("serv_listen error");
	}
	FD_SET (listenfd, &allset);
	maxfd = listenfd;
	maxi = -1;

	for (;;) {
		rset = allset;	/* rset gets modified each time around */
		if ((n = select (maxfd + 1, &rset, NULL, NULL, NULL)) < 0) {
			log_sys ("select error");
		}

		if (FD_ISSET (listenfd, &rset)) {
			/* accept new client request */
			if ((clifd = serv_accept (listenfd, &uid)) < 0) {
				log_sys ("serv_accept error: %d", clifd);
			}
			i = client_add (clifd, uid);
			FD_SET (clifd, &allset);
			if (clifd > maxfd) {
				maxfd = clifd;	/* max fd for select() */
			}
			if (i > maxi) {
				maxi = i;		/* max index in client[] array */
			}
			log_msg ("new connection: uid %d, fd %d", uid, clifd);
		}
		for (i = 0; i <= maxi; i++) {	/* go through client[] array */
			if ((clifd = client[i].fd) < 0) {
				continue;
			}
			if (FD_ISSET (clifd, &rset)) {
				/* read argument buffer from client */
				if ((nread = read (clifd, buf, MAXLINE)) < 0) {
					log_sys ("read error on fd %d", clifd);
				} else if (nread == 0) {
					log_msg ("closed: uid %d, fd %d",
							client[i].uid, clifd);
					client_del (clifd);	 /* client has closed cxn */
					FD_CLR (clifd, &allset);
					close (clifd);
				} else {	/* process client's request */
					request (buf, nread, clifd, client[i].uid);
				}
			}
		}
	}
}
Exemple #7
0
void
loop(void)
{
	int listenfd, clifd;
	int rval, i, nr;
	int maxi, maxfd;
	uid_t uid;
	fd_set rset, allset;
	char buf[MAXLINE];

	/* obtain fd to listen for client request on */
	if ((listenfd = serv_listen(CS_OPEN)) < 0) 
		log_sys("serv_listen error");

	FD_ZERO(&allset);
	FD_SET(listenfd, &allset);
	maxfd = listenfd;
	maxi = -1;
	
	for (;;) {
		rset = allset;              /* rset get modified each time around */
		rval = select(maxfd + 1, &rset, NULL, NULL, NULL);
		if (rval < 0) 
			log_sys("select error");

		if (FD_ISSET(listenfd, &rset)) {
			/* accept new client request */
			if ((clifd = serv_accept(listenfd, &uid)) < 0)
				log_sys("serv_accept error");
			i = client_add(clifd, uid);
			FD_SET(clifd, &allset);
			if (i > maxi)
				maxi = i;
			if (clifd > maxfd)
				maxfd = clifd;
			log_msg("new connection: uid %d, fd %d", uid, clifd);
			continue;
		}
		for (i = 0; i <= maxi; i++) {
			if (client[i].fd == -1)
				continue;
		
			if (FD_ISSET(client[i].fd, &rset)) {
				/* read argument buffer from client */
				if ((nr = read(client[i].fd, buf, MAXLINE)) < 0) {
					log_sys("read error on fd %d", clifd);
				} else if (nr == 0) {
					log_msg("closed: uid %d, fd %d",
						client[i].uid, clifd);
					client_del(client[i].fd);  /* client has closed cxn */
					FD_CLR(clifd, &allset);
					close(clifd);
				} else {  /* process client's request */
					handler_request(buf, nr, clifd, client[i].uid);
				}
			}	
		}
	}
}
Exemple #8
0
void wcb_silent(EV_P_ ev_timer *w, int tev)
{
	if (number_of_clients++ >= MAX_CLIENTS)
	{
		ev_timer_stop(EV_A_ w);
		return;
	}

	client_add();
}
static void handle_server(struct sstate *ss)
{
	int dude;
	struct sockaddr_in s_in;
	socklen_t len;

	len = sizeof(s_in);
	if ((dude = accept(ss->ss_s, (struct sockaddr*) &s_in, &len)) == -1)
		err(1, "accept()");

	client_add(ss, dude, &s_in);
}
Exemple #10
0
static void process_listener(int ci)
{
	int fd, i;

	fd = accept(client[ci].fd, NULL, NULL);
	if (fd < 0) {
		log_error("process_listener: accept error %d %d", fd, errno);
		return;
	}

	i = client_add(fd, process_connection, NULL);

	log_debug("client connection %d fd %d", i, fd);
}
Exemple #11
0
bool client_validate(RADCLIENT_LIST *clients, RADCLIENT *master, RADCLIENT *c)
{
	char buffer[128];

	/*
	 *	No virtual server defined.  Inherit the parent's
	 *	definition.
	 */
	if (master->server && !c->server) {
		c->server = talloc_typed_strdup(c, master->server);
	}

	/*
	 *	If the client network isn't global (not tied to a
	 *	virtual server), then ensure that this clients server
	 *	is the same as the enclosing networks virtual server.
	 */
	if (master->server &&
	     (strcmp(master->server, c->server) != 0)) {
		DEBUG("- Cannot add client %s: Virtual server %s is not the same as the virtual server for the network",
		      ip_ntoh(&c->ipaddr, buffer, sizeof(buffer)), c->server);

		goto error;
	}

	if (!client_add(clients, c)) {
		DEBUG("- Cannot add client %s: Internal error", ip_ntoh(&c->ipaddr, buffer, sizeof(buffer)));

		goto error;
	}

	/*
	 *	Initialize the remaining fields.
	 */
	c->dynamic = true;
	c->lifetime = master->lifetime;
	c->created = time(NULL);
	c->longname = talloc_typed_strdup(c, c->shortname);

	DEBUG("- Added client %s with shared secret %s",
	      ip_ntoh(&c->ipaddr, buffer, sizeof(buffer)),
	      c->secret);

	return true;

error:
	client_free(c);
	return false;
}
Exemple #12
0
int client_accept(struct clients *cls, int server)
{
	int i, t, ret;
	struct sockaddr_un remote;

	t = sizeof(remote);
	ret = accept(server, (struct sockaddr *)&remote, &t);
	if (ret == -1) {
		perror("accept");
		exit(1);
	}
	client_add(cls, ret);

	debugprintf("Connected %i.\n", ret);

	return ret;
}
Exemple #13
0
/** Callback function for the listening TCP socket. */
static void process_listener(int ci)
{
	int fd, i;

	fd = accept(clients[ci].fd, NULL, NULL);
	if (fd < 0) {
		log_error("process_listener: accept error for fd %d: %s (%d)",
			  clients[ci].fd, strerror(errno), errno);
		if (clients[ci].deadfn)
			clients[ci].deadfn(ci);
		return;
	}

	i = client_add(fd, clients[ci].transport, process_connection, NULL);

	log_debug("add client connection %d fd %d", i, fd);
}
static int
main_hook(TSCont contp, TSEvent event, void *edata)
{
  TSHttpTxn txnp = (TSHttpTxn)edata;

  TSDebug(PLUGIN_NAME, "Checking transaction");
  switch (event) {
  case TS_EVENT_HTTP_READ_RESPONSE_HDR:
    if (enable_agent_check(txnp)) {
      TSDebug(PLUGIN_NAME, "Adding data sink to transaction");
      client_add(txnp);
    }
    break;
  default:
    break;
  }

  TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
  return 0;
}
Exemple #15
0
static void process_tcp_listener(int ci)
{
	int fd, i, one = 1;
	socklen_t addrlen = sizeof(struct sockaddr);
	struct sockaddr addr;

	fd = accept(clients[ci].fd, &addr, &addrlen);
	if (fd < 0) {
		log_error("process_tcp_listener: accept error %d %d",
			  fd, errno);
		return;
	}
	setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&one, sizeof(one));


	i = client_add(fd, clients[ci].transport,
			process_connection, NULL);

	log_debug("client connection %d fd %d", i, fd);
}
Exemple #16
0
/*** ZE CLIENT ***/
void shell(void){

    char buffer[MAX_SIZE];
    message_t msg;

    while(1){
        memset(&buffer, '\0', sizeof(buffer) + 1);
        memset(&msg,  0, sizeof(message_t));

        printf("%s", PROMPT);   
        fgets(buffer, sizeof(buffer), stdin);
        printf("DEBUG: %s\n", buffer);
        
        /* Message Decipher */
        if(0 == strncmp(buffer, CMD_ADD, strlen(CMD_ADD))){
            client_add(buffer);
            continue;
        }else if(0 == strncmp(buffer, CMD_INBOX, strlen(CMD_INBOX))){
            client_inbox(buffer);
            continue;
        }else if(0 == strncmp(buffer, CMD_READ, strlen(CMD_READ))){
            client_read(buffer);
            continue;
        }else if(0 == strncmp(buffer, CMD_SEND, strlen(CMD_SEND))){
            client_send(buffer);
            continue;
        }else if(0 == strncmp(buffer, CMD_LIST, strlen(CMD_LIST))){
            client_list(buffer);
            continue;
        }else if(0 == strncmp(buffer, CMD_ISA, strlen(CMD_ISA))){
            client_isa(buffer);
            continue;
        }


    }
}
Exemple #17
0
void loop(void)
{
    int         i,n, maxfd,maxi, listenfd, clifd, nread;
    char        buf[MAXLENLINE];
    uid_t       uid;
    fd_set      rset, allset;

    FD_ZERO(&allset);

    if((listenfd = serv_listen(CS_OPEN)))
    {
        //log_sys("serv_listen error");
    }
    FD_SET(listenfd, &allset);
    maxfd = listenfd;
    maxi = -1;

    for ( ; ; )
    {
        rset = allset;
        if ((n=select(maxfd+1, &rset, NULL, NULL, NULL)) < 0)
        {
            //log_sys("select error");
        }

        if (FD_ISSET(listenfd, &rset))
        {
            if((clifd = serv_accept(listenfd, &uid)) < 0)
            {
                //log_sys("serv_accept error: %d", clifd);
            }
            i = client_add(clifd, uid);
            FD_SET(clifd, &allset);
            if (clifd > maxfd)
            {
                maxfd = clifd;
            }
            if (i > maxi)
            {
                maxi = i;
            }
            //log_msg("new connection: uid %d, fd %d", uid, clifd);
        }
        else
        {
            for (i = 0; i <= maxi; i++)
            {
                if ((clifd = client[i].fd) < 0)
                {
                    continue;
                }

                if (FD_ISSET(clifd, &rset))
                {
                    if ((nread = read(clifd, buf, MAXLENLINE)) < 0)
                    {
                        //log_sys("read error on fd: %d",clifd);
                    }
                    else if(nread == 0)
                    {
                        //log_msg("closed: uid %d, fd %d",client[i].uid, clifd);
                        client_del(clifd);
                        FD_CLR(clifd,&allset);
                        close(clifd);
                    }
                    else
                    {
                        handle_request(buf, nread, clifd, client[i].uid);
                    }
                }
            }
        }
    }
}
Exemple #18
0
void loop2(void)
{
    int             i, listenfd, clifd, nread;
    char            buf[MAXLENLINE];
    uid_t           uid;
    struct pollfd   *pollfd = NULL;
    int             numfd = 1;
    pollfd_wrap     *pfd_wrap;

    struct pollfd *default_pfd;
    default_pfd->fd = -1;
    default_pfd->events = POLLIN;
    default_pfd->events = 0;

    pfd_wrap->pfd   = default_pfd;
    pfd_wrap->maxfd = NALLOC;

    pollfd_init(pfd_wrap, default_pfd);

    pollfd = pfd_wrap->pfd;
    int maxfd = pfd_wrap->maxfd;

    if ((listenfd = serv_listen(CS_OPEN)) < 0)
    {
        //log_sys("serv_listen error");
    }

    client_add(listenfd, 0);
    pollfd[0].fd = listenfd;

    for (;;)
    {
        if (poll(pollfd, numfd, -1) < 0)
        {
            //log_sys("poll error");
        }

        if (pollfd[0].revents & POLLIN)
        {
            if ((clifd = serv_accept(listenfd, &uid)) < 0)
            {
                //log_sys("serv_accept error: %d", clifd);
            }
            client_add(clifd,uid);

            if (numfd == pfd_wrap->maxfd)
            {
                default_pfd->fd = -1;
                pollfd_alloc(pfd_wrap, default_pfd);
            }
            else
            {
                default_pfd->fd = clifd;
                pollfd_add(pfd_wrap, default_pfd);
            }
            pollfd = pfd_wrap->pfd;

            pollfd[numfd].fd = clifd;
            pollfd[numfd].events = POLLIN;
            pollfd[numfd].revents = 0;
            numfd++;
            //log_msg("new connection: uid %d, fd %d, uid, clifd");
        }

        for (i = 1; i < numfd; i++)
        {
            if (pollfd[i].revents & POLLHUP)
            {
                goto hungup;
            }
            else if(pollfd[i].revents & POLLIN)
            {
                if ((nread = read(pollfd[i].fd, buf, MAXLENLINE)) < 0)
                {
                    //log_sys("read error on fd %d",pollfd[i].fd);
                }
                else if(nread == 0)
                {
        hungup:
                    //log_msg("closed: fd %d", pollfd[i].fd);
                    client_del(pollfd[i].fd);
                    close(pollfd[i].fd);
                    //pack the pollfd
                    //TODO there is a drawback, if you allocate
                    //many pollfds, it cannot be released if you
                    //needn't them;
                    if (i < (numfd-1))
                    {
                        pollfd[i].fd = pollfd[numfd-1].fd;
                        pollfd[i].events = pollfd[numfd-1].events;
                        pollfd[i].revents = pollfd[numfd-1].revents;
                        i--;
                    }
                    numfd--;
                }
                else
                {
                    handle_request(buf, nread, pollfd[i].fd,client[i].uid);
                }
            }
        }
    }
}
/** Load clients from LDAP on server start
 *
 * @param[in] inst rlm_ldap configuration.
 * @param[in] cs to load client attribute/LDAP attribute mappings from.
 * @return -1 on error else 0.
 */
int rlm_ldap_client_load(ldap_instance_t const *inst, CONF_SECTION *cs)
{
	int 		ret = 0;
	ldap_rcode_t	status;
	ldap_handle_t	*conn = NULL;

	char const	**attrs = NULL;

	CONF_PAIR	*cp;
	int		count = 0, idx = 0;

	LDAPMessage	*result = NULL;
	LDAPMessage	*entry;
	char		*dn = NULL;

	RADCLIENT	*c;

	LDAP_DBG("Loading dynamic clients");

	rad_assert(inst->clientobj_base_dn);

	if (!inst->clientobj_filter) {
		LDAP_ERR("Told to load clients but 'client.filter' not specified");

		return -1;
	}

	count = cf_pair_count(cs);
	count++;

	/*
	 *	Create an array of LDAP attributes to feed to rlm_ldap_search.
	 */
	attrs = talloc_array(inst, char const *, count);
	if (rlm_ldap_client_get_attrs(attrs, &idx, cs) < 0) return -1;

	conn = rlm_ldap_get_socket(inst, NULL);
	if (!conn) return -1;

	/*
	 *	Perform all searches as the admin user.
	 */
	if (conn->rebound) {
		status = rlm_ldap_bind(inst, NULL, &conn, inst->admin_dn, inst->password, true);
		if (status != LDAP_PROC_SUCCESS) {
			ret = -1;
			goto finish;
		}

		rad_assert(conn);

		conn->rebound = false;
	}

	status = rlm_ldap_search(inst, NULL, &conn, inst->clientobj_base_dn, inst->clientobj_scope,
				 inst->clientobj_filter, attrs, &result);
	switch (status) {
	case LDAP_PROC_SUCCESS:
		break;

	case LDAP_PROC_NO_RESULT:
		LDAP_INFO("No clients were found in the directory");
		ret = 0;
		goto finish;

	default:
		ret = -1;
		goto finish;
	}

	rad_assert(conn);
	entry = ldap_first_entry(conn->handle, result);
	if (!entry) {
		int ldap_errno;

		ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE, &ldap_errno);
		LDAP_ERR("Failed retrieving entry: %s", ldap_err2string(ldap_errno));

		ret = -1;
		goto finish;
	}

	do {
		CONF_SECTION *cc;
		char *id;

		char **value;

		id = dn = ldap_get_dn(conn->handle, entry);
		cp = cf_pair_find(cs, "identifier");
		if (cp) {
			value = ldap_get_values(conn->handle, entry, cf_pair_value(cp));
			if (value) id = value[0];
		}

		/*
		 *	Iterate over mapping sections
		 */
		cc = cf_section_alloc(NULL, "client", id);
		if (rlm_ldap_client_map_section(inst, cc, cs, conn, entry) < 0) {
			talloc_free(cc);
			ret = -1;
			goto finish;
		}

		/*
		 *@todo these should be parented from something
		 */
		c = client_afrom_cs(NULL, cc, false);
		if (!c) {
			talloc_free(cc);
			ret = -1;
			goto finish;
		}

		/*
		 *	Client parents the CONF_SECTION which defined it
		 */
		talloc_steal(c, cc);

		if (!client_add(NULL, c)) {
			LDAP_ERR("Failed to add client \"%s\", possible duplicate?", dn);
			ret = -1;
			client_free(c);
			goto finish;
		}

		LDAP_DBG("Client \"%s\" added", dn);

		ldap_memfree(dn);
		dn = NULL;
	} while ((entry = ldap_next_entry(conn->handle, entry)));

finish:
	talloc_free(attrs);
	if (dn) ldap_memfree(dn);
	if (result) ldap_msgfree(result);

	rlm_ldap_release_socket(inst, conn);

	return ret;
}
/** Load client entries from Couchbase client documents on startup
 *
 * This function executes the view defined in the module configuration and loops
 * through all returned rows.  The view is called with "stale=false" to ensure the
 * most accurate data available when the view is called.  This will force an index
 * rebuild on this design document in Couchbase.  However, since this function is only
 * run once at sever startup this should not be a concern.
 *
 * @param  inst The module instance.
 * @param  cs   The client attribute configuration section.
 * @return      Returns 0 on success, -1 on error.
 */
int mod_load_client_documents(rlm_couchbase_t *inst, CONF_SECTION *cs)
{
	void *handle = NULL;                   /* connection pool handle */
	char vpath[256], docid[MAX_KEY_SIZE];  /* view path and document id */
	char error[512];                       /* view error return */
	int idx = 0;                           /* row array index counter */
	int retval = 0;                        /* return value */
	lcb_error_t cb_error = LCB_SUCCESS;    /* couchbase error holder */
	json_object *json, *jval;              /* json object holders */
	json_object *jrows = NULL;             /* json object to hold view rows */
	CONF_SECTION *client;                  /* freeradius config section */
	RADCLIENT *c;                          /* freeradius client */

	/* get handle */
	handle = fr_connection_get(inst->pool);

	/* check handle */
	if (!handle) return -1;

	/* set handle pointer */
	rlm_couchbase_handle_t *handle_t = handle;

	/* set couchbase instance */
	lcb_t cb_inst = handle_t->handle;

	/* set cookie */
	cookie_t *cookie = handle_t->cookie;

	/* check cookie */
	if (cookie) {
		/* clear cookie */
		memset(cookie, 0, sizeof(cookie_t));
	} else {
		/* log error */
		ERROR("rlm_couchbase: cookie not usable - possibly not allocated");
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* build view path */
	snprintf(vpath, sizeof(vpath), "%s?stale=false", inst->client_view);

	/* init cookie error status */
	cookie->jerr = json_tokener_success;

	/* setup cookie tokener */
	cookie->jtok = json_tokener_new();

	/* query view for document */
	cb_error = couchbase_query_view(cb_inst, cookie, vpath, NULL);

	/* free json token */
	json_tokener_free(cookie->jtok);

	/* check error */
	if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success) {
		/* log error */
		ERROR("rlm_couchbase: failed to execute view request or parse return");
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* debugging */
	DEBUG("rlm_couchbase: cookie->jobj == %s", json_object_to_json_string(cookie->jobj));

	/* check cookie */
	if (!cookie->jobj) {
		/* log error */
		ERROR("rlm_couchbase: failed to fetch view");
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* check for error in json object */
	if (json_object_object_get_ex(cookie->jobj, "error", &json)) {
		/* build initial error buffer */
		strlcpy(error, json_object_get_string(json), sizeof(error));
		/* get error reason */
		if (json_object_object_get_ex(cookie->jobj, "reason", &json)) {
			/* append divider */
			strlcat(error, " - ", sizeof(error));
			/* append reason */
			strlcat(error, json_object_get_string(json), sizeof(error));
		}
		/* log error */
		ERROR("rlm_couchbase: view request failed with error: %s", error);
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* check for document id in return */
	if (!json_object_object_get_ex(cookie->jobj, "rows", &json)) {
		/* log error */
		ERROR("rlm_couchbase: failed to fetch rows from view payload");
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* get and hold rows */
	jrows = json_object_get(json);

	/* free cookie object */
	json_object_put(cookie->jobj);

	/* debugging */
	DEBUG("rlm_couchbase: jrows == %s", json_object_to_json_string(jrows));

	/* check for valid row value */
	if (!json_object_is_type(jrows, json_type_array) && json_object_array_length(jrows) < 1) {
		/* log error */
		ERROR("rlm_couchbase: couldn't find valid rows in view return");
		/* set return */
		retval = -1;
		/* return */
		goto free_and_return;
	}

	/* loop across all row elements */
	for (idx = 0; idx < json_object_array_length(jrows); idx++) {
		/* fetch current index */
		json = json_object_array_get_idx(jrows, idx);

		/* get document id */
		if (json_object_object_get_ex(json, "id", &jval)) {
			/* clear docid */
			memset(docid, 0, sizeof(docid));
			/* copy and check length */
			if (strlcpy(docid, json_object_get_string(jval), sizeof(docid)) >= sizeof(docid)) {
				ERROR("rlm_couchbase: document id from row longer than MAX_KEY_SIZE (%d)", MAX_KEY_SIZE);
				continue;
			}
		}

		/* check for valid doc id */
		if (docid[0] == 0) {
			WARN("rlm_couchbase: failed to fetch document id from row - skipping");
			continue;
		}

		/* debugging */
		DEBUG("rlm_couchbase: preparing to fetch docid '%s'", docid);

		/* reset  cookie error status */
		cookie->jerr = json_tokener_success;

		/* fetch document */
		cb_error = couchbase_get_key(cb_inst, cookie, docid);

		/* check error */
		if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success) {
			/* log error */
			ERROR("rlm_couchbase: failed to execute get request or parse return");
			/* set return */
			retval = -1;
			/* return */
			goto free_and_return;
		}

		/* debugging */
		DEBUG("rlm_couchbase: cookie->jobj == %s", json_object_to_json_string(cookie->jobj));

		/* allocate conf section */
		client = cf_section_alloc(NULL, "client", docid);

		if (_mod_client_map_section(client, cs, cookie->jobj, docid) != 0) {
			/* free config setion */
			talloc_free(client);
			/* set return */
			retval = -1;
			/* return */
			goto free_and_return;
		}

		/*
		 * @todo These should be parented from something.
		 */
		c = client_afrom_cs(NULL, client, false);
		if (!c) {
			ERROR("rlm_couchbase: failed to allocate client");
			/* free config setion */
			talloc_free(client);
			/* set return */
			retval = -1;
			/* return */
			goto free_and_return;
		}

		/*
		 * Client parents the CONF_SECTION which defined it.
		 */
		talloc_steal(c, client);

		/* attempt to add client */
		if (!client_add(NULL, c)) {
			ERROR("rlm_couchbase: failed to add client from %s, possible duplicate?", docid);
			/* free client */
			client_free(c);
			/* set return */
			retval = -1;
			/* return */
			goto free_and_return;
		}

		/* debugging */
		DEBUG("rlm_couchbase: client '%s' added", c->longname);

		/* free json object */
		json_object_put(cookie->jobj);
	}

	free_and_return:

	/* free json object */
	if (cookie->jobj) {
		json_object_put(cookie->jobj);
	}

	/* free rows */
	if (jrows) {
		json_object_put(jrows);
	}

	/* release handle */
	if (handle) {
		fr_connection_release(inst->pool, handle);
	}

	/* return */
	return retval;
}
Exemple #21
0
static int generate_sql_clients(rlm_sql_t *inst)
{
	rlm_sql_handle_t *handle;
	rlm_sql_row_t row;
	char querystr[MAX_QUERY_LEN];
	RADCLIENT *c;
	char *prefix_ptr = NULL;
	unsigned int i = 0;
	int numf = 0;

	DEBUG("rlm_sql (%s): Processing generate_sql_clients",
	      inst->config->xlat_name);

	/* NAS query isn't xlat'ed */
	strlcpy(querystr, inst->config->nas_query, sizeof(querystr));
	DEBUG("rlm_sql (%s) in generate_sql_clients: query is %s",
	      inst->config->xlat_name, querystr);

	handle = sql_get_socket(inst);
	if (handle == NULL)
		return -1;
	if (rlm_sql_select_query(&handle,inst,querystr)){
		return -1;
	}

	while(rlm_sql_fetch_row(&handle, inst) == 0) {
		i++;
		row = handle->row;
		if (row == NULL)
			break;
		/*
		 *  The return data for each row MUST be in the following order:
		 *
		 *  0. Row ID (currently unused)
		 *  1. Name (or IP address)
		 *  2. Shortname
		 *  3. Type
		 *  4. Secret
		 *  5. Virtual Server (optional)
		 */
		if (!row[0]){
			radlog(L_ERR, "rlm_sql (%s): No row id found on pass %d",inst->config->xlat_name,i);
			continue;
		}
		if (!row[1]){
			radlog(L_ERR, "rlm_sql (%s): No nasname found for row %s",inst->config->xlat_name,row[0]);
			continue;
		}
		if (!row[2]){
			radlog(L_ERR, "rlm_sql (%s): No short name found for row %s",inst->config->xlat_name,row[0]);
			continue;
		}
		if (!row[4]){
			radlog(L_ERR, "rlm_sql (%s): No secret found for row %s",inst->config->xlat_name,row[0]);
			continue;
		}

		DEBUG("rlm_sql (%s): Read entry nasname=%s,shortname=%s,secret=%s",inst->config->xlat_name,
			row[1],row[2],row[4]);

		c = talloc_zero(inst, RADCLIENT);

#ifdef WITH_DYNAMIC_CLIENTS
		c->dynamic = 1;
#endif

		/*
		 *	Look for prefixes
		 */
		c->prefix = -1;
		prefix_ptr = strchr(row[1], '/');
		if (prefix_ptr) {
			c->prefix = atoi(prefix_ptr + 1);
			if ((c->prefix < 0) || (c->prefix > 128)) {
				radlog(L_ERR, "rlm_sql (%s): Invalid Prefix value '%s' for IP.",
				       inst->config->xlat_name, prefix_ptr + 1);
				talloc_free(c);
				continue;
			}
			/* Replace '/' with '\0' */
			*prefix_ptr = '\0';
		}

		/*
		 *	Always get the numeric representation of IP
		 */
		if (ip_hton(row[1], AF_UNSPEC, &c->ipaddr) < 0) {
			radlog(L_ERR, "rlm_sql (%s): Failed to look up hostname %s: %s",
			       inst->config->xlat_name,
			       row[1], fr_strerror());
			talloc_free(c);
			continue;
		} else {
			char buffer[256];
			ip_ntoh(&c->ipaddr, buffer, sizeof(buffer));
			c->longname = talloc_strdup(c, buffer);
		}

		if (c->prefix < 0) switch (c->ipaddr.af) {
		case AF_INET:
			c->prefix = 32;
			break;
		case AF_INET6:
			c->prefix = 128;
			break;
		default:
			break;
		}

		/*
		 *	Other values (secret, shortname, nastype, virtual_server)
		 */
		c->secret = talloc_strdup(c, row[4]);
		c->shortname = talloc_strdup(c, row[2]);
		if(row[3] != NULL)
			c->nastype = strdup(row[3]);

		numf = (inst->module->sql_num_fields)(handle, inst->config);
		if ((numf > 5) && (row[5] != NULL) && *row[5]) c->server = strdup(row[5]);

		DEBUG("rlm_sql (%s): Adding client %s (%s, server=%s) to clients list",
		      inst->config->xlat_name,
		      c->longname,c->shortname, c->server ? c->server : "<none>");
		if (!client_add(NULL, c)) {
			sql_release_socket(inst, handle);
			DEBUG("rlm_sql (%s): Failed to add client %s (%s) to clients list.  Maybe there's a duplicate?",
			      inst->config->xlat_name,
			      c->longname,c->shortname);
			client_free(c);
			return -1;
		}
	}
	(inst->module->sql_finish_select_query)(handle, inst->config);
	sql_release_socket(inst, handle);

	return 0;
}
Exemple #22
0
static int loop(int fd)
{
	void (*workfn) (int ci);
	void (*deadfn) (int ci);
	int rv, i;

	rv = setup_transport();
	if (rv < 0)
		goto fail;

	rv = setup_ticket();
	if (rv < 0)
		goto fail;


	client_add(local->tcp_fd, booth_transport + TCP,
			process_listener, NULL);


	rv = write_daemon_state(fd, BOOTHD_STARTED);
	if (rv != 0) {
		log_error("write daemon state %d to lockfile error %s: %s",
                      BOOTHD_STARTED, cl.lockfile, strerror(errno));
		goto fail;
	}

	log_info("BOOTH %s daemon started, node id is 0x%08X (%d).",
		type_to_string(local->type),
			local->site_id, local->site_id);

	while (1) {
		rv = poll(pollfds, client_maxi + 1, poll_timeout);
		if (rv == -1 && errno == EINTR)
			continue;
		if (rv < 0) {
			log_error("poll failed: %s (%d)", strerror(errno), errno);
			goto fail;
		}

		for (i = 0; i <= client_maxi; i++) {
			if (clients[i].fd < 0)
				continue;

			if (pollfds[i].revents & POLLIN) {
				workfn = clients[i].workfn;
				if (workfn)
					workfn(i);
			}
			if (pollfds[i].revents &
					(POLLERR | POLLHUP | POLLNVAL)) {
				deadfn = clients[i].deadfn;
				if (deadfn)
					deadfn(i);
			}
		}

		process_tickets();
	}

	return 0;

fail:
	return -1;
}
Exemple #23
0
RADCLIENT_LIST *client_list_parse_section(CONF_SECTION *section, UNUSED bool tls_required)
#endif
{
	bool		global = false, in_server = false;
	CONF_SECTION	*cs;
	RADCLIENT	*c;
	RADCLIENT_LIST	*clients;

	/*
	 *	Be forgiving.  If there's already a clients, return
	 *	it.  Otherwise create a new one.
	 */
	clients = cf_data_find(section, "clients");
	if (clients) return clients;

	clients = client_list_init(section);
	if (!clients) return NULL;

	if (cf_top_section(section) == section) global = true;

	if (strcmp("server", cf_section_name1(section)) == 0) in_server = true;

	/*
	 *	Associate the clients structure with the section.
	 */
	if (cf_data_add(section, "clients", clients, NULL) < 0) {
		cf_log_err_cs(section,
			   "Failed to associate clients with section %s",
		       cf_section_name1(section));
		client_list_free(clients);
		return NULL;
	}

	for (cs = cf_subsection_find_next(section, NULL, "client");
	     cs != NULL;
	     cs = cf_subsection_find_next(section, cs, "client")) {
		c = client_afrom_cs(cs, cs, in_server, false);
		if (!c) {
			return NULL;
		}

#ifdef WITH_TLS
		/*
		 *	TLS clients CANNOT use non-TLS listeners.
		 *	non-TLS clients CANNOT use TLS listeners.
		 */
		if (tls_required != c->tls_required) {
			cf_log_err_cs(cs, "Client does not have the same TLS configuration as the listener");
			client_free(c);
			client_list_free(clients);
			return NULL;
		}
#endif

		/*
		 *	FIXME: Add the client as data via cf_data_add,
		 *	for migration issues.
		 */

#ifdef WITH_DYNAMIC_CLIENTS
#ifdef HAVE_DIRENT_H
		if (c->client_server) {
			char const *value;
			CONF_PAIR *cp;
			DIR		*dir;
			struct dirent	*dp;
			struct stat stat_buf;
			char buf2[2048];

			/*
			 *	Find the directory where individual
			 *	client definitions are stored.
			 */
			cp = cf_pair_find(cs, "directory");
			if (!cp) goto add_client;

			value = cf_pair_value(cp);
			if (!value) {
				cf_log_err_cs(cs,
					   "The \"directory\" entry must not be empty");
				client_free(c);
				return NULL;
			}

			DEBUG("including dynamic clients in %s", value);

			dir = opendir(value);
			if (!dir) {
				cf_log_err_cs(cs, "Error reading directory %s: %s", value, fr_syserror(errno));
				client_free(c);
				return NULL;
			}

			/*
			 *	Read the directory, ignoring "." files.
			 */
			while ((dp = readdir(dir)) != NULL) {
				char const *p;
				RADCLIENT *dc;

				if (dp->d_name[0] == '.') continue;

				/*
				 *	Check for valid characters
				 */
				for (p = dp->d_name; *p != '\0'; p++) {
					if (isalpha((int)*p) ||
					    isdigit((int)*p) ||
					    (*p == ':') ||
					    (*p == '.')) continue;
						break;
				}
				if (*p != '\0') continue;

				snprintf(buf2, sizeof(buf2), "%s/%s",
					 value, dp->d_name);

				if ((stat(buf2, &stat_buf) != 0) ||
				    S_ISDIR(stat_buf.st_mode)) continue;

				dc = client_read(buf2, in_server, true);
				if (!dc) {
					cf_log_err_cs(cs,
						   "Failed reading client file \"%s\"", buf2);
					client_free(c);
					closedir(dir);
					return NULL;
				}

				/*
				 *	Validate, and add to the list.
				 */
				if (!client_add_dynamic(clients, c, dc)) {

					client_free(c);
					closedir(dir);
					return NULL;
				}
			} /* loop over the directory */
			closedir(dir);
		}
#endif /* HAVE_DIRENT_H */

	add_client:
#endif /* WITH_DYNAMIC_CLIENTS */
		if (!client_add(clients, c)) {
			cf_log_err_cs(cs,
				   "Failed to add client %s",
				   cf_section_name2(cs));
			client_free(c);
			return NULL;
		}

	}

	/*
	 *	Replace the global list of clients with the new one.
	 *	The old one is still referenced from the original
	 *	configuration, and will be freed when that is freed.
	 */
	if (global) {
		root_clients = clients;
	}

	return clients;
}
Exemple #24
0
 /** Load clients from LDAP on server start
  *
  * @param[in] inst rlm_ldap configuration.
  * @return -1 on error else 0.
  */
int rlm_ldap_load_clients(ldap_instance_t const *inst)
{
	int 			ret = 0;
	ldap_rcode_t		status;
	ldap_handle_t		*conn = NULL;
	
	/* This needs to be updated if additional attributes need to be retrieved */
	char const		*attrs[7];
	char const		**attrs_p;
	
	LDAPMessage		*result = NULL;
	LDAPMessage		*entry;
	
	RADCLIENT		*c;

	LDAP_DBG("Loading dynamic clients");

	/*
	 *	Basic sanity checks.
	 */
	if (!inst->clientobj_identifier) {
		LDAP_ERR("Told to load clients but 'client.identifier_attribute' not specified");
	
		return -1;
	}
	
	if (!inst->clientobj_secret) {
		LDAP_ERR("Told to load clients but 'client.secret_attribute' not specified");
		
		return -1;
	}
	
	if (!inst->clientobj_base_dn) {
		LDAP_ERR("Told to load clients but 'client.base_dn' not specified");
		
		return -1;
	}
	
	if (!inst->clientobj_filter) {
		LDAP_ERR("Told to load clients but 'client.filter' not specified");
		
		return -1;
	}

	/*
	 *	Construct the attribute array
	 */
	attrs[0] = inst->clientobj_identifier;
	attrs[1] = inst->clientobj_secret;
	attrs_p  = attrs + 2;
	
	if (inst->clientobj_shortname) { /* 2 */
		*attrs_p++ = inst->clientobj_shortname;
	}
	
	if (inst->clientobj_type) { /* 3 */
		*attrs_p++ = inst->clientobj_type;
	}
	
	if (inst->clientobj_server) { /* 4 */
		*attrs_p++ = inst->clientobj_server;
	}
	
	if (inst->clientobj_require_ma) { /* 5 */
		*attrs_p++ = inst->clientobj_require_ma;
	}
	
	*attrs_p = NULL;	/* 6 - array needs to be NULL terminated */

	conn = rlm_ldap_get_socket(inst, NULL);
	if (!conn) return -1;
	
	/*
	 *	Perform all searches as the admin user.
	 */
	if (conn->rebound) {
		status = rlm_ldap_bind(inst, NULL, &conn, inst->admin_dn, inst->password, true);
		if (status != LDAP_PROC_SUCCESS) {
			return -1;
		}

		rad_assert(conn);
		
		conn->rebound = false;
	}

	status = rlm_ldap_search(inst, NULL, &conn, inst->clientobj_base_dn, inst->clientobj_scope,
				 inst->clientobj_filter, attrs, &result);
	switch (status) {
		case LDAP_PROC_SUCCESS:
			break;
		case LDAP_PROC_NO_RESULT:
			LDAP_INFO("No clients were found in the directory");
			return 0;
		default:
			return -1;
	}
	
	rad_assert(conn);

	entry = ldap_first_entry(conn->handle, result);
	if (!entry) {
		int ldap_errno;
		
		ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE, &ldap_errno);
		LDAP_ERR("Failed retrieving entry: %s", ldap_err2string(ldap_errno));
		
		ret = -1;	 
		goto finish;
	}
	
	do {
		char *dn;
		char **identifier	= NULL;
		char **shortname 	= NULL;
		char **secret		= NULL;
		char **type		= NULL;
		char **server		= NULL;
		char **require_ma	= NULL;
		
		dn = ldap_get_dn(conn->handle, entry);
		
		/*
		 *	Check for the required attributes first
		 */
		identifier = ldap_get_values(conn->handle, entry, inst->clientobj_identifier);
		if (!identifier) {
			LDAP_WARN("Client \"%s\" missing required attribute 'identifier', skipping...", dn);
			goto next;
		}
		
		secret = ldap_get_values(conn->handle, entry, inst->clientobj_secret);
		if (!secret) {
			LDAP_WARN("Client \"%s\" missing required attribute 'secret', skipping...", dn);
			goto next;
		}
		
		if (inst->clientobj_shortname) {
			shortname = ldap_get_values(conn->handle, entry, inst->clientobj_shortname);
			if (!shortname) {
				LDAP_DBG("Client \"%s\" missing optional attribute 'shortname'", dn);
			}
		}
		
		if (inst->clientobj_type) {
			type = ldap_get_values(conn->handle, entry, inst->clientobj_type);
			if (!type) {
				LDAP_DBG("Client \"%s\" missing optional attribute 'type'", dn);
			}
		}
		
		if (inst->clientobj_server) {
			server = ldap_get_values(conn->handle, entry, inst->clientobj_server);
			if (!server) {
				LDAP_DBG("Client \"%s\" missing optional attribute 'server'", dn);
			}
		}
		
		if (inst->clientobj_require_ma) {
			require_ma = ldap_get_values(conn->handle, entry, inst->clientobj_require_ma);
			if (!require_ma) {
				LDAP_DBG("Client \"%s\" missing optional attribute 'require_ma'", dn);
			}
		}
		
		/* FIXME: We should really pass a proper ctx */
		c = client_from_query(NULL,
				      identifier[0],
				      secret[0],
				      shortname ? shortname[0] : NULL,
				      type ? type[0] : NULL,
				      server ? server[0] : NULL,
				      require_ma ? strncmp(require_ma[0], "true", 4) == 0 : false);
		if (!c) {
			goto next;
		}
		
		if (!client_add(NULL, c)) {
			WARN("Failed to add client, possible duplicate?");

			client_free(c);
			goto next;
		}
		
		LDAP_DBG("Client \"%s\" added", dn);
		
		next:
		ldap_memfree(dn);
		if (identifier)	ldap_value_free(identifier);
		if (shortname)	ldap_value_free(shortname);
		if (secret)	ldap_value_free(secret);
		if (type)	ldap_value_free(type);
		if (server)	ldap_value_free(server);
	} while((entry = ldap_next_entry(conn->handle, entry)));
	
	finish:
	if (result) {
		ldap_msgfree(result);
	}

	return ret;
}
void *server_thread(void *par) {
   if (opt.debug_log) {
      _log("[Notice] server_thread: Starting...");
   }
   pthread_t th;
   char *c = NULL, *p = NULL, *v = NULL;

   int gsin_len;
   unsigned int i, r, b, max;
   unsigned long mode = 1;
   int error = 0;
   struct pollfd fds;

   SOCKET gsock, ssock;
   struct sockaddr_in gsin, ssin;
   memset(&ssin, 0, sizeof (ssin));
   ssin.sin_family = AF_INET;
   ssin.sin_port = htons(opt.server_port);
   ssin.sin_addr.s_addr = INADDR_ANY;



   if ((ssock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
      _log("[Error] server_thread: socket()");
      close(ssock);
      return 0;
   }

   int optval = 1;
   setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, (char *) &optval, sizeof (int));

   if (bind(ssock, (struct sockaddr*) & ssin, sizeof (ssin)) == SOCKET_ERROR) {
      _log("[Error] server_thread: bind()");
      close(ssock);
      return 0;
   }

   if (listen(ssock, SOMAXCONN) == SOCKET_ERROR) {
      _log("[Error] server_thread: listen()");
      close(ssock);
      return 0;
   }

   if (ioctl(ssock, FIONBIO, &mode) == SOCKET_ERROR) {
      _log("[Error] server_thread: ioctlsocket()");
      close(ssock);
      return 0;
   }

   if (opt.debug_log) {
      _log("[Notice] server_thread: New connection request");
   }

   fds.fd = ssock;
   fds.events = POLLIN;

   //	CONNECTION con={0};
   for (;;) {
      for (;;) {

         error = mypoll(&fds, 1, 2000);

         if (error >= 1) break;
         if (error == 0) continue;
         if (errno != EAGAIN && errno != EINTR) {
            //sprintf((char *)buf, "poll(): %s/%d", strerror(errno), errno);
            //if(!srv.silent)(*srv.logfunc)(&defparam, buf);
            break;
         }
         continue;
      }

      if (error < 0)
         break;

      gsin_len = sizeof (gsin);

      if ((gsock = accept(ssock, (struct sockaddr*) & gsin, (socklen_t*) & gsin_len)) == INVALID_SOCKET)
         continue;
      else {
         struct sockaddr_in adr;
         int len = sizeof (struct sockaddr);
         getpeername(gsock, (struct sockaddr*) & adr, (socklen_t*) & len);
         unsigned long u = adr.sin_addr.s_addr;

         if (opt.debug_log) {
            _log("[Notice] server_thread: Connection from %d.%d.%d.%d(%u), SOCKET: %u",
                    (u) & 0x000000ff,
                    (u >> 8) & 0x000000ff,
                    (u >> 16) & 0x000000ff,
                    (u >> 24) & 0x000000ff, u, gsock);
         }

         ioctl(gsock, FIONBIO, &mode);
         client_add(u, gsock);
      }
   }
Exemple #26
0
int main(int argc, char *argv[])
{
	uint32_t major, minor, patch;
	struct lk *lk;
	int i, rv, maxi = 0, quit = 0;

	srandom(time(NULL));

	decode_arguments(argc, argv);

	if (maxn < maxr) {
		printf("number of resources must be >= number of locks\n");
		return -1;
	}
	if (maxn % maxr) {
		printf("number of locks must be multiple of number of resources\n");
		return -1;
	}

	printf("maxn = %d\n", maxn);
	printf("maxr = %d\n", maxr);
	printf("locks per resource = %d\n", maxn / maxr);

	signal(SIGTERM, sigterm_handler);

	client_init();

	locks = malloc(maxn * sizeof(struct lk));
	if (!locks) {
		printf("no mem for %d locks\n", maxn);
		return 0;
	}
	memset(locks, 0, sizeof(*locks));

	lk = locks;
	for (i = 0; i < maxn; i++) {
		lk->id = i;
		lk->grmode = -1;
		lk->rqmode = -1;
		lk++;
	}

	rv = dlm_kernel_version(&major, &minor, &patch);
	if (rv < 0) {
		printf("can't detect dlm in kernel %d\n", errno);
		return -1;
	}
	printf("dlm kernel version: %u.%u.%u\n", major, minor, patch);
	dlm_library_version(&major, &minor, &patch);
	printf("dlm library version: %u.%u.%u\n", major, minor, patch);

	if (openclose_ls) {
		printf("dlm_open_lockspace...\n");

		dh = dlm_open_lockspace("test");
		if (!dh) {
			printf("dlm_open_lockspace error %lu %d\n",
				(unsigned long)dh, errno);
			return -ENOTCONN;
		}
	} else {
		printf("dlm_new_lockspace...\n");

		dh = dlm_new_lockspace("test", 0600,
				       timewarn ? DLM_LSFL_TIMEWARN : 0);
		if (!dh) {
			printf("dlm_new_lockspace error %lu %d\n",
				(unsigned long)dh, errno);
			return -ENOTCONN;
		}
	}

	rv = dlm_ls_get_fd(dh);
	if (rv < 0) {
		printf("dlm_ls_get_fd error %d %d\n", rv, errno);
		dlm_release_lockspace("test", dh, 1);
		return rv;
	}
	libdlm_fd = rv;

	client_add(libdlm_fd, &maxi);

	if (opt_cmd) {
		process_command(&quit);
		goto out;
	}

	client_add(STDIN_FILENO, &maxi);

	printf("Type EXIT to finish, help for usage\n");

	while (1) {
		rv = poll(pollfd, maxi + 1, -1);
		if (rv < 0 && errno == EINTR)
			continue;
		if (rv < 0)
			printf("poll error %d errno %d\n", rv, errno);

		for (i = 0; i <= maxi; i++) {
			if (client[i].fd < 0)
				continue;

			if (pollfd[i].revents & POLLIN) {
				if (pollfd[i].fd == libdlm_fd)
					process_libdlm();
				else if (pollfd[i].fd == STDIN_FILENO)
					process_command(&quit);
			}

			if (pollfd[i].revents & (POLLHUP | POLLERR | POLLNVAL))
				client_dead(i);
		}

		if (quit && all_unlocks_done())
			break;
	}

 out:
	if (openclose_ls) {
		printf("dlm_close_lockspace\n");

		rv = dlm_close_lockspace(dh);
		if (rv < 0)
			printf("dlm_close_lockspace error %d %d\n", rv, errno);
	} else {
		printf("dlm_release_lockspace\n");

		rv = dlm_release_lockspace("test", dh, 1);
		if (rv < 0)
			printf("dlm_release_lockspace error %d %d\n", rv, errno);
	}

	return 0;
}
Exemple #27
0
void client_clear_list()
{
	gtk_list_store_clear(client_list);
	client_add(globals_nick, -1);
}
Exemple #28
0
void
loop(void)
{
    int                i, listenfd, clifd, nread;
    char            buf[MAXLINE];
    uid_t            uid;
    struct pollfd    *pollfd;
    int                numfd = 1;
    int                maxfd = NALLOC;

    if ((pollfd = malloc(NALLOC * sizeof(struct pollfd))) == NULL)
        err_sys("malloc error");
    for (i = 0; i < NALLOC; i++) {
        pollfd[i].fd = -1;
        pollfd[i].events = POLLIN;
        pollfd[i].revents = 0;
    }

    /* obtain fd to listen for client requests on */
    if ((listenfd = serv_listen(CS_OPEN)) < 0)
        log_sys("serv_listen error");
    client_add(listenfd, 0);    /* we use [0] for listenfd */
    pollfd[0].fd = listenfd;

    for ( ; ; ) {
        if (poll(pollfd, numfd, -1) < 0)
            log_sys("poll error");

        if (pollfd[0].revents & POLLIN) {
            /* accept new client request */
            if ((clifd = serv_accept(listenfd, &uid)) < 0)
                log_sys("serv_accept error: %d", clifd);
            client_add(clifd, uid);

            /* possibly increase the size of the pollfd array */
            if (numfd == maxfd)
                pollfd = grow_pollfd(pollfd, &maxfd);
            pollfd[numfd].fd = clifd;
            pollfd[numfd].events = POLLIN;
            pollfd[numfd].revents = 0;
            numfd++;
            log_msg("new connection: uid %d, fd %d", uid, clifd);
        }

        for (i = 1; i < numfd; i++) {
            if (pollfd[i].revents & POLLHUP) {
                goto hungup;
            } else if (pollfd[i].revents & POLLIN) {
                /* read argument buffer from client */
                if ((nread = read(pollfd[i].fd, buf, MAXLINE)) < 0) {
                    log_sys("read error on fd %d", pollfd[i].fd);
                } else if (nread == 0) {
hungup:
                    /* the client closed the connection */
                    log_msg("closed: uid %d, fd %d",
                      client[i].uid, pollfd[i].fd);
                    client_del(pollfd[i].fd);
                    close(pollfd[i].fd);
                    if (i < (numfd-1)) {
                        /* pack the array */
                        pollfd[i].fd = pollfd[numfd-1].fd;
                        pollfd[i].events = pollfd[numfd-1].events;
                        pollfd[i].revents = pollfd[numfd-1].revents;
                        i--;    /* recheck this entry */
                    }
                    numfd--;
                } else {        /* process client's request */
                    handle_request(buf, nread, pollfd[i].fd,
                      client[i].uid);
                }
            }
        }
    }
}
Exemple #29
0
static int generate_sql_clients(rlm_sql_t *inst)
{
	rlm_sql_handle_t *handle;
	rlm_sql_row_t row;
	unsigned int i = 0;
	RADCLIENT *c;

	DEBUG("rlm_sql (%s): Processing generate_sql_clients",
	      inst->config->xlat_name);

	DEBUG("rlm_sql (%s) in generate_sql_clients: query is %s",
	      inst->config->xlat_name, inst->config->client_query);

	handle = sql_get_socket(inst);
	if (!handle) {
		return -1;
	}

	if (rlm_sql_select_query(&handle, inst, inst->config->client_query)){
		return -1;
	}

	while((rlm_sql_fetch_row(&handle, inst) == 0) && (row = handle->row)) {
		char *server = NULL;
		i++;

		/*
		 *  The return data for each row MUST be in the following order:
		 *
		 *  0. Row ID (currently unused)
		 *  1. Name (or IP address)
		 *  2. Shortname
		 *  3. Type
		 *  4. Secret
		 *  5. Virtual Server (optional)
		 */
		if (!row[0]){
			ERROR("rlm_sql (%s): No row id found on pass %d",inst->config->xlat_name,i);
			continue;
		}
		if (!row[1]){
			ERROR("rlm_sql (%s): No nasname found for row %s",inst->config->xlat_name,row[0]);
			continue;
		}
		if (!row[2]){
			ERROR("rlm_sql (%s): No short name found for row %s",inst->config->xlat_name,row[0]);
			continue;
		}
		if (!row[4]){
			ERROR("rlm_sql (%s): No secret found for row %s",inst->config->xlat_name,row[0]);
			continue;
		}

		if (((inst->module->sql_num_fields)(handle, inst->config) > 5) && (row[5] != NULL) && *row[5]) {
			server = row[5];
		}

		DEBUG("rlm_sql (%s): Adding client %s (%s) to %s clients list",
		      inst->config->xlat_name,
		      row[1], row[2], server ? server : "global");

		/* FIXME: We should really pass a proper ctx */
		c = client_from_query(NULL,
				      row[1],	/* identifier */
				      row[4],	/* secret */
				      row[2],	/* shortname */
				      row[3],	/* type */
				      server,	/* server */
				      false);	/* require message authenticator */
		if (!c) {
			continue;
		}

		if (!client_add(NULL, c)) {
			WARN("Failed to add client, possible duplicate?");

			client_free(c);
			continue;
		}

		DEBUG("rlm_sql (%s): Client \"%s\" (%s) added", c->longname, c->shortname,
		      inst->config->xlat_name);
	}

	(inst->module->sql_finish_select_query)(handle, inst->config);
	sql_release_socket(inst, handle);

	return 0;
}
Exemple #30
0
void handle_event(XEvent *ev) {
	client *c = owner(ev->xany.window);
	#ifdef DEBUG_EVENTS
	if(ev->type != Expose && ev->type != MotionNotify && !(ev->type == ConfigureNotify && ev->xconfigure.window != root)) /* this makes the output slightly more manageable */
		printf(NAME ": handle_event(): got %s\n\twindow: 0x%X (%s)\n", event_name(ev), (unsigned int) ev->xany.window, c ? c->name : ((ev->xany.window == root) ? "root" : "unknown"));
	#endif
	if((evh && evh(ev)) || button_handle_event(ev) || ewmh_handle_event(ev) || screens_handle_event(ev)) {
		#ifdef DEBUG_EVENTS
		if(ev->type != Expose && ev->type != MotionNotify && (ev->type != ConfigureNotify && ev->xconfigure.window != root))
			printf(NAME ": handle_event(): external event handler claimed last event\n");
		#endif
		return;
	}
	if(c) {
		if(!has_child(c->parent, c->window) && ev->type != DestroyNotify && ev->type != UnmapNotify)
			return;
		switch(ev->type) {
			case UnmapNotify:
				if(c->window == ev->xunmap.window) {
					#ifdef DEBUG_EVENTS
					printf(NAME ": handle_event(): handling UnmapNotify event\n\twindow: 0x%X (%s)\n", (unsigned int) c->window, c->name);
					#endif
					if(has_child(c->parent, c->window)) {
						client_deparent(c);
						set_wm_state(c->window, WithdrawnState);
					}
					client_remove(c);
					ewmh_update_clist();
				}
				return;
			case PropertyNotify:
				if(ev->xproperty.atom == XA_WM_NAME) {
					#ifdef DEBUG_EVENTS
					printf(NAME ": handle_event(): handling PropertyNotify event\n\twindow: 0x%X (%s)\n\tproperty: XA_WM_NAME\n", (unsigned int) c->window, c->name);
					#endif
					if(c->name != no_title)
						XFree(c->name);
					#ifdef USE_XFT
					if(xftfont)
						XftDrawDestroy(c->title_draw);
					#endif
					XFreePixmap(dpy, c->title_pixmap);
					XFetchName(dpy, c->window, &c->name);
					client_update_name(c);
					XClearWindow(dpy, c->title);
					if(evh == wlist_handle_event) {
						XClearWindow(dpy, c->wlist_item);
						wlist_item_draw(c);
					}
				}
				if(ev->xproperty.atom == XA_WM_NORMAL_HINTS) {
					#ifdef DEBUG_EVENTS
					printf(NAME ": handle_event(): handling PropertyNotify event\n\twindow: 0x%X (%s)\n\tproperty: XA_WM_NORMAL_HINTS\n", (unsigned int) c->window, c->name);
					#endif
					get_normal_hints(c);
				}
				return;
			case ClientMessage:
				if(ev->xclient.message_type == xa_wm_change_state && ev->xclient.data.l[0] == IconicState) {
					#ifdef DEBUG_EVENTS
					printf(NAME ": handling ClientMessage event\n\twindow: 0x%X (%s)\n", (unsigned int) c->window, c->name);
					#endif
					client_iconify(c);
					return;
				}
				break; /* we might later need this event */
			case EnterNotify:
				if(c != current && !(c->flags & CLICK_FOCUS) && !click_focus && ev->xcrossing.mode != NotifyGrab && ev->xcrossing.mode != NotifyUngrab && ev->xcrossing.detail != NotifyInferior && (ev->xcrossing.window == c->parent || ev->xcrossing.window == c->wlist_item) && ev->xcrossing.send_event == False) {
					#ifdef DEBUG_EVENTS
					printf(NAME ": handle_event(): handling EnterNotify event\n\twindow: 0x%X (%s)\n", (unsigned int) c->window, c->name);
					#endif
					client_focus(c, true);
				}
				return;
			case Expose:
				if(ev->xexpose.count == 0 && evh == wlist_handle_event && c && ev->xexpose.window == c->wlist_item)
					wlist_item_draw(c);
				return;
			case ButtonPress:
				#ifdef DEBUG_EVENTS
				printf(NAME ": handle_event(): handling ButtonPress event\n\twindow: 0x%X (%s)\n", (unsigned int) c->window, c->name);
				#endif
				if(c != current)
					client_focus(c, true);
				XAllowEvents(dpy, ReplayPointer, CurrentTime);
				if(ev->xbutton.window != c->window) {
					if(lastclick + doubleclick_time > ev->xbutton.time && lastbutton == ev->xbutton.button && lastclick_client == c) {
						client_action(c, buttonaction(ev->xbutton.button, true), ev);
						lastclick = 0;
						lastclick_client = NULL;
						lastbutton = None;
						return;
					}
					lastclick = ev->xbutton.time;
					lastclick_client = c;
					lastbutton = ev->xbutton.button;
					client_action(c, buttonaction(ev->xbutton.button, false), ev);
				} else if(click_raise)
					client_raise(c);
				return;
			case FocusIn: /* we ignore pointer events, these happen if the input focus is on the root window */
				if(allow_focus_stealing && c != current && ev->xfocus.mode != NotifyGrab && ev->xfocus.mode != NotifyUngrab && ev->xfocus.detail != NotifyPointer) {
					#ifdef DEBUG_EVENTS
					printf(NAME ": handle_event(): handling FocusIn event\n\twindow: 0x%X (%s)\n", (unsigned int) c->window, c->name);
					#endif
					client_focus(c, false);
				}
				return;
			case FocusOut:
				if(c == current && ev->xfocus.mode != NotifyGrab && ev->xfocus.mode != NotifyUngrab && ev->xfocus.detail != NotifyInferior) {
					#ifdef DEBUG_EVENTS
					printf(NAME ": handle_event(): handling FocusOut event\n\twindow: 0x%X (%s)\n", (unsigned int) c->window, c->name);
					#endif
					if(allow_focus_stealing && ev->xfocus.detail != NotifyAncestor) {
						#ifdef DEBUG_EVENTS
						printf("\tfocus lost\n");
						#endif
						client_focus(NULL, false); /* we do this so windows that aren't managed can take focus */
					} else {
						#ifdef DEBUG_EVENTS
						printf("\tre-focussing this window\n");
						#endif
						take_focus(c);
					}
				}
				return;
			#ifdef USE_SHAPE
			default:
				if(ev->type == shape_event) {
					#ifdef DEBUG_EVENTS
					printf(NAME ": handle_event(): handling ShapeNotify event\n\twindow 0x%X (%s)\n", (unsigned int) c->window, c->name);
					#endif
					set_shape(c);
					return;
				}
			#endif
		}
	}
	switch(ev->type) {
		case MapRequest:
			c = owner(ev->xmaprequest.window);
			#ifdef DEBUG_EVENTS
			printf(NAME ": handle_event(): handling MapRequest event\n\twindow: 0x%X (%s)\n", (unsigned int) ev->xmaprequest.window, c ? c->name : "unknown");
			#endif
			if(c) {
				if(c->flags & ICONIC && has_child(c->parent, c->window)) {
					client_restore(c);
					if(focus_new)
						client_focus(c, true);
				}
			} else if(has_child(root, ev->xmaprequest.window))
				client_add(ev->xmaprequest.window, false);
			return;
		case DestroyNotify:
			c = owner(ev->xdestroywindow.window);
			if(c)
				if(c->window == ev->xdestroywindow.window) {
					#ifdef DEBUG_EVENTS
					printf(NAME ": handle_event(): handling DestroyNotify event\n\twindow 0x%X (%s)\n", (unsigned int) c->window, c->name);
					#endif
					client_remove(c);
				}
			return;
		case ConfigureRequest:
			c = owner(ev->xconfigurerequest.window);
			#ifdef DEBUG_EVENTS
			printf(NAME ": handle_event(): handling ConfigureRequest event\n\twindow 0x%X (%s)\n", (unsigned int) ev->xconfigurerequest.window, c ? c->name : "unknown");
			#endif
			if(correct_center)
				screens_correct_center(&ev->xconfigurerequest.x, &ev->xconfigurerequest.y, &ev->xconfigurerequest.width, &ev->xconfigurerequest.height);
			if(c) {
				if(!has_child(c->parent, c->window))
					return;
				if(ev->xconfigurerequest.value_mask & CWX)
					c->x = ev->xconfigurerequest.x - gxo(c, false);
				if(ev->xconfigurerequest.value_mask & CWY)
					c->y = ev->xconfigurerequest.y - gyo(c, false);
				if(ev->xconfigurerequest.value_mask & CWWidth)
					c->width = ev->xconfigurerequest.width;
				if(ev->xconfigurerequest.value_mask & CWHeight)
					c->height = ev->xconfigurerequest.height;
				client_update(c);
				#ifdef DEBUG
				printf(NAME ": handle_event(): reconfigured client 0x%X (%s) to %ix%i+%i+%i\n", (unsigned int) c->window, c->name, c->width, c->height, c->x, c->y);
				#endif
			} else if(has_child(root, ev->xconfigurerequest.window)) {
				XWindowChanges wc;
				wc.sibling = ev->xconfigurerequest.above;
				wc.stack_mode = ev->xconfigurerequest.detail;
				wc.x = ev->xconfigurerequest.x;
				wc.y = ev->xconfigurerequest.y;
				wc.width = ev->xconfigurerequest.width;
				wc.height = ev->xconfigurerequest.height;
				XConfigureWindow(dpy, ev->xconfigurerequest.window, ev->xconfigurerequest.value_mask, &wc);
			}
			return;
		case MapNotify:
			if(correct_center_unmanaged && ev->xany.window == root && !owner(ev->xmap.window)) {
				#ifdef DEBUG_EVENTS
				printf(NAME ": handle_event(): handling MapNotify event\n\twindow 0x%X (unknown)\n", (unsigned int) ev->xmap.window);
				#endif
				window_correct_center(ev->xmap.window);
			}
			return;
		case MappingNotify:
			if(ev->xmapping.request != MappingPointer) {
				#ifdef DEBUG_EVENTS
				printf(NAME ": handle_event(): handling MappingNotify event\n");
				#endif
				keys_ungrab();
				XRefreshKeyboardMapping(&ev->xmapping);
				keys_update();
			}
			return;
		case KeyPress:
			#ifdef DEBUG_EVENTS
			printf(NAME ": handle_event(): handling KeyPress event\n");
			#endif
			client_action(current, keyaction(ev), ev);
			return;
		case ButtonPress:
			if(ev->xbutton.window != root)
				return;
			#ifdef DEBUG_EVENTS
			printf(NAME ": handle_event(): handling ButtonPress event\n");
			#endif
			if(lastclick + doubleclick_time > ev->xbutton.time && lastbutton == ev->xbutton.button && lastclick_client == NULL) {
				client_action(current, root_buttonaction(ev->xbutton.button, true), ev);
				lastclick = 0;
				lastclick_client = NULL;
				lastbutton = None;
				return;
			}
			lastclick = ev->xbutton.time;
			lastclick_client = NULL;
			lastbutton = ev->xbutton.button;
			client_action(current, root_buttonaction(ev->xbutton.button, false), ev);
			return;
		case ClientMessage:
			if(ev->xclient.message_type == xa_internal_message) {
				if(((Atom) ev->xclient.data.l[0]) == xa_quit) {
					#ifdef DEBUG
					printf(NAME ": handle_event(): quit message received\n");
					#endif
					exit(0);
				}
				if(((Atom) ev->xclient.data.l[0]) == xa_reinit) {
					#ifdef DEBUG
					printf(NAME ": handle_event(): reinitialize message received\n");
					#endif
					cfg_reinitialize();
				}
			}
	}
}