Пример #1
0
static int
do_one_test (void)
{
  in_sh_body = 0;
  cleanups = 0;
  if (pipe (fd) != 0 || pipe (fd + 2) != 0)
    {
      puts ("pipe failed");
      return 1;
    }

  pthread_t th;
  if (pthread_create (&th, NULL, tf, NULL) != 0)
    {
      puts ("create failed");
      return 1;
    }

  int r = pthread_barrier_wait (&b);
  if (r != 0 && r != PTHREAD_BARRIER_SERIAL_THREAD)
    {
      puts ("parent thread: barrier_wait failed");
      return 1;
    }

  sleep (1);

  r = pthread_kill (th, SIGHUP);
  if (r)
    {
      errno = r;
      printf ("pthread_kill failed %m\n");
      return 1;
    }

  while (in_sh_body == 0)
    sleep (1);

  if (pthread_cancel (th) != 0)
    {
      puts ("cancel failed");
      return 1;
    }

  void *ret;
  if (pthread_join (th, &ret) != 0)
    {
      puts ("join failed");
      return 1;
    }

  if (ret != PTHREAD_CANCELED)
    {
      puts ("result is wrong");
      return 1;
    }

  if (cleanups != 0x1234L)
    {
      printf ("called cleanups %lx\n", cleanups);
      return 1;
    }

  /* The pipe closing must be issued after the cancellation handling to avoid
     a race condition where the cancellation runs after both pipe ends are
     closed.  In this case the read syscall returns EOF and the cancellation
     must not act.  */
  close (fd[0]);
  close (fd[1]);
  close (fd[2]);
  close (fd[3]);

  return 0;
}
Пример #2
0
	void cancel() { if (running()) pthread_cancel(_thread); }
Пример #3
0
static void limitMonitorJoin(void)
{
    pthread_cancel(limit_monitor.th);
    pthread_join(limit_monitor.th, NULL);
    pthread_mutex_destroy(&limit_monitor.lock);
}
Пример #4
0
int16 XSERDPort::open(uint16 config)
{
	// Don't open NULL name devices
	if (device_name == NULL)
		return openErr;

	// Init variables
	io_killed = false;
	quitting = false;

	// Open port, according to the syntax of the path
	if (device_name[0] == '|') {
		// Open a process via ptys
		if (!open_pty())
			goto open_error;
	}
	else if (!strcmp(device_name, "midi")) {
		// MIDI:  not yet implemented
		return openErr;
	}
	else {
		// Device special file
		fd = ::open(device_name, O_RDWR);
		if (fd < 0)
			goto open_error;

#if defined(__linux__)
		// Parallel port?
		struct stat st;
		if (fstat(fd, &st) == 0)
			if (S_ISCHR(st.st_mode))
				protocol = ((MAJOR(st.st_rdev) == LP_MAJOR) ? parallel : serial);
#elif defined(__FreeBSD__) || defined(__NetBSD__)
		// Parallel port?
		struct stat st;
		if (fstat(fd, &st) == 0)
			if (S_ISCHR(st.st_mode))
				protocol = (((st.st_rdev >> 16) == 16) ? parallel : serial);
#endif
	}

	// Configure port for raw mode
	if (protocol == serial || protocol == pty) {
		if (tcgetattr(fd, &mode) < 0)
			goto open_error;
		cfmakeraw(&mode);
		mode.c_cflag |= HUPCL;
		mode.c_cc[VMIN] = 1;
		mode.c_cc[VTIME] = 0;
		tcsetattr(fd, TCSAFLUSH, &mode);
	}
	configure(config);

	// Start input/output threads
	input_thread_cancel = false;
	output_thread_cancel = false;
	if (sem_init(&input_signal, 0, 0) < 0)
		goto open_error;
	if (sem_init(&output_signal, 0, 0) < 0)
		goto open_error;
	input_thread_active = (pthread_create(&input_thread, &thread_attr, input_func, this) == 0);
	output_thread_active = (pthread_create(&output_thread, &thread_attr, output_func, this) == 0);
	if (!input_thread_active || !output_thread_active)
		goto open_error;
	return noErr;

open_error:
	if (input_thread_active) {
		input_thread_cancel = true;
#ifdef HAVE_PTHREAD_CANCEL
		pthread_cancel(input_thread);
#endif
		pthread_join(input_thread, NULL);
		sem_destroy(&input_signal);
		input_thread_active = false;
	}
	if (output_thread_active) {
		output_thread_cancel = true;
#ifdef HAVE_PTHREAD_CANCEL
		pthread_cancel(output_thread);
#endif
		pthread_join(output_thread, NULL);
		sem_destroy(&output_signal);
		output_thread_active = false;
	}
	if (fd > 0) {
		::close(fd);
		fd = -1;
	}
	return openErr;
}
Пример #5
0
void discovery_stop(discovery_t* self) {
  assert(self);

  pthread_cancel(self->thread);
}
Пример #6
0
static int youtube_exitMenu( interfaceMenu_t* pMenu, void *pArg )
{
	youtubeInfo.search[0] = 0;
	pthread_cancel( youtubeInfo.search_thread );
	return 0;
}
Пример #7
0
static void spi_console_exit(int sig)
{
	DEBUG_PRINT("Get SIGINT.\n");
	pthread_cancel(spi_bridge.read_mcu_tidp);
	pthread_cancel(spi_bridge.read_stdin_tidp);
}
Пример #8
0
/* Marks a thread as cancelled. Next time the target thread reaches a
 * cancellation point (while not having disabled cancellation), it will
 * run its cancellation cleanup handler, the thread variable destructors, and
 * terminate. vlc_join() must be used afterward regardless of a thread being
 * cancelled or not. */
void vlc_cancel (vlc_thread_t thread_id)
{
    pthread_cancel (thread_id);
}
Пример #9
0
/*
 * main
 */
int main(int argc, char **argv)
{
	int ret, dns_index = -1, host_port = 22;
	int udp_client_sock = -1, tcp_dns_sock = -1;
	ssize_t recv_size;
	char buf[1024], host_ip[15], username[NAME_MAX];
	struct sockaddr_in saddr;
	pthread_t log_thread;
	void *status;

	progname = argv[0];

	ret = set_signal_handler();
	if (ret < 0) {
		goto error;
	}

	init_default_values();

	ret = parse_args(argc, (const char **)argv);
	if (ret < 0) {
		goto error;
	}

	if (ssh_host != NULL) {
		ret = parse_ssh_host(host_ip, &host_port, username);
		if (ret < 0) {
			usage(stderr);
			goto error;
		}

		/* Setup SSH forward tunneling */
		ssh_info = setup_forward_ssh(host_ip, host_port, username, dns_ip);
		if (ssh_info == NULL) {
			goto error;
		}
	} else {
		/* Connect to forward TCP server */
		tcp_dns_sock = setup_forward_tcp(forward_port, forward_ip);
		if (tcp_dns_sock < 0) {
			goto error;
		}
		DBG("Connected TCP tunnel on %s:%d",
				forward_ip, forward_port);
	}

	/* Logging is used with libnetfilter queue */
	if (opt_logname != NULL && opt_netfilter == -1) {
		opt_netfilter = DEFAULT_NETFILTER_QUEUE_NUM;
	}

	if (opt_netfilter != -1) {
		ret = snprintf(buf, sizeof(buf), IPTABLE_ADD_QUEUE,
				local_port, opt_netfilter);
		if (ret < 0) {
			perror("snprintf iptable rule");
			goto error;
		}
		ret = system(buf);
		if (ret != 0) {
			ERR("NFQUEUE iptables command failed\n%s", buf);
			goto error;
		}
		DBG("Queuing UDP traffic on port 53 on queue num %d",
				opt_netfilter);

		ret = start_logging_thread(&log_thread);
		if (ret < 0) {
			goto error;
		}
	}

	/*
	 * iptables DNAT option. This will redirect all UDP port 53 traffic to the
	 * local-port.
	 */
	if (opt_dnat) {
		/* Execute iptable rule */
		ret = snprintf(buf, sizeof(buf), IPTABLE_ADD_DNAT,
				local_ip, local_port);
		if (ret < 0) {
			perror("snprintf iptable rule");
			goto error;
		}

		ret = system(buf);
		if (ret != 0) {
			ERR("DNAT iptables command failed\n%s", buf);
			goto error;
		}
		DBG("Redirecting all UDP traffic on port 53 to %s:%d",
				local_ip, local_port);
	}

	/* Bind on local port to catch DNS request from client */
	udp_client_sock = dns_client_setup(local_port, local_ip);
	if (udp_client_sock < 0) {
		goto error;
	}
	fprintf(stderr, "Listening for DNS request on UDP port %d\n", local_port);

	while (1) {
		/* Reset buffer */
		memset(buf, 0, sizeof(buf));

		/* Receive DNS UDP request */
		recv_size = dns_udp_recv_query(udp_client_sock, buf, sizeof(buf),
				(struct sockaddr *) &saddr);
		if (recv_size < 0) {
			/* At this point... better clean exit */
			goto error;
		}

		/* Change buf to fit DNS TCP request */
		forge_tcp_request(buf, &recv_size);

		/*
		 * Make the DNS query on the TCP transport layer either using inprocess
		 * SSH or using an already created TCP tunnel (Ex: ssh -L ... on the
		 * command line).
		 */
		if (ssh_host != NULL) {
			/*
			 * Round robin option. We must create the ssh tunnel and close it
			 * at each DNS query.
			 */
			if (opt_rr_dns) {
				if ((open_dns_count - dns_index) == 0) {
					dns_index = 0;
				}

				/*
				 * We don't create a new SSH channel for the first run since it
				 * was created before the main loop hence the reason for
				 * dns_index being -1.
				 */
				if (dns_index != -1) {
					dns_ip = open_dns_list[dns_index];
					/*
					 * Create new SSH direct tcp channel. We don't care about
					 * the return value because on error, the next call will
					 * handle it.
					 */
					libssh2_channel_free(ssh_info->channel);
					ret = ssh_setup_tunnel(ssh_info, dns_ip);
					if (ret < 0) {
						continue;
					}
					DBG("Round robin DNS %s", dns_ip);
				}
				dns_index++;
			}
			recv_size = dig_ssh_request(ssh_info, buf, sizeof(buf),
					recv_size);
			if (ret < 0) {
				do {
					sleep(DEFAULT_RECONNECT_TIME);
					ret = ssh_setup_tunnel(ssh_info, dns_ip);
				} while (ret < 0);
				continue;
			}
		} else {
			recv_size = dig_tcp_request(tcp_dns_sock, buf, sizeof(buf),
					recv_size);
			if (recv_size < 0) {
				/* Connect to forward TCP server */
				do {
					/* Retry every DEFAULT_RECONNECT_TIME sec */
					sleep(DEFAULT_RECONNECT_TIME);
					tcp_dns_sock = setup_forward_tcp(forward_port, forward_ip);
				} while (tcp_dns_sock < 0);
				continue;
			}
		}

		/* Change buf to fit DNS UDP request */
		forge_udp_request(buf, &recv_size);

		ret = dns_udp_send_reply(udp_client_sock, buf, recv_size,
				(struct sockaddr *) &saddr, sizeof(saddr));
		if (ret < 0) {
			/* UDP client disconnected, continue serving */
			continue;
		}
	}

	/* Not suppose to get here */

error:
	ret = pthread_cancel(log_thread);
	if (ret == 0) {
		pthread_join(log_thread, &status);
	}
	close(tcp_dns_sock);
	close(udp_client_sock);

	cleanup(ret);

	return 0;
}
Пример #10
0
/* this stops the logger thread. hard. */
int msg_thread_stop(void)
{
	return(pthread_cancel(log_thread));
}
Пример #11
0
myhtml_status_t myhtml_thread_cancel(mythread_t *mythread, mythread_list_t *thr)
{
    pthread_cancel(thr->pth);
    return MyHTML_STATUS_OK;
}
Пример #12
0
void fullscrape_deinit( ) {
  pthread_cancel( thread_id );
}
Пример #13
0
void Thread::OnStop()
{
	TRACE_BEGIN( LOG_LVL_INFO );	
	pthread_cancel( mThread );
}
Пример #14
0
int
test_cleanup1(void)
#endif
{
    int failed = 0;
    int i;
    pthread_t t[NUMTHREADS + 1];

    memset(&pop_count, 0, sizeof(sharedInt_t));

    InitializeCriticalSection(&pop_count.cs);

    assert((t[0] = pthread_self()).p != NULL);

    for (i = 1; i <= NUMTHREADS; i++)
    {
        threadbag[i].started = 0;
        threadbag[i].threadnum = i;
        assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0);
    }

    /*
     * Code to control or manipulate child threads should probably go here.
     */
    Sleep(500);

    for (i = 1; i <= NUMTHREADS; i++)
    {
        assert(pthread_cancel(t[i]) == 0);
    }

    /*
     * Give threads time to run.
     */
    Sleep(NUMTHREADS * 100);

    /*
     * Standard check that all threads started.
     */
    for (i = 1; i <= NUMTHREADS; i++)
    {
        if (!threadbag[i].started)
        {
            failed |= !threadbag[i].started;
            fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started);
        }
    }

    assert(!failed);

    /*
     * Check any results here. Set "failed" and only print output on failure.
     */
    failed = 0;
    for (i = 1; i <= NUMTHREADS; i++)
    {
        int fail = 0;
        void* result = (void*)0;

        assert(pthread_join(t[i], &result) == 0);

        fail = (result != PTHREAD_CANCELED);

        if (fail)
        {
            fprintf(stderr, "Thread %d: started %d: result %d\n",
                    i,
                    threadbag[i].started,
                    (int)(size_t)result);
        }
        failed = (failed || fail);
    }

    assert(!failed);

    assert(pop_count.i == NUMTHREADS);

    DeleteCriticalSection(&pop_count.cs);

    /*
     * Success.
     */
    return 0;
}
Пример #15
0
int main()
{
	int num,i = 0;
	char tmp[MAX_TH_NUM];
	times = 1;
	num = 2;
	printf("Usage:\n"
		"\tgo: start test\n"
		"\tabort: cancel thread\n"
		"\tstatus: show test status\n"
		"\texit: exit the program\n"
		"\tthread n: create n threads to test\n"
		"\ttimes n: each mem unit tests n times\n"
		"Default: 1 times and 2 threads\n"
		);
	fflush(stdout);
	while(1)
	{
		printf(">>>");
		fflush(stdout);
		scanf(" %s",tmp);
		if(strcmp(tmp,"times") == 0)
		{
			scanf(" %d",&times);
			continue;
		}
		if(strcmp(tmp,"thread") == 0)
		{
			scanf(" %d",&num);
			continue;
		}
		if(strcmp(tmp,"exit") == 0)
		{
			exit(0);
		}
		if(strcmp(tmp,"go") == 0)
		{
			for(i=0;i<num;i++)
			{
				test_addr[i] = (unsigned long) malloc(MEM_SIZE*sizeof(unsigned char));
				pthread_create(&tid[i],memtest,test_addr[i]);
			}
			continue;
		}
		if(strcmp(tmp,"status") == 0)
		{
			for(i=0;i<num;i++)
			{
				printf("Thread %d :  ",tid[i]);
				switch(pthread_status(tid[i]))
				{
					case -1: 
						printf("is to be created\n");
						break;
					case 0: 
						printf("is running\n");
						break;
					case 1:
						printf("is waiting\n");
						break;
					case 2:
						printf("is waiting\n");
						break;
					case 4:
						printf("is stopped\n");
						pthread_join(tid[i],&result[i]);
						printf("\tTest Addr: %X Result: %d/%d(OK)\n",test_addr[i],result[i],MEM_SIZE);
						break;
					case 5:
						printf("is canceled\n");
						break;
					default:
						printf("no such thread\n");
						break;
				}
			}
			continue;
		}
		if(strcmp(tmp,"abort") == 0)
		{
			for(i=0;i<num;i++)
			{
				if(tid[i])
				{
					pthread_cancel(tid[i]);
				}
			}
			continue;
		}
	}
	
}
Пример #16
0
static void cancel_all_threads()
{
     int i = 0;
     int wait_listener_time = 10000;
     int wait_for_workers = CHILD_SHUTDOWN_TIMEOUT>5?CHILD_SHUTDOWN_TIMEOUT:5;
     int servers_running;
     /*Cancel listener thread .... */
     /*we are going to wait maximum about 10 ms */
     while (wait_listener_time > 0 && listener_running != 0) {
          /*Interrupt listener if it is waiting for threads or 
             waiting to accept new connections */
#ifdef SINGLE_ACCEPT
          pthread_cancel(listener_thread_id);   /*..... */
#else
          pthread_kill(listener_thread_id, SIGHUP);
#endif
          ci_thread_cond_signal(&free_server_cond);
          ci_usleep(1000);
          wait_listener_time -= 10;
     }
     if (listener_running == 0) {
          ci_debug_printf(5,
                          "Going to wait for the listener thread (pid: %d) to exit!\n",
                          threads_list[0]->srv_id);
          ci_thread_join(listener_thread_id);
          ci_debug_printf(5, "OK, cancelling the listener thread (pid: %d)!\n",
                          threads_list[0]->srv_id);
     }
     else {
          /*f**k the listener! going down ..... */
     }

     /*We are going to interupt the waiting for queue childs.
        We are going to wait threads which serve a request. */
     ci_thread_cond_broadcast(&(con_queue->queue_cond));
     /*wait for a milisecond*/
     ci_usleep(1000);
     servers_running = CI_CONF.THREADS_PER_CHILD;
     while (servers_running && wait_for_workers >= 0) {
         /*child_data->to_be_killed, may change while we are inside this loop*/
         if (child_data->to_be_killed == IMMEDIATELY) {
             CHILD_HALT = 1;
         }
         for (i=0; i<CI_CONF.THREADS_PER_CHILD; i++) {
             if (threads_list[i] != NULL) { /* if the i thread is still alive*/
                 if (!threads_list[i]->running) { /*if the i thread is not running any more*/
                     ci_debug_printf(5, "Cancel server %d, thread_id %lu (%d)\n",
                                     threads_list[i]->srv_id, threads_list[i]->srv_pthread,
                                     i);
                     ci_thread_join(threads_list[i]->srv_pthread);
                     release_thread_i(i);
                     servers_running --;
                 }
                 else if (child_data->to_be_killed == IMMEDIATELY){ 
                     /*The thread is still running, and we have a timeout for waiting 
                       the thread to exit. */
                     if (wait_for_workers <= 2) {
                         ci_debug_printf(5, "Thread %ld still running near the timeout. Try to kill it\n", threads_list[i]->srv_pthread);
                         pthread_kill( threads_list[i]->srv_pthread, SIGTERM);
                     }
                 }
             }/*the i thread is still alive*/
         } /* for(i=0;i< CI_CONF.THREADS_PER_CHILD;i++)*/

         /*wait for 1 second for the next round*/
         ci_usleep(999999);

         /*
           The child_data->to_be_killed may change while we are running this function.
           In the case it has/got the value IMMEDIATELY decrease wait_for_workers:
         */
         if (child_data->to_be_killed == IMMEDIATELY)
             wait_for_workers --;
         
     } /* while(servers_running)*/

     if (servers_running) {
         ci_debug_printf(5, "Not all the servers canceled. Anyway exiting....\n");
     }
     else {
         ci_debug_printf(5, "All servers canceled\n");
         free(threads_list);
     }
}
Пример #17
0
void *restore_thrd(void *arg) {
	sigset_t sigmask, old_mask;
	int i, sig;

	sigemptyset(&sigmask);
	sigaddset(&sigmask, SIGINT);
	sigaddset(&sigmask, SIGTERM);
	sigaddset(&sigmask, SIGUSR1);
	pthread_sigmask(SIG_BLOCK, &sigmask, &old_mask);

	while (1) {
		sigwait(&sigmask, &sig);

		if ((sig == SIGINT || sig == SIGTERM) && !interrupted) {
			ERROR("Interrupting will restore original " "filesystem!\n");
			ERROR("Interrupt again to quit\n");
			interrupted = TRUE;
			continue;
		}

		/* kill main thread/worker threads and restore */
		set_progressbar_state(FALSE);
		disable_info();

		/* first kill the reader thread */
		pthread_cancel(reader_thread);
		pthread_join(reader_thread, NULL);

		/*
		 * then flush the reader to deflator thread(s) output queue.
		 * The deflator thread(s) will idle
		 */
		queue_flush(to_deflate);

		/* now kill the deflator thread(s) */
		for (i = 0; i < processors; i++)
			pthread_cancel(deflator_thread[i]);
		for (i = 0; i < processors; i++)
			pthread_join(deflator_thread[i], NULL);

		/*
		 * then flush the reader to process fragment thread(s) output
		 * queue.  The process fragment thread(s) will idle
		 */
		queue_flush(to_process_frag);

		/* now kill the process fragment thread(s) */
		for (i = 0; i < processors; i++)
			pthread_cancel(frag_thread[i]);
		for (i = 0; i < processors; i++)
			pthread_join(frag_thread[i], NULL);

		/*
		 * then flush the reader/deflator/process fragment to main
		 * thread output queue.  The main thread will idle
		 */
		seq_queue_flush(to_main);

		/* now kill the main thread */
		pthread_cancel(main_thread);
		pthread_join(main_thread, NULL);

		/* then flush the main thread to fragment deflator thread(s)
		 * queue.  The fragment deflator thread(s) will idle
		 */
		queue_flush(to_frag);

		/* now kill the fragment deflator thread(s) */
		for (i = 0; i < processors; i++)
			pthread_cancel(frag_deflator_thread[i]);
		for (i = 0; i < processors; i++)
			pthread_join(frag_deflator_thread[i], NULL);

		/*
		 * then flush the main thread/fragment deflator thread(s)
		 * to writer thread queue.  The writer thread will idle
		 */
		queue_flush(to_writer);

		/* now kill the writer thread */
		pthread_cancel(writer_thread);
		pthread_join(writer_thread, NULL);

		TRACE("All threads cancelled\n");

		restorefs();
	}
}
Пример #18
0
static int
ssh_aes_ctr_init(EVP_CIPHER_CTX *ctx, const u_char *key, const u_char *iv,
    int enc)
{
	struct ssh_aes_ctr_ctx *c;
	int i;

	if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) {
		c = xmalloc(sizeof(*c));

		c->state = HAVE_NONE;
		for (i = 0; i < NUMKQ; i++) {
			pthread_mutex_init(&c->q[i].lock, NULL);
			pthread_cond_init(&c->q[i].cond, NULL);
		}

		STATS_INIT(c->stats);
		
		EVP_CIPHER_CTX_set_app_data(ctx, c);
	}

	if (c->state == (HAVE_KEY | HAVE_IV)) {
		/* Cancel pregen threads */
		for (i = 0; i < CIPHER_THREADS; i++)
			pthread_cancel(c->tid[i]);
		for (i = 0; i < CIPHER_THREADS; i++)
			pthread_join(c->tid[i], NULL);
		/* Start over getting key & iv */
		c->state = HAVE_NONE;
	}

	if (key != NULL) {
		AES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8,
		    &c->aes_ctx);
		c->state |= HAVE_KEY;
	}

	if (iv != NULL) {
		memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
		c->state |= HAVE_IV;
	}

	if (c->state == (HAVE_KEY | HAVE_IV)) {
		/* Clear queues */
		memcpy(c->q[0].ctr, ctx->iv, AES_BLOCK_SIZE);
		c->q[0].qstate = KQINIT;
		for (i = 1; i < NUMKQ; i++) {
			memcpy(c->q[i].ctr, ctx->iv, AES_BLOCK_SIZE);
			ssh_ctr_add(c->q[i].ctr, i * KQLEN, AES_BLOCK_SIZE);
			c->q[i].qstate = KQEMPTY;
		}
		c->qidx = 0;
		c->ridx = 0;

		/* Start threads */
		for (i = 0; i < CIPHER_THREADS; i++) {
			pthread_create(&c->tid[i], NULL, thread_loop, c);
		}
		pthread_mutex_lock(&c->q[0].lock);
		while (c->q[0].qstate != KQDRAINING)
			pthread_cond_wait(&c->q[0].cond, &c->q[0].lock);
		pthread_mutex_unlock(&c->q[0].lock);
		
	}
	return (1);
}
Пример #19
0
result_t *
sandbox_execute(sandbox_t * psbox)
{
    FUNC_BEGIN("sandbox_execute(%p)", psbox);

    assert(psbox);

    if (psbox == NULL)
    {
        WARNING("psbox: bad pointer");
        FUNC_RET(NULL, "sandbox_execute()");
    }

    if (!sandbox_check(psbox))
    {
        WARNING("sandbox pre-execution state check failed");
        FUNC_RET(&psbox->result, "sandbox_execute()");
    }

#ifdef WITH_CUSTOM_MONITOR
    pthread_t tid;

    if (pthread_create(&tid, NULL, psbox->ctrl.monitor, (void *)psbox) != 0)
    {
        WARNING("failed creating the monitor thread");
        FUNC_RET(&psbox->result, "sandbox_execute()");
    }
    DBG("created the monitor thread");
#endif /* WITH_CUSTOM_MONITOR */

    /* Fork the prisoner process */
    psbox->ctrl.pid = fork();

    /* Execute the prisoner program */
    if (psbox->ctrl.pid == 0)
    {
        DBG("entering: the prisoner program");
        /* Start executing the prisoner program */
        _exit(__sandbox_task_execute(&psbox->task));
    }
    else
    {
        DBG("target program forked as pid %d", psbox->ctrl.pid);
        /* Start executing the tracing thread */
        psbox->ctrl.tracer(psbox);
    }

#ifdef WITH_CUSTOM_MONITOR
    if (pthread_join(tid, NULL) != 0)
    {
        WARNING("failed joining the monitor thread");
        if (pthread_cancel(tid) != 0)
        {
            WARNING("failed canceling the monitor thread");
            FUNC_RET(NULL, "sandbox_execute()");
        }
    }
    DBG("joined the monitor thread");
#endif /* WITH_CUSTOM_MONITOR */

    FUNC_RET(&psbox->result, "sandbox_execute()");
}
Пример #20
0
// ----------------------------------------------------------------------------
//	process_prefs
// ----------------------------------------------------------------------------
int ipsec_process_prefs(struct vpn_params *params)
{
	char *errstr, c;
	CFStringRef	string;
	
	if (ipsec_conf) {
		CFRelease(ipsec_conf);
		ipsec_conf = NULL;
	}

	ipsec_conf = (CFMutableDictionaryRef)CFDictionaryGetValue(params->serverRef, kRASEntIPSec);
	if (ipsec_conf == NULL) {
		vpnlog(LOG_ERR, "IPSec plugin: IPSec dictionary not present\n");
		goto fail;
	}
		
	ipsec_conf = CFDictionaryCreateMutableCopy(NULL, 0, ipsec_conf);

	remoteaddress[0] = 0;
	string  = CFDictionaryGetValue(ipsec_conf, kRASPropIPSecRemoteAddress);
	if (isString(string))
		CFStringGetCString(string, remoteaddress, sizeof(remoteaddress), kCFStringEncodingUTF8);

	if (inet_aton(remoteaddress, &peer_address) == 0) {
			
		if (pipe(resolverfds) < 0) {
			vpnlog(LOG_ERR, "IPSec plugin: failed to create pipe for gethostbyname\n");
			goto fail;
		}

		if (pthread_create(&resolverthread, NULL, ipsec_resolver_thread, NULL)) {
			vpnlog(LOG_ERR, "IPSec plugin: failed to create thread for gethostbyname...\n");
			close(resolverfds[0]);
			close(resolverfds[1]);
			goto fail;
		}
		
		while (read(resolverfds[0], &c, 1) != 1) {
			if (got_terminate()) {
				pthread_cancel(resolverthread);
				break;
			}
		}
		
		close(resolverfds[0]);
		close(resolverfds[1]);
		
		if (got_terminate())
			goto fail;
		
		if (c) {
			vpnlog(LOG_ERR, "IPSec plugin: Host '%s' not found...\n", remoteaddress);
			goto fail;
		}
		
		string = CFStringCreateWithCString(0, addr2ascii(AF_INET, &peer_address, sizeof(peer_address), 0), kCFStringEncodingASCII);
		CFDictionarySetValue(ipsec_conf, kRASPropIPSecRemoteAddress, string);
		CFRelease(string);
	}

	// verify the dictionary
	if (IPSecValidateConfiguration(ipsec_conf, &errstr)) {

		vpnlog(LOG_ERR, "IPSec plugin: Incorrect preferences (%s)\n", errstr);
		goto fail;
	}
	
    return 0;

fail:
	if (ipsec_conf) {
		CFRelease(ipsec_conf);
		ipsec_conf = NULL;
	}
    return -1;
}
Пример #21
0
/*
 * gg_http_connect() // funkcja pomocnicza
 *
 * rozpoczyna po³±czenie po http.
 *
 *  - hostname - adres serwera
 *  - port - port serwera
 *  - async - asynchroniczne po³±czenie
 *  - method - metoda http (GET, POST, cokolwiek)
 *  - path - ¶cie¿ka do zasobu (musi byæ poprzedzona ,,/'')
 *  - header - nag³ówek zapytania plus ewentualne dane dla POST
 *
 * zaalokowana struct gg_http, któr± po¼niej nale¿y
 * zwolniæ funkcj± gg_http_free(), albo NULL je¶li wyst±pi³ b³±d.
 */
struct gg_http *gg_http_connect(const char *hostname, int port, int async, const char *method, const char *path, const char *header)
{
	struct gg_http *h;

	if (!hostname || !port || !method || !path || !header) {
                gg_debug(GG_DEBUG_MISC, "// gg_http_connect() invalid arguments\n");
		errno = EINVAL;
		return NULL;
	}
	
	if (!(h = malloc(sizeof(*h))))
                return NULL;        
	memset(h, 0, sizeof(*h));

	h->async = async;
	h->port = port;
	h->fd = -1;
        h->type = GG_SESSION_HTTP;

	if (gg_proxy_enabled) {
		char *auth = gg_proxy_auth();

		h->query = gg_saprintf("%s http://%s:%d%s HTTP/1.0\r\n%s%s",
				method, hostname, port, path, (auth) ? auth :
				"", header);
		hostname = gg_proxy_host;
		h->port = port = gg_proxy_port;

		if (auth)
			free(auth);
	} else {
		h->query = gg_saprintf("%s %s HTTP/1.0\r\n%s",
				method, path, header);
	}

	if (!h->query) {
                gg_debug(GG_DEBUG_MISC, "// gg_http_connect() not enough memory for query\n");
		free(h);
                errno = ENOMEM;
		return NULL;
	}
	
	gg_debug(GG_DEBUG_MISC, "=> -----BEGIN-HTTP-QUERY-----\n%s\n=> -----END-HTTP-QUERY-----\n", h->query);

	if (async) {
#ifndef __GG_LIBGADU_HAVE_PTHREAD
		if (gg_resolve(&h->fd, &h->pid, hostname)) {
#else
		if (gg_resolve_pthread(&h->fd, &h->resolver, hostname)) {
#endif
                        gg_debug(GG_DEBUG_MISC, "// gg_http_connect() resolver failed\n");
			gg_http_free(h);
                        errno = ENOENT;
			return NULL;
		}

		gg_debug(GG_DEBUG_MISC, "// gg_http_connect() resolver = %p\n", h->resolver);

		h->state = GG_STATE_RESOLVING;
		h->check = GG_CHECK_READ;
		h->timeout = GG_DEFAULT_TIMEOUT;
	} else {
		struct hostent *he;
		struct in_addr a;

		if (!(he = gg_gethostbyname(hostname))) {
                        gg_debug(GG_DEBUG_MISC, "// gg_http_connect() host not found\n");
			gg_http_free(h);
			errno = ENOENT;
			return NULL;
		} else {
			memcpy((char*) &a, he->h_addr, sizeof(a));
			free(he);
		}

		if (!(h->fd = gg_connect(&a, port, 0)) == -1) {
                        gg_debug(GG_DEBUG_MISC, "// gg_http_connect() connection failed (errno=%d, %s)\n", errno, strerror(errno));
			gg_http_free(h);
			return NULL;
		}

		h->state = GG_STATE_CONNECTING;

		while (h->state != GG_STATE_ERROR && h->state != GG_STATE_PARSING) {
			if (gg_http_watch_fd(h) == -1)
				break;
		}

		if (h->state != GG_STATE_PARSING) {
                        gg_debug(GG_DEBUG_MISC, "// gg_http_connect() some strange error\n");
			gg_http_free(h);
			return NULL;
		}
	}

	h->callback = gg_http_watch_fd;
	h->destroy = gg_http_free;
	
	return h;
}

#define gg_http_error(x) \
	close(h->fd); \
	h->fd = -1; \
	h->state = GG_STATE_ERROR; \
	h->error = x; \
	return 0;

/*
 * gg_http_watch_fd()
 *
 * przy asynchronicznej obs³udze HTTP funkcjê t± nale¿y wywo³aæ, je¶li
 * zmieni³o siê co¶ na obserwowanym deskryptorze.
 *
 *  - h - struktura opisuj±ca po³±czenie
 *
 * je¶li wszystko posz³o dobrze to 0, inaczej -1. po³±czenie bêdzie
 * zakoñczone, je¶li h->state == GG_STATE_PARSING. je¶li wyst±pi jaki¶
 * b³±d, to bêdzie tam GG_STATE_ERROR i odpowiedni kod b³êdu w h->error.
 */
int gg_http_watch_fd(struct gg_http *h)
{
	gg_debug(GG_DEBUG_FUNCTION, "** gg_http_watch_fd(%p);\n", h);

	if (!h) {
		gg_debug(GG_DEBUG_MISC, "// gg_http_watch_fd() invalid arguments\n");
		errno = EINVAL;
		return -1;
	}

	if (h->state == GG_STATE_RESOLVING) {
		struct in_addr a;

		gg_debug(GG_DEBUG_MISC, "=> http, resolving done\n");

		if (read(h->fd, &a, sizeof(a)) < (signed)sizeof(a) || a.s_addr == INADDR_NONE) {
			gg_debug(GG_DEBUG_MISC, "=> http, resolver thread failed\n");
			gg_http_error(GG_ERROR_RESOLVING);
		}

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

#ifndef __GG_LIBGADU_HAVE_PTHREAD
		waitpid(h->pid, NULL, 0);
#else
		if (h->resolver) {
			pthread_cancel(*((pthread_t *) h->resolver));
			free(h->resolver);
			h->resolver = NULL;
		}
#endif

		gg_debug(GG_DEBUG_MISC, "=> http, connecting to %s:%d\n", inet_ntoa(a), h->port);

		if ((h->fd = gg_connect(&a, h->port, h->async)) == -1) {
			gg_debug(GG_DEBUG_MISC, "=> http, connection failed (errno=%d, %s)\n", errno, strerror(errno));
			gg_http_error(GG_ERROR_CONNECTING);
		}

		h->state = GG_STATE_CONNECTING;
		h->check = GG_CHECK_WRITE;
		h->timeout = GG_DEFAULT_TIMEOUT;

		return 0;
	}

	if (h->state == GG_STATE_CONNECTING) {
		int res = 0;
		unsigned int res_size = sizeof(res);

		if (h->async && (getsockopt(h->fd, SOL_SOCKET, SO_ERROR, &res, &res_size) || res)) {
			gg_debug(GG_DEBUG_MISC, "=> http, async connection failed (errno=%d, %s)\n", (res) ? res : errno , strerror((res) ? res : errno));
			close(h->fd);
			h->fd = -1;
			h->state = GG_STATE_ERROR;
			h->error = GG_ERROR_CONNECTING;
			if (res)
				errno = res;
			return 0;
		}

		gg_debug(GG_DEBUG_MISC, "=> http, connected, sending request\n");

		h->state = GG_STATE_SENDING_QUERY;
	}

	if (h->state == GG_STATE_SENDING_QUERY) {
		unsigned int res;

		if ((res = write(h->fd, h->query, strlen(h->query))) < 1) {
			gg_debug(GG_DEBUG_MISC, "=> http, write() failed (len=%d, res=%d, errno=%d)\n", strlen(h->query), res, errno);
			gg_http_error(GG_ERROR_WRITING);
		}

		if (res < strlen(h->query)) {
			gg_debug(GG_DEBUG_MISC, "=> http, partial header sent (led=%d, sent=%d)\n", strlen(h->query), res);

			memmove(h->query, h->query + res, strlen(h->query) - res + 1);
			h->state = GG_STATE_SENDING_QUERY;
			h->check = GG_CHECK_WRITE;
			h->timeout = GG_DEFAULT_TIMEOUT;
		} else {
			gg_debug(GG_DEBUG_MISC, "=> http, request sent (len=%d)\n", strlen(h->query));
			free(h->query);
			h->query = NULL;

			h->state = GG_STATE_READING_HEADER;
			h->check = GG_CHECK_READ;
			h->timeout = GG_DEFAULT_TIMEOUT;
		}

		return 0;
	}

	if (h->state == GG_STATE_READING_HEADER) {
		char buf[1024], *tmp;
		unsigned int res;

		if ((res = read(h->fd, buf, sizeof(buf))) == -1) {
			gg_debug(GG_DEBUG_MISC, "=> http, reading header failed (errno=%d)\n", errno);
			if (h->header) {
				free(h->header);
				h->header = NULL;
			}
			gg_http_error(GG_ERROR_READING);
		}

		if (!res) {
			gg_debug(GG_DEBUG_MISC, "=> http, connection reset by peer\n");
			if (h->header) {
				free(h->header);
				h->header = NULL;
			}
			gg_http_error(GG_ERROR_READING);
		}

		gg_debug(GG_DEBUG_MISC, "=> http, read %d bytes of header\n", res);

		if (!(tmp = realloc(h->header, h->header_size + res + 1))) {
			gg_debug(GG_DEBUG_MISC, "=> http, not enough memory for header\n");
			free(h->header);
			h->header = NULL;
			gg_http_error(GG_ERROR_READING);
		}

		h->header = tmp;

		memcpy(h->header + h->header_size, buf, res);
		h->header_size += res;

		gg_debug(GG_DEBUG_MISC, "=> http, header_buf=%p, header_size=%d\n", h->header, h->header_size);

		h->header[h->header_size] = 0;

		if ((tmp = strstr(h->header, "\r\n\r\n")) || (tmp = strstr(h->header, "\n\n"))) {
			int sep_len = (*tmp == '\r') ? 4 : 2;
			unsigned int left;
			char *line;

			left = h->header_size - ((long)(tmp) - (long)(h->header) + sep_len);

			gg_debug(GG_DEBUG_MISC, "=> http, got all header (%d bytes, %d left)\n", h->header_size - left, left);

			/* HTTP/1.1 200 OK */
			if (strlen(h->header) < 16 || strncmp(h->header + 9, "200", 3)) {
			        gg_debug(GG_DEBUG_MISC, "=> -----BEGIN-HTTP-HEADER-----\n%s\n=> -----END-HTTP-HEADER-----\n", h->header);

				gg_debug(GG_DEBUG_MISC, "=> http, didn't get 200 OK -- no results\n");
				free(h->header);
				h->header = NULL;
				gg_http_error(GG_ERROR_CONNECTING);
			}

			h->body_size = 0;
			line = h->header;
			*tmp = 0;
                        
			gg_debug(GG_DEBUG_MISC, "=> -----BEGIN-HTTP-HEADER-----\n%s\n=> -----END-HTTP-HEADER-----\n", h->header);

			while (line) {
				if (!strncasecmp(line, "Content-length: ", 16)) {
					h->body_size = atoi(line + 16);
				}
				line = strchr(line, '\n');
				if (line)
					line++;
			}

			if (h->body_size <= 0) {
				gg_debug(GG_DEBUG_MISC, "=> http, content-length not found\n");
				h->body_size = left;
			}

			if (left > h->body_size) {
				gg_debug(GG_DEBUG_MISC, "=> http, oversized reply (%d bytes needed, %d bytes left)\n", h->body_size, left);
				h->body_size = left;
			}

			gg_debug(GG_DEBUG_MISC, "=> http, body_size=%d\n", h->body_size);

			if (!(h->body = malloc(h->body_size + 1))) {
				gg_debug(GG_DEBUG_MISC, "=> http, not enough memory (%d bytes for body_buf)\n", h->body_size + 1);
				free(h->header);
				h->header = NULL;
				gg_http_error(GG_ERROR_READING);
			}

			if (left) {
				memcpy(h->body, tmp + sep_len, left);
				h->body_done = left;
			}

			h->body[left] = 0;

			h->state = GG_STATE_READING_DATA;
			h->check = GG_CHECK_READ;
			h->timeout = GG_DEFAULT_TIMEOUT;
		}

		return 0;
	}

	if (h->state == GG_STATE_READING_DATA) {
		char buf[1024];
		unsigned int res;

		if ((res = read(h->fd, buf, sizeof(buf))) == -1) {
			gg_debug(GG_DEBUG_MISC, "=> http, reading body failed (errno=%d)\n", errno);
			if (h->body) {
				free(h->body);
				h->body = NULL;
			}
			gg_http_error(GG_ERROR_READING);
		}

		if (!res) {
			if (h->body_done >= h->body_size) {
				gg_debug(GG_DEBUG_MISC, "=> http, we're done, closing socket\n");
				h->state = GG_STATE_PARSING;
				close(h->fd);
				h->fd = -1;
			} else {
				gg_debug(GG_DEBUG_MISC, "=> http, connection closed while reading (have %d, need %d)\n", h->body_done, h->body_size);
				if (h->body) {
					free(h->body);
					h->body = NULL;
				}
				gg_http_error(GG_ERROR_READING);
			}

			return 0;
		}

		gg_debug(GG_DEBUG_MISC, "=> http, read %d bytes of body\n", res);

		if (h->body_done + res > h->body_size) {
			char *tmp;

			gg_debug(GG_DEBUG_MISC, "=> http, too much data (%d bytes, %d needed), enlarging buffer\n", h->body_done + res, h->body_size);

			if (!(tmp = realloc(h->body, h->body_done + res + 1))) {
				gg_debug(GG_DEBUG_MISC, "=> http, not enough memory for data (%d needed)\n", h->body_done + res + 1);
				free(h->body);
				h->body = NULL;
				gg_http_error(GG_ERROR_READING);
			}

			h->body = tmp;
			h->body_size = h->body_done + res;
		}

		h->body[h->body_done + res] = 0;
		memcpy(h->body + h->body_done, buf, res);
		h->body_done += res;

		gg_debug(GG_DEBUG_MISC, "=> body_done=%d, body_size=%d\n", h->body_done, h->body_size);

		return 0;
	}
	
	if (h->fd != -1)
		close(h->fd);

	h->fd = -1;
	h->state = GG_STATE_ERROR;
	h->error = 0;

	return -1;
}
Пример #22
0
/* This method is used to kill the stdin_loop before exiting from factor.
   A Nvidia driver bug on Linux is the reason this has to be done, see:
     http://www.nvnews.net/vbulletin/showthread.php?t=164619 */
void factor_vm::close_console() {
  if (stdin_thread_initialized_p) {
    pthread_cancel(stdin_thread);
    pthread_join(stdin_thread, 0);
  }
}
Пример #23
0
WELS_THREAD_ERROR_CODE    WelsThreadCancel (WELS_THREAD_HANDLE  thread) {
  return pthread_cancel (thread);
}
Пример #24
0
int main(int argc, char **argv)
{
    int shelpid;
    int opt, res;
    pid_t child_pid;
    char pty_name[2000];

    while ((opt = getopt(argc, argv, "tvw")) != EOF) {
        switch (opt) {
        case 't': flags |=  FLAG_NOTCSET; break;
        case 'v': flags |=  FLAG_VERBOSE; break;
        case 'w': flags &= ~FLAG_DOWINCH; break;
        } /* switch */
    } /* while */

    argc -= optind; argv += optind;

    LOG("isatty(0)\n");
    if (!isatty(0)) {
        ERR("stdin is not a tty, aborting\n");
    }

    /* we obtain the tty settings from stdin . */
    LOG("tcgetattr(0, &saved_tty);\n");
    if (tcgetattr(0, &saved_tty) < 0) {
        ERR("tcgetattr" ERRNO "\n", EPMTS);
    }

    /* get the window size */
    if (flags & FLAG_DOWINCH) {
        LOG("ioctl(0, TIOCGWINSZ, &saved_window_size);\n");
        int res = ioctl(0, TIOCGWINSZ, &saved_window_size);
        if (res < 0) {
            WARN("winsize" ERRNO ", disabling\n", EPMTS);
            flags &= ~FLAG_DOWINCH;
        }
    }

    /* flush all descriptors before forking (so no repeated messages
     * on stdout). */
    fflush(NULL);
    child_pid = forkpty(&ptym, pty_name, &saved_tty, &saved_window_size);
    switch(child_pid) {
    case -1:
        ERR("fork" ERRNO "\n", EPMTS);
        break; /* unneeded, but don't hurt */

    case 0: { /* child process */
            int res;

            if (argc) {
                int i;
                LOG("execvp: %s", argv[0]);
                for (i = 1; i < argc; i++) {
                    ADD(" %s", argv[i]);
                }
                ADD("\n");
                execvp(argv[0], argv);
                ERR("execvp: %s" ERRNO "\n", argv[0], EPMTS);
            } else {
                char *shellenv = "SHELL";
                char *shell = getenv(shellenv);
                if (shell) {
                    LOG("Got shell from environment variable SHELL\n");
                } else {
                    struct passwd *u = getpwnam(getlogin());
                    if (!u)
                        ERR("getpwnam failed\n");
                    shell = u->pw_shell;
                    LOG("Got shell from /etc/passwd file\n");
                } /* if */
                LOG("execlp: %s\n", shell);
                execlp(shell, shell, NULL);
                ERR("execlp: %s" ERRNO "\n", shell, EPMTS);
            } /* if */
            /* NOTREACHED */
        } /* case */

    default: { /* parent process */
            struct pthread_info p_in, p_out;
            int res, exit_code = 0;
            struct sigaction sa;
            struct termios stty_raw = saved_tty;

            LOG("forkpty: child_pid == %d, ptym=%d, "
                    "pty_name=[%s]\n",
                    child_pid, ptym, pty_name);

            /* from this point on, we have to use \r in addition
             * to \n, as we have switched to raw mode (in the parent
             * process)  So we first do a fflush(3) to dump all
             * data. */
            fflush(NULL); 
            atexit(atexit_handler);
            cfmakeraw(&stty_raw);
            res = tcsetattr(0, TCSAFLUSH, &stty_raw);
            if (res < 0) {
                ERR("tcsetattr(ptym, ...)" ERRNO "\n", EPMTS);
            } /* if */

            if (flags & FLAG_DOWINCH) {
                LOG("installing signal handler\r\n");
                memset(&sa, 0, sizeof sa);
                sa.sa_handler = pass_winsz;
                sigaction(SIGWINCH, &sa, NULL);
            }

            /* create the subthreads to process info */
            res = pthread_create(
                    &p_in.id,
                    NULL,
                    pthread_body_reader,
                    init_pthread_info(
                        0, ptym,
                        "READ",
                        &p_in));
            LOG("pthread_create: id=%p, name=%s, res=%d\r\n", 
                    p_in.id, p_in.name, res);
            if (res < 0)
                ERR("pthread_create" ERRNO "\r\n", EPMTS);

            res = pthread_create(
                    &p_out.id,
                    NULL,
                    pthread_body_writer,
                    init_pthread_info(
                        ptym, 1, 
                        "WRITE",
                        &p_out));
            LOG("pthread_create: id=%p, name=%s, res=%d\r\n", 
                    p_out.id, p_out.name, res);
            if (res < 0)
                ERR("pthread_create" ERRNO "\r\n", EPMTS);

            /* wait for subprocess to terminate */
            wait(&exit_code);
            LOG("wait(&exit_code <= %d);\r\n", exit_code);

            /* join writing thread */
            LOG("pthread_join(%p, NULL);...\r\n", p_out.id);
            if ((res = pthread_join(p_out.id, NULL)) < 0)
                ERR("pthread_join" ERRNO "\r\n", EPMTS);
            LOG("pthread_join(%p, NULL); => %d\r\n", p_out.id, res);

            /* cancel reading thread */
            res = pthread_cancel(p_in.id);
            LOG("pthread_cancel(%p); => %d\r\n", p_in.id, res);

            /* join it */
            LOG("pthread_join(%p, NULL);...\r\n", p_in.id);
            res = pthread_join(p_in.id, NULL);
            LOG("pthread_join(%p, NULL); => %d\r\n", p_in.id, res);

            /* exit with the subprocess exit code */
            LOG("exit(%d);\r\n", WEXITSTATUS(exit_code));
            exit(WEXITSTATUS(exit_code));
        } /* case */
    } /* switch */
} /* main */
SSocket::~SSocket ()
{
  pthread_cancel (ThreadID);
}
Пример #26
0
/******************************************************************************
Description.: calling this function stops the worker thread
Input Value.: -
Return Value: always 0
******************************************************************************/
int output_stop(int id)
{
    DBG("will cancel worker thread\n");
    pthread_cancel(worker);
    return 0;
}
Пример #27
0
/* We have only one thread that ever re-initialises GPUs, thus if any GPU
 * init command fails due to a completely wedged GPU, the thread will never
 * return, unable to harm other GPUs. If it does return, it means we only had
 * a soft failure and then the reinit_gpu thread is ready to tackle another
 * GPU */
void *reinit_gpu(void *userdata)
{
	struct thr_info *mythr = userdata;
	struct cgpu_info *cgpu;
	struct thr_info *thr;
	struct timeval now;
	char name[256];
	int thr_id;
	int gpu;

	pthread_detach(pthread_self());

select_cgpu:
	cgpu = tq_pop(mythr->q, NULL);
	if (!cgpu)
		goto out;

	if (clDevicesNum() != nDevs) {
		applog(LOG_WARNING, "Hardware not reporting same number of active devices, will not attempt to restart GPU");
		goto out;
	}

	gpu = cgpu->device_id;

	for (thr_id = 0; thr_id < mining_threads; ++thr_id) {
		thr = &thr_info[thr_id];
		cgpu = thr->cgpu;
		if (cgpu->api != &opencl_api)
			continue;
		if (dev_from_id(thr_id) != gpu)
			continue;

		thr = &thr_info[thr_id];
		if (!thr) {
			applog(LOG_WARNING, "No reference to thread %d exists", thr_id);
			continue;
		}

		thr->rolling = thr->cgpu->rolling = 0;
		/* Reports the last time we tried to revive a sick GPU */
		gettimeofday(&thr->sick, NULL);
		if (!pthread_cancel(thr->pth)) {
			applog(LOG_WARNING, "Thread %d still exists, killing it off", thr_id);
		} else
			applog(LOG_WARNING, "Thread %d no longer exists", thr_id);
	}

	for (thr_id = 0; thr_id < mining_threads; ++thr_id) {
		int virtual_gpu;

		thr = &thr_info[thr_id];
		cgpu = thr->cgpu;
		if (cgpu->api != &opencl_api)
			continue;
		if (dev_from_id(thr_id) != gpu)
			continue;

		virtual_gpu = cgpu->virtual_gpu;
		/* Lose this ram cause we may get stuck here! */
		//tq_freeze(thr->q);

		thr->q = tq_new();
		if (!thr->q)
			quit(1, "Failed to tq_new in reinit_gpu");

		/* Lose this ram cause we may dereference in the dying thread! */
		//free(clState);

		applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
		clStates[thr_id] = initCl(virtual_gpu, name, sizeof(name));
		if (!clStates[thr_id]) {
			applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
			goto select_cgpu;
		}
		applog(LOG_INFO, "initCl() finished. Found %s", name);

		if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
			applog(LOG_ERR, "thread %d create failed", thr_id);
			return NULL;
		}
		applog(LOG_WARNING, "Thread %d restarted", thr_id);
	}

	gettimeofday(&now, NULL);
	get_datestamp(cgpu->init, &now);

	for (thr_id = 0; thr_id < mining_threads; ++thr_id) {
		thr = &thr_info[thr_id];
		cgpu = thr->cgpu;
		if (cgpu->api != &opencl_api)
			continue;
		if (dev_from_id(thr_id) != gpu)
			continue;

		tq_push(thr->q, &ping);
	}

	goto select_cgpu;
out:
	return NULL;
}
Пример #28
0
static void *
tf2 (void *arg)
{
  int r = pthread_barrier_wait (&b);
  if (r != 0 && r != PTHREAD_BARRIER_SERIAL_THREAD)
    {
      puts ("tf2: barrier_wait failed");
      exit (1);
    }

  pthread_cleanup_push (cl, NULL);

  const struct aiocb *l[1] = { arg };
  struct timespec ts = { .tv_sec = 1000, .tv_nsec = 0 };

  TEMP_FAILURE_RETRY (aio_suspend (l, 1, &ts));

  pthread_cleanup_pop (0);

  puts ("tf2: aio_suspend returned");

  exit (1);
}


static int
do_test (void)
{
  int fds[2];
  if (pipe (fds) != 0)
    {
      puts ("pipe failed");
      return 1;
    }

  struct aiocb a, a2, *ap;
  char mem[1];
  memset (&a, '\0', sizeof (a));
  a.aio_fildes = fds[0];
  a.aio_buf = mem;
  a.aio_nbytes = sizeof (mem);
  if (aio_read (&a) != 0)
    {
      puts ("aio_read failed");
      return 1;
    }

  if (pthread_barrier_init (&b, NULL, 2) != 0)
    {
      puts ("barrier_init failed");
      return 1;
    }

  pthread_t th;
  if (pthread_create (&th, NULL, tf, &a) != 0)
    {
      puts ("1st create failed");
      return 1;
    }

  int r = pthread_barrier_wait (&b);
  if (r != 0 && r != PTHREAD_BARRIER_SERIAL_THREAD)
    {
      puts ("barrier_wait failed");
      exit (1);
    }

  struct timespec  ts = { .tv_sec = 0, .tv_nsec = 100000000 };
  while (nanosleep (&ts, &ts) != 0)
    continue;

  puts ("going to cancel tf in-time");
  if (pthread_cancel (th) != 0)
    {
      puts ("1st cancel failed");
      return 1;
    }

  void *status;
  if (pthread_join (th, &status) != 0)
    {
      puts ("1st join failed");
      return 1;
    }
  if (status != PTHREAD_CANCELED)
    {
      puts ("1st thread not canceled");
      return 1;
    }

  if (cl_called == 0)
    {
      puts ("tf cleanup handler not called");
      return 1;
    }
  if (cl_called > 1)
    {
      puts ("tf cleanup handler called more than once");
      return 1;
    }

  cl_called = 0;

  if (pthread_create (&th, NULL, tf2, &a) != 0)
    {
      puts ("2nd create failed");
      return 1;
    }

  r = pthread_barrier_wait (&b);
  if (r != 0 && r != PTHREAD_BARRIER_SERIAL_THREAD)
    {
      puts ("2nd barrier_wait failed");
      exit (1);
    }

  ts.tv_sec = 0;
  ts.tv_nsec = 100000000;
  while (nanosleep (&ts, &ts) != 0)
    continue;

  puts ("going to cancel tf2 in-time");
  if (pthread_cancel (th) != 0)
    {
      puts ("2nd cancel failed");
      return 1;
    }

  if (pthread_join (th, &status) != 0)
    {
      puts ("2nd join failed");
      return 1;
    }
  if (status != PTHREAD_CANCELED)
    {
      puts ("2nd thread not canceled");
      return 1;
    }

  if (cl_called == 0)
    {
      puts ("tf2 cleanup handler not called");
      return 1;
    }
  if (cl_called > 1)
    {
      puts ("tf2 cleanup handler called more than once");
      return 1;
    }

  puts ("in-time cancellation succeeded");

  ap = &a;
  if (aio_cancel (fds[0], &a) != AIO_CANCELED)
    {
      puts ("aio_cancel failed");
      /* If aio_cancel failed, we cannot reuse aiocb a.  */
      ap = &a2;
    }


  cl_called = 0;

  size_t len2 = fpathconf (fds[1], _PC_PIPE_BUF);
  size_t page_size = sysconf (_SC_PAGESIZE);
  len2 = 20 * (len2 < page_size ? page_size : len2) + sizeof (mem) + 1;
  char *mem2 = malloc (len2);
  if (mem2 == NULL)
    {
      puts ("could not allocate memory for pipe write");
      return 1;
    }

  memset (ap, '\0', sizeof (*ap));
  ap->aio_fildes = fds[1];
  ap->aio_buf = mem2;
  ap->aio_nbytes = len2;
  if (aio_write (ap) != 0)
    {
      puts ("aio_write failed");
      return 1;
    }

  if (pthread_create (&th, NULL, tf, ap) != 0)
    {
      puts ("3rd create failed");
      return 1;
    }

  puts ("going to cancel tf early");
  if (pthread_cancel (th) != 0)
    {
      puts ("3rd cancel failed");
      return 1;
    }

  r = pthread_barrier_wait (&b);
  if (r != 0 && r != PTHREAD_BARRIER_SERIAL_THREAD)
    {
      puts ("3rd barrier_wait failed");
      exit (1);
    }

  if (pthread_join (th, &status) != 0)
    {
      puts ("3rd join failed");
      return 1;
    }
  if (status != PTHREAD_CANCELED)
    {
      puts ("3rd thread not canceled");
      return 1;
    }

  if (cl_called == 0)
    {
      puts ("tf cleanup handler not called");
      return 1;
    }
  if (cl_called > 1)
    {
      puts ("tf cleanup handler called more than once");
      return 1;
    }

  cl_called = 0;

  if (pthread_create (&th, NULL, tf2, ap) != 0)
    {
      puts ("4th create failed");
      return 1;
    }

  puts ("going to cancel tf2 early");
  if (pthread_cancel (th) != 0)
    {
      puts ("4th cancel failed");
      return 1;
    }

  r = pthread_barrier_wait (&b);
  if (r != 0 && r != PTHREAD_BARRIER_SERIAL_THREAD)
    {
      puts ("4th barrier_wait failed");
      exit (1);
    }

  if (pthread_join (th, &status) != 0)
    {
      puts ("4th join failed");
      return 1;
    }
  if (status != PTHREAD_CANCELED)
    {
      puts ("4th thread not canceled");
      return 1;
    }

  if (cl_called == 0)
    {
      puts ("tf2 cleanup handler not called");
      return 1;
    }
  if (cl_called > 1)
    {
      puts ("tf2 cleanup handler called more than once");
      return 1;
    }

  puts ("early cancellation succeeded");

  if (ap == &a2)
    {
      /* The aio_read(&a) was not canceled because the read request was
	 already in progress. In the meanwhile aio_write(ap) wrote something
	 to the pipe and the read request either has already been finished or
	 is able to read the requested byte.
	 Wait for the read request before returning from this function because
	 the return value and error code from the read syscall will be written
	 to the struct aiocb a, which lies on the stack of this function.
	 Otherwise the stack from subsequent function calls - e.g. _dl_fini -
	 will be corrupted, which can lead to undefined behaviour like a
	 segmentation fault.  */
      const struct aiocb *l[1] = { &a };
      TEMP_FAILURE_RETRY (aio_suspend(l, 1, NULL));
    }

  return 0;
}
Пример #29
0
int
main(int argc, char *argv[])
{
	struct sockaddr_in sin;
	struct sockaddr_conn sconn;
	struct sctp_event event;
	uint16_t event_types[] = {SCTP_ASSOC_CHANGE,
	                          SCTP_PEER_ADDR_CHANGE,
	                          SCTP_SEND_FAILED_EVENT};
	unsigned int i;
#ifdef _WIN32
	SOCKET fd;
#else
	int fd;
#endif
	struct socket *s;
#ifdef _WIN32
	HANDLE tid;
#else
	pthread_t tid;
#endif
	struct sctp_sndinfo sndinfo;
	char line[LINE_LENGTH];

	usrsctp_init(0, conn_output, debug_printf);
	/* set up a connected UDP socket */
#ifdef _WIN32
	if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) {
		printf("socket() failed with error: %ld\n", WSAGetLastError());
	}
#else
	if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		perror("socket");
	}
#endif
	memset(&sin, 0, sizeof(struct sockaddr_in));
	sin.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
	sin.sin_len = sizeof(struct sockaddr_in);
#endif
	sin.sin_port = htons(atoi(argv[2]));
	sin.sin_addr.s_addr = inet_addr(argv[1]);
#ifdef _WIN32
	if (bind(fd, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
		printf("bind() failed with error: %ld\n", WSAGetLastError());
	}
#else
	if (bind(fd, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)) < 0) {
		perror("bind");
	}
#endif
	memset(&sin, 0, sizeof(struct sockaddr_in));
	sin.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
	sin.sin_len = sizeof(struct sockaddr_in);
#endif
	sin.sin_port = htons(atoi(argv[4]));
	sin.sin_addr.s_addr = inet_addr(argv[3]);
#ifdef _WIN32
	if (connect(fd, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
		printf("connect() failed with error: %ld\n", WSAGetLastError());
	}
#else
	if (connect(fd, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)) < 0) {
		perror("connect");
	}
#endif
#ifdef _WIN32
	tid = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&handle_packets, (void *)&fd, 0, NULL);
#else
	pthread_create(&tid, NULL, &handle_packets, (void *)&fd);
#endif
#ifdef SCTP_DEBUG
	usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_NONE);
#endif
	usrsctp_register_address((void *)&fd);
	usrsctp_sysctl_set_sctp_ecn_enable(0);
	if ((s = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP, receive_cb, NULL, 0, &fd)) == NULL) {
		perror("usrsctp_socket");
	}
	/* Enable the events of interest. */
	if (usrsctp_set_non_blocking(s, 1) < 0) {
		perror("usrsctp_set_non_blocking");
	}
	memset(&event, 0, sizeof(event));
	event.se_assoc_id = SCTP_ALL_ASSOC;
	event.se_on = 1;
	for (i = 0; i < sizeof(event_types)/sizeof(uint16_t); i++) {
		event.se_type = event_types[i];
		if (usrsctp_setsockopt(s, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(event)) < 0) {
			perror("setsockopt SCTP_EVENT");
		}
	}
	memset(&sconn, 0, sizeof(struct sockaddr_conn));
	sconn.sconn_family = AF_CONN;
#ifdef HAVE_SCONN_LEN
	sconn.sconn_len = sizeof(struct sockaddr_conn);
#endif
	sconn.sconn_port = htons(atoi(argv[5]));
	sconn.sconn_addr = &fd;
	if (usrsctp_bind(s, (struct sockaddr *)&sconn, sizeof(struct sockaddr_conn)) < 0) {
		perror("usrsctp_bind");
	}
	memset(&sconn, 0, sizeof(struct sockaddr_conn));
	sconn.sconn_family = AF_CONN;
#ifdef HAVE_SCONN_LEN
	sconn.sconn_len = sizeof(struct sockaddr_conn);
#endif
	sconn.sconn_port = htons(atoi(argv[6]));
	sconn.sconn_addr = &fd;
	if (usrsctp_connect(s, (struct sockaddr *)&sconn, sizeof(struct sockaddr_conn)) < 0) {
		perror("usrsctp_connect");
	}
	for (;;) {
#ifdef _WIN32
		if (gets_s(line, LINE_LENGTH) == NULL) {
#else
		if (fgets(line, LINE_LENGTH, stdin) == NULL) {
#endif
			if (usrsctp_shutdown(s, SHUT_WR) < 0) {
				perror("usrsctp_shutdown");
			}
			while (usrsctp_finish() != 0) {
#ifdef _WIN32
				Sleep(1000);
#else
				sleep(1);
#endif
			}
			break;
		}
		sndinfo.snd_sid = 1;
		sndinfo.snd_flags = 0;
		sndinfo.snd_ppid = htonl(DISCARD_PPID);
		sndinfo.snd_context = 0;
		sndinfo.snd_assoc_id = 0;
		if (usrsctp_sendv(s, line, strlen(line), NULL, 0, (void *)&sndinfo,
	                          (socklen_t)sizeof(struct sctp_sndinfo), SCTP_SENDV_SNDINFO, 0) < 0) {
			perror("usrsctp_sendv");
		}
	}
	while (usrsctp_finish() != 0) {
#ifdef _WIN32
		Sleep(1000);
#else
		sleep(1);
#endif
	}
#ifdef _WIN32
	TerminateThread(tid, 0);
	WaitForSingleObject(tid, INFINITE);
	if (closesocket(fd) == SOCKET_ERROR) {
		printf("closesocket() failed with error: %ld\n", WSAGetLastError());
	}
#else
	pthread_cancel(tid);
	pthread_join(tid, NULL);
	if (close(fd) < 0) {
		perror("close");
	}
#endif
	return (0);
}
Пример #30
0
void newgame() {
	char d; 
	short i;
	running = 1;  
	nbullets = cmax / 2;
	nbugs = 5;
	
	if(getlives())
		lives = getlives();
	else {
		int fl = senddiff();
		if(fl == 1)
			lives = 15;
		else if(fl == 2)
			lives = 10;
		else if(fl == 3)
			lives = 8;
	}
	if(lives == 0)
		lives = 15;
	
	
	//	lives = 5;//Kitni baar takraye then game over
	score = 0;
	level = 25;
	levels = 1;
/*arrow.r and .c are positions of the gun on teh window rows and colmsms*/
	arrow.r = rmax / 2;
	arrow.c = cmax - 3;
	arrow.w = 3;//width 
	arrow.h = 7;//height
	arrow.str =
	"  * \n"
	" ** \n"
	"*** \n"
	"    \n"
	"*** \n"
	" ** \n"
	"  * \n";
	bullets = malloc(nbullets * sizeof(object));
	for (i = 0; i < nbullets; i++) {
		newbullet(&bullets[i], 0, 0);
	}  
	bugs = malloc(nbugs * sizeof(object));
	for (i = 0; i < nbugs; i++) {
		newbug(&bugs[i]);
	}  
	drawmessage("SEGFAULT SHOOTER", -3);
	drawmessage("Stop the SEGFAULTS from getting past you", -1);
	drawmessage("Arrow keys to move, space to shoot", 0);
	drawmessage("Q to exit", 1);
	drawmessage("Anything else to start", 2);
	d = getch();
	if (d == 'q') {
		return;
	}
	
/*Enables the keyboard arrow keys*/  
	pthread_t pth;
	pthread_create(&pth, NULL, input, "get keys");
	game();
	pthread_cancel(pth);  
	clear();
/* This is printed on the window when game is over*/
	drawmessage("Game Over", -1);
	char string[10] = {'\0'};
	sprintf(string, "%d", score);
	drawmessage(string, 0);
	drawmessage("Return to continue", 2);
	while ((d = getch()) && d != '\n')
		if (d == 'q') 
			return;
	clear();
	highscore();
	clear();
	highscores();
	while ((d = getch()) && d != '\n')
		if (d == 'q')
			return;
}