Exemple #1
0
static int rar_open(char *rarname, mode_t m, stream_t *stream)
{
	stream_0day_priv_t *p;
	char RarTag[7], method, *pp, type = 0;
	WORD w, n, flag;

	int h = open(rarname, m);
	if (h < 0) return h;

	read(h, RarTag, 7);						/* Read Rar!... Tag */
	if (strncmp(RarTag, "Rar!", 4)) {
		lseek(h, 0, SEEK_SET);				/* Not a RAR */
		return h;
	}

	p = (stream_0day_priv_t*)malloc(sizeof(stream_0day_priv_t));
	memset(p, 0, sizeof(stream_0day_priv_t));
	p->headSize = 7;
	while (type != 0x74) {
		lseek(h, 2, SEEK_CUR);				/* CRC */
		read(h, &type, 1);					/* Type */
		read(h, (char*)&flag, 2);			/* Flag */
		read(h, (char*)&w, 2);				/* Size */
		p->headSize += w;
		if (type == 0x73) { /* main header */
			p->naming = flag & 0x10;
		} else
		if (type == 0x74) {	/* file header */
			read(h, (char*)&(p->packSize), 4);
			read(h, (char*)&(p->fileSize), 4);
			lseek(h, 10, SEEK_CUR);			/* Skip OS/CRC/Time/Ver */
			read(h, &method, 1);			/* Compression Method */
			read(h, (char*)&n, 2);			/* Size of rarname */
			if (w == n + 0x2D) {
				/* fileSize is 64bit */
				lseek(h, 8, SEEK_CUR);
				read(h, ((char*)&(p->fileSize))+4, 4);
			} else {
				lseek(h, 4, SEEK_CUR);		/* Attr */
			}
			p->filename = (char *)malloc(n + 1);
			read(h, p->filename, n);		/* filename */
			p->filename[n] = 0;
		} else
		if (type == 0x7A) {	/* comment header */
			read(h, (char*)&w, 2);			/* Size of comment */
			p->headSize += w;
		}
		lseek(h, p->headSize, SEEK_SET);	/* Seek to next header */
	}
	mp_msg(MSGT_STREAM,MSGL_INFO, "File Flags=%04x\tCompression Method=%x\n", flag, method);

	if (!(flag & 0x04) && (method == 0x30)) {	/* 0day stream */
		n = strlen(rarname);
		p->basename = strdup(rarname);
		if (p->naming) {
			p->naming = rarname + n - strrchr(rarname, 't') - 5;
			n -= (p->naming + 4);
		} else {
			n -= 3;
		}
		p->basename[n] = 0;

		close(h);
		h = open_0day_volume(p, 0);
		if (h < 0) {
			free(p->filename);
			free(p->basename);
			free(p);
		} else {
			/* reget packSize, avoid got the last volume's packSize */
			type = 0;
			n = 7;
			lseek(h, 7, SEEK_SET);
			while (type != 0x74) {
				lseek(h, 2, SEEK_CUR);				/* CRC */
				read(h, &type, 1);					/* Type */
				read(h, (char*)&flag, 2);			/* Flag */
				read(h, (char*)&w, 2);				/* Size */
				n += w;
				if (type == 0x74) {	/* file header */
					read(h, (char*)&(p->packSize), 4);
				} else
				if (type == 0x7A) {	/* comment header */
					read(h, (char*)&w, 2);			/* Size of comment */
					n += w;
				}
				lseek(h, n, SEEK_SET);	/* Seek to next header */
			}

			stream->priv = (void*)p;
			stream->close = close_0day;
			stream->seek = seek_0day;
			stream->fill_buffer = fill_buffer_0day;
			stream->end_pos = p->fileSize;
			stream->type = STREAMTYPE_FILE;
		}
		return h;
	}

	free(p);

	if (unrardll) {								/* rar stream */
		struct RAROpenArchiveDataEx OpenArchiveData;
		struct RARHeaderDataEx HeaderData;
		HANDLE hPipeRead, hPipeWrite;
		int hArcData;

		memset(&OpenArchiveData,0,sizeof(OpenArchiveData));
		OpenArchiveData.ArcName=rarname;
		OpenArchiveData.OpenMode=RAR_OM_EXTRACT;

		hArcData=(*RAROpenArchiveEx)(&OpenArchiveData);
		if (!OpenArchiveData.OpenResult) {
			HeaderData.CmtBuf=NULL;
			if (!(*RARReadHeaderEx)(hArcData,&HeaderData)) {
				if (HeaderData.Flags & 0x04) {
					/* Request password */
					if (DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_PASSWORD),
						GetForegroundWindow(), unrar_pw_dlgproc) == IDOK) {
						(*RARSetPassword)(hArcData, pw);
					} else {
						close(h);
						h = -2;
						goto rar_open_break;
					}
				}
				if (CreatePipe(&hPipeRead, &hPipeWrite, 0, 0x10000)) {
					stream_rar_priv_t *p;

					(*RARSetCallback)(hArcData, unrar_callback, (int)hPipeWrite);
					p = (stream_rar_priv_t*)malloc(sizeof(stream_rar_priv_t));
					p->filename = strdup(HeaderData.FileName);
					p->hArcData = hArcData;
					p->hPipeWrite = hPipeWrite;
					if (_beginthread((void (*)())unrar_thread, 0, (void*)p) != -1) {
						stream->priv = (void*)p;
						stream->close = close_rar;
						close(h);
						return (int)hPipeRead;
					}
					else {
						free(p->filename);
						free(p);
						CloseHandle(hPipeRead);
						CloseHandle(hPipeWrite);
					}
				}
			}

rar_open_break:
			(*RARCloseArchive)(hArcData);
		}
	}

	return h;
}
Exemple #2
0
bool TCPConnection::ConnectIP(uint32 in_ip, uint16 in_port, char* errbuf) {
	if (errbuf)
		errbuf[0] = 0;
	if (ConnectionType != Outgoing) {
		// If this code runs, we got serious problems
		// Crash and burn.
		return false;
	}
	MState.lock();
	if (ConnectReady()) {
		pState = TCPS_Connecting;
	} else {
		MState.unlock();
		SetAsyncConnect(false);
		return false;
	}
	MState.unlock();
	if (!pRunLoop) {
		pRunLoop = true;
#ifdef _WINDOWS
		_beginthread(TCPConnectionLoop, 0, this);
#else
		pthread_t thread;
		pthread_create(&thread, nullptr, TCPConnectionLoop, this);
#endif
	}

	connection_socket = INVALID_SOCKET;
	struct sockaddr_in	server_sin;
	//struct in_addr	in;

	if ((connection_socket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET || connection_socket == 0) {
#ifdef _WINDOWS
		if (errbuf)
			snprintf(errbuf, TCPConnection_ErrorBufferSize, "TCPConnection::Connect(): Allocating socket failed. Error: %i", WSAGetLastError());
#else
		if (errbuf)
			snprintf(errbuf, TCPConnection_ErrorBufferSize, "TCPConnection::Connect(): Allocating socket failed. Error: %s", strerror(errno));
#endif
		SetState(TCPS_Ready);
		SetAsyncConnect(false);
		return false;
	}
	server_sin.sin_family = AF_INET;
	server_sin.sin_addr.s_addr = in_ip;
	server_sin.sin_port = htons(in_port);

	// Establish a connection to the server socket.
#ifdef _WINDOWS
	if (connect(connection_socket, (PSOCKADDR) &server_sin, sizeof (server_sin)) == SOCKET_ERROR) {
		if (errbuf)
			snprintf(errbuf, TCPConnection_ErrorBufferSize, "TCPConnection::Connect(): connect() failed. Error: %i", WSAGetLastError());
		closesocket(connection_socket);
		connection_socket = 0;
		SetState(TCPS_Ready);
		SetAsyncConnect(false);
		return false;
	}
#else
	if (connect(connection_socket, (struct sockaddr *) &server_sin, sizeof (server_sin)) == SOCKET_ERROR) {
		if (errbuf)
			snprintf(errbuf, TCPConnection_ErrorBufferSize, "TCPConnection::Connect(): connect() failed. Error: %s", strerror(errno));
		close(connection_socket);
		connection_socket = 0;
		SetState(TCPS_Ready);
		SetAsyncConnect(false);
		return false;
	}
#endif
	int bufsize = 64 * 1024; // 64kbyte recieve buffer, up from default of 8k
	setsockopt(connection_socket, SOL_SOCKET, SO_RCVBUF, (char*) &bufsize, sizeof(bufsize));
#ifdef _WINDOWS
	unsigned long nonblocking = 1;
	ioctlsocket(connection_socket, FIONBIO, &nonblocking);
#else
	fcntl(connection_socket, F_SETFL, O_NONBLOCK);
#endif

	SetEcho(false);
	ClearBuffers();

	rIP = in_ip;
	rPort = in_port;
	SetState(TCPS_Connected);
	SetAsyncConnect(false);
	return true;
}
Exemple #3
0
NOEXPORT int gui_loop() {
#ifdef _WIN32_WCE
    WNDCLASS wc;
#else
    WNDCLASSEX wc;
#endif
    MSG msg;
    LPTSTR classname=TEXT("stunnel_main_window_class");

    /* register the class */
#ifndef _WIN32_WCE
    wc.cbSize=sizeof wc;
#endif
    wc.style=CS_VREDRAW|CS_HREDRAW;
    wc.lpfnWndProc=window_proc;
    wc.cbClsExtra=wc.cbWndExtra=0;
    wc.hInstance=ghInst;
    wc.hIcon=LoadIcon(ghInst, MAKEINTRESOURCE(IDI_STUNNEL_MAIN));
    wc.hCursor=LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName=NULL;
    wc.lpszClassName=classname;
#ifdef _WIN32_WCE
    RegisterClass(&wc);
#else
    /* load 16x16 icon */
    wc.hIconSm=LoadImage(ghInst, MAKEINTRESOURCE(IDI_STUNNEL_MAIN), IMAGE_ICON,
        GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0);
    RegisterClassEx(&wc);
#endif

    /* create main window */
#ifdef _WIN32_WCE
    hwnd=CreateWindow(classname, win32_name, 0,
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
        NULL, NULL, ghInst, NULL);
#else
    main_menu_handle=LoadMenu(ghInst, MAKEINTRESOURCE(IDM_MAINMENU));
    if(main_menu_handle && cmdline.service) {
        /* block unsafe operations in the service mode */
        EnableMenuItem(main_menu_handle, IDM_EDIT_CONFIG, MF_GRAYED);
        EnableMenuItem(main_menu_handle, IDM_SAVE_LOG, MF_GRAYED);
    }
    hwnd=CreateWindow(classname, win32_name, WS_TILEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
        NULL, main_menu_handle, ghInst, NULL);
#endif

    /* auto-reset, non-signaled events */
    main_initialized=CreateEvent(NULL, FALSE, FALSE, NULL);
    config_ready=CreateEvent(NULL, FALSE, FALSE, NULL);
    /* hwnd needs to be initialized before _beginthread() */
    _beginthread(daemon_thread, DEFAULT_STACK_SIZE, NULL);
    WaitForSingleObject(main_initialized, INFINITE);
    /* logging subsystem is now available */

    /* setup periodic event to trigger update_logs() */
    SetTimer(NULL, 0, 1000, timer_proc); /* run callback once per second */

    s_log(LOG_DEBUG, "GUI message loop initialized");
    for(;;)
        switch(GetMessage(&msg, NULL, 0, 0)) {
        case -1:
            ioerror("GetMessage");
            return 0;
        case 0:
            s_log(LOG_DEBUG, "GUI message loop terminated");
            return (int)msg.wParam;
        default:
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
}
Exemple #4
0
/*
 *--------------------------------------------------------------
 *
 * OS_LibInit --
 *
 *	Set up the OS library for use.
 *
 * Results:
 *	Returns 0 if success, -1 if not.
 *
 * Side effects:
 *	Sockets initialized, pseudo file descriptors setup, etc.
 *
 *--------------------------------------------------------------
 */
int OS_LibInit(int stdioFds[3])
{
    WORD  wVersion;
    WSADATA wsaData;
    int err;
    int fakeFd;
    char *cLenPtr = NULL;
    char *val = NULL;

//	char * abc;
//	int nTestFcgi;

	char namepipe[256];

    if(libInitialized)
        return 0;

    InitializeCriticalSection(&fdTableCritical);   
        
    /*
     * Initialize windows sockets library.
     */
    wVersion = MAKEWORD(2,0);
    err = WSAStartup( wVersion, &wsaData );
    if (err) {
        fprintf(stderr, "Error starting Windows Sockets.  Error: %d",
		WSAGetLastError());
	exit(111);
    }

    /*
     * Create the I/O completion port to be used for our I/O queue.
     */
    if (hIoCompPort == INVALID_HANDLE_VALUE) {
	hIoCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
					      0, 1);
	if(hIoCompPort == INVALID_HANDLE_VALUE) {
	    printf("<H2>OS_LibInit Failed CreateIoCompletionPort!  ERROR: %d</H2>\r\n\r\n",
	       GetLastError());
	    return -1;
	}
    }

    /*
     * If a shutdown event is in the env, save it (I don't see any to 
     * remove it from the environment out from under the application).
     * Spawn a thread to wait on the shutdown request.
     */
    val = getenv(SHUTDOWN_EVENT_NAME);
    if (val != NULL) 
    {
        HANDLE shutdownEvent = (HANDLE) atoi(val);

        if (_beginthread(ShutdownRequestThread, 0, shutdownEvent) == -1)
        {
            return -1;
        }
    }

    if (acceptMutex == INVALID_HANDLE_VALUE)
    {
        /* If an accept mutex is in the env, use it */
        val = getenv(MUTEX_VARNAME);
        if (val != NULL) 
        {
            acceptMutex = (HANDLE) atoi(val);
        }
    }

    /*
     * Determine if this library is being used to listen for FastCGI
     * connections.  This is communicated by STDIN containing a
     * valid handle to a listener object.  In this case, both the
     * "stdout" and "stderr" handles will be INVALID (ie. closed) by
     * the starting process.
     *
     * The trick is determining if this is a pipe or a socket...
     *
     * XXX: Add the async accept test to determine socket or handle to a
     *      pipe!!!
     */
    if((GetStdHandle(STD_OUTPUT_HANDLE) == INVALID_HANDLE_VALUE) &&
       (GetStdHandle(STD_ERROR_HANDLE)  == INVALID_HANDLE_VALUE) &&
       (GetStdHandle(STD_INPUT_HANDLE)  != INVALID_HANDLE_VALUE) ) 
    {
        DWORD pipeMode = PIPE_READMODE_BYTE | PIPE_WAIT;
        HANDLE oldStdIn = GetStdHandle(STD_INPUT_HANDLE);

        // Move the handle to a "low" number
        if (! DuplicateHandle(GetCurrentProcess(), oldStdIn,
		                         GetCurrentProcess(), &hListen,
                              0, TRUE, DUPLICATE_SAME_ACCESS))
        {
            return -1;
        }

        if (! SetStdHandle(STD_INPUT_HANDLE, hListen))
        {
            return -1;
        }

        CloseHandle(oldStdIn);
		//OutputDebugString("CloseHandle(oldStdIn);\n");
#ifdef DEBUG_CGI
		//OutputDebugString("in  DEBUG_CGI \n");
		
		sprintf(namepipe,"%s\\%d","\\\\.\\pipe\\FastCGI\\dynamic",getpid());
		//OutputDebugString(namepipe);
		hListen=CreateNamedPipe( 
			//"\\\\.\\pipe\\FastCGI\\dynamic\\abc",             // pipe name 
			namepipe,
			PIPE_ACCESS_DUPLEX,       // read/write access 
			PIPE_TYPE_MESSAGE |       // message type pipe 
			PIPE_READMODE_MESSAGE |   // message-read mode 
			PIPE_WAIT,                // blocking mode 
			PIPE_UNLIMITED_INSTANCES, // max. instances  
			4096,                  // output buffer size 
			4096,                  // input buffer size 
			NMPWAIT_USE_DEFAULT_WAIT, // client time-out 
			NULL);


  #endif
	/*
	 * Set the pipe handle state so that it operates in wait mode.
	 *
	 * NOTE: The listenFd is not mapped to a pseudo file descriptor
	 *       as all work done on it is contained to the OS library.
	 *
	 * XXX: Initial assumption is that SetNamedPipeHandleState will
	 *      fail if this is an IP socket...
	 */
        if (SetNamedPipeHandleState(hListen, &pipeMode, NULL, NULL)) 
        {
            listenType = FD_PIPE_SYNC;
        } 
        else 
        {
            listenType = FD_SOCKET_SYNC;
        }
    }

    /*
     * If there are no stdioFds passed in, we're done.
     */
    if(stdioFds == NULL) {
        libInitialized = 1;
        return 0;
    }

    /*
     * Setup standard input asynchronous I/O.  There is actually a separate
     * thread spawned for this purpose.  The reason for this is that some
     * web servers use anonymous pipes for the connection between itself
     * and a CGI application.  Anonymous pipes can't perform asynchronous
     * I/O or use I/O completion ports.  Therefore in order to present a
     * consistent I/O dispatch model to an application we emulate I/O
     * completion port behavior by having the standard input thread posting
     * messages to the hIoCompPort which look like a complete overlapped
     * I/O structure.  This keeps the event dispatching simple from the
     * application perspective.
     */
    stdioHandles[STDIN_FILENO] = GetStdHandle(STD_INPUT_HANDLE);

    if(!SetHandleInformation(stdioHandles[STDIN_FILENO],
			     HANDLE_FLAG_INHERIT, 0)) {
/*
 * XXX: Causes error when run from command line.  Check KB
        err = GetLastError();
        DebugBreak();
	exit(99);
 */
    }

    if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
				     (int)stdioHandles[STDIN_FILENO],
				     STDIN_FILENO)) == -1) {
        return -1;
    } else {
        /*
	 * Set stdin equal to our pseudo FD and create the I/O completion
	 * port to be used for async I/O.
	 */
	stdioFds[STDIN_FILENO] = fakeFd;
    }

    /*
     * Create the I/O completion port to be used for communicating with
     * the thread doing I/O on standard in.  This port will carry read
     * and possibly thread termination requests to the StdinThread.
     */
    if (hStdinCompPort == INVALID_HANDLE_VALUE) {
	hStdinCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
					      0, 1);
	if(hStdinCompPort == INVALID_HANDLE_VALUE) {
	    printf("<H2>OS_LibInit Failed CreateIoCompletionPort: STDIN!  ERROR: %d</H2>\r\n\r\n",
	       GetLastError());
	    return -1;
	}
    }

    /*
     * Create the thread that will read stdin if the CONTENT_LENGTH
     * is non-zero.
     */
    if((cLenPtr = getenv("CONTENT_LENGTH")) != NULL &&
       atoi(cLenPtr) > 0) {
        hStdinThread = (HANDLE) _beginthread(StdinThread, 0, NULL);
	if (hStdinThread == (HANDLE) -1) {
	    printf("<H2>OS_LibInit Failed to create STDIN thread!  ERROR: %d</H2>\r\n\r\n",
		   GetLastError());
	    return -1;
        }
    }

    /*
     * STDOUT will be used synchronously.
     *
     * XXX: May want to convert this so that it could be used for OVERLAPPED
     *      I/O later.  If so, model it after the Stdin I/O as stdout is
     *      also incapable of async I/O on some servers.
     */
    stdioHandles[STDOUT_FILENO] = GetStdHandle(STD_OUTPUT_HANDLE);
    if(!SetHandleInformation(stdioHandles[STDOUT_FILENO],
			     HANDLE_FLAG_INHERIT, FALSE)) {
        DebugBreak();
	exit(99);
    }

    if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
				     (int)stdioHandles[STDOUT_FILENO],
				     STDOUT_FILENO)) == -1) {
        return -1;
    } else {
        /*
	 * Set stdout equal to our pseudo FD
	 */
	stdioFds[STDOUT_FILENO] = fakeFd;
    }

    stdioHandles[STDERR_FILENO] = GetStdHandle(STD_ERROR_HANDLE);
    if(!SetHandleInformation(stdioHandles[STDERR_FILENO],
			     HANDLE_FLAG_INHERIT, FALSE)) {
        DebugBreak();
	exit(99);
    }
    if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
				     (int)stdioHandles[STDERR_FILENO],
				     STDERR_FILENO)) == -1) {
        return -1;
    } else {
        /*
	 * Set stderr equal to our pseudo FD
	 */
	stdioFds[STDERR_FILENO] = fakeFd;
    }

    return 0;
}
Exemple #5
0
void do_send(char *host,int timeout) {
	t1=(HANDLE)_beginthread(sendstr,0,host);
	if (t1==0) { err_exit("-> Failed to send exploit string..."); }
	t2=(HANDLE)_beginthread(setalarm,0,timeout);
	if (t2==0) { err_exit("-> Failed to set alarm clock..."); }
}
Exemple #6
0
int
pthread_create (pthread_t * tid,
                const pthread_attr_t * attr,
                void *(PTW32_CDECL *start) (void *), void *arg)
/*
 * ------------------------------------------------------
 * DOCPUBLIC
 *      This function creates a thread running the start function,
 *      passing it the parameter value, 'arg'. The 'attr'
 *      argument specifies optional creation attributes.
 *      The identity of the new thread is returned
 *      via 'tid', which should not be NULL.
 *
 * PARAMETERS
 *      tid
 *              pointer to an instance of pthread_t
 *
 *      attr
 *              optional pointer to an instance of pthread_attr_t
 *
 *      start
 *              pointer to the starting routine for the new thread
 *
 *      arg
 *              optional parameter passed to 'start'
 *
 *
 * DESCRIPTION
 *      This function creates a thread running the start function,
 *      passing it the parameter value, 'arg'. The 'attr'
 *      argument specifies optional creation attributes.
 *      The identity of the new thread is returned
 *      via 'tid', which should not be the NULL pointer.
 *
 * RESULTS
 *              0               successfully created thread,
 *              EINVAL          attr invalid,
 *              EAGAIN          insufficient resources.
 *
 * ------------------------------------------------------
 */
{
    pthread_t thread = { 0 };		// init to shut up MSVC2013: warning C4701 : potentially uninitialized local variable 'thread' used
    ptw32_thread_t * tp;
    ptw32_thread_t * sp;
    register pthread_attr_t a;
    HANDLE threadH = 0;
    int result = EAGAIN;
    int run = PTW32_TRUE;
    ThreadParms *parms = NULL;
    unsigned int stackSize;
    int priority;

    /*
     * Before doing anything, check that tid can be stored through
     * without invoking a memory protection error (segfault).
     * Make sure that the assignment below can't be optimised out by the compiler.
     * This is assured by conditionally assigning *tid again at the end.
     */
    tid->x = 0;

    if (NULL == (sp = (ptw32_thread_t *)pthread_self().p))
    {
        goto FAIL0;
    }

    if (attr != NULL)
    {
        a = *attr;
    }
    else
    {
        a = NULL;
    }

    thread = ptw32_new();
    if (thread.p == NULL)
    {
        goto FAIL0;
    }

    tp = (ptw32_thread_t *) thread.p;

    priority = tp->sched_priority;

    if ((parms = (ThreadParms *) malloc (sizeof (*parms))) == NULL)
    {
        goto FAIL0;
    }

    parms->tid = thread;
    parms->start = start;
    parms->arg = arg;

    /*
     * Threads inherit their initial sigmask and CPU affinity from their creator thread.
     */
#if defined(HAVE_SIGSET_T)
    tp->sigmask = sp->sigmask;
#endif
#if defined(HAVE_CPU_AFFINITY)
    tp->cpuset = sp->cpuset;
#endif

    if (a != NULL)
    {
#if defined(HAVE_CPU_AFFINITY)
        cpu_set_t none;
        cpu_set_t attr_cpuset;
        ((_sched_cpu_set_vector_*)&attr_cpuset)->_cpuset = a->cpuset;

        CPU_ZERO(&none);
        if (! CPU_EQUAL(&attr_cpuset, &none))
        {
            tp->cpuset = a->cpuset;
        }
#endif
        stackSize = (unsigned int)a->stacksize;
        tp->detachState = a->detachstate;
        priority = a->param.sched_priority;
        if (a->thrname != NULL)
            tp->name = _strdup(a->thrname);

#if (THREAD_PRIORITY_LOWEST > THREAD_PRIORITY_NORMAL)
        /* WinCE */
#else
        /* Everything else */

        /*
         * Thread priority must be set to a valid system level
         * without altering the value set by pthread_attr_setschedparam().
         */

        /*
         * PTHREAD_EXPLICIT_SCHED is the default because Win32 threads
         * don't inherit their creator's priority. They are started with
         * THREAD_PRIORITY_NORMAL (win32 value). The result of not supplying
         * an 'attr' arg to pthread_create() is equivalent to defaulting to
         * PTHREAD_EXPLICIT_SCHED and priority THREAD_PRIORITY_NORMAL.
         */
        if (PTHREAD_INHERIT_SCHED == a->inheritsched)
        {
            /*
             * If the thread that called pthread_create() is a Win32 thread
             * then the inherited priority could be the result of a temporary
             * system adjustment. This is not the case for POSIX threads.
             */
            priority = sp->sched_priority;
        }

#endif

    }
    else
    {
        /*
         * Default stackSize
         */
        stackSize = PTHREAD_STACK_MIN;
    }

    tp->state = run ? PThreadStateInitial : PThreadStateSuspended;

    tp->keys = NULL;

    /*
     * Threads must be started in suspended mode and resumed if necessary
     * after _beginthreadex returns us the handle. Otherwise we set up a
     * race condition between the creating and the created threads.
     * Note that we also retain a local copy of the handle for use
     * by us in case thread.p->threadH gets NULLed later but before we've
     * finished with it here.
     */

#if ! defined (PTW32_CONFIG_MINGW) || defined (__MSVCRT__) || defined (__DMC__)

    tp->threadH =
        threadH =
            (HANDLE) _beginthreadex ((void *) NULL,	/* No security info             */
                                     stackSize,		/* default stack size   */
                                     ptw32_threadStart,
                                     parms,
                                     (unsigned)
                                     CREATE_SUSPENDED,
                                     (unsigned *) &(tp->thread));

    if (threadH != 0)
    {
        if (a != NULL)
        {
            (void) ptw32_setthreadpriority (thread, SCHED_OTHER, priority);
        }

#if defined(HAVE_CPU_AFFINITY)

        SetThreadAffinityMask(tp->threadH, tp->cpuset);

#endif

        if (run)
        {
            ResumeThread (threadH);
        }
    }

#else

    {
        ptw32_mcs_local_node_t stateLock;

        /*
         * This lock will force pthread_threadStart() to wait until we have
         * the thread handle and have set the priority.
         */
        ptw32_mcs_lock_acquire(&tp->stateLock, &stateLock);

        tp->threadH =
            threadH =
                (HANDLE) _beginthread (ptw32_threadStart, stackSize,	/* default stack size   */
                                       parms);

        /*
         * Make the return code match _beginthreadex's.
         */
        if (threadH == (HANDLE) - 1L)
        {
            tp->threadH = threadH = 0;
        }
        else
        {
            if (!run)
            {
                /*
                 * beginthread does not allow for create flags, so we do it now.
                 * Note that beginthread itself creates the thread in SUSPENDED
                 * mode, and then calls ResumeThread to start it.
                 */
                SuspendThread (threadH);
            }

            if (a != NULL)
            {
                (void) ptw32_setthreadpriority (thread, SCHED_OTHER, priority);
            }

#if defined(HAVE_CPU_AFFINITY)

            SetThreadAffinityMask(tp->threadH, tp->cpuset);

#endif

        }

        ptw32_mcs_lock_release (&stateLock);
    }
#endif

    result = (threadH != 0) ? 0 : EAGAIN;

    /*
     * Fall Through Intentionally
     */

    /*
     * ------------
     * Failure Code
     * ------------
     */

FAIL0:
    if (result != 0)
    {
        ptw32_threadDestroy (thread);
        tp = NULL;

        if (parms != NULL)
        {
            free (parms);
        }
    }
    else
    {
        *tid = thread;
    }

#if defined(_UWIN)
    if (result == 0)
        pthread_count++;
#endif
    return (result);
}				/* pthread_create */
void CGitPropertyPage::InitWorkfileView()
{
	if (filenames.empty())
		return;

	CTGitPath path(filenames.front().c_str());

	CString ProjectTopDir;
	if(!path.HasAdminDir(&ProjectTopDir))
		return;

	CAutoRepository repository(CUnicodeUtils::GetUTF8(ProjectTopDir));
	if (!repository)
		return;

	CString username;
	CString useremail;
	CString autocrlf;
	CString safecrlf;

	CAutoConfig config(repository);
	if (config)
	{
		config.GetString(L"user.name", username);
		config.GetString(L"user.email", useremail);
		config.GetString(L"core.autocrlf", autocrlf);
		config.GetString(L"core.safecrlf", safecrlf);
	}

	CString branch;
	CString remotebranch;
	if (!git_repository_head_detached(repository))
	{
		CAutoReference head;
		if (git_repository_head_unborn(repository))
		{
			git_reference_lookup(head.GetPointer(), repository, "HEAD");
			branch = CUnicodeUtils::GetUnicode(git_reference_symbolic_target(head));
			if (branch.Find(_T("refs/heads/")) == 0)
				branch = branch.Mid(11); // 11 = len("refs/heads/")
		}
		else if (!git_repository_head(head.GetPointer(), repository))
		{
			const char * branchChar = git_reference_shorthand(head);
			branch = CUnicodeUtils::GetUnicode(branchChar);

			const char * branchFullChar = git_reference_name(head);
			CAutoBuf upstreambranchname;
			if (!git_branch_upstream_name(upstreambranchname, repository, branchFullChar))
			{
				remotebranch = CUnicodeUtils::GetUnicode(CStringA(upstreambranchname->ptr, (int)upstreambranchname->size));
				remotebranch = remotebranch.Mid(13); // 13=len("refs/remotes/")
			}
		}
	}
	else
		branch = _T("detached HEAD");

	if (autocrlf.Trim().IsEmpty())
		autocrlf = _T("false");
	if (safecrlf.Trim().IsEmpty())
		safecrlf = _T("false");

	SetDlgItemText(m_hwnd,IDC_CONFIG_USERNAME,username.Trim());
	SetDlgItemText(m_hwnd,IDC_CONFIG_USEREMAIL,useremail.Trim());
	SetDlgItemText(m_hwnd,IDC_CONFIG_AUTOCRLF,autocrlf.Trim());
	SetDlgItemText(m_hwnd,IDC_CONFIG_SAFECRLF,safecrlf.Trim());

	SetDlgItemText(m_hwnd,IDC_SHELL_CURRENT_BRANCH,branch.Trim());
	SetDlgItemText(m_hwnd,IDC_SHELL_REMOTE_BRANCH, remotebranch);

	git_oid oid;
	CAutoCommit HEADcommit;
	if (!git_reference_name_to_id(&oid, repository, "HEAD") && !git_commit_lookup(HEADcommit.GetPointer(), repository, &oid) && HEADcommit)
		DisplayCommit(HEADcommit, IDC_HEAD_HASH, IDC_HEAD_SUBJECT, IDC_HEAD_AUTHOR, IDC_HEAD_DATE);

	{
		int stripLength = ProjectTopDir.GetLength();
		if (ProjectTopDir[stripLength - 1] != _T('\\'))
			++stripLength;

		bool allAreFiles = true;
		for (auto it = filenames.cbegin(); it < filenames.cend(); ++it)
		{
			if (PathIsDirectory(it->c_str()))
			{
				allAreFiles = false;
				break;
			}
		}
		if (allAreFiles)
		{
			size_t assumevalid = 0;
			size_t skipworktree = 0;
			size_t executable = 0;
			size_t symlink = 0;
			do
			{
				CAutoIndex index;
				if (git_repository_index(index.GetPointer(), repository))
					break;

				for (auto it = filenames.cbegin(); it < filenames.cend(); ++it)
				{
					CTGitPath file;
					file.SetFromWin(CString(it->c_str()).Mid(stripLength));
					CStringA pathA = CUnicodeUtils::GetMulti(file.GetGitPathString(), CP_UTF8);
					size_t idx;
					if (!git_index_find(&idx, index, pathA))
					{
						const git_index_entry *e = git_index_get_byindex(index, idx);

						if (e->flags & GIT_IDXENTRY_VALID)
							++assumevalid;

						if (e->flags_extended & GIT_IDXENTRY_SKIP_WORKTREE)
							++skipworktree;

						if (e->mode & 0111)
							++executable;

						if ((e->mode & GIT_FILEMODE_LINK) == GIT_FILEMODE_LINK)
							++symlink;
					}
					else
					{
						// do not show checkboxes for unversioned files
						ShowWindow(GetDlgItem(m_hwnd, IDC_ASSUMEVALID), SW_HIDE);
						ShowWindow(GetDlgItem(m_hwnd, IDC_SKIPWORKTREE), SW_HIDE);
						ShowWindow(GetDlgItem(m_hwnd, IDC_EXECUTABLE), SW_HIDE);
						ShowWindow(GetDlgItem(m_hwnd, IDC_SYMLINK), SW_HIDE);
						break;
					}
				}
			} while (0);

			if (assumevalid != 0 && assumevalid != filenames.size())
			{
				SendMessage(GetDlgItem(m_hwnd, IDC_ASSUMEVALID), BM_SETSTYLE, (DWORD)GetWindowLong(GetDlgItem(m_hwnd, IDC_ASSUMEVALID), GWL_STYLE) & ~BS_AUTOCHECKBOX | BS_AUTO3STATE, 0);
				SendMessage(GetDlgItem(m_hwnd, IDC_ASSUMEVALID), BM_SETCHECK, BST_INDETERMINATE, 0);
			}
			else
				SendMessage(GetDlgItem(m_hwnd, IDC_ASSUMEVALID), BM_SETCHECK, (assumevalid == 0) ? BST_UNCHECKED : BST_CHECKED, 0);

			if (skipworktree != 0 && skipworktree != filenames.size())
			{
				SendMessage(GetDlgItem(m_hwnd, IDC_SKIPWORKTREE), BM_SETSTYLE, (DWORD)GetWindowLong(GetDlgItem(m_hwnd, IDC_SKIPWORKTREE), GWL_STYLE) & ~BS_AUTOCHECKBOX | BS_AUTO3STATE, 0);
				SendMessage(GetDlgItem(m_hwnd, IDC_SKIPWORKTREE), BM_SETCHECK, BST_INDETERMINATE, 0);
			}
			else
				SendMessage(GetDlgItem(m_hwnd, IDC_SKIPWORKTREE), BM_SETCHECK, (skipworktree == 0) ? BST_UNCHECKED : BST_CHECKED, 0);

			if (executable != 0 && executable != filenames.size())
			{
				SendMessage(GetDlgItem(m_hwnd, IDC_EXECUTABLE), BM_SETSTYLE, (DWORD)GetWindowLong(GetDlgItem(m_hwnd, IDC_EXECUTABLE), GWL_STYLE) & ~BS_AUTOCHECKBOX | BS_AUTO3STATE, 0);
				SendMessage(GetDlgItem(m_hwnd, IDC_EXECUTABLE), BM_SETCHECK, BST_INDETERMINATE, 0);
				EnableWindow(GetDlgItem(m_hwnd, IDC_SYMLINK), TRUE);
			}
			else
			{
				SendMessage(GetDlgItem(m_hwnd, IDC_EXECUTABLE), BM_SETCHECK, (executable == 0) ? BST_UNCHECKED : BST_CHECKED, 0);
				EnableWindow(GetDlgItem(m_hwnd, IDC_SYMLINK), (executable == 0) ? TRUE : FALSE);
			}

			if (symlink != 0 && symlink != filenames.size())
			{
				SendMessage(GetDlgItem(m_hwnd, IDC_SYMLINK), BM_SETSTYLE, (DWORD)GetWindowLong(GetDlgItem(m_hwnd, IDC_SYMLINK), GWL_STYLE) & ~BS_AUTOCHECKBOX | BS_AUTO3STATE, 0);
				SendMessage(GetDlgItem(m_hwnd, IDC_SYMLINK), BM_SETCHECK, BST_INDETERMINATE, 0);
				EnableWindow(GetDlgItem(m_hwnd, IDC_EXECUTABLE), TRUE);
			}
			else
			{
				SendMessage(GetDlgItem(m_hwnd, IDC_SYMLINK), BM_SETCHECK, (symlink == 0) ? BST_UNCHECKED : BST_CHECKED, 0);
				EnableWindow(GetDlgItem(m_hwnd, IDC_EXECUTABLE), (symlink == 0) ? TRUE : FALSE);
			}
		}
		else
		{
			ShowWindow(GetDlgItem(m_hwnd, IDC_ASSUMEVALID), SW_HIDE);
			ShowWindow(GetDlgItem(m_hwnd, IDC_SKIPWORKTREE), SW_HIDE);
			ShowWindow(GetDlgItem(m_hwnd, IDC_EXECUTABLE), SW_HIDE);
			ShowWindow(GetDlgItem(m_hwnd, IDC_SYMLINK), SW_HIDE);
		}
	}

	if (filenames.size() == 1 && !PathIsDirectory(filenames[0].c_str()))
	{
		SetDlgItemText(m_hwnd, IDC_LAST_SUBJECT, CString(MAKEINTRESOURCE(IDS_LOADING)));
		_beginthread(LogThreadEntry, 0, this);
	}
	else
		ShowWindow(GetDlgItem(m_hwnd, IDC_STATIC_LASTMODIFIED), SW_HIDE);
}
Exemple #8
0
void doCalccPrintSamples(int channel)
{	// no sample buffering - use in single cal mode
	_beginthread(CalccPrintSamples, 0, (void *)channel);
}
Exemple #9
0
void Character::Control(GLdouble FrameInterval)
{
	GLdouble step = WALK_SPEED;
	if(bSpecial[GLUT_KEY_SHIFT_L])
		step *= SPRINT_KOEF;

	if(bKeyboard['W']) {
		dVelocityX -= FrameInterval*AIR_ACCEL*step*sin(TORAD(dSpinY));
		dVelocityZ -= FrameInterval*AIR_ACCEL*step*cos(TORAD(dSpinY));
	}
	if(bKeyboard['S']) {
		dVelocityX += FrameInterval*AIR_ACCEL*step*sin(TORAD(dSpinY));
		dVelocityZ += FrameInterval*AIR_ACCEL*step*cos(TORAD(dSpinY));
	}
	if(bKeyboard['D']) {
		dVelocityX += FrameInterval*AIR_ACCEL*step*cos(TORAD(dSpinY));
		dVelocityZ -= FrameInterval*AIR_ACCEL*step*sin(TORAD(dSpinY));
	}
	if(bKeyboard['A']) {
		dVelocityX -= FrameInterval*AIR_ACCEL*step*cos(TORAD(dSpinY));
		dVelocityZ += FrameInterval*AIR_ACCEL*step*sin(TORAD(dSpinY));
	}
	if(bKeyboard['R']) {
		dVelocityY += FrameInterval*AIR_ACCEL*step;
	}
	if(bKeyboard['F']) {
		dVelocityY -= FrameInterval*AIR_ACCEL*step;
	}

	GLdouble ko = dVelocityX*dVelocityX + dVelocityZ*dVelocityZ;
	if(ko > WALK_SPEED*WALK_SPEED*SPRINT_KOEF*SPRINT_KOEF) {
		ko = pow(ko, 0.5);
		dVelocityX = dVelocityX*WALK_SPEED*SPRINT_KOEF/ko;
		dVelocityZ = dVelocityZ*WALK_SPEED*SPRINT_KOEF/ko;
	}

	if(bKeyboard[VK_SPACE]) {
	}
	
	if(bKeyboard['X']) {
		dVelocityX = 0;
		dVelocityY = 0;
		dVelocityZ = 0;
	}
	
	GLdouble yerr, xerr, zerr;
	GetPlane(&xerr, &yerr, &zerr);
	
	PosInWorld pos;
	if(zerr < xerr && zerr < yerr) {
		if((position.bz < centerPos.bz && position.cz == centerPos.cz) || position.cz < centerPos.cz) {
			pos = PosInWorld(0, 0, 0.5);
		} else {
			pos = PosInWorld(0, 0, -0.5);
		}
	} else if(xerr < zerr && xerr < yerr) {
		if((position.bx < centerPos.bx && position.cx == centerPos.cx) || position.cx < centerPos.cx) {
			pos = PosInWorld(0.5, 0, 0);
		} else {
			pos = PosInWorld(-0.5, 0, 0);
		}
	} else if(yerr < xerr && yerr < zerr) {
		if(position.by < centerPos.by) {
			pos = PosInWorld(0, 0.5, 0);
		} else {
			pos = PosInWorld(0, -0.5, 0);
		}
	}
	aimedBlock = BlockInWorld(centerPos + pos);
	freeBlock = BlockInWorld(centerPos + pos.inv());

	int num = 100;
	int sq = 100;
	int sqb2 = sq/2;

	if(bKeyboard['1']) {
		int i = 0;
		while(i < num) {
			if(wWorld.AddBlock(BlockInWorld(rand()%sq-sqb2, abs(rand()%sq-sqb2), rand()%sq-sqb2), rand()%14+1, true))
				i++;
		}
	}
	if(bKeyboard['2']) {
		int i = 0;
		while(i < num) {
			if(wWorld.RemoveBlock(BlockInWorld(rand()%sq-sqb2, rand()%sq-sqb2, rand()%sq-sqb2), true))
				i++;
		}
	}

	if(bKeyboard['3']) {
		for(BlockCoord i = -sqb2; i <= sqb2; i++) {
			for(BlockCoord j = -sqb2; j <= sqb2; j++) {
				for(BlockCoord k = -sqb2; k <= sqb2; k++) {
					wWorld.RemoveBlock(BlockInWorld(i, j, k), true);
				}
			}
		}
	}

	if(bKeyboard['4']) {
		wWorld.LoadChunk(0, 0);
		bKeyboard['4'] = false;
	}
	if(bKeyboard['5']) {
		wWorld.UnLoadChunk(0, 0);
		bKeyboard['5'] = false;
	}
	if(bKeyboard['6']) {
		for(int i = 0; i < 8; i++)
			for(int j = 0; j < 8; j++)
				wWorld.LoadChunk(i, j);
		bKeyboard['6'] = false;
	}
	if(bKeyboard['7']) {
		for(int i = 0; i < 8; i++)
			for(int j = 0; j < 8; j++)
				wWorld.UnLoadChunk(i, j);
		bKeyboard['7'] = false;
	}

	if(bKeyboard['0']) {
		static Param par = {0, 1, &wWorld};

		_beginthread(LoadNGenerate, 0, &par);

		WaitForSingleObject(wWorld.parget2, INFINITE);
		ResetEvent(wWorld.parget2);

		par.z++;
		bKeyboard['0'] = false;
	}
	
	if(bKeyboard['C']) {
		Chunk *chunk;
		int index;
		wWorld.FindBlock(aimedBlock, &chunk, &index);
		if ((chunk)&&(chunk->bBlocks[index].cMaterial == MAT_DIRT)) {
			chunk->bBlocks[index].bVisible ^= (1 << SNOWCOVERED);
		}
	}
	if(bKeyboard['V']) {
		Chunk *chunk;
		int index;
		wWorld.FindBlock(aimedBlock, &chunk, &index);
		if ((chunk)&&(chunk->bBlocks[index].cMaterial == MAT_DIRT)) {
			chunk->bBlocks[index].bVisible ^= (1 << GRASSCOVERED);
		}
	}
	if(bKeyboard['E']) {
		wWorld.RemoveBlock(aimedBlock, true);
	}
	if(bKeyboard['Q']) {
		wWorld.AddBlock(freeBlock, MAT_PUMPKIN_SHINE, true);
	}
	if(bKeyboard['O']) {
		wWorld.SaveChunks();
	}

	position = position + PosInWorld(FrameInterval*dVelocityX, FrameInterval*dVelocityY, FrameInterval*dVelocityZ);

	/*{
		signed short xx, yy, zz;
		GLdouble wx = gfPosX + gfVelX;
		GLdouble wy = gfPosY - PLAYER_HEIGHT + 0.1;
		GLdouble wz = gfPosZ;

		xx = floor(wx/TILE_SIZE + 0.5);
		zz = floor(wz/TILE_SIZE + 0.5);
		yy = floor(wy/TILE_SIZE);

		if((FindTile(xx, yy, zz) == NULL)&&(FindTile(xx, yy + 1, zz) == NULL))
			gfPosX += g_FrameInterval*gfVelX;
		else gfVelX = 0;
	}
	{
		signed short xx, yy, zz;
		GLdouble wx = gfPosX;
		GLdouble wy = gfPosY - PLAYER_HEIGHT + 0.1;
		GLdouble wz = gfPosZ + gfVelZ;

		xx = floor(wx/TILE_SIZE + 0.5);
		zz = floor(wz/TILE_SIZE + 0.5);
		yy = floor(wy/TILE_SIZE);

		if((FindTile(xx, yy, zz) == NULL)&&(FindTile(xx, yy + 1, zz) == NULL))
			gfPosZ += g_FrameInterval*gfVelZ;
		else gfVelZ = 0;
	}
	*/
	/*if(falling)
	{
		gfPosY -= g_FrameInterval*gfVelY;
		if(gfVelY < MAX_DOWNSTEP)
			gfVelY += g_FrameInterval*STEP_DOWNSTEP;
	}*/
	/*
	{
		signed short xx, yy, zz;
		GLdouble wx = gfPosX;
		GLdouble wy = gfPosY - PLAYER_HEIGHT;
		GLdouble wz = gfPosZ;

		xx = floor(wx/TILE_SIZE + 0.5);
		zz = floor(wz/TILE_SIZE + 0.5);
		yy = floor(wy/TILE_SIZE);

		if(FindTile(xx, yy, zz) == NULL) falling = true;
		else
		{
			gfVelY = 0;
			if(falling)
			{
				falling = false;
				gfPosY = (yy + 1)*TILE_SIZE + PLAYER_HEIGHT - 0.001;
			}
		}
	}

	if(!falling)
	{
		gfVelX = 0;
		gfVelZ = 0;
	}*/
	//falling = 1;

// 	if(dPositionX >= LOCATION_SIZE_XZ*TILE_SIZE) { dPositionX -= LOCATION_SIZE_XZ*TILE_SIZE; lnwPositionX++;}
// 	if(dPositionX < 0) { dPositionX += LOCATION_SIZE_XZ*TILE_SIZE; lnwPositionX--;}
// 	if(dPositionZ >= LOCATION_SIZE_XZ*TILE_SIZE) { dPositionZ -= LOCATION_SIZE_XZ*TILE_SIZE; lnwPositionZ++;}
// 	if(dPositionZ < 0) { dPositionZ += LOCATION_SIZE_XZ*TILE_SIZE; lnwPositionZ--;}

}
Exemple #10
0
int main(){

    HWND hwnd = GetConsoleWindow();
	ShowWindow(hwnd,SW_MAXIMIZE);
    console_settings();
    console_resize(3);
    login=fopen("save\\logins.dat","rb");
    if(login==NULL)
        admin_settings_signup();
    else
        admin_settings_signin();

    main_menu();
    start_socket();
    start_server();

    handleAccept = (HANDLE) _beginthread(thd_accept_connections,0,0);
    handleMessages = (HANDLE) _beginthread(thd_program_messages,0,0);
    //clientHandle = (HANDLE) _beginthread( thd_receive_data,0,0);

    while(1){  // The interface part
      switch(getch()){
        case '1':
                if(flag_menu==0)
                   requests();
                else if(flag_menu==2)
                    services();
                else if(flag_menu==21)
                    add_services();
                else if(flag_menu==22)
                    setcost();
                else if(flag_menu==24)
                    change_password();
                break;
            case '2':
                if(flag_menu==0)
                    settings();
                else if(flag_menu==2)
                    cost();
                else if(flag_menu==22)
                    viewcost();
                else if(flag_menu==21)
                    view_services();
                break;
            case '3':
                if(flag_menu==0){
                    saveMessagesToFile();
                    exit(0);
                }
                else if(flag_menu==2)
                    member_settings_signup();
                else if(flag_menu==21)
                    edit_services();
                break;
            case '4':
                if(flag_menu==21)
                    search_services();
                else if(flag_menu==2)
                    admin_settings();
                break;
            case '5':
                if(flag_menu==21)
                    delete_services();
                         break;
            case 'r':
                if(flag_menu == 0)
                    flag_reset = true;
                    main_menu();
                    break;

            case 27:
                if(flag_menu==2 || flag_menu==1 )
                    main_menu();
                else if(flag_menu==21)
                     settings();
                else if( flag_menu==22)
                     settings();
                else if(flag_menu==23)
                     settings();
                else if(flag_menu==24)
                     settings();
                else if(flag_menu==211)
                     services();
                else if(flag_menu==212)
                     services();
                else if(flag_menu==213)
                     services();
                else if(flag_menu==214)
                     services();
                else if(flag_menu==215)
                     services();
                else if(flag_menu==221 || flag_menu==222)
                     cost();
                break;
            default:
                break;
            }
        }
return 0;
}
Exemple #11
0
CFtpGet::CFtpGet(char *URL,char *localfile,char *Username,char *Password)
{
	SOCKADDR_IN listensockaddr;
	m_State = FTP_STATE_STARTUP;

	m_ListenSock = INVALID_SOCKET;
	m_DataSock = INVALID_SOCKET;
	m_ControlSock = INVALID_SOCKET;
	m_iBytesIn = 0;
	m_iBytesTotal = 0;
	m_Aborting = false;
	m_Aborted = false;

	LOCALFILE = fopen(localfile,"wb");
	if(NULL == LOCALFILE)
	{
		m_State = FTP_STATE_CANT_WRITE_FILE;
		return;
	}

	if(Username)
	{
		strcpy(m_szUserName,Username);
	}
	else
	{
		strcpy(m_szUserName,"anonymous");
	}
	if(Password)
	{
		strcpy(m_szPassword,Password);
	}
	else
	{
		strcpy(m_szPassword,"*****@*****.**");
	}
	m_ListenSock = socket(AF_INET, SOCK_STREAM, 0);
	if(INVALID_SOCKET == m_ListenSock)
	{
		// vint iWinsockErr = WSAGetLastError();
		m_State = FTP_STATE_SOCKET_ERROR;
		return;
	}
	else
	{
		listensockaddr.sin_family = AF_INET;		
		listensockaddr.sin_port = 0;
		listensockaddr.sin_addr.s_addr = INADDR_ANY;
							
		// Bind the listen socket
		if (bind(m_ListenSock, (SOCKADDR *)&listensockaddr, sizeof(SOCKADDR)))
		{
			//Couldn't bind the socket
			// int iWinsockErr = WSAGetLastError();
			m_State = FTP_STATE_SOCKET_ERROR;
			return;
		}

		// Listen for the server connection
		if (listen(m_ListenSock, 1))	
		{
			//Couldn't listen on the socket
			// int iWinsockErr = WSAGetLastError();
			m_State = FTP_STATE_SOCKET_ERROR;
			return;
		}
	}
	m_ControlSock = socket(AF_INET, SOCK_STREAM, 0);
	if(INVALID_SOCKET == m_ControlSock)
	{
		m_State = FTP_STATE_SOCKET_ERROR;
		return;
	}
	//Parse the URL
	//Get rid of any extra ftp:// stuff
	char *pURL = URL;
	if(_strnicmp(URL,"ftp:",4)==0)
	{
		pURL +=4;
		while(*pURL == '/')
		{
			pURL++;
		}
	}
	//There shouldn't be any : in this string
	if(strchr(pURL,':'))
	{
		m_State = FTP_STATE_URL_PARSING_ERROR;
		return;
	}
	//read the filename by searching backwards for a /
	//then keep reading until you find the first /
	//when you found it, you have the host and dir
	char *filestart = NULL;
	char *dirstart = NULL;
	for(int i = strlen(pURL);i>=0;i--)
	{
		if(pURL[i]== '/')
		{
			if(!filestart)
			{
				filestart = pURL+i+1;
				dirstart = pURL+i+1;
				strcpy(m_szFilename,filestart);
			}
			else
			{
				dirstart = pURL+i+1;
			}
		}
	}
	if((dirstart==NULL) || (filestart==NULL))
	{
		m_State = FTP_STATE_URL_PARSING_ERROR;
		return;
	}
	else
	{
		strncpy(m_szDir,dirstart,(filestart-dirstart));
		m_szDir[(filestart-dirstart)] = '\0';
		strncpy(m_szHost,pURL,(dirstart-pURL));
		m_szHost[(dirstart-pURL)-1] = '\0';
	}
	//At this point we should have a nice host,dir and filename
	
	//if(NULL==CreateThread(NULL,0,ObjThread,this,0,&m_dwThreadId))
	if(NULL==_beginthread(FTPObjThread,0,this))
	{
		m_State = FTP_STATE_INTERNAL_ERROR;
		return;
	}
	m_State = FTP_STATE_CONNECTING;
}
void main(int argc, char* argv[])
{
    // error message
    wchar_t pTemp[121];
    unsigned int errStrSize = 120;

    // initialize global critical section
    ::InitializeCriticalSection(&gCS);

    // initialize variables for .exe, .ini, and .log file names
    wchar_t pModuleFile[nBufferSize + 1];
    DWORD dwSize = GetModuleFileName(nullptr, (LPTSTR)pModuleFile, nBufferSize);
    pModuleFile[dwSize] = 0;

    if (dwSize > 4 && pModuleFile[dwSize - 4] == '.')
    {
        swprintf(pExeFile, nBufferSize, L"%s", pModuleFile);
        pModuleFile[dwSize - 4] = 0;
        swprintf(pLogFile, nBufferSize, L"%s.log", pModuleFile);
    }
    else
    {
        printf("Invalid module file name: %ws\r\n", pModuleFile);
        return;
    }

    WriteLog(pExeFile);
    WriteLog(pLogFile);
    wcscpy_s(pServiceName, 500, L"CodeXLDriversLoadService");
    WriteLog(pServiceName);

    // uninstall service if switch is "-u"
    if (argc == 2 && _stricmp("-uninstall", argv[1]) == 0)
    {
        UnInstall(pServiceName);
    }
    // install service if switch is "-i"
    else if (argc == 2 && _stricmp("-install", argv[1]) == 0)
    {
        Install(pExeFile, pServiceName);
    }
    // stop a service with given name
    else if (argc == 2 && _stricmp("-stop", argv[1]) == 0)
    {
        if (StopService(pServiceName))
        {
            swprintf(pTemp, errStrSize, L"Stopped service %s", pServiceName);
            WriteLog(pTemp);
        }
        else
        {
            swprintf(pTemp, errStrSize, L"Failed to stop service %s", pServiceName);
            WriteLog(pTemp);
        }
    }
    // run a service with given name
    else if (argc == 2 && _stricmp("-start", argv[1]) == 0)
    {
        WriteLog(L"StartService");

        if (StartService(pServiceName, 0, nullptr))
        {
            swprintf(pTemp, errStrSize, L"Ran service %s", pServiceName);
            WriteLog(pTemp);
        }
        else
        {
            swprintf(pTemp, errStrSize, L"Failed to run service %s", pServiceName);
            WriteLog(pTemp);
        }
    }
    // assume user is starting this service
    else
    {
        // start a worker thread to load driver
        if (_beginthread(WorkerProc, 0, nullptr) == -1)
        {
            WriteErrorLog(L"_beginthread failed");
        }

        // pass dispatch table to service controller
        if (!StartServiceCtrlDispatcher(DispatchTable))
        {
            WriteErrorLog(L"StartServiceCtrlDispatcher failed");
        }

        // you don't get here unless the service is shutdown
    }

    ::DeleteCriticalSection(&gCS);
}
CFrameWorkApp::CFrameWorkApp()
{
    uintptr_t hThread = _beginthread(framework_main_thread,0,0);
};
Exemple #14
0
BOOL CALLBACK ExpandVolProgressDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static EXPAND_VOL_THREAD_PARAMS *pProgressDlgParam;
	static BOOL bVolTransformStarted = FALSE;
	static BOOL showRandPool = TRUE;

	WORD lw = LOWORD (wParam);

	switch (msg)
	{
	case WM_INITDIALOG:
		{
			char szOldHostSize[512], szNewHostSize[512];

			pProgressDlgParam = (EXPAND_VOL_THREAD_PARAMS*)lParam;
			bVolTransformStarted = FALSE;
			showRandPool = TRUE;

			hCurPage = hwndDlg;
			nPbar = IDC_PROGRESS_BAR;

			GetSpaceString(szOldHostSize,sizeof(szOldHostSize),pProgressDlgParam->oldSize,pProgressDlgParam->bIsDevice);
			GetSpaceString(szNewHostSize,sizeof(szNewHostSize),pProgressDlgParam->newSize,pProgressDlgParam->bIsDevice);

			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_OLDSIZE), szOldHostSize);
			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NEWSIZE), szNewHostSize);
			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NAME), pProgressDlgParam->szVolumeName);
			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_FILE_SYSTEM), szFileSystemStr[pProgressDlgParam->FileSystem]);
			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_INITSPACE), pProgressDlgParam->bInitFreeSpace?"Yes":"No");

			SendMessage (GetDlgItem (hwndDlg, IDC_BOX_STATUS), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE);

			SendMessage (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE);

			// set status text
			if ( !pProgressDlgParam->bInitFreeSpace && pProgressDlgParam->bIsLegacy )
			{
				showRandPool = FALSE;
				EnableWindow (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), FALSE);
				EnableWindow (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), FALSE);
				SetDlgItemText(hwndDlg, IDC_BOX_STATUS, "Click 'Continue' to expand the volume.");
			}
			else
			{
				SetDlgItemText(hwndDlg, IDC_BOX_STATUS, "IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the encryption keys. Then click 'Continue' to expand the volume.");
			}

			SendMessage (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), BM_SETCHECK, showRandPool ? BST_CHECKED : BST_UNCHECKED, 0);
			SetTimer (hwndDlg, TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL);
		}
		return 0;
	case TC_APPMSG_VOL_TRANSFORM_THREAD_ENDED:
		{
			int nStatus = (int)lParam;

			NormalCursor ();
			if (nStatus != 0)
			{
				if ( nStatus != ERR_USER_ABORT )
					AddProgressDlgStatus (hwndDlg, "Error: volume expansion failed.");
				else
					AddProgressDlgStatus (hwndDlg, "Error: operation aborted by user.");
			}
			else
			{
				AddProgressDlgStatus (hwndDlg, "Finished. Volume successfully expanded.");
			}

			SetWindowText (GetDlgItem (hwndDlg, IDOK), "Exit");
			EnableWindow (GetDlgItem (hwndDlg, IDOK), TRUE);
			EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE);
		}
		return 1;

	case WM_TIMER:

		switch (wParam)
		{
		case TIMER_ID_RANDVIEW:
			{
				unsigned char tmp[16] = {0};
				char szRndPool[64] = {0};

				if (!showRandPool)
					return 1;

				RandpeekBytes (hwndDlg, tmp, sizeof (tmp));

				StringCbPrintfA (szRndPool, sizeof(szRndPool), "%08X%08X%08X%08X", 
					*((DWORD*) (tmp + 12)), *((DWORD*) (tmp + 8)), *((DWORD*) (tmp + 4)), *((DWORD*) (tmp)));

				SetWindowText (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), szRndPool);

				burn (tmp, sizeof(tmp));
				burn (szRndPool, sizeof(szRndPool));
			}
			return 1;
		}
		return 0;

	case WM_COMMAND:
		if (lw == IDC_DISPLAY_POOL_CONTENTS)
		{
			showRandPool = IsButtonChecked (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS));
			return 1;
		}
		if (lw == IDCANCEL)
		{
			if (bVolTransformStarted)
			{
				if (MessageBoxW (hwndDlg, L"Warning: Volume expansion is in progress!\n\nStopping now may result in a damaged volume.\n\nDo you really want to cancel?", lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO)
					return 1;

				// tell the volume transform thread to terminate
				bVolTransformThreadCancel = TRUE;
			}
			EndDialog (hwndDlg, lw);
			return 1;
		}

		if (lw == IDOK)
		{
			if (bVolTransformStarted)
			{
				// TransformThreadFunction finished -> OK button is now exit
				EndDialog (hwndDlg, lw);
			}
			else
			{
				showRandPool = FALSE;
				KillTimer (hwndDlg, TIMER_ID_RANDVIEW);
				EnableWindow (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), FALSE);
				EnableWindow (GetDlgItem (hwndDlg, IDOK), FALSE);
				SetProgressDlgStatus (hwndDlg, "Starting volume expansion ...\r\n");
				bVolTransformStarted = TRUE;
				pProgressDlgParam->hwndDlg = hwndDlg;
				if ( _beginthread (volTransformThreadFunction, 0, pProgressDlgParam) == -1L )
				{
					handleError (hwndDlg, ERR_OS_ERROR, SRC_POS);
					EndDialog (hwndDlg, lw);
				}
				WaitCursor();
			}
			return 1;
		}

		return 0;
	}

	return 0;
}
Exemple #15
0
void CClock::Start(void)
{
	// 시계스레드 시작
	_beginthread(OnTimer, 0, this);
}
Exemple #16
0
void fnSaverThread(void *p)
{
  HWND hwndOldFocus;
  HWND hwndParent = (HWND) p;
  HWND hwndOldSysModal;
  HAB hab;
  QMSG msg;
  ULONG ulStyle;

  // Set our thread to slightly more than regular to be able
  // to update the screen fine.
  DosSetPriority(PRTYS_THREAD, PRTYC_REGULAR, +5, 0);

  hab = WinInitialize(0);
  hmqSaverThreadMsgQueue = WinCreateMsgQueue(hab, 0);

  if (bOnlyPreviewMode)
  {
    PFNWP pfnOldWindowProc;
    // We should run in preview mode, so the hwndParent we have is not the
    // desktop, but a special window we have to subclass.
    pfnOldWindowProc = WinSubclassWindow(hwndParent,
                                         (PFNWP) fnSaverWindowProc);

    // Initialize window proc (simulate WM_CREATE)
    WinSendMsg(hwndParent, WM_SUBCLASS_INIT, (MPARAM) NULL, (MPARAM) NULL);
    // Also make sure that the window will be redrawn with this new
    // window proc.
    WinInvalidateRect(hwndParent, NULL, FALSE);

    iSaverThreadState = STATE_RUNNING;

#ifdef DEBUG_LOGGING
    AddLog("[fnSaverThread] : Starting Cairo drawing thread\n");
#endif
    // Start Cairo drawing thread
    tidCairoDrawThread = _beginthread(CairoDrawThread,
                                      0,
                                      1024*1024,
                                      (void *) hwndParent);

#ifdef DEBUG_LOGGING
    AddLog("[fnSaverThread] : Entering message loop (Preview)\n");
#endif

    // Process messages until WM_QUIT!
    while (WinGetMsg(hab, &msg, 0, 0, 0))
      WinDispatchMsg(hab, &msg);

#ifdef DEBUG_LOGGING
    AddLog("[fnSaverThread] : Leaved message loop (Preview)\n");
#endif

#ifdef DEBUG_LOGGING
    AddLog("[fnSaverThread] : Stopping Cairo drawing thread\n");
#endif
    bShutdownDrawing = 1;
    DosWaitThread(&tidCairoDrawThread, DCWW_WAIT);


    // Uinitialize window proc (simulate WM_DESTROY)
    WinSendMsg(hwndParent, WM_SUBCLASS_UNINIT, (MPARAM) NULL, (MPARAM) NULL);

    // Undo subclassing
    WinSubclassWindow(hwndParent,
                      pfnOldWindowProc);
    // Also make sure that the window will be redrawn with the old
    // window proc.
    WinInvalidateRect(hwndParent, NULL, FALSE);

    iSaverThreadState = STATE_STOPPED_OK;
  } else
  {
    // We should run in normal mode, so create a new window, topmost, and everything else...
    WinRegisterClass(hab, (PSZ) pchSaverWindowClassName,
                     (PFNWP) fnSaverWindowProc,
                     CS_SIZEREDRAW | CS_CLIPCHILDREN | CS_CLIPSIBLINGS, 0);

    hwndOldFocus = WinQueryFocus(HWND_DESKTOP);

    // Create the saver output window so that it will be the child of
    // the given parent window.
    // Make window 'Always on top' because we'll be in real screensaver mode!
    ulStyle = WS_VISIBLE | WS_TOPMOST;
    hwndSaverWindow = WinCreateWindow(HWND_DESKTOP, pchSaverWindowClassName, "Screen saver",
                                      ulStyle,
                                      0, 0,
                                      (int) WinQuerySysValue(HWND_DESKTOP, SV_CXSCREEN),
                                      (int) WinQuerySysValue(HWND_DESKTOP, SV_CYSCREEN),
                                      HWND_DESKTOP,
                                      HWND_TOP,
                                      0x9fff, // Some ID....
                                      NULL, NULL);
    if (!hwndSaverWindow)
    {
#ifdef DEBUG_LOGGING
      AddLog("[fnSaverThread] : Could not create window!\n");
#endif
      // Yikes, could not create window!
      iSaverThreadState = STATE_STOPPED_ERROR;
    } else
    {
      // Cool, window created!

      // Make sure nobody will be able to switch away of it!
      // We do this by making the window system-modal, and giving it the focus!
      hwndOldSysModal = WinQuerySysModalWindow(HWND_DESKTOP);
      WinSetSysModalWindow(HWND_DESKTOP, hwndSaverWindow);
      WinSetFocus(HWND_DESKTOP, hwndSaverWindow);

      iSaverThreadState = STATE_RUNNING;

#ifdef DEBUG_LOGGING
      AddLog("[fnSaverThread] : Starting Cairo drawing thread\n");
#endif
      // Start Cairo drawing thread
      tidCairoDrawThread = _beginthread(CairoDrawThread,
                                        0,
                                        1024*1024,
                                        (void *) hwndSaverWindow);

#ifdef DEBUG_LOGGING
      AddLog("[fnSaverThread] : Entering message loop (Real)\n");
#endif
      // Process messages until WM_QUIT!
      while (WinGetMsg(hab, &msg, 0, 0, 0))
        WinDispatchMsg(hab, &msg);
#ifdef DEBUG_LOGGING
      AddLog("[fnSaverThread] : Leaved message loop (Real)\n");
#endif

#ifdef DEBUG_LOGGING
      AddLog("[fnSaverThread] : Stopping Cairo drawing thread\n");
#endif
      bShutdownDrawing = 1;
      DosWaitThread(&tidCairoDrawThread, DCWW_WAIT);

      // Undo system modalling
      WinSetSysModalWindow(HWND_DESKTOP, hwndOldSysModal);

      // Window closed, so destroy every resource we created!
      WinDestroyWindow(hwndSaverWindow);

      // Restore focus to old window
      WinSetFocus(HWND_DESKTOP, hwndOldFocus);

#ifdef DEBUG_LOGGING
      AddLog("[fnSaverThread] : STATE_STOPPED_OK\n");
#endif

      iSaverThreadState = STATE_STOPPED_OK;
    }
  }

  WinDestroyMsgQueue(hmqSaverThreadMsgQueue);
  WinTerminate(hab);

  _endthread();
}
Exemple #17
0
/***************************************************************
【函数功能】: 打开串口
【输    入】: port:串口号(默认0)。【构造函数时也可指定串口号】
【输    出】: 执行结果:0正确,-1错误。
【说    明】: 正确用法有3种:<1> CSensor *p = new CSensor(n);  p->open();
					<2> CSensor *p = new CSensor(n); p->open(n);
					<3> CSensor *p = new CSensor;   p->open(n);
***************************************************************/
int CSensor::Open(int port)
{
	if(m_bPortOpened)
		return -1;
	// 读取配置
	
	string iniFile = string(INI_FILE);
	//if (mrpt::system::fileExists(iniFile) == false)	// INI 文件找不到
	//{
	//	cout << "!Sensor传感:start():找不到ini文件!" << iniFile << endl;
	//	return -1;	
	//}						// ini文件在主窗口init时检查一次即可,不存在则退出
	mrpt::utils::CConfigFile INI_Cfg(iniFile);
	m_iPort = INI_Cfg.read_int("Sensor", "COM_Port", 0);
	// 读取传感器位置及配置
	std::vector<double> aux; // Auxiliar vector
	std::stringstream sname;
	for (int i=0; i<NUM_OF_USENSOR; i++)
	{
		sname.str("");
		sname.clear();
		sname<<"pose"<<i;
		INI_Cfg.read_vector("Sensor", sname.str(), aux, aux, false);
		m_pUS[i].pose = TPose3D( aux[0], aux[1], aux[2], 
			DEG2RAD( (double)aux[3]), DEG2RAD( (double)aux[4]), DEG2RAD( (double)aux[5]) );
		m_pUS[i].stopZone = (double)aux[6];
		m_pUS[i].id = i;
		m_pUS[i].distance = 2.0;	// 初始值设为2m
		m_pUS[i].bValid = true;		// 初始化都有效
	}
	m_timestamp_US = mrpt::system::now();
	// 如果形参有传入,则以传入值为主,并修改ini文件
	if (port > 0)
	{
		INI_Cfg.write("Sensor", "COM_Port", port);	// 用传入形参更新配置文件数据
		m_iPort = port;
	}
	else
	{
		if (m_iPort <= 0)
		{
			cout<<"[!!!] Sensor: 必须指定一个大于0的串口号!"<<endl;
			return -1;
		}
	}
	// 打开串口
	if(sio_open(m_iPort) != SIO_OK)
	{
		cout<<"[!!!] Sensor: 打开串口错误!"<<endl;
		return -1;
	}
	sio_ioctl(m_iPort, B115200, P_NONE | BIT_8 | STOP_1 );
	sio_cnt_irq(m_iPort,RecvCall, 1);
	// 创建发送线程
	m_bSendThreadStopFlag = false;
	//m_hSendThreadHandle = CreateThread(NULL,NULL,
	//				(LPTHREAD_START_ROUTINE)SendThread,this,NULL,NULL);
	m_hSendThreadHandle = (HANDLE)_beginthread(SendThread, 0, this);
	////////////////////////////////
	m_bPortOpened = true;
	cout<<"[+] Sensor: Started !"<<endl;
	return 0;
}
Exemple #18
0
void node_init() {
    node_bundled_backend_js = str_printf("%s/bin/livereload-backend.js", os_bundled_backend_path);
    _beginthread(node_thread, 0, NULL);
}
int __cdecl main()
{
	// [+] socket setup
	// borrowed from MSDN - https://msdn.microsoft.com/en-us/library/windows/desktop/ms738545%28v=vs.85%29.aspx

	// Initialize Winsock
	WSADATA wsaData = { 0 };
	int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (result != 0) {
		printf("WSAStartup failed: %d\n", result);
		return -1;
	}

	struct addrinfo hints = { 0 };
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE;

	// Resolve the local address and port to be used by the server
	struct addrinfo *ainfo;
	result = getaddrinfo(LHOST, LPORT, &hints, &ainfo);
	if (result != 0) {
		printf("getaddrinfo failed: %d\n", result);
		WSACleanup();
		return -1;
	}

	// Create a SOCKET for the server to listen for client connections
	SOCKET listenSocket;
	if ((listenSocket = socket(ainfo->ai_family, ainfo->ai_socktype, ainfo->ai_protocol)) == INVALID_SOCKET) {
		printf("socket() failed with error: %ld\n", WSAGetLastError());
		freeaddrinfo(ainfo);
		WSACleanup();
		return -1;
	}

	// Setup the TCP listening socket
	if ((bind(listenSocket, ainfo->ai_addr, (int)ainfo->ai_addrlen)) == SOCKET_ERROR) {
		printf("bind() failed with error: %d\n", WSAGetLastError());
		freeaddrinfo(ainfo);
		closesocket(listenSocket);
		WSACleanup();
		return -1;
	}
	freeaddrinfo(ainfo);

	// Listen on the socket
	if (listen(listenSocket, SOMAXCONN) == SOCKET_ERROR) {
		printf("listen() failed with error: %ld\n", WSAGetLastError());
		closesocket(listenSocket);
		WSACleanup();
		return -1;
	}

	printf("[+] Listening for connections.\n");
	
	// [+] handle connections
	// borrowed from http://stackoverflow.com/a/15185627
	while (1) {
		// Accept a connection
		SOCKET clientSocket;
		if ((clientSocket = accept(listenSocket, NULL, NULL)) == INVALID_SOCKET) {
			printf("accept failed: %d\n", WSAGetLastError());
			continue;
		}
		printf("Received connection from remote host.\n");

		// Create thread to handle connection
		_beginthread(&handleConnection, 0, (void*)clientSocket);
		printf("Connection handed off to handler thread.\n");
	}
}
Exemple #20
0
int go(char *input, ENGINE_STATE *stat)
{  
  stat->control->max_depth = MAXDEPTH;
  stat->control->max_time = INFINITE;
  stat->control->wish_time = INFINITE;
  stat->control->stop = 1;
  stat->control->ponder = 0;
  ResetTimes(stat);
  int movestogo = 20;
  char manage_times = 1;
  char *str_param = strtok(input, " \n\t");
  for (str_param = strtok(NULL, " \n\t"); str_param; str_param = strtok(NULL, " \n\t")) {
    if (!strcmp("depth",  str_param)) {
      str_param = strtok(NULL, " \n\t");
      if (str_param) {
        stat->control->max_depth = atoi(str_param);
        manage_times = 0;
      }
      break;
    } else if (!strcmp("time",  str_param)) {
      str_param = strtok(NULL, " \n\t");
      if (str_param) {
        stat->control->wish_time = INFINITE;
        stat->control->max_time = atol(str_param);
        manage_times = 0;
      }
    } else if (!strcmp("infinite",  str_param)) {
      manage_times = 0;
      break;
    } else if (!strcmp("ponder", str_param)) {
      stat->control->ponder = 1;
    } else if (!strcmp("btime",  str_param)) {
      str_param = strtok(NULL, " \n\t");
      if (str_param) {
        stat->control->btime = atoi(str_param);
      }
    } else if (!strcmp("wtime",  str_param)) {
      str_param = strtok(NULL, " \n\t");
      if (str_param) {
        stat->control->wtime = atoi(str_param);
      }
    } else if (!strcmp("binc",  str_param)) {
      str_param = strtok(NULL, " \n\t");
      if (str_param) {
        stat->control->btime_inc = atoi(str_param);
      }
    } else if (!strcmp("winc",  str_param)) {
      str_param = strtok(NULL, " \n\t");
      if (str_param) {
        stat->control->wtime_inc = atoi(str_param);
      }
    } else if (!strcmp("movestogo",  str_param)) {
      str_param = strtok(NULL, " \n\t");
      if (str_param) {
        movestogo = atoi(str_param);
      }
    } else break;
  }

  if (stat->control->stop) {
    if (manage_times) {
      ManageTimes(movestogo, stat);
    }
    stat->control->stop = 0;
    stat->control->init_time = clock();
#ifdef __linux__
    pthread_attr_t tattr;
    pthread_attr_init(&tattr);
    pthread_attr_setdetachstate(&tattr,PTHREAD_CREATE_DETACHED);

    pthread_t thread_id;
    pthread_create(&thread_id, &tattr, (void *)(think), stat);
#elif defined _WIN32
    _beginthread(think, 0, stat);
#endif
  }
  return 1;
}
Exemple #21
0
//
//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	TCHAR szHello[MAX_LOADSTRING];
	LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);

	switch (message) 
	{
		case WM_COMMAND:
			wmId    = LOWORD(wParam); 
			wmEvent = HIWORD(wParam); 
			// Parse the menu selections:
			switch (wmId)
			{
				case IDM_ABOUT:
				   DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
				   break;
				case IDM_VIEW_25:
				case IDM_VIEW_33:
				case IDM_VIEW_50:
				case IDM_VIEW_100:
				case IDM_VIEW_200:
				case IDM_VIEW_300:
				case IDM_VIEW_400:
                    iViewScale = wmId - IDM_VIEW_100;
                    InvalidateRect(hWnd, NULL, TRUE);
                    UpdateMenu(hWnd);
                    break;
                case ID_VIEW_ANIMATE:
                    bAnimate = !bAnimate;
                    UpdateMenu(hWnd);
                    break;
                case ID_VIEW_FRAME:
                    bAnimate = FALSE;
                    if (hFrameEvent)
                        SetEvent(hFrameEvent);
                    UpdateMenu(hWnd);
                    break;
				case IDM_EXIT:
				   DestroyWindow(hWnd);
				   break;
				default:
				   return DefWindowProc(hWnd, message, wParam, lParam);
			}
			break;
		case WM_DROPFILES:
		{
			HDROP hDrop = (HDROP) wParam;

			// Don't accept more dropped files
			::DragAcceptFiles(hWnd, FALSE);

			// Get number of files dropped
			const int iFiles = ::DragQueryFile(hDrop, ~0U, NULL, 0);

			// Free previous file list (if allocated)
			if (pszFileList)
			{
				GlobalFreePtr(pszFileList);
			}

			// Allocate buffer to hold list of files
			pszFileList = (LPTSTR) GlobalAllocPtr(GMEM_ZEROINIT, iFiles * MAX_PATH);
			if (pszFileList)
			{
				LPTSTR pFile = pszFileList;
				for (int iIndex = 0; iIndex < iFiles; ++iIndex)
				{
					if (::DragQueryFile(hDrop, iIndex, pFile, MAX_PATH))
					{
						TRACE("WM_DROPFILES (%d of %d) szPathName=%s\n", iIndex, iFiles, pFile);
						// Add terminating '\n' between files
						int iLength = lstrlen(pFile);
						pFile += (iLength + 1);
					}
				}
				*pFile++ = '\0';
				pszCurrentFile = pszFileList;
			}
			DragFinish(hDrop);
			break;
		}
		case WM_CREATE:
		{
			HDC hDC = ::GetDC(hWnd);
#ifdef PALETTE_SUPPORT
			hPalette = ::CreateHalftonePalette(hDC);
#endif // PALETTE_SUPPORT
			::ReleaseDC(hWnd, hDC);
			ghwndGIF = hWnd;
			_beginthread(DrawGifThread, 0, hWnd);
            UpdateMenu(hWnd);
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		case WM_PAINT:
		{	
			RECT rect;
			GetClientRect(hWnd, &rect);

			HDC hDC = BeginPaint(hWnd, &ps);
#ifdef PALETTE_SUPPORT
			// Select and realize palette (for 8-bit displays)
			HPALETTE hOldPal = ::SelectPalette(hDC, hPalette, TRUE);
			::RealizePalette(hDC);
			gif.Draw(hDC, &rect, iViewScale);
			if (hOldPal)
				::SelectPalette(hDC, hOldPal, TRUE);
#else
			gif.Draw(hDC, &rect, iViewScale);
#endif // PALETTE_SUPPORT
			EndPaint(hWnd, &ps);
			break;
		}
		case WM_DESTROY:
		{
			ghwndGIF = NULL;
			Sleep(1000);			// Wait for thread to self destruct

			// Free previous file list (if allocated)
			if (pszFileList)
			{
				TRACE("Free pszFileList!\n");
				GlobalFreePtr(pszFileList);
				pszFileList = NULL;
			}
#ifdef PALETTE_SUPPORT
			if (hPalette)
			{
				TRACE("Delete palette!\n");
				::DeleteObject(hPalette);
				hPalette = NULL;
			}
#endif // PALETTE_SUPPORT
			PostQuitMessage(0);
			break;
		}
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}
Exemple #22
0
void Server::start(unsigned short port)
{
	_port = port;
	serverThread = _beginthread(&_startThread, 0, this);
}
Exemple #23
0
bool dlmstp_init(
    char *ifname)
{
    unsigned long hThread = 0;
    uint32_t arg_value = 0;
    TIMECAPS tc;

    /* initialize packet queue */
    Receive_Packet.ready = false;
    Receive_Packet.pdu_len = 0;
    Receive_Packet_Flag = CreateSemaphore(NULL, 0, 1, "dlmstpReceivePacket");
    if (Receive_Packet_Flag == NULL)
        exit(1);
    Received_Frame_Flag = CreateSemaphore(NULL, 0, 1, "dlsmtpReceiveFrame");
    if (Received_Frame_Flag == NULL) {
        CloseHandle(Receive_Packet_Flag);
        exit(1);
    }
    /* initialize hardware */
    /* initialize hardware */
    if (ifname) {
        RS485_Set_Interface(ifname);
#if PRINT_ENABLED
        fprintf(stderr, "MS/TP Interface: %s\n", ifname);
#endif
    }
    RS485_Initialize();
    MSTP_Port.InputBuffer = &RxBuffer[0];
    MSTP_Port.InputBufferSize = sizeof(RxBuffer);
    MSTP_Port.OutputBuffer = &TxBuffer[0];
    MSTP_Port.OutputBufferSize = sizeof(TxBuffer);
    MSTP_Port.SilenceTimer = Timer_Silence;
    MSTP_Port.SilenceTimerReset = Timer_Silence_Reset;
    MSTP_Init(&MSTP_Port);
#if 0
    uint8_t data;

    /* FIXME: implement your data storage */
    data = 64;  /* I2C_Read_Byte(
                   EEPROM_DEVICE_ADDRESS,
                   EEPROM_MSTP_MAC_ADDR); */
    if (data <= 127)
        MSTP_Port.This_Station = data;
    else
        dlmstp_set_my_address(DEFAULT_MAC_ADDRESS);
    /* FIXME: implement your data storage */
    data = 127; /* I2C_Read_Byte(
                   EEPROM_DEVICE_ADDRESS,
                   EEPROM_MSTP_MAX_MASTER_ADDR); */
    if ((data <= 127) && (data >= MSTP_Port.This_Station))
        MSTP_Port.Nmax_master = data;
    else
        dlmstp_set_max_master(DEFAULT_MAX_MASTER);
    /* FIXME: implement your data storage */
    data = 1;
    /* I2C_Read_Byte(
       EEPROM_DEVICE_ADDRESS,
       EEPROM_MSTP_MAX_INFO_FRAMES_ADDR); */
    if (data >= 1)
        MSTP_Port.Nmax_info_frames = data;
    else
        dlmstp_set_max_info_frames(DEFAULT_MAX_INFO_FRAMES);
#endif
#if PRINT_ENABLED
    fprintf(stderr, "MS/TP MAC: %02X\n", MSTP_Port.This_Station);
    fprintf(stderr, "MS/TP Max_Master: %02X\n", MSTP_Port.Nmax_master);
    fprintf(stderr, "MS/TP Max_Info_Frames: %u\n", MSTP_Port.Nmax_info_frames);
#endif
    /* set timer resolution */
    if (timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
        fprintf(stderr, "Failed to set timer resolution\n");
    }
    TimeBeginPeriod =
        min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);
    timeBeginPeriod(TimeBeginPeriod);

    /* start the threads */
    hThread = _beginthread(dlmstp_receive_fsm_task, 4096, &arg_value);
    if (hThread == 0) {
        fprintf(stderr, "Failed to start recive FSM task\n");
    }
    hThread = _beginthread(dlmstp_master_fsm_task, 4096, &arg_value);
    if (hThread == 0) {
        fprintf(stderr, "Failed to start Master Node FSM task\n");
    }

    return true;
}
Exemple #24
0
void
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
    int   file_count=0;
    int   getoptch;
    int   currarg;
    extern char *optarg;
    extern int  optind;
    int   i, j;
    char  *tempch;
    int   err;

#define SLEEP_USEC  100
#ifdef WIN32
    WSADATA   WSAData;
#else

    struct timeval sleeptime;

    /* set the amount of time that we'll pause before sending a "." to the
       webmaster */

    sleeptime.tv_sec = SLEEP_USEC/1000000;
    sleeptime.tv_usec = SLEEP_USEC % 1000000;
#endif /* WIN32 */

    debugfile = stderr;

#ifdef WIN32
    MessageBeep(~0U); /* announce our existence */
    MessageBeep(~0U);
    MessageBeep(~0U);

    err = WSAStartup(MAKEWORD(1,1), &WSAData);
    if (err != 0) {
  errexit("Error in WSAStartup()\n");
    }

    atexit(sock_cleanup);

    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);

    /* create semaphore in locked state */
    hSemaphore = CreateSemaphore(0, 0, 1, 0);
    if(hSemaphore == 0)
    {
  errexit("Create semaphore failed: %d", GetLastError());
    }
#endif /* WIN32 */

    memset(webserver, 0, sizeof(webserver));
    memset(webmaster, 0, sizeof(webmaster));
    memset(proxyserver, 0, sizeof(proxyserver));
    memset(connectstr, 0, sizeof(connectstr));

    /*
     * PARSE THE COMMAND LINE OPTIONS
     */

    while((getoptch = getopt(argc,argv,"P:f:t:l:p:u:R:w:c:n:sdv")) != EOF)
    {
        switch(getoptch)
        {
  case 'c':
            sprintf(connectstr, "%s", optarg);
      amclient = 1;
            printf("%s", OKSTR);     /* sent back to webmaster */
            fflush(stdout);
      break;
        case 'd':
            debug = 0; /* sumedh */
            break;
  case 'f':
      sprintf(configfile, "%s", optarg);
      break;
        case 'l':
            numloops = atoi(optarg);
            break;
        case 'n':
            numclients = atoi(optarg);
            break;
  case 'u':
      sprintf(uil_filelist, "%s", optarg);
      uil_filelist_f = 1;
      break;
  case 'p':
      portnum = atoi(optarg);
      break;
  case 's':
      savefile = 1;
      break;
        case 't':
            testtime = 60 * atoi(optarg);
            break;
  case 'v':
      verbose = 1;
      break;
        case 'w':
            havewebserver = 1;
            sprintf(webserver,"%s",optarg);
            break;
  case 'P':
      haveproxyserver = 1;
      sprintf(proxyserver, "%s", optarg);
      break;
  case 'R':
      record_all_transactions = 1;
      break;
        default:
            usage(argv[0]);
        }
    }

    returnerr("Client begins...\n");
    D_PRINTF( "Running in debug mode\n\n" );

    /* print the command line */
    for (i = 0; i < argc; i++)
  D_PRINTF( "%s ", argv[i] );
    D_PRINTF( "\n\n" );

    if(testtime && numloops)
    {
  /*
         * EITHER numloops OR testtime, BUT NOT BOTH.
         */
        usage(argv[0]);
    }

    if(havewebserver != 1)
    {
#ifdef WIN32
        /*
         * THE SERVER'S NAME MUST BE SPECIFIED
         */
        returnerr("No WWW Server specified\n");
        usage(argv[0]);
#else
  /* IF IT ISN'T, WE ASSUME LOCALHOST */
  sprintf(webserver, "%s", "localhost");
  havewebserver = 1;
#endif /* WIN32 */
    }

    currarg = optind;
    numfiles = 0;
    while(currarg != argc)
    {
       /*
        * GET THE URLS TO RETRIEVE.
        */
       if (numfiles == MAXNUMOFFILES) {
     returnerr("Maximum of %d files on the command line.\n");
     usage(argv[0]);
       }
       sscanf(argv[currarg],"%s",filelist[numfiles]);
       numfiles++;
       currarg++;
    }

    if ((numfiles != 0) && uil_filelist_f)
    {
  returnerr("Both a filelist and UIL specified.\n");
  usage(argv[0]);
    }

    if((numfiles == 0) && !(uil_filelist_f))
    {
        /*
         * AT LEAST ONE FILE MUST BE SPECIFIED
         */
  returnerr("No UIL resources or filelist specified \n");
        usage(argv[0]);
    }

    if((numloops == 0) && (testtime == 0))
    {
        /*
         * NO SPECIFIED NUMBER OF LOOPS, AND NO TEST TIME
         */
       usage(argv[0]);
    }
    if(numclients > MAXPROCSPERNODE || numclients < 1)
    {
  returnerr("Number of Clients must be between 1 and %d\n", MAXPROCSPERNODE);
  exit(1);
    }

    /* allow use of IP address */
    if(amclient) {
  if((tempch = strpbrk(connectstr,":")) == 0)
  {
      /*
       * INCORRECT FORMAT OF ConnectStr. CORRECT FORMAT IS
       * HOSTNAME:PORT OR HOST-IP:PORT
       */
      D_PRINTF( "Incorrect format %s: use hostname:port or ip_addr:port\n",
         connectstr );
      returnerr("Incorrect format %s: use host:port or ip_addr:port\n", connectstr);
      exit(1);
  } else {
      strncpy(webmaster, connectstr, tempch-connectstr);
  }
  if(resolve_addrs(webmaster, "tcp", &webmast_phe, &webmast_ppe, &webmast_addr, &webmast_type))
      exit(1);
    }

    if (haveproxyserver)
    {
  D_PRINTF( "Copying proxy %s to webserver\n", proxyserver );
  strcpy(webserver, proxyserver);
    }

    if (resolve_addrs(webserver, "tcp", &webserv_phe, &webserv_ppe, &webserv_addr, &webserv_type))
  exit(1);

    /*
     * INITIALIZE DATA
     */
    /* allocate space for dynamic arrays */
    load_file_list =
      (page_list_t *)mymalloc((MAXNUMOFPAGES)*sizeof(page_list_t));

    if (uil_filelist_f)
    {
      /* take a guess at the number of URLs in the file */
      D_PRINTF( "About to parse filelist %s\n", uil_filelist );
      number_of_pages = count_file_list(uil_filelist);
      numfiles = 1;

      /* IF WE HAVE A FILELIST, PARSE IT */
      /* allocate memory */
      D_PRINTF( "Allocating page list: %ld by %d\n",
  number_of_pages, numfiles );
      for (i=0; i<number_of_pages; i++)
  {
    for (j=0; j<MAXNUMOFFILES; j++)
      {
        load_file_list[i].servername[j] =
    (char *)mymalloc(URL_SIZE);
        load_file_list[i].filename[j] =
    (char *)mymalloc(URL_SIZE);
      }
  }

      D_PRINTF( "Parsing file list: %s\n", uil_filelist );
      parse_file_list(uil_filelist, load_file_list,
          &number_of_pages, &numfiles);
      /* free memory for pages that won't be used? */
      D_PRINTF( "Actual page list: %ld by %d\n",
  number_of_pages, MAXNUMOFFILES );

      D_PRINTF( "Setting up weighting for %ld pages\n",
  number_of_pages );
      total_weight = load_percent(load_file_list, number_of_pages);
      /*      total_weight = load_percent(load_file_list, number_of_pages, pages); */
    }
    else
    {
  /* no uil file */
  number_of_pages = numfiles;
    }

    if (number_of_pages < 1)
      {
  /* no pages - exit */
  D_PRINTF( "No valid URLs found\n" );
  errexit("No valid URLs found\n");
      }

#ifndef WIN32
    /*
     * IF WE ARE TO FORK ADDITIONAL CLIENTS ON THIS MACHINE,
     * WE MUST DO IT BEFORE WE CONNECT TO THE MASTER.
     *
     * FIRST, SET UP SIGNAL HANDLING
     */
    signal(SIGCHLD, childhandler);
    for(i = 0; i < numclients; i++)
    {
      thr_create (0, 0, ClientThread, 0, THR_BOUND, 0);

      /* switch(fork())
         {
             case 0:
                 numclients = 1;
                 ClientThread(0);
                 exit(0);
                 break;
             case -1:
                 errexit("Error forking child processes\n");
                 exit(1);
             default:
                break;
         } */
      select(0,(fd_set *)0,(fd_set *)0, (fd_set *)0, &sleeptime);
    }

    /*
     * Wait for all children to exit.
     */

    while (thr_join(0, 0, 0) == 0);

    /*     for(;;)
       {
      int pid = wait((int*)0);
  if ((pid == -1) && errno == ECHILD) break;
       } */
#else
    /* start threads on NT */
    for (i = 0; i < numclients; i++)
    {
  if (_beginthread(ClientThread, 0, 0) == -1)
  {
      errexit("_beginthread failed: %d", GetLastError());
  }
    }
#endif /* WIN32 */

#ifdef WIN32
    /* wait for children to get to sync point */
    while (CounterSemaphore < numclients)
        sleep(1);
    CounterSemaphore = 0;

    /* start all children simultaneously */
    ReleaseSemaphore(hSemaphore, 1, 0);

    if (testtime) {
  sleep(testtime);
  alarmhandler(); /* signal end of test to threads */
    }

    /*
     * Wait for all threads to exit.
     */
    while (CounterSemaphore < numclients)
        sleep(1);

    CloseHandle(hSemaphore);
#endif /* WIN32 */

    return;
} /* end main() */
Exemple #25
0
bool CFunctionInterface::StartWork()
{
	m_hThread = (HANDLE)_beginthread( WorkThreadPro, 0, this);

	return true;
}
Exemple #26
0
void Win32MidiDriver::start() {
	HANDLE processingThreadHandle = (HANDLE)_beginthread(&messageLoop, 16384, NULL);
	SetThreadPriority(processingThreadHandle, THREAD_PRIORITY_TIME_CRITICAL);
}
Exemple #27
0
bool InternalThread::createThread()
{
    thread_printf("%s[%d]  welcome to createThread(%s)\n", __FILE__, __LINE__, idstr);
  if (isRunning()) {
     fprintf(stderr, "%s[%d]:  WARNING:  cannot create thread '%s'which is already running\n", 
             __FILE__, __LINE__, idstr);
     return true;
  }
  
  startupLock = new eventLock();
  startupLock->_Lock(__FILE__, __LINE__);

#if defined(os_windows)
  handler_thread = _beginthread(eventHandlerWrapper, 0, (void *) this);
  if (-1L == handler_thread) {
    bperr("%s[%d]:  _beginthread(...) failed\n", __FILE__, __LINE__);
    return false;
  }
#else  // Unixes

  int err = 0;
  pthread_attr_t handler_thread_attr;

  err = pthread_attr_init(&handler_thread_attr);
  if (err) {
    bperr("%s[%d]:  could not init async handler thread attributes: %s, %d\n",
          __FILE__, __LINE__, strerror(err), err);
    return false;
  }

  err = pthread_attr_setdetachstate(&handler_thread_attr, PTHREAD_CREATE_DETACHED);
  if (err) {
    bperr("%s[%d]:  could not set async handler thread attrixibcutes: %s, %d\n",
          __FILE__, __LINE__, strerror(err), err);
    return false;
  }

  try {
  err = pthread_create(&handler_thread, &handler_thread_attr,
                       &eventHandlerWrapper, (void *) this);
  if (err) {
    bperr("%s[%d]:  could not start async handler thread: %s, %d\n",
          __FILE__, __LINE__, strerror(err), err);
    fprintf(stderr,"%s[%d]:  could not start async handler thread: %s, %d\n",
          __FILE__, __LINE__, strerror(err), err);
    return false;
  }
  } catch(...) {
    assert(0);
  }

  err = pthread_attr_destroy(&handler_thread_attr);
  if (err) {
    bperr("%s[%d]:  could not destroy async handler attr: %s, %d\n",
          __FILE__, __LINE__, strerror(err), err);
    return false;
  }
#endif

  while (!_isRunning && (init_ok)) {
      thread_printf("%s[%d]:  createThread (%s) waiting for thread main to start\n", __FILE__, __LINE__, idstr);
      startupLock->_WaitForSignal(__FILE__, __LINE__);
      thread_printf("%s[%d]:  createThread (%s) got signal\n", __FILE__, __LINE__, idstr);
  }
  startupLock->_Unlock(__FILE__, __LINE__);

  thread_printf("%s[%d]: createThread returning %d\n", FILE__, __LINE__, init_ok);

  if (!init_ok) {
    return false;
  }
  return true;

}
Exemple #28
0
int 
WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
     MSG msg = {0};
     WNDCLASS wc = {0};
     RECT wr;
     unsigned threadNum;

     wr.left   = 0;
     wr.right  = VIEW_WIDTH;
     wr.top    = 0;
     wr.bottom = VIEW_HEIGHT;

     wc.lpfnWndProc = WndProc;
     wc.hInstance   = hInstance;
     wc.lpszClassName = "C8WinClass";

     if (!RegisterClass(&wc))
          return 0;

     AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);

     long style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
     /*
     style ^= WS_THICKFRAME;
     style ^= WS_MAXIMIZEBOX;
     */

     CreateWindow(wc.lpszClassName, "C8", style, 0, 0, (SCREEN_WIDTH * 4)+30, (SCREEN_HEIGHT * 4) + 30,
                  0, 0, hInstance, 0);

     freopen("stdout.txt", "w", stdout);
     freopen("stderr.txt", "w", stderr);

     if (!CHIP8_Init(lpCmdLine)) {
          running = false;
          return;
     }

     CHIP8_Reset();

     InitKeymap();

     _beginthread(InterpreterThread, 0, NULL);

     // TODO: formatting?
     while (running)
     {
          PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
          TranslateMessage(&msg);
          DispatchMessage(&msg);

          glClear(GL_COLOR_BUFFER_BIT);

          UpdateDisplay();

          SwapBuffers(dc);
     }

     return 0;
}
Exemple #29
0
/* =========================== */
int main(int argc,char *argv[])
{
   unsigned short       port;
   int                  result;
   int                  err;
   SOCKET               masterSock;
   SOCKET               clientSock;
   em_workspace_t       *wrk;
   struct sockaddr_in   servAddr;
   int                  i;
   WORD                 wVersionRequested;
   WSADATA              wsaData;
   int                  clientAddrLen;
   struct sockaddr      clientAddr;

   fprintf(stdout,"Embedded Web Server - Windows 95 : %s\n",__TIMESTAMP__);
   fprintf(stdout,"Copyright (c) 1995-1996 David M. Howard\n");

   port = w95t_server_port;

   /* initialize printf */
   printf_init();

   /* =============================================== */
   /* initialize winsock library                      */
   /* =============================================== */

   wVersionRequested = MAKEWORD(1, 1);

   err = WSAStartup(wVersionRequested, &wsaData);
   if (err != 0) {
      fprintf(stderr,"Can't initialize winsock lib\n");
      exit(1);
   }

   /* Confirm that the Windows Sockets DLL supports 1.1.*/
   /* Note that if the DLL supports versions greater */
   /* than 1.1 in addition to 1.1, it will still return */
   /* 1.1 in wVersion since that is the version we */
   /* requested. */

   if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) {
      /* Tell the user that we couldn't find a useable */
      /* winsock.dll. */
      WSACleanup();
      fprintf(stderr,"Winsock doesn't support version 1.1\n");
      exit(1);
   }

   ews_printf("Winsock Initialized OK\n");

   /* =============================================== */
   /* The Windows Sockets DLL is acceptable. Proceed. */
   /* =============================================== */

   /* Create a socket and bind address, listen for incoming connections */
   masterSock = socket( PF_INET, SOCK_STREAM, 0 );
   if ( masterSock == INVALID_SOCKET ) {
      ews_printf("socket(..) failed\n");
      exit(1);
   }

   /*lint -e740 unusual pointer cast */
   memset((char *) &servAddr, 0, sizeof servAddr );
   servAddr.sin_family      = AF_INET;
   servAddr.sin_addr.s_addr = htonl( INADDR_ANY );
   servAddr.sin_port        = htons( port );
   result = bind( masterSock, ( struct sockaddr * ) &servAddr, sizeof servAddr );
   if ( result == -1 ) {
      ews_printf("bind(..) failed\n");
      exit(1);
   }

   /*lint _e740 */

   result = listen( masterSock, 3 );
   if ( result == -1 ) {
      ews_printf("listen(..) failed\n");
      exit(1);
   }

   ews_printf("masterSock listening on port %hu\n",port);

   /* ================================== */
   /* create the client connection queue */
   /* ================================== */
   thread_sockq = socket_qinit(NUMBER_OF_SERVER_TASKS);

   /* for each vrtx connection thread */
   for(i=0;i<NUMBER_OF_SERVER_TASKS;i++) {
      /* initialize a workspace  */
      wrk = &w95t_workspace[i];

      /* clear it to all 0's to start */
      memset(wrk,0,sizeof(em_workspace_t));

      /* SOCKET IO FUNCTIONS */
      wrk->system.p           = &w95t_dresp[i];
      wrk->system.read        = w95t_Read;
      wrk->system.write       = w95t_Write;
      wrk->system.open        = w95t_Open;
      wrk->system.close       = w95t_Close;
      wrk->system.exit        = w95t_Exit;
      wrk->system.gmt         = w95t_GMT;
      wrk->system.pagebin     = app_binurl;

      /* spawn the thread and pass it the workspace pointer */
      _beginthread(w95t_server_thread,0,wrk);
   }

   /* all threads are spawned */
   /* loop, waiting for connections */
   /* when a connection is received, enqueue it for the server threads */
   for(;;) {
      /* specify the max length of the address structure and accept the
      next connection.  clientAddrLen is passed as a pointer as it is
      updated by the accept call.
      retry accept until it works
      */
      ews_printf("Accept : masterSock = %ld\n",masterSock);

      clientAddrLen = sizeof (clientAddr);
      clientSock = accept( masterSock, &clientAddr, &clientAddrLen );


      /* if accept call fails */
      if ( clientSock == INVALID_SOCKET ) {
         /* get winsock error */
         err = WSAGetLastError();

         /* print it to error output */
         ews_printf("Accept failed : %d\n",err);

         /* quit */
         break;
      }

      ews_printf("Connect : clientSock = %ld\n",clientSock);

      /* client socket is accepted  */
      /* enqueue it for the servers */
      /* return (long)clientSock;   */
      socket_qsend(thread_sockq,clientSock);
   }

   return 0;
}
void VirtualWifiNotifyIcon::start_dynamic_show()
{
	m_isdynamic_show=true;
	_beginthread(dynamic_show_icon_thread,0,this);
}