Exemple #1
0
 void Geometry::setIntersectionFilterFunction8 (RTCFilterFunc8 filter, bool ispc) 
 { 
   if (type != TRIANGLE_MESH && type != BEZIER_CURVES) {
     process_error(RTC_INVALID_OPERATION,"filter functions only supported for triangle meshes and hair geometries"); 
     return;
   }
   atomic_sub(&parent->numIntersectionFilters8,intersectionFilter8 != NULL);
   atomic_add(&parent->numIntersectionFilters8,filter != NULL);
   intersectionFilter8 = filter;
   if (ispc) ispcIntersectionFilter8 = (void*) filter; 
   else      ispcIntersectionFilter8 = NULL;
 }
Exemple #2
0
void process_float3(struct state_t* state, enum token_t t, const char* s, unsigned len, const char** attributes)
{
	if (t == token_data) {
		unsigned i;
		for(i=0;i<len;++i) {
			if (!isdigit(s[i]) && s[i] != '.') {
				process_error(state, state->level[3].tag, "float number expected");
				return;
			}
		}
		process_item3(state, t, s, len, attributes);
	}
}
Exemple #3
0
bool check_request(int clientDescriptor, std::vector<std::string> &lines,
                   std::vector<std::string> &startString) {
    if (lines.size() == 0) {
        process_error(clientDescriptor, BAD_REQUEST);
        return false;
    }
    if (startString.size() != 3) {
        process_error(clientDescriptor, BAD_REQUEST);
        return false;
    }
    if (startString[0] != "GET") {
        process_error(clientDescriptor, METHOD_NOT_ALLOWED);
        return false;
    }
    if (startString[2] != "HTTP/0.9" && startString[2] != "HTTP/1.0" &&
        startString[2] != "HTTP/1.1" && startString[2] != "HTTP/1.x") {
        process_error(clientDescriptor, HTTP_VER_NOT_SUPPORTED);
        return false;
    }

    return true;
}
Exemple #4
0
void http1_1_handler(int clientDescriptor) {

    std::vector<std::string> lines = get_request_lines(clientDescriptor);

    std::vector<std::string> startString = split(lines[0], ' ');
    if (!check_request(clientDescriptor, lines, startString)) {
        return;
    }
    std::string requestPath = startString[1];

    if (requestPath[0] == '/') {
        requestPath = requestPath.substr(1, requestPath.length() - 1);
    }
    for (size_t i = 1; i < requestPath.length(); ++i) {
        if (requestPath[i] == '.' && requestPath[i - 1] == '.') {
            process_error(clientDescriptor, FORBIDDEN);
            return;
        }
    }
    if (requestPath == "") {
        requestPath += homePageFile;
    }
    std::string mime = define_MIME(requestPath);
    if (mime == "none") {
        requestPath += ".html";
        mime = "text/html";
    }

    std::string fileBuf;

    if (get_file(sitePath + requestPath, fileBuf) == -1) {
        process_error(clientDescriptor, NOT_FOUND);
        return;
    }

    http_reply(clientDescriptor, OK, mime, fileBuf);
    wr_close(clientDescriptor);
}
  void BezierCurves::setBuffer(RTCBufferType type, void* ptr, size_t offset, size_t stride) 
  { 
    if (parent->isStatic() && parent->isBuild()) {
      process_error(RTC_INVALID_OPERATION,"static geometries cannot get modified");
      return;
    }

    /* verify that all accesses are 4 bytes aligned */
    if (((size_t(ptr) + offset) & 0x3) || (stride & 0x3)) {
      process_error(RTC_INVALID_OPERATION,"data must be 4 bytes aligned");
      return;
    }

    /* verify that all vertex accesses are 16 bytes aligned */
#if defined(__MIC__)
    if (type == RTC_VERTEX_BUFFER0 || type == RTC_VERTEX_BUFFER1) {
      if (((size_t(ptr) + offset) & 0xF) || (stride & 0xF)) {
        process_error(RTC_INVALID_OPERATION,"data must be 16 bytes aligned");
        return;
      }
    }
#endif

    switch (type) {
    case RTC_INDEX_BUFFER  : 
      curves.set(ptr,offset,stride); 
      break;
    case RTC_VERTEX_BUFFER0: 
      vertices[0].set(ptr,offset,stride); 
      break;
    case RTC_VERTEX_BUFFER1: 
      vertices[1].set(ptr,offset,stride); 
      break;
    default: 
      process_error(RTC_INVALID_ARGUMENT,"unknown buffer type");
      break;
    }
  }
Exemple #6
0
static void scan_file(struct a6o_on_demand *on_demand, const char *path)
{
	struct a6o_file_context file_context;
	enum a6o_file_context_status context_status;

	context_status = a6o_file_context_get(&file_context, -1, path, on_demand->scan_conf);

	if (context_status == ARMADITO_FC_MUST_SCAN)
		a6o_scan_context(on_demand->scan, &file_context);
	else if (context_status == ARMADITO_FC_FILE_OPEN_ERROR)
		process_error(on_demand->scan, path, errno);

	a6o_file_context_destroy(&file_context);
}
Exemple #7
0
Fichier : io.cpp Projet : cgdb/cgdb
int io_read_byte(char *c, int source)
{
    int ret_val = 0;

    if ((ret_val = read(source, c, 1)) == 0) {
        return -1;
    } else if (ret_val == -1) {
        logger_write_pos(logger, __FILE__, __LINE__, "I/O error");
        process_error();
        return -1;
    }

    return 0;
}
Exemple #8
0
static DIR_ITER* ctr_drives_diropen_r(struct _reent *r, DIR_ITER *dirState, const char *path)
{
	DIR_extension *dir = (DIR_extension*)dirState;
	*dir = (DIR_extension){0};

	int err = f_opendir_(&dir->directory, path);
	if (err)
	{
		process_error(r, err);
		return NULL;
	}

	err = f_readdir_(&dir->directory, NULL);
	if (err)
	{
		process_error(r, err);
		return NULL;
	}

	dir->name_size = strlen(path)+1;
	memcpy(dir->name, path, dir->name_size);
	dir->name = malloc(dir->name_size);
	return dirState;
}
Exemple #9
0
  void Buffer::set(void* ptr_in, size_t ofs_in, size_t stride_in)
  {
#if !defined(RTCORE_BUFFER_STRIDE)
    if (stride_in != stride) {
      process_error(RTC_INVALID_OPERATION,"buffer stride feature disabled at compile time and specified stride does not match default stride");
      return;
    }
#endif

    ptr = (char*) ptr_in;
    bytes = 0;
    ptr_ofs = (char*) ptr_in + ofs_in;
    stride = stride_in;
    shared = true;
  }
 int_type read(char_type * data, int_type count)
 {
     ::boost::detail::winapi::DWORD_ read_len;
     if (!::boost::detail::winapi::ReadFile(
             _source, data, count * sizeof(char_type), &read_len, nullptr
             ))
     {
         auto ec = ::boost::process::detail::get_last_error();
         if ((ec.value() == ::boost::detail::winapi::ERROR_BROKEN_PIPE_) ||
             (ec.value() == ::boost::detail::winapi::ERROR_NO_DATA_))
             return 0;
         else
             throw process_error(ec, "ReadFile failed");
     }
     return static_cast<int_type>(read_len);
 }
 int_type write(const char_type * data, int_type count)
 {
     ::boost::detail::winapi::DWORD_ write_len;
     if (!::boost::detail::winapi::WriteFile(
             _sink, data, count * sizeof(char_type), &write_len, nullptr
             ))
     {
         auto ec = ::boost::process::detail::get_last_error();
         if ((ec.value() == ::boost::detail::winapi::ERROR_BROKEN_PIPE_) ||
             (ec.value() == ::boost::detail::winapi::ERROR_NO_DATA_))
             return 0;
         else
             throw process_error(ec, "WriteFile failed");
     }
     return static_cast<int_type>(write_len);
 }
Exemple #12
0
nscp::packet handler_impl::process(const nscp::packet &packet) {
	nscp::packet response;
	BOOST_FOREACH(const nscp::data::frame &frame, packet.frames_) {
		if (frame.header.type == nscp::data::frame_payload) {
			process_payload(response, frame);
		} else if (frame.header.type == nscp::data::frame_envelope) {
			process_header(response, frame);
		} else if (frame.header.type == nscp::data::frame_error) {
			process_error(response, frame);
		} else {
			this->log_error("nscp:handler", __FILE__, __LINE__, "Unknown packet: " + packet.to_string());
			return nscp::factory::create_error("Unknown packet: " + packet.to_string());
		}
	}
	return response;
}
Exemple #13
0
  void* Buffer::map(atomic_t& cntr)
  {
    /* report error if buffer is already mapped */
    if (mapped) {
      process_error(RTC_INVALID_OPERATION,"buffer is already mapped");
      return NULL;
    }

    /* allocate buffer */
    if (!ptr && !shared && bytes)
      alloc();

    /* return mapped buffer */
    atomic_add(&cntr,+1); 
    mapped = true;
    return ptr;
  }
Exemple #14
0
Fichier : io.cpp Projet : cgdb/cgdb
int io_rw_byte(int source, int dest)
{
    char c;

    if (read(source, &c, 1) != 1) {
        logger_write_pos(logger, __FILE__, __LINE__, "I/O error");
        process_error();
        return -1;
    }

    if (write(dest, &c, 1) != 1) {
        logger_write_pos(logger, __FILE__, __LINE__, "I/O error");
        return -1;
    }

    return 0;
}
Exemple #15
0
/**
 * Data Handler for the Expat parser.
 */
void data_handler(void* data, const XML_Char* s, int len)
{
	struct state_t* state = (struct state_t*)data;

	if (state->depth < DEPTH_MAX) {
		if (state->error == 0) {
			/* accumulate the data */
			unsigned new_len = state->level[state->depth].len + len;
			state->level[state->depth].data = realloc(state->level[state->depth].data, new_len);
			if (!state->level[state->depth].data) {
				process_error(state, state->level[state->depth].tag, "low memory");
				return;
			}
			memcpy(state->level[state->depth].data + state->level[state->depth].len, s, len);
			state->level[state->depth].len += len;
		}
	}
}
Exemple #16
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    QObject::connect(&mb,  SIGNAL(error(QModBus::ModBusError)),
                     this, SLOT(process_error(QModBus::ModBusError)));



    QObject::connect(&mb,  SIGNAL(connected()),
                     this, SLOT(change_status()));

    QObject::connect(&mb,  SIGNAL(disconnected()),
                     this, SLOT(change_status()));



    QObject::connect(ui->connect_button, SIGNAL(clicked()),
                     this,  SLOT(connect_btn_clicked()));



    //read button
    QObject::connect(ui->rd_button, SIGNAL(clicked()),
                     this, SLOT(read_regs()));


    QObject::connect(&mb,  SIGNAL(response_to_read_regs(int)),
                     this, SLOT(response_to_read_regs(int)));



    //write button
    QObject::connect(ui->wr_button, SIGNAL(clicked()),
                     this, SLOT(write_reg()));


    QObject::connect(&mb,  SIGNAL(response_to_write_reg(int)),
                     this, SLOT(response_to_write_reg(int)));
}
Exemple #17
0
int os_send_unix_stream(option_block *opts, char *str, size_t len)
{
#ifdef __WIN32__
    return -1;
#endif

    FILE *log = stdout;
    struct sockaddr_un sa_unix;
    int sockfd = -1;

    if(opts->fp_log)
        log = opts->fp_log;

    sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (sockfd != -1)
    {
        sa_unix.sun_family = AF_UNIX;
        strcpy(sa_unix.sun_path, opts->host_spec);
        if(connect(sockfd, (const struct sockaddr *)&sa_unix,
                   sizeof sa_unix) < 0)
        {
            close(sockfd);
            fprintf(log, "[%s] error: unable to connect to unix socket [%s]\n",
                    get_time_as_log(), process_error());
            return -1;
        }

        // connected - send
        if (send(sockfd, str, len, 0) < 0){
            // handle the failure case...
        }

        if (opts->verbosity != QUIET)
            fprintf(log, "[%s] info: tx fuzz - scanning for reply.\n",
                    get_time_as_log());

        close(sockfd);
        return 0;
        
    }
    return -1;
}
Exemple #18
0
enum status  start_memLoc(enum status cur_status, int key_value)
{
    /* variables */
      /* none */



    /* clear the memory location */
    memloc = 0;

    /* and display it */
    display_memory_addr(memloc);


    /* save the current status so can go back to it after saving/restoring */
    old_status = cur_status;


    /* figure out the new system status */
    switch (key_value)  {

        case  KEYCODE_MEMSAVE:	/* <Memory Save> key was seen */
				/* new status is saving an IP to memory */
				cur_status = STAT_MEMSAVE;
				break;

        case  KEYCODE_MEMRECALL:/* <Memory Recall> key was seen */
				/* new status is recalling an IP from memory */
				cur_status = STAT_MEMRECALL;
				break;

        default:		/* some other key was seen */
				/* generate an error and leave status unchanged */
				process_error(UNKNOWN_KEYCODE_INIT);
				break;
    }


    /* and return the new status */
    return  cur_status;

}
Exemple #19
0
void handle_event(xcb_generic_event_t *evt)
{
	uint8_t resp_type = XCB_EVENT_RESPONSE_TYPE(evt);
	switch (resp_type) {
		case XCB_MAP_REQUEST:
			map_request(evt);
			break;
		case XCB_DESTROY_NOTIFY:
			destroy_notify(evt);
			break;
		case XCB_UNMAP_NOTIFY:
			unmap_notify(evt);
			break;
		case XCB_CLIENT_MESSAGE:
			client_message(evt);
			break;
		case XCB_CONFIGURE_REQUEST:
			configure_request(evt);
			break;
		case XCB_PROPERTY_NOTIFY:
			property_notify(evt);
			break;
		case XCB_ENTER_NOTIFY:
			enter_notify(evt);
			break;
		case XCB_MOTION_NOTIFY:
			motion_notify(evt);
			break;
		case XCB_FOCUS_IN:
			focus_in(evt);
			break;
		case 0:
			process_error(evt);
			break;
		default:
			if (randr && resp_type == randr_base + XCB_RANDR_SCREEN_CHANGE_NOTIFY) {
				update_monitors();
			}
			break;
	}
}
Exemple #20
0
void http1_1_handler(int clientDescriptor) {

    std::vector<std::string> lines = get_request_lines(clientDescriptor);

    std::vector<std::string> startString = split(lines[0], ' ');
    if (!check_request(clientDescriptor, lines, startString)) {
        return;
    }
    std::string requestPath = startString[1];

    if (requestPath[0] == '/') {
        requestPath = requestPath.substr(1, requestPath.length() - 1);
    }
    for (size_t i = 1; i < requestPath.length(); ++i) {
        if (requestPath[i] == '.' && requestPath[i - 1] == '.') {
            process_error(clientDescriptor, FORBIDDEN);
            return;
        }
    }
    if (requestPath == "") {
        requestPath += homePageFile;
    }
    std::string mime = define_MIME(requestPath);
    if (mime == "none") {
        requestPath += ".html";
        mime = "text/html";
    }

    std::string fileBuf;

    FILE *file = popen(("python3 " + CGIPath + "cgi.py " + sitePath + requestPath + " " + CGIPath).c_str(), "r");
    while (!feof(file)) {
        fileBuf += fgetc(file);
    }
    fileBuf.pop_back();

    http_reply(clientDescriptor, OK, mime, fileBuf);
    wr_close(clientDescriptor);
}
Exemple #21
0
  void Geometry::update() 
  {
    if (parent->isStatic()) {
      process_error(RTC_INVALID_OPERATION,"static geometries cannot get updated");
      return;
    }

    switch (state) {
    case ENABLING:
      break;
    case ENABLED:
      state = MODIFIED;
      break;
    case MODIFIED:
      break;
    case DISABLING: 
      break;
    case DISABLED: 
      break;
    case ERASING:
      break;
    }
  }
Exemple #22
0
static void thread_loop(void *arg)
{
    struct example_sink_userdata *u = arg;
    pa_assert(u);

    pa_thread_mq_install(&u->thread_mq);

    const pa_usec_t poll_interval = 10000;

    pa_usec_t start_time = 0;
    pa_usec_t next_time = 0;

    for (;;) {
        /* process rewind */
        if (u->sink->thread_info.rewind_requested) {
            process_rewind(u);
        }

        /* process sink inputs */
        if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
            pa_usec_t now_time = pa_rtclock_now();

            if (start_time == 0) {
                start_time = now_time;
                next_time = start_time + poll_interval;
            }
            else {
                while (now_time >= next_time) {
                    uint64_t expected_bytes =
                        pa_usec_to_bytes(next_time - start_time, &u->sink->sample_spec);

                    /* render samples from sink inputs and write them to output file */
                    process_samples(u, expected_bytes);

                    /* next tick */
                    next_time += poll_interval;
                }
            }

            /* schedule set next rendering tick */
            pa_rtpoll_set_timer_absolute(u->rtpoll, next_time);
        }
        else {
            /* sleep until state change */
            start_time = 0;
            next_time = 0;
            pa_rtpoll_set_timer_disabled(u->rtpoll);
        }

        /* process events and wait next rendering tick */
#if PA_CHECK_VERSION(5, 99, 0)
        int ret = pa_rtpoll_run(u->rtpoll);
#else
        int ret = pa_rtpoll_run(u->rtpoll, true);
#endif
        if (ret < 0) {
            pa_log("[example sink] pa_rtpoll_run returned error");
            goto error;
        }

        if (ret == 0) {
            break;
        }
    }

    return;

error:
    process_error(u);
}
Exemple #23
0
// TODO: allow commandline options (v2)
// TODO: remove existing infs for similar devices (v2)
int __cdecl main(int argc_ansi, char** argv_ansi)
{
	DWORD r;
	BOOL b;
	int i, ret, argc = argc_ansi, si=0;
	char** argv = argv_ansi;
	wchar_t **wenv, **wargv;
	char* hardware_id = NULL;
	char* device_id = NULL;
	char* user_sid = NULL;
	char* inf_name = NULL;
	char path[MAX_PATH_LENGTH];
	char destname[MAX_PATH_LENGTH];
	uintptr_t syslog_reader_thid = -1L;

	// Connect to the messaging pipe
	pipe_handle = CreateFileA(INSTALLER_PIPE_NAME, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, NULL);
	if (pipe_handle == INVALID_HANDLE_VALUE) {
		// If we can't connect to the pipe, someone is probably trying to run us standalone
		printf("This application can not be run from the command line.\n");
		printf("Please use your initial installer application if you want to install the driver.\n");
		return WDI_ERROR_NOT_SUPPORTED;
	}

	if (init_dlls()) {
		plog("could not init DLLs");
		ret = WDI_ERROR_RESOURCE;
		goto out;
	}

	// Initialize COM for Restore Point disabling
	CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

	// libwdi provides the arguments as UTF-16 => read them and convert to UTF-8
	if (__wgetmainargs != NULL) {
		__wgetmainargs(&argc, &wargv, &wenv, 1, &si);
		argv = calloc(argc, sizeof(char*));
		for (i=0; i<argc; i++) {
			argv[i] = wchar_to_utf8(wargv[i]);
		}
	} else {
		plog("unable to access UTF-16 args - trying ANSI");
	}

	if (argc < 2) {
		printf("usage: %s <inf_name>\n", argv[0]);
		plog("missing inf_name parameter");
	}

	inf_name = argv[1];
	plog("got parameter %s", argv[1]);
	r = GetFullPathNameU(".", MAX_PATH_LENGTH, path, NULL);
	if ((r == 0) || (r > MAX_PATH_LENGTH)) {
		plog("could not retrieve absolute path of working directory");
		ret = WDI_ERROR_ACCESS;
		goto out;
	}
	safe_strcat(path, MAX_PATH_LENGTH, "\\");
	safe_strcat(path, MAX_PATH_LENGTH, inf_name);

	device_id = req_id(IC_GET_DEVICE_ID);
	hardware_id = req_id(IC_GET_HARDWARE_ID);
	// Will be used if we ever need to create a file, as the original user, from this app
	user_sid = req_id(IC_GET_USER_SID);
	ConvertStringSidToSidA(user_sid, &user_psid);

	// Setup the syslog reader thread
	syslog_ready_event = CreateEvent(NULL, TRUE, FALSE, NULL);
	syslog_terminate_event = CreateEvent(NULL, TRUE, FALSE, NULL);
	syslog_reader_thid = _beginthread(syslog_reader_thread, 0, 0);
	if ( (syslog_reader_thid == -1L)
	  || (WaitForSingleObject(syslog_ready_event, 2000) != WAIT_OBJECT_0) )	{
		plog("Unable to create syslog reader thread");
		SetEvent(syslog_terminate_event);
		// NB: if you try to close the syslog reader thread handle, you get a
		// "more recent driver was found" error from UpdateForPnP. Weird...
	}

	// Disable the creation of a restore point
	disable_system_restore(true);

	// Find if the device is plugged in
	send_status(IC_SET_TIMEOUT_INFINITE);
	if (hardware_id != NULL) {
		plog("Installing driver for %s - please wait...", hardware_id);
		b = UpdateDriverForPlugAndPlayDevicesU(NULL, hardware_id, path, INSTALLFLAG_FORCE, NULL);
		send_status(IC_SET_TIMEOUT_DEFAULT);
		if (b == true) {
			// Success
			plog("driver update completed");
			enumerate_device(device_id);
			ret = WDI_SUCCESS;
			goto out;
		}

		ret = process_error(GetLastError(), path);
		if (ret != WDI_SUCCESS) {
			goto out;
		}
	}

	// TODO: try URL for OEMSourceMediaLocation (v2)
	plog("Copying inf file (for the next time device is plugged) - please wait...");
	send_status(IC_SET_TIMEOUT_INFINITE);
	b = SetupCopyOEMInfU(path, NULL, SPOST_PATH, 0, destname, MAX_PATH_LENGTH, NULL, NULL);
	send_status(IC_SET_TIMEOUT_DEFAULT);
	if (b) {
		plog("copied inf to %s", destname);
		ret = WDI_SUCCESS;
		enumerate_device(device_id);
		goto out;
	}

	ret = process_error(GetLastError(), path);
	if (ret != WDI_SUCCESS) {
		goto out;
	}

	// If needed, flag removed devices for reinstallation. see:
	// http://msdn.microsoft.com/en-us/library/aa906206.aspx
	check_removed(hardware_id);

out:
	// Report any error status code and wait for target app to read it
	send_status(IC_INSTALLER_COMPLETED);
	pstat(ret);
	// Restore the system restore point creation original settings
	disable_system_restore(false);
	// TODO: have libwi send an ACK?
	Sleep(1000);
	SetEvent(syslog_terminate_event);
	if (argv != argv_ansi) {
		for (i=0; i<argc; i++) {
			safe_free(argv[i]);
		}
		safe_free(argv);
	}
	CloseHandle(syslog_ready_event);
	CloseHandle(syslog_terminate_event);
	CloseHandle((HANDLE)syslog_reader_thid);
	CloseHandle(pipe_handle);
	return ret;
}
Exemple #24
0
int os_send_tcp(option_block *opts, char *str, size_t len)
{
#ifdef __WIN32__
    WSADATA wsaData;
#endif
    FILE *log = stdout;
    struct timeval tv;
    fd_set fds;
    int sockfd = -1;

    struct addrinfo hints, *servinfo, *p;

    int ret;
    int snt = 0;
    unsigned long int to = MAX(100, opts->time_out);

    if(opts->fp_log)
        log = opts->fp_log;

#ifdef __WIN32__
    if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0)
    {
        fprintf(stderr, "[%s]: error: Unable to init winsock!\n",
                get_time_as_log());
        fprintf(log, "[%s]: error: Unable to init winsock!\n",
                get_time_as_log());
        return -1;
    }
#endif

    
    if(opts->sockfd != -1)
    {
        sockfd = opts->sockfd;
    }
    else
    {
        memset(&hints, 0, sizeof(hints));

        hints.ai_family   = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;

        if(getaddrinfo(opts->host_spec, opts->port_spec, &hints, &servinfo) != 0)
        {
            fprintf(stderr, "[%s]: error: unable to get addrinfo\n",
                    get_time_as_log());
            fprintf(log, "[%s]: error: unable to get addrinfo\n",
                    get_time_as_log());
#ifdef __WIN32__
            WSACleanup();
#endif
            return -1;
        }
        
        for(p = servinfo; p!= NULL; p = p->ai_next)
        {
            sockfd = socket(p->ai_family, p->ai_socktype,
                            p->ai_protocol);
            if(sockfd < 0)
                continue;

            opts->sockfd = sockfd;
            
            if(connect(sockfd, 
                       p->ai_addr, p->ai_addrlen) < 0)
            {
#ifdef __WIN32__
                closesocket(sockfd);
#else
                close(sockfd);
#endif
                opts->sockfd = sockfd = -1;
                continue;
            }
            break; /* faster than setting p = NULL; (I think)*/
        }
        freeaddrinfo(servinfo);
    }

    if(sockfd == -1)
    {
        fprintf(stderr,
                "[%s] error: unable to connect to remote system [%s].\n",
                get_time_as_log(), process_error());
        fprintf(log,
                "[%s] error: unable to connect to remote system [%s].\n",
                get_time_as_log(), process_error());
#ifdef __WIN32__
        WSACleanup();
#endif
        return -1;
    }

    while(len)
    {
        ret = send(sockfd, str + snt, len, 0);
    
        if(ret < 0)
        {
            fprintf(stderr,"[%s] error: tcp send() failed.\n", get_time_as_log());
            fprintf(log,"[%s] error: tcp send() failed.\n", get_time_as_log());
#ifdef __WIN32__
            WSACleanup();
#endif
            return -1;
        }
        len -= ret;
        snt += ret;
    }
    

    if(opts->verbosity != QUIET)
        fprintf(log, "[%s] info: tx fuzz - (%d bytes) - scanning for reply.\n",
                get_time_as_log(), snt);
    
    FD_ZERO(&fds);
    FD_SET(sockfd, &fds);

    tv.tv_sec  = to / 1000;
    tv.tv_usec = (to % 1000) * 1000; /*time out*/

    mssleep(opts->reqw_inms);

    ret = select(sockfd+1, &fds, NULL, NULL, &tv);
    if(ret > 0)
    {
        if(FD_ISSET(sockfd, &fds))
        {
            char buf[8193] = {0};
            int r_len = 0;
            r_len = read(sockfd, &buf, 8192);
            buf[8192] = 0;
            if(opts->verbosity != QUIET)
                fprintf(log, "[%s] read:\n%s\n===============================================================================\n", 
                        get_time_as_log(),
                        buf);
            if((opts->s_syms_count) && (opts->repl_pol))
            {
                for(ret = 0; ret < opts->s_syms_count; ++ret)
                {
                    sym_t *pSym = &(opts->s_syms[ret]);
                    int    cpy_len = pSym->is_len;

                    if((opts->repl_pol == 2) &&
                       pSym->increment)
                        continue;

                    if(cpy_len > r_len)
                        continue;
                    memset(pSym->sym_val, 0, 1024);
                    memcpy(pSym->sym_val, buf+(pSym->offset),cpy_len);
                    pSym->sym_val[cpy_len] = 0;
                    pSym->s_len = cpy_len;
                    pSym->increment = 1;
                }
            }
#ifndef NOPLUGIN
            if((g_plugin != NULL) &&
               ((g_plugin->capex() & PLUGIN_PROVIDES_POST_FUZZ) ==
                PLUGIN_PROVIDES_POST_FUZZ))
            {
                g_plugin->post_fuzz(opts, buf, r_len);
            }
#endif
        }
    }
    
    if(opts->close_conn)
        opts->sockfd = -1;
    
    if((opts->close_conn) && (!opts->forget_conn))
    {
#ifdef __WIN32__
        closesocket(sockfd);
#else
        close(sockfd);
#endif
    }
    
#ifdef __WIN32__
    WSACleanup();
#endif
    return 0;
}
Exemple #25
0
int
main(int argc, char *argv[])
{
	int c, i, j, configured = 0;
	pid_t opid;
	char prgname[80], filename[256], *p;
	struct servent *servent;
	pthread_t tid;

	/* Default plugin_base */
	strlcpy(plugin_base, PLUGIN_PATH, sizeof(plugin_base));

	if ((servent = getservbyname("bootps", 0)) == NULL)
		errx(EX_UNAVAILABLE, "getservbyname(bootps)");
	bootps_port = servent->s_port;
	if ((servent = getservbyname("bootpc", 0)) == NULL)
		errx(EX_UNAVAILABLE, "getservbyname(bootpc)");
	bootpc_port = servent->s_port;

	openlog("dhcprelya", LOG_NDELAY | LOG_PID, LOG_DAEMON);

	strlcpy(prgname, argv[0], sizeof(prgname));
	filename[0] = '\0';
	while ((c = getopt(argc, argv, "A:c:df:hi:p:")) != -1) {
		switch (c) {
		case 'A':
			if (configured == 2)
				errx(1, "Either config file or command line options allowed. Not both.");
			max_packet_size = strtol(optarg, NULL, 10);
			if (max_packet_size < 300 || max_packet_size > DHCP_MTU_MAX)
				errx(1, "Wrong packet size");
			break;
		case 'c':
			if (configured == 2)
				errx(1, "Either config file or command line options allowed. Not both.");
			max_hops = strtol(optarg, NULL, 10);
			if (max_hops < 1 || max_hops > 16)
				errx(1, "Wrong hops number");
			break;
		case 'd':
			debug++;
			break;
		case 'f':
			if (configured == 1)
				errx(1, "Either config file or command line options allowed. Not both.");
			if (configured == 2)
				errx(1, "only one config file allowed");
			configured = 2;
			read_config(optarg);
			break;
		case 'i':
			if (configured == 2)
				errx(1, "Either config file or command line options allowed. Not both.");
			configured = 1;
			if (!open_interface(optarg))
				logd(LOG_DEBUG, "Interface %s does not exist. Ignored.", optarg);
			break;
		case 'p':
			strlcpy(filename, optarg, sizeof(filename));
			break;
		case 'h':
		default:
			usage(prgname);
		}
	}

	argc -= optind;
	argv += optind;

	if (optind == 0)
		argc--;

	if ((configured == 1 && argc < 1) || (configured == 2 && argc >= 1))
		usage(prgname);

	/* Initialize polugins */
	for (i = 0; i < plugins_number; i++) {
		if (plugins[i]->init)
			if ((plugins[i]->init) (options_heads[i]) == 0)
				errx(1, "Can't initialize a plugin %s\n", plugins[i]->name);
	}

	for (i = 0; i < argc; i++) {
		open_server(argv[i]);
		for (j = 0; j < if_num; j++) {
			if (i > ifs[j]->srv_num - 1) {
				ifs[j]->srv_num++;
				ifs[j]->srvrs = realloc(ifs[j]->srvrs, ifs[j]->srv_num * sizeof(int));
			}
			ifs[j]->srvrs[ifs[j]->srv_num - 1] = i;
		}
	}

	if (if_num == 0)
		errx(1, "No interfaces found to listen. Exiting.");

	logd(LOG_WARNING, "Total interfaces: %d", if_num);

	/* Make a PID filename */
	if (filename[0] == '\0') {
		strlcpy(filename, "/var/run/", sizeof(filename));
		p = strrchr(prgname, '/');
		if (p == NULL)
			p = prgname;
		else
			p++;
		strlcat(filename, p, sizeof(filename));
		strlcat(filename, ".pid", sizeof(filename));
	}
	/* Create a PID file and daemonize if no debug flag */
	if (!debug && (pfh = pidfile_open(filename, 0644, &opid)) == NULL) {
		if (errno == EEXIST)
			errx(1, "Already run with PID %lu. Exiting.", (unsigned long)opid);
		errx(1, "Can't create PID file");
	}
	signal(SIGHUP, SIG_IGN);

	if (!debug) {
		if (daemon(0, 0) == -1)
			process_error(1, "Can't daemonize. Exiting.");
		else
			logd(LOG_DEBUG, "Runned as %d", getpid());
	}
	if (pfh)
		pidfile_write(pfh);

	STAILQ_INIT(&q_head);

	pthread_mutex_init(&queue_lock, NULL);

	/* Create listeners for every interface */
	for (i = 0; i < if_num; i++) {
		pthread_create(&tid, NULL, listener, ifs[i]);
		pthread_detach(tid);
	}

	/* Main loop */
	while (1) {
		if (queue_size > 0)
			process_queue();

		/* Process one packet from server(s) */
		process_server_answer();
	}

	/* Destroy polugins */
	for (i = 0; i < plugins_number; i++) {
		if (plugins[i]->destroy)
			(plugins[i]->destroy) ();
	}
	pthread_mutex_destroy(&queue_lock);
}
Exemple #26
0
int
open_interface(char *iname)
{
	int i, j, x = 1;
	struct ifreq ifr;
	struct bpf_program fp;
	struct sockaddr_in baddr;
	char errbuf[PCAP_ERRBUF_SIZE], file[32], buf[256];

	if (if_num >= IF_MAX - 1)
		process_error(EX_RES, "too many interfaces");

	logd(LOG_DEBUG, "Trying to open interface: %s", iname);

	/* If we already have the interface, bind to the current server then */
	for (i = 0; i < if_num; i++) {
		if (strcmp(ifs[i]->name, iname) == 0) {
			/* If the interface is already binded to this server
			 * (appears twice). Ignore it. */
			if (ifs[i]->srv_num != srv_num) {
				ifs[i]->srv_num++;
				ifs[i]->srvrs = realloc(ifs[i]->srvrs, ifs[i]->srv_num * sizeof(int));
				ifs[i]->srvrs[ifs[i]->srv_num - 1] = srv_num - 1;
			}
			return 1;
		}
	}

	ifs[if_num] = malloc(sizeof(struct interface));
	if (ifs[if_num] == NULL)
		process_error(EX_MEM, "malloc");

	ifs[if_num]->idx = if_num;
	strlcpy(ifs[if_num]->name, iname, INTF_NAME_LEN);

	if (!get_mac(iname, (char *)ifs[if_num]->mac) ||
	    !get_ip(iname, &ifs[if_num]->ip, &ifs[if_num]->mask)) {
		free(ifs[if_num]);
		return 0;
	}
	ifs[i]->srv_num = 1;
	ifs[i]->srvrs = malloc(ifs[i]->srv_num * sizeof(int));
	if (ifs[i]->srvrs == NULL)
		process_error(EX_MEM, "malloc");
	ifs[i]->srvrs[0] = srv_num - 1;

	/* Looking for a free BPF device and open it */
	for (j = 0; j < 255; j++) {
		snprintf(file, sizeof(file), "/dev/bpf%d", j);
		ifs[if_num]->bpf = open(file, O_WRONLY);
		if (ifs[if_num]->bpf != -1 || errno != EBUSY)
			break;
	}
	/* Bind BPF to an interface */
	bzero(&ifr, sizeof(ifr));
	strlcpy(ifr.ifr_name, iname, sizeof(ifr.ifr_name));
	if (ioctl(ifs[if_num]->bpf, BIOCSETIF, (char *)&ifr) < 0)
		process_error(EX_RES, "Can't BIOCSETIF");

	if ((ifs[if_num]->cap = pcap_open_live(iname, max_packet_size, 0, 100, errbuf)) == NULL)
		process_error(EX_RES, "pcap_open_live(%s): %s", iname, errbuf);
	if (pcap_compile(ifs[if_num]->cap, &fp, "udp and dst port bootps", 0, 0) < 0)
		process_error(EX_RES, "pcap_compile");
	if (pcap_setfilter(ifs[if_num]->cap, &fp) < 0)
		process_error(EX_RES, "pcap_setfilter");

	if ((ifs[if_num]->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
		process_error(EX_RES, "socket for listener at %s: %s", iname, strerror(errno));

	if (setsockopt(ifs[if_num]->fd, SOL_SOCKET, SO_BROADCAST, (char *)&x, sizeof(x)) < 0)
		process_error(EX_RES, "setsockopt: SO_BROADCAST");
	if (setsockopt(ifs[if_num]->fd, SOL_SOCKET, SO_REUSEADDR, (char *)&x, sizeof(x)) < 0)
		process_error(EX_RES, "setsockopt: SO_REUSEADDR");

	bzero(&baddr, sizeof(baddr));
	baddr.sin_family = AF_INET;
	baddr.sin_port = bootps_port;
	memcpy(&baddr.sin_addr.s_addr, &ifs[if_num]->ip, sizeof(ip_addr_t));
	if (bind(ifs[if_num]->fd, (struct sockaddr *)&baddr, sizeof(baddr)) < 0)
		process_error(EX_RES, "bind: %s", strerror(errno));

	logd(LOG_WARNING, "Listen at %s: %s/%s, %s", iname, print_ip(ifs[if_num]->ip, buf),
	     print_ip(ifs[if_num]->mask, buf + 16), print_mac(ifs[if_num]->mac, buf + 32));

	if_num++;
	return 1;
}
Exemple #27
0
int main(void)
{
  HANDLE hSCManager;
  HANDLE hService;
  SERVICE_STATUS ss;
  int retval = 0;

  /* First of all, maybe concatenate the current working directory
   * with the desired driver file name - before we start messing with
   * the service manager etc. */
  if (getcwd(cwd, MAX_CWD_LEN) == NULL) {
    printf("Failed to learn the current working directory!\n");
    retval = -8;
    goto err_out1;
  } /* else got CWD just fine */

  if (strlen(cwd) + strlen(MY_DRIVER_FILENAME) + 1 > MAX_CWD_LEN) {
    printf("Current working dir + driver filename is longer than %d.\n",
           MAX_CWD_LEN);
    retval = -9;
    goto err_out1;
  } /* else our buffer is long enough :-) */

  strcat(cwd, "\\");
  strcat(cwd, MY_DRIVER_FILENAME);
  printf("Driver path+name: %s\n", cwd);

  printf("Going to open the service manager... ");
  hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
  if (!hSCManager) {
    printf("FAIL.\n");
    process_error();
    retval = -1;
    goto err_out1;
  }

  printf("OK.\n");
  printf("Going to open the service... ");
  hService = OpenService(hSCManager, MY_SERVICE_NAME_SHORT,
                       SERVICE_START | DELETE | SERVICE_STOP);
  if(!hService) {
    printf("FAILED.\n");
    process_error();
    retval = -2;
    goto err_out2;
  }

  printf("OK.\n");
  printf("Going to stop the service... ");
  if (ControlService(hService, SERVICE_CONTROL_STOP, &ss) == 0) {
    printf("FAIL.\n");
    process_error();
    retval = -4;
  } else printf("OK.\n");

  printf("Going to delete the service... ");
  if (DeleteService(hService) == 0) {
    printf("FAIL.\n");
    process_error();
    retval = -5;
  } else printf("OK.\n");

  printf("Going to close the service handle... ");
  if (CloseServiceHandle(hService) == 0) {
    printf("FAIL.\n");
    process_error();
    retval = -6;
  } else printf("okay.\n");

 err_out2:
  printf("Going to close the service manager... ");
  if (CloseServiceHandle(hSCManager) == 0) {
    printf("FAIL.\n");
    process_error();
    retval = -7;
  } else printf("OK.\n");

err_out1:
  printf("Finished!\n");
  return(retval);
}
Exemple #28
0
/* Read and parse a configuration file */
void
read_config(const char *filename)
{
	char buf[5000], plugin_name[50], plugin_path[100];
	char plugin_data_name[100];
	FILE *f, *fs;
	char *p;
	int line = 0;
	void *handle;
	enum sections {
		Servers, Options, Plugin
	} section = Servers;
	struct plugins_data *plugins_data;
	struct plugin_options *popt, *last_popt = NULL;

	if ((f = fopen(filename, "r")) == NULL)
		errx(1, "Can't open: %s", filename);
	while (fgets(buf, sizeof(buf), f) != NULL) {
		line++;
		/* Ignore empty lines and comments */
		if (buf[0] == '\n' || buf[0] == '#')
			continue;

		/* strip \n */
		if ((p = strchr(buf, '\n')) != NULL)
			*p = '\0';

		/* A new section starts */
		if (buf[0] == '[') {
			p = strchr(buf, ']');
			if (p == NULL || *(p + 1) != '\0')
				errx(1, "Config file syntax error. Line: %d", line);
			*p = '\0';
			if (strcasecmp(buf + 1, "servers") == 0) {
				section = Servers;
				continue;
			}
			if (strcasecmp(buf + 1, "options") == 0) {
				section = Options;
				continue;
			}
			if ((p = strcasestr(buf, "-plugin")) != NULL) {
				if (plugins_number > MAX_PLUGINS - 1)
					errx(1, "Too many plugins. Line: %d", line);

				section = Plugin;
				*p = '\0';
				strlcpy(plugin_name, buf + 1, sizeof(plugin_name));

				strlcpy(plugin_data_name, plugin_name, sizeof(plugin_data_name));
				strlcat(plugin_data_name, "_plugin", sizeof(plugin_data_name));

				strlcpy(plugin_path, plugin_base, sizeof(plugin_path));
				strlcat(plugin_path, "dhcprelya_", sizeof(plugin_path));
				strlcat(plugin_path, plugin_name, sizeof(plugin_path));
				strlcat(plugin_path, "_plugin.so", sizeof(plugin_path));
				handle = dlopen(plugin_path, RTLD_LAZY);
				if (handle == NULL) {
					printf("dlerror(): %s\n", dlerror());
					errx(1, "Can't open plugin: %s", plugin_path);
				}
				plugins_data = dlsym(handle, plugin_data_name);
				if (plugins_data == NULL)
					errx(1, "Can't load symbol %s", plugin_data_name);
				plugins[plugins_number] = malloc(sizeof(struct plugin_data));
				if (plugins[plugins_number] == NULL)
					process_error(EX_MEM, "malloc");

				memcpy(plugins[plugins_number], plugins_data, sizeof(struct plugin_data));

				/* head for options list for this plugin */
				options_heads[plugins_number] = malloc(sizeof(plugin_options_head_t));
				if (options_heads[plugins_number] == NULL)
					process_error(EX_MEM, "malloc");
				SLIST_INIT(options_heads[plugins_number]);

				plugins_number++;

				logd(LOG_DEBUG, "Plugin #%d (%s) loaded", plugins_number, plugin_name);
				continue;
			}
			errx(1, "Section name error. Line: %d", line);
		}
		if (section == Servers) {
			if ((p = strchr(buf, '=')) == NULL)
				parse_servers_line(buf);
			else {
				*p = '\0';
				p++;
				if (strcasecmp(buf, "file") != 0)
					errx(1, "Unknown option in Server section. Line: %d", line);
				if ((fs = fopen(p, "r")) == NULL)
					errx(1, "Can't open servers config file: %s", p);
				while (fgets(buf, sizeof(buf), fs) != NULL) {
					/* Ignore empty lines and comments */
					if (buf[0] == '\n' || buf[0] == '#')
						continue;

					/* strip \n */
					if ((p = strchr(buf, '\n')) != NULL)
						*p = '\0';

					parse_servers_line(buf);
				}
				fclose(fs);
			}
		}
		if (section == Options) {
			p = strchr(buf, '=');
			if (p == NULL)
				errx(1, "Option error. Line: %d", line);
			*p = '\0';
			p++;

			if (strcasecmp(buf, "max_packet_size") == 0) {
				max_packet_size = strtol(p, NULL, 10);
				if (max_packet_size < 300 || max_packet_size > DHCP_MTU_MAX)
					errx(1, "Wrong packet size. Line: %d", line);
				logd(LOG_DEBUG, "Option max_packet_size set to: %d", max_packet_size);
				continue;
			}
			if (strcasecmp(buf, "max_hops") == 0) {
				max_hops = strtol(p, NULL, 10);
				if (max_hops < 1 || max_hops > 16)
					errx(1, "Wrong hops number. Line: %d", line);
				logd(LOG_DEBUG, "Option max_hops set to: %d", max_hops);
				continue;
			}
			if (strcasecmp(buf, "rps_limit") == 0) {
				errno = 0;
				rps_limit = strtol(p, NULL, 10);
				if (errno != 0)
					errx(1, "rps_limit number error");
				logd(LOG_DEBUG, "Option rps_limit set to: %d", rps_limit);
				continue;
			}
			if (strcasecmp(buf, "plugin_path") == 0) {
				strlcpy(plugin_base, p, sizeof(plugin_base));
				if (plugin_base[strlen(plugin_base) - 1] != '/')
					strlcat(plugin_base, "/", sizeof(plugin_base));
				logd(LOG_DEBUG, "Option plugin_base set to: %s", plugin_base);
				continue;
			}
			errx(1, "Unknown option. Line: %d", line);
		}
		if (section == Plugin) {
			popt = malloc(sizeof(struct plugin_options));
			if (popt == NULL)
				process_error(EX_MEM, "malloc");
			popt->option_line = malloc(strlen(buf) + 1);
			if (popt->option_line == NULL)
				process_error(EX_MEM, "malloc");
			strcpy(popt->option_line, buf);
			if (SLIST_EMPTY(options_heads[plugins_number - 1])) {
				SLIST_INSERT_HEAD(options_heads[plugins_number - 1], popt, next);
				last_popt = popt;
			} else {
				SLIST_INSERT_AFTER(last_popt, popt, next);
				last_popt = popt;
			}
		}
	}
	fclose(f);
	if (if_num == 0)
		errx(1, "No interfaces found to listen. Exiting.");
}
Exemple #29
0
  void Scene::build (size_t threadIndex, size_t threadCount) 
  {
    /* all user worker threads properly enter and leave the tasking system */
    LockStepTaskScheduler::Init init(threadIndex,threadCount,&lockstep_scheduler);
    if (threadIndex != 0) return;

    /* allow only one build at a time */
    Lock<MutexSys> lock(mutex);

    if (isStatic() && isBuild()) {
      process_error(RTC_INVALID_OPERATION,"static geometries cannot get committed twice");
      return;
    }

    if (!ready()) {
      process_error(RTC_INVALID_OPERATION,"not all buffers are unmapped");
      return;
    }

    /* verify geometry in debug mode  */
#if 0 && defined(DEBUG) // FIXME: enable
    for (size_t i=0; i<geometries.size(); i++) {
      if (geometries[i]) {
        if (!geometries[i]->verify()) {
          process_error(RTC_INVALID_OPERATION,"invalid geometry specified");
          return;
        }
      }
    }
#endif

    /* select fast code path if no intersection filter is present */
    accels.select(numIntersectionFilters4,numIntersectionFilters8,numIntersectionFilters16);

    /* if user provided threads use them */
    if (threadCount)
      accels.build(threadIndex,threadCount);

    /* otherwise use our own threads */
    else
    {
      TaskScheduler::EventSync event;
      new (&task) TaskScheduler::Task(&event,_task_build_parallel,this,TaskScheduler::getNumThreads(),NULL,NULL,"scene_build");
      TaskScheduler::addTask(-1,TaskScheduler::GLOBAL_FRONT,&task);
      event.sync();
    }

    /* make static geometry immutable */
    if (isStatic()) 
    {
      accels.immutable();
      for (size_t i=0; i<geometries.size(); i++)
        if (geometries[i]) geometries[i]->immutable();
    }

    /* delete geometry that is scheduled for delete */
    for (size_t i=0; i<geometries.size(); i++) 
    {
      Geometry* geom = geometries[i];
      if (geom == NULL || geom->state != Geometry::ERASING) continue;
      remove(geom);
    }

    /* update bounds */
    bounds = accels.bounds;
    intersectors = accels.intersectors;
    is_build = true;

    /* enable only algorithms choosen by application */
    if ((aflags & RTC_INTERSECT1) == 0) {
      intersectors.intersector1.intersect = NULL;
      intersectors.intersector1.occluded = NULL;
    }
    if ((aflags & RTC_INTERSECT4) == 0) {
      intersectors.intersector4.intersect = NULL;
      intersectors.intersector4.occluded = NULL;
    }
    if ((aflags & RTC_INTERSECT8) == 0) {
      intersectors.intersector8.intersect = NULL;
      intersectors.intersector8.occluded = NULL;
    }
    if ((aflags & RTC_INTERSECT16) == 0) {
      intersectors.intersector16.intersect = NULL;
      intersectors.intersector16.occluded = NULL;
    }

    if (g_verbose >= 2) {
      std::cout << "created scene intersector" << std::endl;
      accels.print(2);
      std::cout << "selected scene intersector" << std::endl;
      intersectors.print(2);
    }
    
    /* update commit counter */
    commitCounter++;
  }
Exemple #30
0
  RTCORE_API void rtcInit(const char* cfg) 
  {
      cout << "in rtcInit " << endl;
    Lock<MutexSys> lock(g_mutex);
    TRACE(rtcInit);
    CATCH_BEGIN;

    if (g_initialized) {
      g_mutex.unlock();
      process_error(RTC_INVALID_OPERATION,"already initialized");
      g_mutex.lock();
      return;
    }
    g_initialized = true;

    /* reset global state */
    initSettings();
    
    if (cfg != NULL) 
    {
      size_t pos = 0;
      do {
        std::string tok = parseIdentifier (cfg,pos);

        if (tok == "threads" && parseSymbol(cfg,'=',pos)) 
	{
	  g_numThreads = parseInt(cfg,pos);
#if defined(__MIC__)
	  if (!(g_numThreads == 1 || (g_numThreads % 4) == 0)) {
	    g_mutex.unlock();
	    process_error(RTC_INVALID_OPERATION,"Xeon Phi supports only number of threads % 4 == 0, or threads == 1");
	    g_mutex.lock();
            return;
          }
#endif
        }
        else if (tok == "isa" && parseSymbol (cfg,'=',pos)) 
	{
	  std::string isa = parseIdentifier (cfg,pos);
	  if      (isa == "sse" ) cpu_features = SSE;
	  else if (isa == "sse2") cpu_features = SSE2;
	  else if (isa == "sse3") cpu_features = SSE3;
	  else if (isa == "ssse3") cpu_features = SSSE3;
	  else if (isa == "sse41") cpu_features = SSE41;
	  else if (isa == "sse42") cpu_features = SSE42;
	  else if (isa == "avx") cpu_features = AVX;
	  else if (isa == "avxi") cpu_features = AVXI;
	  else if (isa == "avx2") cpu_features = AVX2;
	}
        else if ((tok == "tri_accel" || tok == "accel") && parseSymbol (cfg,'=',pos))
            g_tri_accel = parseIdentifier (cfg,pos);
	else if ((tok == "tri_builder" || tok == "builder") && parseSymbol (cfg,'=',pos))
	    g_tri_builder = parseIdentifier (cfg,pos);
	else if ((tok == "tri_traverser" || tok == "traverser") && parseSymbol (cfg,'=',pos))
            g_tri_traverser = parseIdentifier (cfg,pos);
      	else if ((tok == "tri_accel_mb" || tok == "accel_mb") && parseSymbol (cfg,'=',pos))
            g_tri_accel = parseIdentifier (cfg,pos);
	else if ((tok == "tri_builder_mb" || tok == "builder_mb") && parseSymbol (cfg,'=',pos))
	    g_tri_builder = parseIdentifier (cfg,pos);
        else if ((tok == "tri_traverser_mb" || tok == "traverser_mb") && parseSymbol (cfg,'=',pos))
            g_tri_traverser = parseIdentifier (cfg,pos);
        else if (tok == "hair_accel" && parseSymbol (cfg,'=',pos))
            g_hair_accel = parseIdentifier (cfg,pos);
	else if (tok == "hair_builder" && parseSymbol (cfg,'=',pos))
            g_hair_builder = parseIdentifier (cfg,pos);
	else if (tok == "hair_traverser" && parseSymbol (cfg,'=',pos))
            g_hair_traverser = parseIdentifier (cfg,pos);
	else if (tok == "hair_builder_replication_factor" && parseSymbol (cfg,'=',pos))
            g_hair_builder_replication_factor = parseInt (cfg,pos);
	
        else if (tok == "verbose" && parseSymbol (cfg,'=',pos))
            g_verbose = parseInt (cfg,pos);
	else if (tok == "benchmark" && parseSymbol (cfg,'=',pos))
            g_benchmark = parseInt (cfg,pos);
        else if (tok == "flags") {
          g_scene_flags = 0;
          if (parseSymbol (cfg,'=',pos)) {
            do {
              std::string flag = parseIdentifier (cfg,pos);
              if      (flag == "static" ) g_scene_flags |= RTC_SCENE_STATIC;
              else if (flag == "dynamic") g_scene_flags |= RTC_SCENE_DYNAMIC;
              else if (flag == "compact") g_scene_flags |= RTC_SCENE_COMPACT;
              else if (flag == "coherent") g_scene_flags |= RTC_SCENE_COHERENT;
              else if (flag == "incoherent") g_scene_flags |= RTC_SCENE_INCOHERENT;
              else if (flag == "high_quality") g_scene_flags |= RTC_SCENE_HIGH_QUALITY;
              else if (flag == "robust") g_scene_flags |= RTC_SCENE_ROBUST;
            } while (parseSymbol (cfg,',',pos));
          }
        }
        
      } while (findNext (cfg,',',pos));
    }

    if (g_verbose >= 1)
    {
      std::cout << "Embree Ray Tracing Kernels " << __EMBREE_VERSION__ << " (" << __DATE__ << ")" << std::endl;
      std::cout << "  Compiler : " << getCompilerName() << std::endl;
      std::cout << "  Platform : " << getPlatformName() << std::endl;
      std::cout << "  CPU      : " << stringOfCPUFeatures(getCPUFeatures()) << std::endl;
      std::cout << "  Features : ";
#if defined(__USE_RAY_MASK__)
      std::cout << "raymasks ";
#endif
#if defined (__BACKFACE_CULLING__)
      std::cout << "backfaceculling ";
#endif
#if defined(__INTERSECTION_FILTER__)
      std::cout << "intersection_filter ";
#endif
#if defined(__BUFFER_STRIDE__)
      std::cout << "bufferstride ";
#endif
      std::cout << std::endl;

#if defined (__MIC__)
#if defined(__BUFFER_STRIDE__)
      std::cout << "  WARNING: enabled 'bufferstride' support will lower BVH build performance" << std::endl;
#endif
#endif
    }

    /* CPU has to support at least SSE2 */
#if !defined (__MIC__)
    if (!has_feature(SSE2)) {
      g_mutex.unlock();
      process_error(RTC_UNSUPPORTED_CPU,"CPU does not support SSE2");
      g_mutex.lock();
      return;
    }
#endif

    g_error = createTls();
    g_error_function = NULL;

    init_globals();
    cout << "in rtcInit(), BVH4Register() " << endl;
#if !defined(__MIC__)
    cout << "BVH4Register()" << endl;
    BVH4Register();
#else
    cout << "BVH4iRegister() " << endl;
    BVH4iRegister();
#endif 
    cout << "BVH4MBRegister() " << endl;
    BVH4MBRegister();
    BVH4HairRegister();    
#if defined(__TARGET_AVX__)
    cout << "BVH8Register() " << endl;
    if (has_feature(AVX)) {
      BVH8Register();
    }
#endif
    
    InstanceIntersectorsRegister();

//if (g_verbose >= 2) 
    printSettings();
    
    TaskScheduler::create(g_numThreads);

    cout << " end rtcInit " << endl;
    CATCH_END;
  }