void dump_tree_connections(tree *t, int ntax, int numnodes)
{
    printf("Tree %i:\n", t->index);
    printf("Root: %p\nLength: %i\n", t->root, t->length);
    dump_connections(t->trnodes, ntax, numnodes);
    printf("\n");
}
Beispiel #2
0
VOIDSIG s_die() 
{
#ifdef SAVE_MAXCLIENT_STATS
	FILE *fp;
#endif
   dump_connections(me.fd);
#ifdef	USE_SYSLOG
   (void) syslog(LOG_CRIT, "Server killed By SIGTERM");
#endif
#ifdef SAVE_MAXCLIENT_STATS
	fp=fopen(DPATH "/.maxclients", "w");
	if(fp!=NULL) {
		fprintf(fp, "%d %d %li %li %li %ld %ld %ld %ld", Count.max_loc, 
			Count.max_tot, Count.weekly, Count.monthly, 
			Count.yearly, Count.start, Count.week, Count.month, 
			Count.year);
		fclose(fp);
	}
#endif
   exit(-1);
}
Beispiel #3
0
void server_reboot() 
{
   int     i;
   sendto_ops("Aieeeee!!!  Restarting server... sbrk(0)-etext: %d",
				  (u_int) sbrk((size_t) 0) - (u_int) sbrk0);
	
   Debug((DEBUG_NOTICE, "Restarting server..."));
   dump_connections(me.fd);
   /*
    * fd 0 must be 'preserved' if either the -d or -i options have
    * been passed to us before restarting.
    */
#ifdef USE_SYSLOG
   (void) closelog();
#endif
   for (i = 3; i < MAXCONNECTIONS; i++)
      (void) close(i);

   if (!(bootopt & (BOOT_TTY | BOOT_DEBUG)))
      (void) close(2);

   (void) close(1);

   if ((bootopt & BOOT_CONSOLE))
      (void) close(0);

   if (!(bootopt & (BOOT_INETD)))
      (void) execv(MYNAME, myargv);

#ifdef USE_SYSLOG
   /* Have to reopen since it has been closed above */
   openlog(myargv[0], LOG_PID | LOG_NDELAY, LOG_FACILITY);
   syslog(LOG_CRIT, "execv(%s,%s) failed: %m\n", MYNAME, myargv[0]);
   closelog();
#endif

   Debug((DEBUG_FATAL, "Couldn't restart server: %s", strerror(errno)));
   exit(-1);
}
Beispiel #4
0
static RETSIGTYPE sigusr1_handler(int a) {
	dump_connections();
}
Beispiel #5
0
/*
  this is where it all happens...
*/
int main_loop(void) {
	fd_set readset, writeset;
#ifdef HAVE_PSELECT
	struct timespec tv;
	sigset_t omask, block_mask;
	time_t next_event;
#else
	struct timeval tv;
#endif
	int r, maxfd;
	time_t last_ping_check, last_config_check, last_graph_dump;
	event_t *event;

	last_ping_check = now;
	last_config_check = now;
	last_graph_dump = now;
	
	srand(now);

#ifdef HAVE_PSELECT
	if(lookup_config(config_tree, "GraphDumpFile"))
		graph_dump = true;
	/* Block SIGHUP & SIGALRM */
	sigemptyset(&block_mask);
	sigaddset(&block_mask, SIGHUP);
	sigaddset(&block_mask, SIGALRM);
	sigprocmask(SIG_BLOCK, &block_mask, &omask);
#endif

	running = true;

	while(running) {
#ifdef HAVE_PSELECT
		next_event = last_ping_check + pingtimeout;
		if(graph_dump && next_event > last_graph_dump + 60)
			next_event = last_graph_dump + 60;

		if((event = peek_next_event()) && next_event > event->time)
			next_event = event->time;

		if(next_event <= now)
			tv.tv_sec = 0;
		else
			tv.tv_sec = next_event - now;
		tv.tv_nsec = 0;
#else
		tv.tv_sec = 1;
		tv.tv_usec = 0;
#endif

		maxfd = build_fdset(&readset, &writeset);

#ifdef HAVE_MINGW
		LeaveCriticalSection(&mutex);
#endif
#ifdef HAVE_PSELECT
		r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
#else
		r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
#endif
		now = time(NULL);
#ifdef HAVE_MINGW
		EnterCriticalSection(&mutex);
#endif

		if(r < 0) {
			if(!sockwouldblock(sockerrno)) {
				logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
				dump_connections();
				return 1;
			}
		}

		if(r > 0)
			check_network_activity(&readset, &writeset);

		if(do_purge) {
			purge();
			do_purge = false;
		}

		/* Let's check if everybody is still alive */

		if(last_ping_check + pingtimeout <= now) {
			check_dead_connections();
			last_ping_check = now;

			if(routing_mode == RMODE_SWITCH)
				age_subnets();

			age_past_requests();

			/* Should we regenerate our key? */

			if(keyexpires <= now) {
				avl_node_t *node;
				node_t *n;

				ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");

				for(node = node_tree->head; node; node = node->next) {
					n = node->data;
					if(n->inkey) {
						free(n->inkey);
						n->inkey = NULL;
					}
				}

				send_key_changed();
				keyexpires = now + keylifetime;
			}

			/* Detect ADD_EDGE/DEL_EDGE storms that are caused when
			 * two tinc daemons with the same name are on the VPN.
			 * If so, sleep a while. If this happens multiple times
			 * in a row, sleep longer. */

			if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
				logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
				usleep(sleeptime * 1000000LL);
				sleeptime *= 2;
				if(sleeptime < 0)
					sleeptime = 3600;
			} else {
				sleeptime /= 2;
				if(sleeptime < 10)
					sleeptime = 10;
			}

			contradicting_add_edge = 0;
			contradicting_del_edge = 0;
		}

		if(sigalrm) {
			avl_node_t *node;
			logger(LOG_INFO, "Flushing event queue");
			expire_events();
			for(node = connection_tree->head; node; node = node->next) {
				connection_t *c = node->data;
				if(c->status.active)
					send_ping(c);
			}
			sigalrm = false;
		}

		while((event = get_expired_event())) {
			event->handler(event->data);
			free_event(event);
		}

		if(sighup) {
			connection_t *c;
			avl_node_t *node, *next;
			char *fname;
			struct stat s;
			
			sighup = false;

			reopenlogger();
			
			/* Reread our own configuration file */

			exit_configuration(&config_tree);
			init_configuration(&config_tree);

			if(!read_server_config()) {
				logger(LOG_ERR, "Unable to reread configuration file, exitting.");
				return 1;
			}

			/* Cancel non-active outgoing connections */

			for(node = connection_tree->head; node; node = next) {
				next = node->next;
				c = node->data;

				c->outgoing = NULL;

				if(c->status.connecting) {
					terminate_connection(c, false);
					connection_del(c);
				}
			}

			/* Wipe list of outgoing connections */

			for(list_node_t *node = outgoing_list->head; node; node = node->next) {
				outgoing_t *outgoing = node->data;

				if(outgoing->event)
					event_del(outgoing->event);
			}

			list_delete_list(outgoing_list);

			/* Close connections to hosts that have a changed or deleted host config file */
			
			for(node = connection_tree->head; node; node = node->next) {
				c = node->data;
				
				xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
				if(stat(fname, &s) || s.st_mtime > last_config_check)
					terminate_connection(c, c->status.active);
				free(fname);
			}

			last_config_check = now;

			/* If StrictSubnet is set, expire deleted Subnets and read new ones in */

			if(strictsubnets) {
				subnet_t *subnet;

				for(node = subnet_tree->head; node; node = node->next) {
					subnet = node->data;
					subnet->expires = 1;
				}

				load_all_subnets();

				for(node = subnet_tree->head; node; node = next) {
					next = node->next;
					subnet = node->data;
					if(subnet->expires == 1) {
						send_del_subnet(everyone, subnet);
						if(subnet->owner->status.reachable)
							subnet_update(subnet->owner, subnet, false);
						subnet_del(subnet->owner, subnet);
					} else if(subnet->expires == -1) {
						subnet->expires = 0;
					} else {
						send_add_subnet(everyone, subnet);
						if(subnet->owner->status.reachable)
							subnet_update(subnet->owner, subnet, true);
					}
				}
			}

			/* Try to make outgoing connections */
			
			try_outgoing_connections();
		}
		
		/* Dump graph if wanted every 60 seconds*/

		if(last_graph_dump + 60 <= now) {
			dump_graph();
			last_graph_dump = now;
		}
	}

#ifdef HAVE_PSELECT
	/* Restore SIGHUP & SIGALARM mask */
	sigprocmask(SIG_SETMASK, &omask, NULL);
#endif

	return 0;
}
/**
 * Цикл обработки входящий соединений.
 *
 * @param[in] server_sockfd сокет, принимающий входящие соединения.
 * @param[in] handler обработчик соединения.
 * @param статус завершения.
 */
int
connections_loop(IN int server_sockfd,
                 IN void * (*_handler)(struct connection_vars_t*))
{
	int status = 0;

	while (true) {
		TRACE;

#ifdef DEBUG
		pthread_mutex_lock(&connections_lock);
		printf("Connections: %d\n", connections);
		printf("Free places: %d\n", get_free_places());

		if (HANDLE_CONNS_COUNT != (connections + get_free_places())) {
			fprintf(stderr, "Something went wrong\n");

			TRACE;
			dump_connections();

			pthread_mutex_unlock(&connections_lock);
			return -EINVAL;
		}

		pthread_mutex_unlock(&connections_lock);
#endif

		struct sockaddr_in client_addr;

		memset(&client_addr, 0, sizeof(struct sockaddr_in));

		socklen_t client_addr_size = sizeof(struct sockaddr_in);

		int client_sockfd = accept(
			server_sockfd,
			(struct sockaddr*) &client_addr,
			&client_addr_size
                        );

		CHECK_ERRNO(client_sockfd, "Accept connection");

		/* Проверка лимита соединений для IP */
		pthread_mutex_lock(&connections_lock);
		int ip_conn = get_ip_conn(client_addr.sin_addr.s_addr);
		pthread_mutex_unlock(&connections_lock);

		if (ip_conn > MAX_IP_CONN) {
			TRACE;

			/* Отправка клиенту сообщение о лимите */
			send(client_sockfd, IP_CONN_LIMIT_MSG,
			     sizeof(IP_CONN_LIMIT_MSG), 0);

			shutdown(client_sockfd, SHUT_RDWR);
			close(client_sockfd);

			continue;
		}

		/* Проверка общего лимита соединений. */
		pthread_mutex_lock(&connections_lock);
		int is_limit = connections > HANDLE_CONNS_COUNT - 1;
		pthread_mutex_unlock(&connections_lock);

		if (is_limit) {
			TRACE;

			/* Отправка клиенту сообщение о лимите */
			send(client_sockfd, ALL_CONN_LIMIT_MSG,
			     sizeof(ALL_CONN_LIMIT_MSG), 0);

			shutdown(client_sockfd, SHUT_RDWR);
			close(client_sockfd);

			continue;
		}

		pthread_mutex_lock(&init_connection_lock);

		++connections_count;

		DBG_printf("Connect: %lld\n", connections_count);

		pthread_t client_thread;

		struct connection_vars_t* connection =
			calloc(sizeof(struct connection_vars_t), 1);

		if (NULL == connection) {
			TRACE;
			fprintf(stderr, "Allocation failed\n");
			exit(EXIT_FAILURE);
		}

		TRACE;

		connection->sockfd = client_sockfd;
		connection->addr = client_addr;
		connection->n = connections_count;

		TRACE;

		status = pthread_create(
			&client_thread,
			NULL,
			(void * (*)(void*)) _handler,
			(void*) connection
			);

		CHECK_ERRNO(status, "Create handle connection thread");

		pthread_detach(client_thread);

		CHECK_ERRNO(status, "Detach connection thread");

		pthread_mutex_lock(&connections_lock);

		if (save_conn(connection)) {
			/* Опасная ситуация */
			fprintf(stderr, "No free place for connection\n");

			TRACE;
			dump_connection_vars(connection);

			dump_connections();

			pthread_mutex_unlock(&connections_lock);
			pthread_mutex_unlock(&init_connection_lock);
			exit(EXIT_FAILURE);
		}

		pthread_mutex_unlock(&connections_lock);
		pthread_mutex_unlock(&init_connection_lock);
	}
}
/* Restart download from incomplete ___ARESTRA___ file. This will fail if the
 * file is not found/corrupt/etc.
 */
as_bool as_download_restart (ASDownload *dl, const char *path)
{
	if (dl->state != DOWNLOAD_NEW)
	{
		assert (dl->state == DOWNLOAD_NEW);
		return FALSE;
	}

	if (!path)
	{
		assert (path);
		return FALSE;
	}

	/* copy file path */
	dl->path = strdup (path);

	/* set filename after __ARESTRA__prefix */
	dl->filename = as_get_filename (dl->path);
	if (strncmp (dl->filename, AS_DOWNLOAD_INCOMPLETE_PREFIX,
		         strlen (AS_DOWNLOAD_INCOMPLETE_PREFIX)) == 0)
		dl->filename += strlen (AS_DOWNLOAD_INCOMPLETE_PREFIX);

	/* make sure the file exists */
	if (!as_file_exists (dl->path))
	{
		AS_ERR_1 ("Incomplete file \"%s\" does not exist.", dl->path);
		free (dl->path);
		dl->path = NULL;
		dl->filename = NULL;
		return FALSE;
	}

	/* open file */
	if (!(dl->fp = fopen (dl->path, "r+b")))
	{
		AS_ERR_1 ("Unable to open download file \"%s\" for writing",
		          dl->path);
		free (dl->path);
		dl->path = NULL;
		dl->filename = NULL;
		return FALSE;
	}

	/* read download state from file */
	if (!as_downstate_load (dl))
	{
		AS_ERR_1 ("Unable to load state for incomplete download file \"%s\"",
		          dl->path);
		fclose (dl->fp);
		dl->fp = NULL;
		free (dl->path);
		dl->path = NULL;
		dl->filename = NULL;
		return FALSE;	
	}
	
	AS_HEAVY_DBG_3 ("Loaded state for \"%s\", size: %u, received: %u",
	                dl->filename, dl->size, dl->received);

#ifdef HEAVY_DEBUG
	assert (verify_chunks (dl));

	AS_HEAVY_DBG ("Chunk state after restoring download:");
	dump_chunks (dl);

	AS_HEAVY_DBG ("Connection state after restoring download:");
	dump_connections (dl);
#endif

	/* raise callback with state set by as_downstate_load */
	if (!download_set_state (dl, dl->state, TRUE))
		return FALSE;

	/* start things off if we are in active state */
	if (dl->state == DOWNLOAD_ACTIVE)
		download_maintain (dl);

	return TRUE;
}
/*
 * The heart of the download system. It is called whenever there are new
 * sources, finished chunks, etc.
 * Merges complete chunks and tries to assign sources to inactive ones. If 
 * there are more sources than chunks the chunks are split up.
 */
static void download_maintain (ASDownload *dl)
{
	if (dl->state != DOWNLOAD_ACTIVE)
	{
		/* Must not happen. */
		assert (dl->state == DOWNLOAD_ACTIVE);
		return;
	}

#ifdef VERIFY_CONN_LIST
	/* Verify integrity of connection list */
	verify_connections (dl);
#endif

	/* Verify integrity of chunk list. */
	if (!verify_chunks (dl))
	{
		AS_ERR_1 ("Corrupted chunk list detected for \"%s\"", dl->filename);
		
		/* Fail download */
		download_failed (dl);

		assert (0);
		return;
	}

	/* Clean up chunks. */
	if (!consolidate_chunks (dl))
	{
		AS_ERR_1 ("Consolidating chunks failed for \"%s\"", dl->filename);
		
		/* Fail download */
		download_failed (dl);

		assert (0);
		return;
	}

#ifdef CHUNK_DEBUG
	AS_HEAVY_DBG ("Chunk state after consolidating:");
	dump_chunks (dl);


	AS_HEAVY_DBG ("Connection state after consolidating:");
	dump_connections (dl);
#endif

	/* Is the download complete? */
	if (((ASDownChunk *)dl->chunks->data)->received == dl->size)
	{
		/* Download complete */
		download_finished (dl);
		return;
	}

	/* Download not complete. Start more chunk downloads. */
	if (!start_chunks (dl))
	{
		/* This should be harmless. */
		AS_WARN_1 ("Starting chunks failed for \"%s\"", dl->filename);
	}

	/* Check if we need more sources */
	if (dl->conns == NULL)
	{
		/* TODO: start source search  */
		AS_ERR_1 ("FIXME: No more sources for \"%s\". Make me find more.",
		          dl->filename);
	}
}
Beispiel #9
0
/*
 * m_webirc
 * parv[0] = sender prefix
 * parv[1] = password that authenticates the WEBIRC command from this client
 * parv[2] = username or client requesting spoof (cgiirc defaults to cgiirc)
 * parv[3] = hostname of user
 * parv[4] = IP address of user
 */
int m_webirc(aClient *cptr, aClient *sptr, int parc, char *parv[])
{
    char oldusername[USERLEN + 1];
    struct userBan *ban;
    int i;

    if (parc < 5 || *parv[1] == '\0' || *parv[2] == '\0' ||
	*parv[3] == '\0' || *parv[4] == '\0')
    {
	sendto_one(sptr, err_str(ERR_NEEDMOREPARAMS), me.name, parv[0], "WEBIRC");
	return 0;
    }
    if (!MyConnect(sptr) || !IsUnknown(cptr) || cptr->receiveM != 1)
    {
	sendto_one(sptr, err_str(ERR_ALREADYREGISTRED), me.name, parv[0]);
	return 0;
    }

    strncpyzt(oldusername, cptr->username, USERLEN + 1);
    make_user(cptr);
    if (!(cptr->flags & FLAGS_GOTID))
	strcpy(cptr->username, "webirc");
    i = attach_Iline(cptr, cptr->hostp, cptr->sockhost);
    if (i == 0)
    {
	aAllow *pwaconf = sptr->user->allow;

	if (BadPtr(pwaconf->passwd) ||
	    strncmp(pwaconf->passwd, "webirc.", strlen("webirc.")) != 0)
	{
	    sendto_one(sptr, "NOTICE * :Not a CGI:IRC auth block");
	    i = -1;
	}
	else if (!StrEq(parv[1], pwaconf->passwd + strlen("webirc.")))
	{
	    sendto_one(sptr, "NOTICE * :CGI:IRC password incorrect");
	    i = -1;
	}
	else if (pwaconf->flags & CONF_FLAGS_NOTHROTTLE)
	    throttle_remove(cptr->sockhost);
    }
    clear_conflinks(cptr);
    free_user(cptr->user, cptr);
    cptr->user = NULL;
    cptr->flags &= ~FLAGS_DOID;
    strncpyzt(cptr->username, oldusername, USERLEN + 1);
    if (i != 0)
	return 0;

    if (inet_pton(AF_INET, parv[4], &cptr->ip.ip4))
	cptr->ip_family = AF_INET;
    else if (inet_pton(AF_INET6, parv[4], &cptr->ip.ip6))
	cptr->ip_family = AF_INET6;
    else
    {
	sendto_one(sptr, "NOTICE * :Invalid IP");
	return 0;
    }

    if (cptr->flags & FLAGS_GOTID)
    {
	cptr->webirc_username = MyMalloc(strlen(cptr->username) + 1);
	strcpy(cptr->webirc_username, cptr->username);
    }
    else
    {
	cptr->webirc_username = MyMalloc(strlen(parv[2]) + 1);
	strcpy(cptr->webirc_username, parv[2]);
    }
    cptr->webirc_ip = MyMalloc(strlen(cptr->sockhost) + 1);
    strcpy(cptr->webirc_ip, cptr->sockhost);

    get_sockhost(cptr, parv[3]);
    cptr->hostp = NULL;

    /*
     * Acknowledge that WEBIRC was accepted, and flush the client's send queue
     * to make debugging easier.
     */
    sendto_one(sptr, ":%s NOTICE AUTH :*** CGI:IRC host/IP set to %s %s",
	       me.name, cptr->sockhost, parv[4]);
    dump_connections(cptr->fd);

    /* if they are throttled, drop them silently. */
    if (throttle_check(parv[4], cptr->fd, NOW) == 0)
    {
	cptr->flags |= FLAGS_DEADSOCKET;

	ircstp->is_ref++;
	ircstp->is_throt++;
	return exit_client(cptr, sptr, &me, "Client throttled");
    }

    ban = check_userbanned(cptr, UBAN_IP|UBAN_CIDR4|UBAN_WILDUSER, 0);
    if(ban)
    {
	int loc = (ban->flags & UBAN_LOCAL) ? 1 : 0;

	ircstp->is_ref++;
	ircstp->is_ref_2++;
	return exit_banned_client(cptr, loc, loc ? 'K' : 'A', ban->reason, 0);
    }
    return 0;
}