Exemplo n.º 1
0
int main()
{
	apr_thread_t* push_thds[1000];
	apr_thread_t* pop_thds[1000];
	apr_threadattr_t* thd_attr;
	apr_initialize();
	apr_pool_create(&global_pool, NULL);
	apr_atomic_init(global_pool);
	frl_queue_create(&queue, global_pool, 1, FRL_LOCK_FREE);
	apr_threadattr_create(&thd_attr, global_pool);
	apr_time_t now = apr_time_now();
	for (int i = 0; i < 100; i++)
	{
		apr_thread_create(&pop_thds[i], thd_attr, threadsafe_test_pop, (void*)i, global_pool);
		apr_thread_create(&push_thds[i], thd_attr, threadsafe_test_push, (void*)i, global_pool);
	}
	apr_status_t rv;
	for (int i = 0; i < 100; i++)
	{
		printf("Stop at %d\n", i+1);
		apr_thread_join(&rv, push_thds[i]);
		apr_thread_join(&rv, pop_thds[i]);
	}
	printf("Pass with %dus.\n", apr_time_now()-now);
	apr_terminate();
}
Exemplo n.º 2
0
void slayer_server_stats_timer_thread(apr_pool_t *mpool,slayer_server_stats_t *stats) {
	apr_threadattr_t *thread_attr;
	apr_thread_t *thread;
	apr_threadattr_create(&thread_attr,mpool);
	apr_threadattr_detach_set(thread_attr,1); // detach
	apr_threadattr_stacksize_set(thread_attr,4096*10);
	apr_thread_create(&thread,thread_attr,slayer_server_stats_timer_thread_run,stats,mpool);
}
Exemplo n.º 3
0
apr_status_t handle_new_client(apr_socket_t *socket, apr_pool_t *pool,
		dynalogin_session_t *h)
{
	char buf[ERRBUFLEN + 1];

	apr_status_t res;
	apr_threadattr_t *t_attr;
	apr_thread_t *t;
	apr_pool_t *subpool;
	socket_thread_data_t *thread_data;

	res = apr_pool_create(&subpool, pool);
	if(res != APR_SUCCESS)
	{
		syslog(LOG_ERR, "failed to create pool: %s",
				apr_strerror(res, buf, ERRBUFLEN));
		apr_socket_close(socket);
		return res;
	}

	res = apr_threadattr_create(&t_attr, subpool);
	if(res != APR_SUCCESS)
	{
		syslog(LOG_ERR, "failed to create threadattr: %s",
				apr_strerror(res, buf, ERRBUFLEN));
		apr_pool_destroy(subpool);
		apr_socket_close(socket);
		return res;
	}

	thread_data = apr_pcalloc(subpool, sizeof(struct socket_thread_data_t));
	if(thread_data == NULL)
	{
		syslog(LOG_ERR, "handle_new_client: apr_pcalloc failed");
		apr_pool_destroy(subpool);
		apr_socket_close(socket);
		return res;
	}

	thread_data->pool = subpool;
	thread_data->socket = socket;
	thread_data->tls_session = NULL;  // to be populated later if using TLS
	thread_data->dynalogin_session = h;

	res = apr_thread_create(&t, t_attr,
			(apr_thread_start_t)socket_thread_main, thread_data, subpool);

	if(res != APR_SUCCESS)
	{
		syslog(LOG_ERR, "failed to spawn a thread: %s",
				apr_strerror(res, buf, ERRBUFLEN));
		apr_pool_destroy(subpool);
		apr_socket_close(socket);
	}

	return res;
}
Exemplo n.º 4
0
int openenv(DB_ENV **pdb_env,const char *home,const char *data_dir,
		const char *log_dir,FILE *err_file,
		int cachesize,unsigned int flag,apr_pool_t *p)
{
	int rv = -1;
	if((rv = db_env_create(pdb_env,0)) != 0){
		return rv;
	}

	if((rv = (*pdb_env)->set_cachesize((*pdb_env),0,cachesize,0)) != 0){
		return rv;
	}

	if((rv = (*pdb_env)->set_data_dir((*pdb_env),data_dir)) != 0){
		return rv;
	}
	if((rv = (*pdb_env)->set_lg_dir((*pdb_env),log_dir)) != 0){
		return rv;
	}
	if((rv = (*pdb_env)->set_lk_detect((*pdb_env),DB_LOCK_DEFAULT)) != 0){
		return rv;
	}
	if((rv = (*pdb_env)->set_tx_max((*pdb_env),1024)) != 0){
		return rv;
	}
	if((rv = (*pdb_env)->set_lg_bsize((*pdb_env),cachesize)) != 0){
		return rv;
	}
	if((rv =(*pdb_env)->set_flags((*pdb_env),
					DB_TXN_NOSYNC,1) !=0))
	{
		return rv;
	}


	if((rv = (*pdb_env)->open((*pdb_env),home,flag,0)) != 0){

		(*pdb_env)->close((*pdb_env),0);
		return rv;
	}

        if((rv=(*pdb_env)->log_set_config((*pdb_env),DB_LOG_AUTO_REMOVE,1) != 0))
	{
		return rv;
	}

	apr_threadattr_create(&thread_attr,p);
	apr_threadattr_detach_set(thread_attr,1);
	rv = apr_thread_create(&chkpnt_threadid,thread_attr,chkpnt_thread,*pdb_env,p);
	if(rv != APR_SUCCESS){
		return -1;
	}

	return 0;
}
Exemplo n.º 5
0
SWITCH_DECLARE(switch_status_t) switch_threadattr_create(switch_threadattr_t ** new_attr, switch_memory_pool_t *pool)
{
	switch_status_t status;

	if ((status = apr_threadattr_create(new_attr, pool)) == SWITCH_STATUS_SUCCESS) {
#ifndef WIN32
		(*new_attr)->priority = SWITCH_PRI_LOW;
#endif
	}

	return status;
}
Exemplo n.º 6
0
test_server_handle * test_start_looped_server(char *response_string, int port, apr_pool_t *mp) {
	server_thread_data *data = apr_palloc(mp, sizeof(server_thread_data));
	data->handle = apr_palloc(mp, sizeof(test_server_handle));
	//apr_thread_mutex_create(&data->handle->mutex, APR_THREAD_MUTEX_UNNESTED, mp);
    //apr_thread_cond_create(&data->handle->cond, mp);

	
	data->port = port;
	data->request_process_callback = looped_response_test;
	data->callback_data = response_string;
	apr_threadattr_t *thd_attr;
	apr_threadattr_create(&thd_attr, mp);
	data->handle->test_server_running = 0;
	apr_status_t rv = apr_thread_create(&data->handle->test_server_thread, thd_attr, test_server_run, (void*)data, mp);
	assert(rv == APR_SUCCESS);
	while(data->handle->test_server_running ==0) {
		apr_sleep(100);
	}
	return data->handle;
}
Exemplo n.º 7
0
static int selinux_handler(request_rec *r)
{
    apr_threadattr_t *thread_attr;
    apr_thread_t *thread;
    apr_status_t rv, thread_rv;

    /*
     * If the hook is invoked under the worker context,
     * we simply skips this module.
     */
    if (am_worker)
        return DECLINED;

    apr_threadattr_create(&thread_attr, r->pool);
    /* 0 means PTHREAD_CREATE_JOINABLE */
    apr_threadattr_detach_set(thread_attr, 0);

    rv = apr_thread_create(&thread, thread_attr,
                           selinux_worker_handler,
                           r, r->pool);
    if (rv != APR_SUCCESS) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
                      "Unable to launch a one-time worker thread");
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    rv = apr_thread_join(&thread_rv, thread);
    if (rv != APR_SUCCESS) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
                      "Unable to join the one-time worker thread");
        /* kill itself to clean up the thread */
        r->connection->aborted = 1;
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    return thread_rv;
}
Exemplo n.º 8
0
int main(int argc, const char **argv)
{
    apr_status_t status;
    apr_pool_t *pool;
    apr_sockaddr_t *address;
    serf_context_t *context;
    serf_connection_t *connection;
    app_baton_t app_ctx;
    handler_baton_t *handler_ctx;
    apr_uri_t url;
    const char *raw_url, *method;
    int count;
    apr_getopt_t *opt;
    char opt_c;
    char *authn = NULL;
    const char *opt_arg;

    /* For the parser threads */
    apr_thread_t *thread[3];
    apr_threadattr_t *tattr;
    apr_status_t parser_status;
    parser_baton_t *parser_ctx;

    apr_initialize();
    atexit(apr_terminate);

    apr_pool_create(&pool, NULL);
    apr_atomic_init(pool);
    /* serf_initialize(); */

    /* Default to one round of fetching. */
    count = 1;
    /* Default to GET. */
    method = "GET";

    apr_getopt_init(&opt, pool, argc, argv);

    while ((status = apr_getopt(opt, "a:hv", &opt_c, &opt_arg)) ==
           APR_SUCCESS) {
        int srclen, enclen;

        switch (opt_c) {
        case 'a':
            srclen = strlen(opt_arg);
            enclen = apr_base64_encode_len(srclen);
            authn = apr_palloc(pool, enclen + 6);
            strcpy(authn, "Basic ");
            (void) apr_base64_encode(&authn[6], opt_arg, srclen);
            break;
        case 'h':
            print_usage(pool);
            exit(0);
            break;
        case 'v':
            puts("Serf version: " SERF_VERSION_STRING);
            exit(0);
        default:
            break;
        }
    }

    if (opt->ind != opt->argc - 1) {
        print_usage(pool);
        exit(-1);
    }

    raw_url = argv[opt->ind];

    apr_uri_parse(pool, raw_url, &url);
    if (!url.port) {
        url.port = apr_uri_port_of_scheme(url.scheme);
    }
    if (!url.path) {
        url.path = "/";
    }

    if (strcasecmp(url.scheme, "https") == 0) {
        app_ctx.using_ssl = 1;
    }
    else {
        app_ctx.using_ssl = 0;
    }

    status = apr_sockaddr_info_get(&address,
                                   url.hostname, APR_UNSPEC, url.port, 0,
                                   pool);
    if (status) {
        printf("Error creating address: %d\n", status);
        exit(1);
    }

    context = serf_context_create(pool);

    /* ### Connection or Context should have an allocator? */
    app_ctx.bkt_alloc = serf_bucket_allocator_create(pool, NULL, NULL);
    app_ctx.ssl_ctx = NULL;
    app_ctx.authn = authn;

    connection = serf_connection_create(context, address,
                                        conn_setup, &app_ctx,
                                        closed_connection, &app_ctx,
                                        pool);

    handler_ctx = (handler_baton_t*)serf_bucket_mem_alloc(app_ctx.bkt_alloc,
                                                      sizeof(handler_baton_t));
    handler_ctx->allocator = app_ctx.bkt_alloc;
    handler_ctx->doc_queue = apr_array_make(pool, 1, sizeof(doc_path_t*));
    handler_ctx->doc_queue_alloc = app_ctx.bkt_alloc;

    handler_ctx->requests_outstanding =
        (apr_uint32_t*)serf_bucket_mem_alloc(app_ctx.bkt_alloc,
                                             sizeof(apr_uint32_t));
    apr_atomic_set32(handler_ctx->requests_outstanding, 0);
    handler_ctx->hdr_read = 0;

    parser_ctx = (void*)serf_bucket_mem_alloc(app_ctx.bkt_alloc,
                                       sizeof(parser_baton_t));

    parser_ctx->requests_outstanding = handler_ctx->requests_outstanding;
    parser_ctx->connection = connection;
    parser_ctx->app_ctx = &app_ctx;
    parser_ctx->doc_queue = handler_ctx->doc_queue;
    parser_ctx->doc_queue_alloc = handler_ctx->doc_queue_alloc;
    /* Restrict ourselves to this host. */
    parser_ctx->hostinfo = url.hostinfo;

    status = apr_thread_mutex_create(&parser_ctx->mutex,
                                     APR_THREAD_MUTEX_DEFAULT, pool);
    if (status) {
        printf("Couldn't create mutex %d\n", status);
        return status;
    }

    status = apr_thread_cond_create(&parser_ctx->condvar, pool);
    if (status) {
        printf("Couldn't create condvar: %d\n", status);
        return status;
    }

    /* Let the handler now which condvar to use. */
    handler_ctx->doc_queue_condvar = parser_ctx->condvar;

    apr_threadattr_create(&tattr, pool);

    /* Start the parser thread. */
    apr_thread_create(&thread[0], tattr, parser_thread, parser_ctx, pool);

    /* Deliver the first request. */
    create_request(url.hostinfo, url.path, NULL, NULL, parser_ctx, pool);

    /* Go run our normal thread. */
    while (1) {
        int tries = 0;

        status = serf_context_run(context, SERF_DURATION_FOREVER, pool);
        if (APR_STATUS_IS_TIMEUP(status))
            continue;
        if (status) {
            char buf[200];

            printf("Error running context: (%d) %s\n", status,
                   apr_strerror(status, buf, sizeof(buf)));
            exit(1);
        }

        /* We run this check to allow our parser threads to add more
         * requests to our queue.
         */
        for (tries = 0; tries < 3; tries++) {
            if (!apr_atomic_read32(handler_ctx->requests_outstanding)) {
#ifdef SERF_VERBOSE
                printf("Waiting...");
#endif
                apr_sleep(100000);
#ifdef SERF_VERBOSE
                printf("Done\n");
#endif
            }
            else {
                break;
            }
        }
        if (tries >= 3) {
            break;
        }
        /* Debugging purposes only! */
        serf_debug__closed_conn(app_ctx.bkt_alloc);
    }

    printf("Quitting...\n");
    serf_connection_close(connection);

    /* wake up the parser via condvar signal */
    apr_thread_cond_signal(parser_ctx->condvar);

    status = apr_thread_join(&parser_status, thread[0]);
    if (status) {
        printf("Error joining thread: %d\n", status);
        return status;
    }

    serf_bucket_mem_free(app_ctx.bkt_alloc, handler_ctx->requests_outstanding);
    serf_bucket_mem_free(app_ctx.bkt_alloc, parser_ctx);

    apr_pool_destroy(pool);
    return 0;
}
Exemplo n.º 9
0
void mapcache_prefetch_tiles(mapcache_context *ctx, mapcache_tile **tiles, int ntiles)
{

  apr_thread_t **threads;
  apr_threadattr_t *thread_attrs;
  int nthreads;
#if !APR_HAS_THREADS
  int i;
  for(i=0; i<ntiles; i++) {
    mapcache_tileset_tile_get(ctx, tiles[i]);
    GC_CHECK_ERROR(ctx);
  }
#else
  int i,rv;
  _thread_tile* thread_tiles;
  if(ntiles==1 || ctx->config->threaded_fetching == 0) {
    /* if threads disabled, or only fetching a single tile, don't launch a thread for the operation */
    for(i=0; i<ntiles; i++) {
      mapcache_tileset_tile_get(ctx, tiles[i]);
      GC_CHECK_ERROR(ctx);
    }
    return;
  }


  /* allocate a thread struct for each tile. Not all will be used */
  thread_tiles = (_thread_tile*)apr_pcalloc(ctx->pool,ntiles*sizeof(_thread_tile));
#if 1 || !USE_THREADPOOL
  /* use multiple threads, to fetch from multiple metatiles and/or multiple tilesets */
  apr_threadattr_create(&thread_attrs, ctx->pool);
  threads = (apr_thread_t**)apr_pcalloc(ctx->pool, ntiles*sizeof(apr_thread_t*));
  nthreads = 0;
  for(i=0; i<ntiles; i++) {
    int j;
    thread_tiles[i].tile = tiles[i];
    thread_tiles[i].launch = 1;
    j=i-1;
    /*
     * we only launch one thread per metatile as in the unseeded case the threads
     * for a same metatile will lock while only a single thread launches the actual
     * rendering request
     */
    while(j>=0) {
      /* check that the given metatile hasn't been rendered yet */
      if(thread_tiles[j].launch &&
          (thread_tiles[i].tile->tileset == thread_tiles[j].tile->tileset) &&
          (thread_tiles[i].tile->x / thread_tiles[i].tile->tileset->metasize_x  ==
           thread_tiles[j].tile->x / thread_tiles[j].tile->tileset->metasize_x)&&
          (thread_tiles[i].tile->y / thread_tiles[i].tile->tileset->metasize_y  ==
           thread_tiles[j].tile->y / thread_tiles[j].tile->tileset->metasize_y)) {
        thread_tiles[i].launch = 0; /* this tile will not have a thread spawned for it */
        break;
      }
      j--;
    }
    if(thread_tiles[i].launch)
      thread_tiles[i].ctx = ctx->clone(ctx);
  }
  for(i=0; i<ntiles; i++) {
    if(!thread_tiles[i].launch) continue; /* skip tiles that have been marked */
    rv = apr_thread_create(&threads[i], thread_attrs, _thread_get_tile, (void*)&(thread_tiles[i]), thread_tiles[i].ctx->pool);
    if(rv != APR_SUCCESS) {
      ctx->set_error(ctx,500, "failed to create thread %d of %d\n",i,ntiles);
      break;
    }
    nthreads++;
  }

  /* wait for launched threads to finish */
  for(i=0; i<ntiles; i++) {
    if(!thread_tiles[i].launch) continue;
    apr_thread_join(&rv, threads[i]);
    if(rv != APR_SUCCESS) {
      ctx->set_error(ctx,500, "thread %d of %d failed on exit\n",i,ntiles);
    }
    if(GC_HAS_ERROR(thread_tiles[i].ctx)) {
      /* transfer error message from child thread to main context */
      ctx->set_error(ctx,thread_tiles[i].ctx->get_error(thread_tiles[i].ctx),
                     thread_tiles[i].ctx->get_error_message(thread_tiles[i].ctx));
    }
  }
  for(i=0; i<ntiles; i++) {
    /* fetch the tiles that did not get a thread launched for them */
    if(thread_tiles[i].launch) continue;
    mapcache_tileset_tile_get(ctx, tiles[i]);
    GC_CHECK_ERROR(ctx);
  }
#else
  /* experimental version using a threadpool, disabled for stability reasons */
  apr_thread_pool_t *thread_pool;
  apr_thread_pool_create(&thread_pool,2,ctx->config->download_threads,ctx->pool);
  for(i=0; i<ntiles; i++) {
    ctx->log(ctx,MAPCACHE_DEBUG,"starting thread for tile %s",tiles[i]->tileset->name);
    thread_tiles[i].tile = tiles[i];
    thread_tiles[i].ctx = ctx->clone(ctx);
    rv = apr_thread_pool_push(thread_pool,_thread_get_tile,(void*)&(thread_tiles[i]), 0,NULL);
    if(rv != APR_SUCCESS) {
      ctx->set_error(ctx,500, "failed to push thread %d of %d in thread pool\n",i,ntiles);
      break;
    }
  }
  GC_CHECK_ERROR(ctx);
  while(apr_thread_pool_tasks_run_count(thread_pool) != ntiles || apr_thread_pool_busy_count(thread_pool)>0)
    apr_sleep(10000);
  apr_thread_pool_destroy(thread_pool);
  for(i=0; i<ntiles; i++) {
    if(GC_HAS_ERROR(thread_tiles[i].ctx)) {
      ctx->set_error(ctx,thread_tiles[i].ctx->get_error(thread_tiles[i].ctx),
                     thread_tiles[i].ctx->get_error_message(thread_tiles[i].ctx));
    }
  }
#endif

#endif

}
Exemplo n.º 10
0
SWITCH_DECLARE(switch_status_t) switch_threadattr_create(switch_threadattr_t ** new_attr, switch_memory_pool_t *pool)
{
	return apr_threadattr_create(new_attr, pool);
}
Exemplo n.º 11
0
void lfd_listen(apr_pool_t * mp)
{
	apr_pool_t		* thd_pool = NULL;
	apr_socket_t		* listen_sock;
	apr_socket_t		* client_sock;
	apr_thread_t *thd;
	apr_threadattr_t	* thattr;
	apr_pollfd_t		  pfd;
	apr_interval_time_t	  timeout = lfd_config_max_acceptloop_timeout;
	apr_int32_t		  nsds;
	apr_status_t		  rc;

	create_listen_socket(&listen_sock, mp);
	if(NULL == listen_sock)
	{
		lfd_log(LFD_ERROR, "lfd_listen: could not create listen socket");
		return;
	}

	rc = apr_threadattr_create(&thattr, mp);
	if(APR_SUCCESS != rc)
	{
		lfd_log_apr_err(rc, "apr_threadattr_create failed");
		return;
	}
	while(1)
	{
		//###: Should I allocate the pool as a subpool of the root pool?
		//What is the amount allocated per pool and is it freed when the child pool is destroyed?
		//rc = apr_pool_create(&thd_pool, mp);
		if(NULL == thd_pool)
		{
			rc = apr_pool_create(&thd_pool, NULL);
			if(APR_SUCCESS != rc)
			{
				lfd_log_apr_err(rc, "apr_pool_create of thd_pool failed");
				continue;
			}
		}

		create_pollfd_from_socket(&pfd, listen_sock, mp);

		rc = apr_poll(&pfd, 1, &nsds, timeout);
		if((APR_SUCCESS != rc) && (!APR_STATUS_IS_TIMEUP(rc)) && (!APR_STATUS_IS_EINTR(rc)))
		{
			//break - an unrecoverable error occured
			lfd_log_apr_err(rc, "apr_poll failed");
			break;
		}

		if(apr_atomic_read32(&ftp_must_exit))
		{
			//if the flag says we must exit, we comply, so bye bye!
			return;
		}
		if(APR_STATUS_IS_TIMEUP(rc) || APR_STATUS_IS_EINTR(rc) || (APR_POLLIN != pfd.rtnevents))
		{
			continue;
		}


		rc = apr_socket_accept(&client_sock, listen_sock, thd_pool);
		if(APR_SUCCESS != rc)
		{
			//###: For which errorcode must we break out of the loop?
			lfd_log_apr_err(rc, "apr_socket_accept failed");
			if(APR_STATUS_IS_EAGAIN(rc))
			{
				lfd_log(LFD_ERROR, "lfd_listen: APR_STATUS_IS_EAGAIN");
			}
			continue;
		}
		rc = apr_thread_create(&thd, thattr, &lfd_worker_protocol_main, (void*)client_sock, thd_pool);
		if(APR_SUCCESS != rc)
		{
			lfd_log_apr_err(rc, "apr_thread_create failed");
			apr_socket_close(client_sock);
			continue;
		}
		thd_pool = NULL;
	}
}
void * CALLBACK mosquitto_on_connect(const WebSocketServer *server)
{
  MosquittoData *dib = NULL;
  apr_sockaddr_t *sa;

  if ((server != NULL) && (server->version == WEBSOCKET_SERVER_VERSION_1)) {
    /* Get access to the request_rec strucure for this connection */
    request_rec *r = server->request(server);

    if (r != NULL) {
      apr_pool_t *pool = NULL;
      size_t i, count = server->protocol_count(server);

      /* Only support "mqtt" */
      for (i = 0; i < count; i++) {
        const char *protocol = server->protocol_index(server, i);

        if ((protocol != NULL) &&
            (strncmp(protocol, "mqtt",4) == 0)) {
          /* If the client can speak the protocol, set it in the response */
          server->protocol_set(server, protocol);
          break;
        }
      }
      /* If the protocol negotiation worked, create a new memory pool */
      if ((i < count) &&
          (apr_pool_create(&pool, r->pool) == APR_SUCCESS)) {
        /* Allocate memory to hold mosquitto state */
        if ((dib = (MosquittoData *) apr_palloc(pool, sizeof(MosquittoData))) != NULL) {
          apr_thread_t *thread = NULL;
          apr_threadattr_t *thread_attr = NULL;

          dib->server = server;
          dib->pool = pool;
          dib->thread = NULL;
          dib->counter = 0;
          dib->active = 1;

		  request_rec *r = server->request(server);
		  mosquitto_cfg* dir = ap_get_module_config(r->per_dir_config, &mod_websocket_mosquitto) ;
		  
		  int rv = apr_sockaddr_info_get(&sa,dir->broker,APR_UNSPEC,atoi(dir->port),APR_IPV6_ADDR_OK ,pool);
		  if (rv)
			  ap_log_error(APLOG_MARK, APLOG_CRIT,0,NULL,"apr_sockaddr_info_get failed #%x",rv);
		  else
			  ap_log_error(APLOG_MARK, APLOG_DEBUG,0,NULL,"Address family %s",sa->family == APR_INET6 ? "IPv6" : "IPv4");

		  rv = apr_socket_create(&dib->sockfd,sa->family, SOCK_STREAM, APR_PROTO_TCP,pool);
		  if (rv) ap_log_error(APLOG_MARK, APLOG_CRIT,0,NULL,"apr_socket_create failed #%x",rv);
		  
		  rv = apr_socket_connect(dib->sockfd,sa);
		  if (rv) ap_log_error(APLOG_MARK, APLOG_CRIT,0,NULL,"apr_socket_connect failed #%x",rv);
		  			
          /* Create a non-detached thread that will perform the work */
          if ((apr_threadattr_create(&thread_attr, pool) == APR_SUCCESS) &&
              (apr_threadattr_detach_set(thread_attr, 0) == APR_SUCCESS) &&
              (apr_thread_create(&thread, thread_attr, mosquitto_run, dib, pool) == APR_SUCCESS)) {
            dib->thread = thread;
            /* Success */
            pool = NULL;
          } else {
            dib = NULL;
          }
        }
        if (pool != NULL) {
          apr_pool_destroy(pool);
        }
      }
    }
  }
  return dib;
}
Exemplo n.º 13
0
static int process_security_handler(request_rec *r)
{
    int i;
    const char *extension;
    apr_threadattr_t *thread_attr;
    apr_thread_t *thread;
    apr_status_t status, thread_status;

    int enable   = 0;
    int name_len = 0;

    process_security_config_t *conf = ap_get_module_config(r->server->module_config, &process_security_module);

    if (thread_on)
        return DECLINED;

    if (conf->all_ext_enable) {
        enable = ON;
    } else {
        for (i = 0; i < conf->extensions->nelts; i++) {
            extension = ((char **)conf->extensions->elts)[i];
            name_len = strlen(r->filename) - strlen(extension);
            if (name_len >= 0 && strcmp(&r->filename[name_len], extension) == 0)
                enable = ON;
        }
    }

    if (!enable)
        return DECLINED;

    apr_threadattr_create(&thread_attr, r->pool);
    apr_threadattr_detach_set(thread_attr, 0);

    status = apr_thread_create(&thread
            , thread_attr
            , process_security_thread_handler
            , r
            , r->pool);

    if (status != APR_SUCCESS) {
        ap_log_error (APLOG_MARK
            , APLOG_ERR
            , 0
            , NULL
            , "%s ERROR %s: Unable to create a thread"
            , MODULE_NAME
            , __func__
        );
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    status = apr_thread_join(&thread_status, thread);

    if (status != APR_SUCCESS) {
        ap_log_error (APLOG_MARK
            , APLOG_ERR
            , 0
            , NULL
            , "%s ERROR %s: Unable to join a thread"
            , MODULE_NAME
            , __func__
        );
        r->connection->aborted = 1;
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    return thread_status;
}
Exemplo n.º 14
0
static int build_startup_data(const WebSocketServer *server) {

    apr_pool_t *main_pool = NULL;                                                
    apr_pool_t *stateful_session_pool = NULL;                                                
    apr_thread_t *thread = NULL;
    apr_threadattr_t *thread_attr = NULL;
    apr_thread_mutex_t *mutex = NULL;
    request_rec *r = server->request(server);

    // create a pool for our translator data
    // Do not use r->pool as the parent, since r->pool will be freed
    // when the current client disconnects.
    if (apr_pool_create(&main_pool, NULL) != APR_SUCCESS) {
        osrfLogError(OSRF_LOG_MARK, "WS Unable to create apr_pool");
        return 1;
    }

    trans = (osrfWebsocketTranslator*) 
        apr_palloc(main_pool, sizeof(osrfWebsocketTranslator));

    if (trans == NULL) {
        osrfLogError(OSRF_LOG_MARK, "WS Unable to create translator");
        return 1;
    }

    trans->server = server;
    trans->main_pool = main_pool;
    trans->osrf_router = osrfConfigGetValue(NULL, "/router_name");                      
    trans->osrf_domain = osrfConfigGetValue(NULL, "/domain");

    // opensrf session / recipient cache
    trans->stateful_session_cache = apr_hash_make(trans->main_pool);
    if (trans->stateful_session_cache == NULL) {
        osrfLogError(OSRF_LOG_MARK, "WS unable to create session cache");
        return 1;
    }

    // opensrf session / recipient string pool; cleared regularly
    // the only data entering this pools are the session strings.
    if (apr_pool_create(&stateful_session_pool, trans->main_pool) != APR_SUCCESS) {
        osrfLogError(OSRF_LOG_MARK, "WS Unable to create apr_pool");
        return NULL;
    }
    trans->stateful_session_pool = stateful_session_pool;

    if (apr_thread_mutex_create(
            &mutex, APR_THREAD_MUTEX_UNNESTED, 
            trans->main_pool) != APR_SUCCESS) {
        osrfLogError(OSRF_LOG_MARK, "WS unable to create thread mutex");
        return 1;
    }
    trans->mutex = mutex;

    // responder thread
    if ( (apr_threadattr_create(&thread_attr, trans->main_pool) == APR_SUCCESS) &&
         (apr_threadattr_detach_set(thread_attr, 0) == APR_SUCCESS) &&
         (apr_thread_create(&thread, thread_attr, 
                osrf_responder_thread_main, trans, trans->main_pool) == APR_SUCCESS)) {

        trans->responder_thread = thread;
        
    } else {
        osrfLogError(OSRF_LOG_MARK, "WS unable to create responder thread");
        return 1;
    }

    // idle timeout thread
    thread = NULL; // reset
    thread_attr = NULL; // reset
    if ( (apr_threadattr_create(&thread_attr, trans->main_pool) == APR_SUCCESS) &&
         (apr_threadattr_detach_set(thread_attr, 0) == APR_SUCCESS) &&
         (apr_thread_create(&thread, thread_attr, 
            osrf_idle_timeout_thread_main, trans, trans->main_pool) == APR_SUCCESS)) {

        osrfLogDebug(OSRF_LOG_MARK, "WS created idle timeout thread");
        trans->idle_timeout_thread = thread;
        
    } else {
        osrfLogError(OSRF_LOG_MARK, "WS unable to create idle timeout thread");
        return 1;
    }

    return APR_SUCCESS;
}
void *CALLBACK tcp_proxy_on_connect(const WebSocketServer * server)
{
    TcpProxyData *tpd = NULL;

    if ((server != NULL) && (server->version == WEBSOCKET_SERVER_VERSION_1)) {
        /* Get access to the request_rec strucure for this connection */
        request_rec *r = server->request(server);

        APACHELOG(APLOG_DEBUG, r, "tcp_proxy_on_connect starting");

        if (r != NULL) {

            apr_pool_t *pool = NULL;
            size_t i = 0, count = server->protocol_count(server);

            websocket_tcp_proxy_config_rec *conf =
                (websocket_tcp_proxy_config_rec *) ap_get_module_config(r->
                                                                        per_dir_config,
                                                                        &websocket_tcp_proxy_module);
            const char *requiredprotocol = conf ? conf->protocol : NULL;

            if (requiredprotocol) {
                for (i = 0; i < count; i++) {
                    const char *protocol = server->protocol_index(server, i);

                    if (protocol && (strcmp(protocol, requiredprotocol) == 0)) {
                        /* If the client can speak the protocol, set it in the response */
                        server->protocol_set(server, protocol);
                        break;
                    }
                }
            }
            else {
                count = 1;      /* ensure i<count */
            }

            /* If the protocol negotiation worked, create a new memory pool */
            if ((i < count) &&
                (apr_pool_create(&pool, r->pool) == APR_SUCCESS)) {

                APACHELOG(APLOG_DEBUG, r,
                          "tcp_proxy_on_connect protocol correct");

                /* Allocate memory to hold the tcp proxy state */
                if ((tpd =
                     (TcpProxyData *) apr_palloc(pool,
                                                 sizeof(TcpProxyData))) !=
                    NULL) {
                    apr_thread_t *thread = NULL;
                    apr_threadattr_t *thread_attr = NULL;

                    tpd->server = server;
                    tpd->pool = pool;
                    tpd->thread = NULL;
                    tpd->tcpsocket = NULL;
                    tpd->active = 1;
                    tpd->base64 = 0;
                    tpd->timeout = 30;
                    tpd->port = "echo";
                    tpd->host = "127.0.0.1";
                    tpd->initialdata = NULL;

                    websocket_tcp_proxy_config_rec *conf =
                        (websocket_tcp_proxy_config_rec *)
                        ap_get_module_config(r->per_dir_config,
                                             &websocket_tcp_proxy_module);
                    if (conf) {
                        tpd->base64 = conf->base64;
                        tpd->timeout = conf->timeout;
                        if (conf->host)
                            tpd->host = apr_pstrdup(pool, conf->host);
                        if (conf->port)
                            tpd->port = apr_pstrdup(pool, conf->port);
                        APACHELOG(APLOG_DEBUG, r,
                                  "tcp_proxy_on_connect: base64 is %d",
                                  conf->base64);
                    }
                    else {
                        APACHELOG(APLOG_DEBUG, r,
                                  "tcp_proxy_on_connect: no config");
                    }

                    /* Check we can authenticate the incoming user (this is a hook for others to add to)
                     * Check we can connect
                     * And if we have initial data to send, then send that
                     */
                    if ((APR_SUCCESS ==
                         tcp_proxy_do_authenticate(r, tpd, pool))
                        && (APR_SUCCESS ==
                            tcp_proxy_do_tcp_connect(r, tpd, pool))
                        && (APR_SUCCESS ==
                            tcp_proxy_send_initial_data(r, tpd, pool))) {

                        /* Create a non-detached thread that will perform the work */
                        if ((apr_threadattr_create(&thread_attr, pool) ==
                             APR_SUCCESS)
                            && (apr_threadattr_detach_set(thread_attr, 0) ==
                                APR_SUCCESS)
                            &&
                            (apr_thread_create
                             (&thread, thread_attr, tcp_proxy_run, tpd,
                              pool) == APR_SUCCESS)) {
                            tpd->thread = thread;
                            /* Success */
                            pool = NULL;
                        }
                        else {
                            tpd = NULL;
                        }
                    }
                    else
                        tpd = NULL;
                }
                if (pool != NULL) {
                    apr_pool_destroy(pool);
                }
            }
        }
    }
    return tpd;
}