Example #1
0
static int gather_sd_fds(void) {
#ifdef SUPERVISOR_SUPPORT
    if (ssh_fd == 0) {
#else
    if (main_fd == 0 && ssh_fd == 0 && scdaemon_fd == 0) {
#endif
        int num_fds;
        char **fdmap = NULL;
        void *libsystemd = NULL;
        int (*_sd_listen_fds_with_names)(int, char ***);

        if ((libsystemd = dlopen(LIBSYSTEMD, RTLD_LAZY)) == NULL) {
            fprintf(stderr, "dlopen %s\n", dlerror());
            return -4;
        }

        _sd_listen_fds_with_names =
            dlsym(libsystemd, "sd_listen_fds_with_names");

        if (_sd_listen_fds_with_names == NULL) {
            fprintf(stderr, "dlsym %s\n", dlerror());
            return -4;
        }

        num_fds = _sd_listen_fds_with_names(0, &fdmap);

        if (num_fds <= 0) {
            fputs("No suitable file descriptors in LISTEN_FDS.\n", stderr);
            if (num_fds == 0)
                return -3;
            return -4;
        }

        if (fdmap != NULL) {
            for (int i = 0; i < num_fds; i++) {
                if (strncmp(fdmap[i], "ssh", 4) == 0)
                    ssh_fd = SD_LISTEN_FDS_START + i;
#ifndef SUPERVISOR_SUPPORT
                else if (strncmp(fdmap[i], "main", 5) == 0)
                    main_fd = SD_LISTEN_FDS_START + i;
                else if (strncmp(fdmap[i], "scdaemon", 9) == 0)
                    scdaemon_fd = SD_LISTEN_FDS_START + i;
#endif
                free(fdmap[i]);
            }
            free(fdmap);
        }

        if (dlclose(libsystemd) != 0)
            return -1;
    }

    return 0;
}

#ifndef SUPERVISOR_SUPPORT

/* Get a systemd file descriptor corresponding to the specified socket path.
 *
 * Return values:
 *   -1 Socket path not a systemd socket
 *   -2 Provided socket path is not absolute
 *   -3 No suitable file descriptors in LISTEN_FDS
 *   -4 Error while determining LISTEN_FDS
 */
static int get_sd_fd(const char *sockpath)
{
    int ret;

    if ((ret = gather_sd_fds()) != 0)
        return ret;

    char *basename = strrchr(sockpath, '/');
    if (basename == NULL)
        return -2;
    else
        basename++;

    if (strncmp(basename, "S.gpg-agent", 12) == 0)
        return main_fd;
    else if (strncmp(basename, "S.gpg-agent.ssh", 16) == 0)
        return ssh_fd;
    else if (strncmp(basename, "S.scdaemon", 11) == 0)
        return scdaemon_fd;

    return -1;
}
int Atcleci_Init(Tcl_Interp *interp) {
  int rc;
  size_t chunk_bytes = 0;
  void *eciHandle;
  void *eciLib;
  //< configure shared library symbols

  eciLib = dlopen(ECILIBRARYNAME, RTLD_LAZY);
  if (eciLib == NULL) {
    Tcl_AppendResult(interp, "Could not load ", ECILIBRARYNAME, "\n", dlerror(),
                     "\nPlease install the IBM ViaVoice Outloud RTK", NULL);
    return TCL_ERROR;
  }

  _eciVersion = (void (*)(char *))(unsigned long)dlsym(eciLib, "eciVersion");
  _eciGetAvailableLanguages = (int (*)(enum ECILanguageDialect *, int *))(
      unsigned long)dlsym(eciLib, "eciGetAvailableLanguages");
  _eciNewEx = (void *(*)(enum ECILanguageDialect))(unsigned long)dlsym(
      eciLib, "eciNewEx");
  _eciDelete = (void (*)(void *))(unsigned long)dlsym(eciLib, "eciDelete");
  _eciReset = (int (*)(void *))(unsigned long)dlsym(eciLib, "eciReset");
  _eciStop = (int (*)(void *))(unsigned long)dlsym(eciLib, "eciStop");
  _eciClearInput =
      (int (*)(void *))(unsigned long)dlsym(eciLib, "eciClearInput");
  _eciPause = (int (*)(void *, int))(unsigned long)dlsym(eciLib, "eciPause");
  _eciSynthesize =
      (int (*)(void *))(unsigned long)dlsym(eciLib, "eciSynthesize");
  _eciSynchronize =
      (int (*)(void *))(unsigned long)dlsym(eciLib, "eciSynchronize");
  _eciSpeaking = (int (*)(void *))(unsigned long)dlsym(eciLib, "eciSpeaking");
  _eciInsertIndex =
      (int (*)(void *, int))(unsigned long)dlsym(eciLib, "eciInsertIndex");
  _eciAddText =
      (int (*)(void *, char *))(unsigned long)dlsym(eciLib, "eciAddText");
  _eciSetParam =
      (int (*)(void *, int, int))(unsigned long)dlsym(eciLib, "eciSetParam");
  _eciGetVoiceParam = (int (*)(void *, int, int))(unsigned long)dlsym(
      eciLib, "eciGetVoiceParam");
  _eciSetVoiceParam = (int (*)(void *, int, int, int))(unsigned long)dlsym(
      eciLib, "eciSetVoiceParam");
  _eciRegisterCallback =
      (void (*)(void *, int (*)(void *, int, long, void *), void *))(
          unsigned long)dlsym(eciLib, "eciRegisterCallback");
  _eciSetOutputBuffer = (int (*)(void *, int, short *))(unsigned long)dlsym(
      eciLib, "eciSetOutputBuffer");
  _eciSetOutputDevice =
      (int (*)(void *, int))(unsigned long)dlsym(eciLib, "eciSetOutputDevice");

  //>
  //< check for needed symbols

  int okay = 1;
  if (!_eciNewEx) {
    okay = 0;
    Tcl_AppendResult(interp, "eciNewEx undef\n", NULL);
  }
  if (!_eciDelete) {
    okay = 0;
    Tcl_AppendResult(interp, "eciDelete undef\n", NULL);
  }
  if (!_eciReset) {
    okay = 0;
    Tcl_AppendResult(interp, "eciReset undef\n", NULL);
  }
  if (!_eciStop) {
    okay = 0;
    Tcl_AppendResult(interp, "eciStop undef\n", NULL);
  }
  if (!_eciClearInput) {
    okay = 0;
    Tcl_AppendResult(interp, "eciClearInput undef\n", NULL);
  }
  if (!_eciPause) {
    okay = 0;
    Tcl_AppendResult(interp, "eciPause undef\n", NULL);
  }
  if (!_eciSynthesize) {
    okay = 0;
    Tcl_AppendResult(interp, "eciSynthesize undef\n", NULL);
  }
  if (!_eciSpeaking) {
    okay = 0;
    Tcl_AppendResult(interp, "eciSpeaking undef\n", NULL);
  }
  if (!_eciInsertIndex) {
    okay = 0;
    Tcl_AppendResult(interp, "eciInsertIndex undef\n", NULL);
  }
  if (!_eciAddText) {
    okay = 0;
    Tcl_AppendResult(interp, "eciAddText undef\n", NULL);
  }
  if (!_eciSetParam) {
    okay = 0;
    Tcl_AppendResult(interp, "eciSetParam undef\n", NULL);
  }
  if (!_eciSetParam) {
    okay = 0;
    Tcl_AppendResult(interp, "eciSetParam undef\n", NULL);
  }
  if (!_eciGetVoiceParam) {
    okay = 0;
    Tcl_AppendResult(interp, "eciGetVoiceParam undef\n", NULL);
  }
  if (!_eciSetVoiceParam) {
    okay = 0;
    Tcl_AppendResult(interp, "eciSetVoiceParam undef\n", NULL);
  }
  if (!_eciRegisterCallback) {
    okay = 0;
    Tcl_AppendResult(interp, "eciRegisterCallback undef\n", NULL);
  }
  if (!_eciSetOutputBuffer) {
    okay = 0;
    Tcl_AppendResult(interp, "eciSetOutputBuffer undef\n", NULL);
  }
  if (!_eciSetOutputDevice) {
    okay = 0;
    Tcl_AppendResult(interp, "eciSetOutputDevice undef\n", NULL);
  }
  if (!_eciGetAvailableLanguages) {
    okay = 0;
    Tcl_AppendResult(interp, "_eciGetAvailableLanguages undef\n", NULL);
  }
  if (!okay) {
    Tcl_AppendResult(interp, "Missing symbols from ", ECILIBRARYNAME, NULL);
    return TCL_ERROR;
  }
  //>
  //<setup package, create tts handle

  if (Tcl_PkgProvide(interp, PACKAGENAME, PACKAGEVERSION) != TCL_OK) {
    Tcl_AppendResult(interp, "Error loading ", PACKAGENAME, NULL);
    return TCL_ERROR;
  }

  static enum ECILanguageDialect aLanguages[LANG_INFO_MAX];
  int nLanguages = LANG_INFO_MAX;
  _eciGetAvailableLanguages(aLanguages, &nLanguages);

  enum ECILanguageDialect aDefaultLanguage =
      initLanguage(interp, aLanguages, nLanguages);
  if (aDefaultLanguage == NODEFINEDCODESET) {
    Tcl_AppendResult(interp, "No language found", PACKAGENAME, NULL);
    return TCL_ERROR;
  }
  fprintf(stderr, "Found %d languages.\n", nLanguages);
  eciHandle = _eciNewEx(aDefaultLanguage);
  if (eciHandle == 0) {
    Tcl_AppendResult(interp, "Could not open text-to-speech engine", NULL);
    return TCL_ERROR;
  }
  //>
  //<initialize alsa
  chunk_bytes = alsa_init();
  //<Finally, allocate waveBuffer

  fprintf(stderr, "allocating %d samples\n", (int)chunk_bytes);
  waveBuffer = (short *)malloc(chunk_bytes * sizeof(short));
  if (waveBuffer == NULL) {
    fprintf(stderr, "not enough memory");
    alsa_close();
    exit(EXIT_FAILURE);
  }
  //>
  //>
  //<initialize TTS

  if ((_eciSetParam(eciHandle, eciInputType, 1) == -1) ||
      (_eciSetParam(eciHandle, eciSynthMode, 1) == -1) ||
      (_eciSetParam(eciHandle, eciSampleRate, 1) == -1)) {
    Tcl_AppendResult(interp, "Could not initialized tts", NULL);
    _eciDelete(eciHandle);
    return TCL_ERROR;
  }
  _eciRegisterCallback(eciHandle, eciCallback, interp);

  //>
  //<set output to buffer

  rc = _eciSynchronize(eciHandle);
  if (!rc) {
    Tcl_AppendResult(interp, "Error  resetting TTS engine.\n", NULL);
    return TCL_ERROR;
  }
  rc = _eciSetOutputBuffer(eciHandle, chunk_bytes, waveBuffer);
  if (!rc) {
    Tcl_AppendResult(interp, "Error setting output buffer.\n", NULL);
    return TCL_ERROR;
  }
  fprintf(stderr, "output buffered to waveBuffer with size %d\n",
          (int)chunk_bytes);

  //>
  //<register tcl commands

  Tcl_CreateObjCommand(interp, "setRate", SetRate, (ClientData)eciHandle,
                       TclEciFree);
  Tcl_CreateObjCommand(interp, "getRate", GetRate, (ClientData)eciHandle,
                       TclEciFree);
  Tcl_CreateObjCommand(interp, "ttsVersion", getTTSVersion,
                       (ClientData)eciHandle, TclEciFree);
  Tcl_CreateObjCommand(interp, "alsaState", showAlsaState, (ClientData)NULL,
                       TclEciFree);
  Tcl_CreateObjCommand(interp, "say", Say, (ClientData)eciHandle, TclEciFree);
  Tcl_CreateObjCommand(interp, "synth", Say, (ClientData)eciHandle, NULL);
  Tcl_CreateObjCommand(interp, "synchronize", Synchronize,
                       (ClientData)eciHandle, TclEciFree);
  Tcl_CreateObjCommand(interp, "stop", Stop, (ClientData)eciHandle, TclEciFree);
  Tcl_CreateObjCommand(interp, "speakingP", SpeakingP, (ClientData)eciHandle,
                       TclEciFree);
  Tcl_CreateObjCommand(interp, "pause", Pause, (ClientData)eciHandle,
                       TclEciFree);
  Tcl_CreateObjCommand(interp, "resume", Resume, (ClientData)eciHandle,
                       TclEciFree);
  Tcl_CreateObjCommand(interp, "setLanguage", SetLanguage,
                       (ClientData)eciHandle, TclEciFree);
  //>
  //<set up index processing

  rc = Tcl_Eval(interp,
                "proc index x {global tts; \
set tts(last_index) $x}");
Example #3
0
static void *ll_load (lua_State *L, const char *path) {
  void *lib = dlopen(path, RTLD_NOW);
  if (lib == NULL) lua_pushstring(L, dlerror());
  return lib;
}
Example #4
0
/* load a particular module */
int neb_load_module(nebmodule *mod) {
	int (*initfunc)(int, char *, void *);
	int *module_version_ptr = NULL;
	char output_file[PATH_MAX];
	int dest_fd, result = OK;

	if(mod == NULL || mod->filename == NULL)
		return ERROR;

	/* don't reopen the module */
	if(mod->is_currently_loaded == TRUE)
		return OK;

	/* don't load modules unless they should be loaded */
	if(mod->should_be_loaded == FALSE)
		return ERROR;

	/**********
	   Using dlopen() is great, but a real danger as-is.  The problem with loaded modules is that if you overwrite the original file (e.g. using 'mv'),
	   you do not alter the inode of the original file.  Since the original file/module is memory-mapped in some fashion, Nagios will segfault the next
	   time an event broker call is directed to one of the module's callback functions.  This is extremely problematic when it comes to upgrading NEB
	   modules while Nagios is running.  A workaround is to (1) 'mv' the original/loaded module file to another name (on the same filesystem)
	   and (2) copy the new module file to the location of the original one (using the original filename).  In this scenario, dlopen() will keep referencing
	   the original file/inode for callbacks.  This is not an ideal solution.   A better one is to delete the module file once it is loaded by dlopen().
	   This prevents other processed from unintentially overwriting the original file, which would cause Nagios to crash.  However, if we delete the file
	   before anyone else can muck with it, things should be good.  'lsof' shows that a deleted file is still referenced by the kernel and callback
	   functions continue to work once the module has been loaded.  Long story, but this took quite a while to figure out, as there isn't much
	   of anything I could find on the subject other than some sketchy info on similar problems on HP-UX.  Hopefully this will save future coders some time.
	   So... the trick is to (1) copy the module to a temp file, (2) dlopen() the temp file, and (3) immediately delete the temp file.
	************/

	/*
	 * open a temp file for copying the module. We use my_fdcopy() so
	 * we re-use the destination file descriptor returned by mkstemp(3),
	 * which we have to close ourselves.
	 */
	snprintf(output_file, sizeof(output_file) - 1, "%s/nebmodXXXXXX", temp_path);
	dest_fd = mkstemp(output_file);
	result = my_fdcopy(mod->filename, output_file, dest_fd);
	close(dest_fd);
	if(result == ERROR) {
		logit(NSLOG_RUNTIME_ERROR, FALSE, "Error: Failed to safely copy module '%s'. The module will not be loaded\n", mod->filename);
		return ERROR;
		}

	/* load the module (use the temp copy we just made) */
	mod->module_handle = dlopen(output_file, RTLD_NOW | RTLD_GLOBAL);
	if(mod->module_handle == NULL) {
		logit(NSLOG_RUNTIME_ERROR, FALSE, "Error: Could not load module '%s' -> %s\n", mod->filename, dlerror());

		return ERROR;
		}

	/* mark the module as being loaded */
	mod->is_currently_loaded = TRUE;

	/* delete the temp copy of the module we just created and loaded */
	/* this will prevent other processes from overwriting the file (using the same inode), which would cause Nagios to crash */
	/* the kernel will keep the deleted file in memory until we unload it */
	/* NOTE: This *should* be portable to most Unices, but I've only tested it on Linux */
	if(unlink(output_file) == -1) {
		logit(NSLOG_RUNTIME_ERROR, FALSE, "Error: Could not delete temporary file '%s' used for module '%s'.  The module will be unloaded: %s\n", output_file, mod->filename, strerror(errno));
		neb_unload_module(mod, NEBMODULE_FORCE_UNLOAD, NEBMODULE_ERROR_API_VERSION);

		return ERROR;
		}

	/*
	 * now that it's loaded and removed, we create a new file in
	 * its place so debuggers can find the correct symbols properly,
	 * but only if we're supposed to dump core
	 */
	if(daemon_dumps_core == TRUE) {
		dest_fd = open(output_file, O_CREAT | O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH);
		result = my_fdcopy(mod->filename, output_file, dest_fd);
		mod->dl_file = strdup(output_file);
		}

	/* find module API version */
	module_version_ptr = (int *)dlsym(mod->module_handle, "__neb_api_version");

	/* check the module API version */
	if(module_version_ptr == NULL || ((*module_version_ptr) != CURRENT_NEB_API_VERSION)) {

		logit(NSLOG_RUNTIME_ERROR, FALSE, "Error: Module '%s' is using an old or unspecified version of the event broker API.  Module will be unloaded.\n", mod->filename);

		neb_unload_module(mod, NEBMODULE_FORCE_UNLOAD, NEBMODULE_ERROR_API_VERSION);

		return ERROR;
		}

	/* locate the initialization function */
	mod->init_func = dlsym(mod->module_handle, "nebmodule_init");

	/* if the init function could not be located, unload the module */
	if(mod->init_func == NULL) {

		logit(NSLOG_RUNTIME_ERROR, FALSE, "Error: Could not locate nebmodule_init() in module '%s'.  Module will be unloaded.\n", mod->filename);

		neb_unload_module(mod, NEBMODULE_FORCE_UNLOAD, NEBMODULE_ERROR_NO_INIT);

		return ERROR;
		}

	/* run the module's init function */
	initfunc = mod->init_func;
	result = (*initfunc)(NEBMODULE_NORMAL_LOAD, mod->args, mod->module_handle);

	/* if the init function returned an error, unload the module */
	if(result != OK) {

		logit(NSLOG_RUNTIME_ERROR, FALSE, "Error: Function nebmodule_init() in module '%s' returned an error.  Module will be unloaded.\n", mod->filename);

		neb_unload_module(mod, NEBMODULE_FORCE_UNLOAD, NEBMODULE_ERROR_BAD_INIT);

		return ERROR;
		}

	logit(NSLOG_INFO_MESSAGE, FALSE, "Event broker module '%s' initialized successfully.\n", mod->filename);

	/* locate the de-initialization function (may or may not be present) */
	mod->deinit_func = dlsym(mod->module_handle, "nebmodule_deinit");

	log_debug_info(DEBUGL_EVENTBROKER, 0, "Module '%s' loaded with return code of '%d'\n", mod->filename, result);
	if(mod->deinit_func != NULL)
		log_debug_info(DEBUGL_EVENTBROKER, 0, "nebmodule_deinit() found\n");

	return OK;
	}
Example #5
0
static av_cold int a52_decode_init(AVCodecContext *avctx)
{
    AC3DecodeState *s = avctx->priv_data;

#ifdef CONFIG_LIBA52BIN
    s->handle = dlopen(liba52name, RTLD_LAZY);
    if (!s->handle)
    {
        av_log( avctx, AV_LOG_ERROR, "A52 library %s could not be opened! \n%s\n", liba52name, dlerror());
        return -1;
    }
    s->a52_init = (a52_state_t* (*)(uint32_t)) dlsymm(s->handle, "a52_init");
    s->a52_samples = (sample_t* (*)(a52_state_t*)) dlsymm(s->handle, "a52_samples");
    s->a52_syncinfo = (int (*)(uint8_t*, int*, int*, int*)) dlsymm(s->handle, "a52_syncinfo");
    s->a52_frame = (int (*)(a52_state_t*, uint8_t*, int*, sample_t*, sample_t)) dlsymm(s->handle, "a52_frame");
    s->a52_block = (int (*)(a52_state_t*)) dlsymm(s->handle, "a52_block");
    s->a52_free = (void (*)(a52_state_t*)) dlsymm(s->handle, "a52_free");
    if (!s->a52_init || !s->a52_samples || !s->a52_syncinfo
        || !s->a52_frame || !s->a52_block || !s->a52_free)
    {
        dlclose(s->handle);
        return -1;
    }
#else
    s->handle = 0;
    s->a52_init = a52_init;
    s->a52_samples = a52_samples;
    s->a52_syncinfo = a52_syncinfo;
    s->a52_frame = a52_frame;
    s->a52_block = a52_block;
    s->a52_free = a52_free;
#endif
    s->state = s->a52_init(0); /* later use CPU flags */
    s->samples = s->a52_samples(s->state);

    /* allow downmixing to stereo or mono */
    if (avctx->channels > 0 && avctx->request_channels > 0 &&
            avctx->request_channels < avctx->channels &&
            avctx->request_channels <= 2) {
        avctx->channels = avctx->request_channels;
    }

    return 0;
}
Example #6
0
File: ui.c Project: haobug/fcitx
boolean FcitxUILoadInternal(FcitxInstance* instance, FcitxAddon* addon)
{
    boolean success = false;
    char *modulePath;

    switch (addon->type) {

    case AT_SHAREDLIBRARY: {
        FILE *fp = FcitxXDGGetLibFile(addon->library, "r", &modulePath);
        void *handle;

        if (!fp)
            break;

        fclose(fp);

        handle = dlopen(modulePath, RTLD_NOW | (addon->loadLocal ? RTLD_LOCAL : RTLD_GLOBAL));

        if (!handle) {
            FcitxLog(ERROR, _("UI: open %s fail %s") , modulePath , dlerror());
            break;
        }

        if (!FcitxCheckABIVersion(handle, addon->name)) {
            FcitxLog(ERROR, "%s ABI Version Error", addon->name);
            dlclose(handle);
            break;
        }

        addon->ui = FcitxGetSymbol(handle, addon->name, "ui");

        if (!addon->ui || !addon->ui->Create) {
            FcitxLog(ERROR, _("UI: bad ui"));
            dlclose(handle);
            break;
        }

        if ((addon->addonInstance = addon->ui->Create(instance)) == NULL) {
            dlclose(handle);
            break;
        }

        /* some may register before ui load, so load it here */
        if (addon->ui->RegisterStatus) {
            UT_array* uistats = &instance->uistats;
            FcitxUIStatus *status;

            for (status = (FcitxUIStatus *) utarray_front(uistats);
                    status != NULL;
                    status = (FcitxUIStatus *) utarray_next(uistats, status))
                addon->ui->RegisterStatus(addon->addonInstance, status);
        }

        /* some may register before ui load, so load it here */
        if (addon->ui->RegisterComplexStatus) {
            UT_array* uicompstats = &instance->uicompstats;
            FcitxUIComplexStatus *status;

            for (status = (FcitxUIComplexStatus *) utarray_front(uicompstats);
                 status != NULL;
                 status = (FcitxUIComplexStatus *) utarray_next(uicompstats, status))
                addon->ui->RegisterComplexStatus(addon->addonInstance, status);
        }

        if (addon->ui->RegisterMenu) {
            UT_array* uimenus = &instance->uimenus;
            FcitxUIMenu **menupp;

            for (menupp = (FcitxUIMenu **) utarray_front(uimenus);
                    menupp != NULL;
                    menupp = (FcitxUIMenu **) utarray_next(uimenus, menupp))
                addon->ui->RegisterMenu(addon->addonInstance, *menupp);
        }

        success = true;
    }

    break;

    default:
        break;
    }

    free(modulePath);
    return success;
}
/*
 * Background process -- runs with privilege.
 */
static void
pam_server (int fd, const char *service, int verb, const struct name_value_list *name_value_list)
{
  struct user_pass up;
  int command;
#if DLOPEN_PAM
  static const char pam_so[] = "libpam.so";
#endif

  /*
   * Do initialization
   */
  if (DEBUG (verb))
    fprintf (stderr, "AUTH-PAM: BACKGROUND: INIT service='%s'\n", service);

#if DLOPEN_PAM
  /*
   * Load PAM shared object
   */
  if (!dlopen_pam (pam_so))
    {
      fprintf (stderr, "AUTH-PAM: BACKGROUND: could not load PAM lib %s: %s\n", pam_so, dlerror());
      send_control (fd, RESPONSE_INIT_FAILED);
      goto done;
    }
#endif

  /*
   * Tell foreground that we initialized successfully
   */
  if (send_control (fd, RESPONSE_INIT_SUCCEEDED) == -1)
    {
      fprintf (stderr, "AUTH-PAM: BACKGROUND: write error on response socket [1]\n");
      goto done;
    }

  /*
   * Event loop
   */
  while (1)
    {
      memset (&up, 0, sizeof (up));
      up.verb = verb;
      up.name_value_list = name_value_list;

      /* get a command from foreground process */
      command = recv_control (fd);

      if (DEBUG (verb))
	fprintf (stderr, "AUTH-PAM: BACKGROUND: received command code: %d\n", command);

      switch (command)
	{
	case COMMAND_VERIFY:
	  if (recv_string (fd, up.username, sizeof (up.username)) == -1
	      || recv_string (fd, up.password, sizeof (up.password)) == -1)
	    {
	      fprintf (stderr, "AUTH-PAM: BACKGROUND: read error on command channel: code=%d, exiting\n",
		       command);
	      goto done;
	    }

	  if (DEBUG (verb))
	    {
#if 0
	      fprintf (stderr, "AUTH-PAM: BACKGROUND: USER/PASS: %s/%s\n",
		       up.username, up.password);
#else
	      fprintf (stderr, "AUTH-PAM: BACKGROUND: USER: %s\n", up.username);
#endif
	    }

	  if (pam_auth (service, &up)) /* Succeeded */
	    {
	      if (send_control (fd, RESPONSE_VERIFY_SUCCEEDED) == -1)
		{
		  fprintf (stderr, "AUTH-PAM: BACKGROUND: write error on response socket [2]\n");
		  goto done;
		}
	    }
	  else /* Failed */
	    {
	      if (send_control (fd, RESPONSE_VERIFY_FAILED) == -1)
		{
		  fprintf (stderr, "AUTH-PAM: BACKGROUND: write error on response socket [3]\n");
		  goto done;
		}
	    }
	  break;

	case COMMAND_EXIT:
	  goto done;

	case -1:
	  fprintf (stderr, "AUTH-PAM: BACKGROUND: read error on command channel\n");
	  goto done;

	default:
	  fprintf (stderr, "AUTH-PAM: BACKGROUND: unknown command code: code=%d, exiting\n",
		   command);
	  goto done;
	}
    }
 done:

#if DLOPEN_PAM
  dlclose_pam ();
#endif
  if (DEBUG (verb))
    fprintf (stderr, "AUTH-PAM: BACKGROUND: EXIT\n");

  return;
}
Example #8
0
int ExecuteManagedAssembly(
            const char* currentExeAbsolutePath,
            const char* clrFilesAbsolutePath,
            const char* managedAssemblyAbsolutePath,
            int managedAssemblyArgc,
            const char** managedAssemblyArgv)
{
    // Indicates failure
    int exitCode = -1;

    std::string coreClrDllPath(clrFilesAbsolutePath);
    coreClrDllPath.append("/");
    coreClrDllPath.append(coreClrDll);

    if (coreClrDllPath.length() >= PATH_MAX)
    {
        fprintf(stderr, "Absolute path to libcoreclr.so too long\n");
        return -1;
    }

    // Get just the path component of the managed assembly path
    std::string appPath;
    GetDirectory(managedAssemblyAbsolutePath, appPath);

    // Construct native search directory paths
    std::string nativeDllSearchDirs(appPath);
    char *coreLibraries = getenv("CORE_LIBRARIES");
    if (coreLibraries)
    {
        nativeDllSearchDirs.append(":");
        nativeDllSearchDirs.append(coreLibraries);
    }
    nativeDllSearchDirs.append(":");
    nativeDllSearchDirs.append(clrFilesAbsolutePath);

    std::string tpaList;
    AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList);

    void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL);
    if (coreclrLib != nullptr)
    {
        coreclr_initialize_ptr initializeCoreCLR = (coreclr_initialize_ptr)dlsym(coreclrLib, "coreclr_initialize");
        coreclr_execute_assembly_ptr executeAssembly = (coreclr_execute_assembly_ptr)dlsym(coreclrLib, "coreclr_execute_assembly");
        coreclr_shutdown_ptr shutdownCoreCLR = (coreclr_shutdown_ptr)dlsym(coreclrLib, "coreclr_shutdown");

        if (initializeCoreCLR == nullptr)
        {
            fprintf(stderr, "Function coreclr_initialize not found in the libcoreclr.so\n");
        }
        else if (executeAssembly == nullptr)
        {
            fprintf(stderr, "Function coreclr_execute_assembly not found in the libcoreclr.so\n");
        }
        else if (shutdownCoreCLR == nullptr)
        {
            fprintf(stderr, "Function coreclr_shutdown not found in the libcoreclr.so\n");
        }
        else
        {
            // Check whether we are enabling server GC (off by default)
            const char* useServerGc = std::getenv(serverGcVar);
            if (useServerGc == nullptr)
            {
                useServerGc = "0";
            }

            // CoreCLR expects strings "true" and "false" instead of "1" and "0".
            useServerGc = std::strcmp(useServerGc, "1") == 0 ? "true" : "false";

            // Allowed property names:
            // APPBASE
            // - The base path of the application from which the exe and other assemblies will be loaded
            //
            // TRUSTED_PLATFORM_ASSEMBLIES
            // - The list of complete paths to each of the fully trusted assemblies
            //
            // APP_PATHS
            // - The list of paths which will be probed by the assembly loader
            //
            // APP_NI_PATHS
            // - The list of additional paths that the assembly loader will probe for ngen images
            //
            // NATIVE_DLL_SEARCH_DIRECTORIES
            // - The list of paths that will be probed for native DLLs called by PInvoke
            //
            const char *propertyKeys[] = {
                "TRUSTED_PLATFORM_ASSEMBLIES",
                "APP_PATHS",
                "APP_NI_PATHS",
                "NATIVE_DLL_SEARCH_DIRECTORIES",
                "AppDomainCompatSwitch",
                "System.GC.Server",
            };
            const char *propertyValues[] = {
                // TRUSTED_PLATFORM_ASSEMBLIES
                tpaList.c_str(),
                // APP_PATHS
                appPath.c_str(),
                // APP_NI_PATHS
                appPath.c_str(),
                // NATIVE_DLL_SEARCH_DIRECTORIES
                nativeDllSearchDirs.c_str(),
                // AppDomainCompatSwitch
                "UseLatestBehaviorWhenTFMNotSpecified",
                // System.GC.Server
                useServerGc,
            };

            void* hostHandle;
            unsigned int domainId;

            int st = initializeCoreCLR(
                        currentExeAbsolutePath, 
                        "unixcorerun", 
                        sizeof(propertyKeys) / sizeof(propertyKeys[0]), 
                        propertyKeys, 
                        propertyValues, 
                        &hostHandle, 
                        &domainId);

            if (!SUCCEEDED(st))
            {
                fprintf(stderr, "coreclr_initialize failed - status: 0x%08x\n", st);
                exitCode = -1;
            }
            else 
            {
                st = executeAssembly(
                        hostHandle,
                        domainId,
                        managedAssemblyArgc,
                        managedAssemblyArgv,
                        managedAssemblyAbsolutePath,
                        (unsigned int*)&exitCode);

                if (!SUCCEEDED(st))
                {
                    fprintf(stderr, "coreclr_execute_assembly failed - status: 0x%08x\n", st);
                    exitCode = -1;
                }

                st = shutdownCoreCLR(hostHandle, domainId);
                if (!SUCCEEDED(st))
                {
                    fprintf(stderr, "coreclr_shutdown failed - status: 0x%08x\n", st);
                    exitCode = -1;
                }
            }
        }

        if (dlclose(coreclrLib) != 0)
        {
            fprintf(stderr, "Warning - dlclose failed\n");
        }
    }
    else
    {
        char* error = dlerror();
        fprintf(stderr, "dlopen failed to open the libcoreclr.so with error %s\n", error);
    }

    return exitCode;
}
// Call back Declaration
ReturnType InertiaMeasurementUnitComp::onInitialize()
{
	Property parameter;
	std::map<std::string, std::string> temp = getPropertyMap();
	parameter.SetProperty(temp);
	
	if(parameter.FindName("ApiName") == false) {
		PrintMessage("ERROR : InertiaMeasurementUnitComp::onInitialize() -> Can't find the APIName in property\n");
		return lastError = OPROS_FIND_PROPERTY_ERROR;
	}
	
#if defined(WIN32)
	//	DLL 로드
	hOprosAPI = LoadLibrary((LPCSTR)parameter.GetValue("ApiName").c_str());
	if(hOprosAPI == NULL) {
		PrintMessage("ERROR : InertiaMeasurementUnitComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("ApiName").c_str());
		return lastError = OPROS_FIND_DLL_ERROR;
	}
	
	//	API 로드
	GET_OPROS_API getOprosAPI;
	getOprosAPI = (GET_OPROS_API)GetProcAddress(hOprosAPI, "GetAPI");
	if(getOprosAPI == NULL) {
		PrintMessage("ERROR : InertiaMeasurementUnitComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n");
		FreeLibrary(hOprosAPI);
		hOprosAPI = NULL;
		return lastError = OPROS_LOAD_DLL_ERROR;
	}

	//	API Casting
	imu = dynamic_cast<InertiaMeasurementUnit *>(getOprosAPI());
	if(imu == NULL) {
		PrintMessage("ERROR : InertiaMeasurementUnitComp::onInitialize() -> Can't get a handle of AccelerationSensor API\n");
		FreeLibrary(hOprosAPI);
		hOprosAPI = NULL;
		return lastError = OPROS_LOAD_DLL_ERROR;
	}
#else
	//	Shared Library 로드
	hOprosAPI = dlopen(parameter.GetValue("ApiName").c_str(), RTLD_NOW);
	if(hOprosAPI == NULL) {
		PrintMessage("ERROR : InertiaMeasurementUnitComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("ApiName").c_str());
		return lastError = OPROS_FIND_DLL_ERROR;
	}

	//	API 로드
	GET_OPROS_API getOprosAPI = (GET_OPROS_API)dlsym(hOprosAPI, "GetAPI");
	char *error = dlerror();
	if(error != NULL) {
		PrintMessage("ERROR : InertiaMeasurementUnitComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n");
		dlclose(hOprosAPI);
		hOprosAPI = NULL;
		return lastError = OPROS_LOAD_DLL_ERROR;
	}
	
	//	API Casting
	imu = static_cast<InertiaMeasurementUnit *>(getOprosAPI());
	if(imu == NULL) {
		PrintMessage("ERROR : InertiaMeasurementUnitComp::onInitialize() -> Can't get a handle of AccelerationSensor API\n");
		dlclose(hOprosAPI);
		hOprosAPI = NULL;
		return lastError = OPROS_LOAD_DLL_ERROR;
	}
#endif

	if(imu->Initialize(parameter) != API_SUCCESS) {
		delete imu;
		imu = NULL;

#if defined(WIN32)
		FreeLibrary(hOprosAPI);
#else
		dlclose(hOprosAPI);
#endif
		hOprosAPI = NULL;
		return lastError = OPROS_INITIALIZE_API_ERROR;
	}

	return lastError = OPROS_SUCCESS;
}
Example #10
0
static int load_sym_fail(const char* sym)
{
  fprintf(stderr, LPF "ERROR: dlsym(\"%s\") failed\n", sym);
  fprintf(stderr, LPF "ERROR: dlerror '%s'\n", dlerror());
  exit(-1);
}
Example #11
0
void UpdatePluginsBIOS() {
	DIR *dir;
	struct dirent *ent;
	void *Handle;
	char name[256];
	gchar *linkname;

	GpuConfS.plugins  = 0;
	SpuConfS.plugins  = 0;
	CdrConfS.plugins  = 0;
#ifdef ENABLE_SIO1API
	Sio1ConfS.plugins = 0;
#endif
	Pad1ConfS.plugins = 0;
	Pad2ConfS.plugins = 0;
	BiosConfS.plugins = 0;
	GpuConfS.glist  = NULL;
	SpuConfS.glist  = NULL;
	CdrConfS.glist  = NULL;
#ifdef ENABLE_SIO1API
	Sio1ConfS.glist  = NULL;
#endif
	Pad1ConfS.glist = NULL;
	Pad2ConfS.glist = NULL;
	BiosConfS.glist = NULL;
	GpuConfS.plist[0][0]  = '\0';
	SpuConfS.plist[0][0]  = '\0';
	CdrConfS.plist[0][0]  = '\0';
#ifdef ENABLE_SIO1API
	Sio1ConfS.plist[0][0]  = '\0';
#endif
	Pad1ConfS.plist[0][0] = '\0';
	Pad2ConfS.plist[0][0] = '\0';
	BiosConfS.plist[0][0] = '\0';

	// Load and get plugin info
	dir = opendir(Config.PluginsDir);
	if (dir == NULL) {
		printf(_("Could not open directory: '%s'\n"), Config.PluginsDir);
		return;
	}
	while ((ent = readdir(dir)) != NULL) {
		long type, v;
		linkname = g_build_filename(Config.PluginsDir, ent->d_name, NULL);

		// only libraries past this point, not config tools
		if (strstr(linkname, ".so") == NULL && strstr(linkname, ".dylib") == NULL)
			continue;

		Handle = dlopen(linkname, RTLD_NOW);
		if (Handle == NULL) {
			printf("%s\n", dlerror());
			g_free(linkname);
			continue;
		}

		PSE_getLibType = (PSEgetLibType)dlsym(Handle, "PSEgetLibType");
		if (PSE_getLibType == NULL) {
			if (strstr(linkname, "gpu") != NULL) type = PSE_LT_GPU;
			else if (strstr(linkname, "cdr") != NULL) type = PSE_LT_CDR;
#ifdef ENABLE_SIO1API
			else if (strstr(linkname, "sio1") != NULL) type = PSE_LT_SIO1;
#endif
			else if (strstr(linkname, "spu") != NULL) type = PSE_LT_SPU;
			else if (strstr(linkname, "pad") != NULL) type = PSE_LT_PAD;
			else { g_free(linkname); continue; }
		}
		else type = PSE_getLibType();

		PSE_getLibName = (PSEgetLibName) dlsym(Handle, "PSEgetLibName");
		if (PSE_getLibName != NULL) {
			sprintf(name, "%s", PSE_getLibName());
			PSE_getLibVersion = (PSEgetLibVersion) dlsym(Handle, "PSEgetLibVersion");
			if (PSE_getLibVersion != NULL) {
				char ver[32];

				v = PSE_getLibVersion();
				sprintf(ver, " %ld.%ld.%ld", v >> 16, (v >> 8) & 0xff, v & 0xff);
				strcat(name, ver);
			}
		}
Example #12
0
static void *ll_load(lua_State *L, const char *path, int gl)
{
  void *lib = dlopen(path, RTLD_NOW | (gl ? RTLD_GLOBAL : RTLD_LOCAL));
  if (lib == NULL) lua_pushstring(L, dlerror());
  return lib;
}
Example #13
0
/*--------------------------------------------------------------------------------------
    Name: OS_ModuleLoad

    Purpose: Loads an object file into the running operating system

    Parameters:

    Returns: OS_ERROR if the module cannot be loaded
             OS_INVALID_POINTER if one of the parameters is NULL
             OS_ERR_NO_FREE_IDS if the module table is full
             OS_ERR_NAME_TAKEN if the name is in use
             OS_SUCCESS if the module is loaded successfuly
---------------------------------------------------------------------------------------*/
int32 OS_ModuleLoad ( uint32 *module_id, char *module_name, char *filename )
{
   int         i;
   uint32      possible_moduleid;
   char        translated_path[OS_MAX_LOCAL_PATH_LEN];
   int32       return_code;
   void       *function_lib;     /*  Handle to shared lib file */
   const char *dl_error;    /*  Pointer to error string   */
   sigset_t    previous;
   sigset_t    mask;

   /*
   ** Check parameters
   */
   if (( filename == NULL ) || (module_id == NULL ) || (module_name == NULL))
   {
      return(OS_INVALID_POINTER);
   }

   OS_InterruptSafeLock(&OS_module_table_mut, &mask, &previous);

   /*
   ** Find a free module id
   */
   for( possible_moduleid = 0; possible_moduleid < OS_MAX_MODULES; possible_moduleid++)
   {
       if (OS_module_table[possible_moduleid].free == TRUE)
       {
           break;
       }
   }

   /*
   ** Check to see if the id is out of bounds
   */
   if( possible_moduleid >= OS_MAX_MODULES || OS_module_table[possible_moduleid].free != TRUE)
   {
       OS_InterruptSafeUnlock(&OS_module_table_mut, &previous);
       return OS_ERR_NO_FREE_IDS;
   }

   /*
   ** Check to see if the module file is already loaded
   */
   for (i = 0; i < OS_MAX_MODULES; i++)
   {
       if ((OS_module_table[i].free == FALSE) &&
          ( strcmp((char*) module_name, OS_module_table[i].name) == 0))
       {
           OS_InterruptSafeUnlock(&OS_module_table_mut, &previous);
           return OS_ERR_NAME_TAKEN;
       }
   }

   /*
   ** Set the possible task Id to not free so that
   ** no other task can try to use it
   */
   OS_module_table[possible_moduleid].free = FALSE ;
   OS_InterruptSafeUnlock(&OS_module_table_mut, &previous);

   /*
   ** Translate the filename to the Host System
   */
   return_code = OS_TranslatePath((const char *)filename, (char *)translated_path);
   if ( return_code != OS_SUCCESS )
   {
      OS_module_table[possible_moduleid].free = TRUE;
      return(return_code);
   }

   /*
   ** File is ready to load
   */

   /*
   ** Open the loadble bundle .. just opening it loads it into the system.
   */
   function_lib = dlopen(translated_path, RTLD_LAZY | RTLD_GLOBAL);
   dl_error = dlerror();
   if( dl_error )
   {
      OS_module_table[possible_moduleid].free = TRUE;
      return(OS_ERROR);
   }

   /*
   ** fill out the OS_module_table entry for this new module
   */
   OS_module_table[possible_moduleid].entry_point = 0; /* Only for certain targets */
   OS_module_table[possible_moduleid].host_module_id = (uint32) function_lib;
   strncpy(OS_module_table[possible_moduleid].filename , filename, OS_MAX_PATH_LEN);
   strncpy(OS_module_table[possible_moduleid].name , module_name, OS_MAX_API_NAME);

   /*
   ** For now, do not store the module address information
   ** Let the OS_ModuleInfo function fetch that information and return it.
   */
   OS_module_table[possible_moduleid].addr.valid = FALSE;

   /*
   ** Return the OSAPI Module ID
   */
   *module_id = possible_moduleid;

   return(OS_SUCCESS);

}/* end OS_ModuleLoad */
Example #14
0
/**
 * Try to \c dlopen the named driver.
 *
 * This function adds the "_dri.so" suffix to the driver name and searches the
 * directories specified by the \c LIBGL_DRIVERS_PATH environment variable in
 * order to find the driver.
 *
 * \param driverName - a name like "tdfx", "i810", "mga", etc.
 *
 * \returns
 * A handle from \c dlopen, or \c NULL if driver file not found.
 */
_X_HIDDEN void *
driOpenDriver(const char *driverName)
{
   void *glhandle, *handle;
   const char *libPaths, *p, *next;
   char realDriverName[200];
   int len;

   /* Attempt to make sure libGL symbols will be visible to the driver */
   glhandle = dlopen("libGL.so.1", RTLD_NOW | RTLD_GLOBAL);

   libPaths = NULL;
   if (geteuid() == getuid()) {
      /* don't allow setuid apps to use LIBGL_DRIVERS_PATH */
      libPaths = getenv("LIBGL_DRIVERS_PATH");
      if (!libPaths)
         libPaths = getenv("LIBGL_DRIVERS_DIR");        /* deprecated */
   }
   if (libPaths == NULL)
      libPaths = DEFAULT_DRIVER_DIR;

   handle = NULL;
   for (p = libPaths; *p; p = next) {
      next = strchr(p, ':');
      if (next == NULL) {
         len = strlen(p);
         next = p + len;
      }
      else {
         len = next - p;
         next++;
      }

#ifdef GLX_USE_TLS
      snprintf(realDriverName, sizeof realDriverName,
               "%.*s/tls/%s_dri.so", len, p, driverName);
      InfoMessageF("OpenDriver: trying %s\n", realDriverName);
      handle = dlopen(realDriverName, RTLD_NOW | RTLD_GLOBAL);
#endif

      if (handle == NULL) {
         snprintf(realDriverName, sizeof realDriverName,
                  "%.*s/%s_dri.so", len, p, driverName);
         InfoMessageF("OpenDriver: trying %s\n", realDriverName);
         handle = dlopen(realDriverName, RTLD_NOW | RTLD_GLOBAL);
      }

      if (handle != NULL)
         break;
      else
         ErrorMessageF("dlopen %s failed (%s)\n", realDriverName, dlerror());
   }

   if (!handle)
      ErrorMessageF("unable to load driver: %s_dri.so\n", driverName);

   if (glhandle)
      dlclose(glhandle);

   return handle;
}
Example #15
0
static void _module_free(struct module *module) {
	pixel_alloc((void *)module->name, 0);
	if (dlclose(module->dl))
		pixel_log(0, "dlclose: %s\n", dlerror());
}
Example #16
0
/*
 *  Our version of time() allows us to return fake values, so the calling
 *  program thinks it's retrieving the current date and time, while it is
 *  not
 *  Note that this routine is split into two parts so that the initialization
 *  piece can call the 'real' time function to establish a base time.
 */
static time_t _ftpl_time(time_t *time_tptr) {
#ifdef __APPLE__
    struct timeval tvm, *tv = &tvm;
#else
    static time_t (*real_time)(time_t *);
    static int has_real_time = 0;
#endif

    time_t result;

    time_t null_dummy;

    /* Handle null pointers correctly, fix as suggested by Andres Ojamaa */
    if (time_tptr == NULL) {
        time_tptr = &null_dummy;
        /* (void) fprintf(stderr, "NULL pointer caught in time().\n"); */
    }

#ifdef __APPLE__
    /* Check whether we've got a pointer to the real ftime() function yet */
    SINGLE_IF(has_real_gettimeofday==0)
        real_gettimeofday = NULL;
        real_gettimeofday = dlsym(RTLD_NEXT, "gettimeofday");

        /* check whether dlsym() worked */
        if (dlerror() == NULL) {
            has_real_gettimeofday = 1;
        }
    END_SINGLE_IF
    if (!has_real_gettimeofday) {  /* dlsym() failed */
#ifdef DEBUG
            (void) fprintf(stderr, "faketime problem: original gettimeofday() not found.\n");
#endif
            return -1; /* propagate error to caller */
    }

    /* initialize our result with the real current time */
    result = (*real_gettimeofday)(tv, NULL);
    if (result == -1) return result; /* original function failed */
    if (time_tptr != NULL)
        *time_tptr = tv->tv_sec;
    result = tv->tv_sec;
#else
    /* Check whether we've got a pointer to the real time function yet */
    SINGLE_IF(has_real_time==0)
        real_time = NULL;
        real_time = dlsym(RTLD_NEXT, "time");

        /* check whether dlsym() worked */
        if (dlerror() == NULL) {
            has_real_time = 1;
        }
    END_SINGLE_IF
    if (!has_real_time) {  /* dlsym() failed */
#ifdef DEBUG
            (void) fprintf(stderr, "faketime problem: original time() not found.\n");
#endif
            if (time_tptr != NULL)
                *time_tptr = -1;
            return -1; /* propagate error to caller */
    }

    /* initialize our result with the real current time */
    result = (*real_time)(time_tptr);
#endif

    return result;
}
Example #17
0
/**
 * @brief load all handlers found in the ::HANDLERS_DIR
 * @returns 0 on success, -1 on error.
 */
int load_handlers() {
    DIR *d;
    struct dirent *de;
    handler *h;
    char *path, *cwd;
    void *handle;
    size_t len;

    len = 50;
    cwd = malloc(len);

    while(cwd && len < PATH_MAX) {
        if(getcwd(cwd, len)) break;
        if(errno != ERANGE) {
            print( ERROR, "getcwd: %s", strerror(errno));
            free(cwd);
            return -1;
        }
        len += 50;
        cwd = realloc(cwd, len);
    }

    if(!cwd) {
        print( ERROR, "malloc(%d): %s", len, strerror(errno));
        return -1;
    }

    d = opendir(HANDLERS_DIR);

    if(!d) {
        print( ERROR, "opendir: %s", strerror(errno) );
        free(cwd);
        return -1;
    }

    while((de=readdir(d))) {
        if(!strncmp(de->d_name, ".", 2) || !strncmp(de->d_name, "..", 3)) {
            continue;
        }

        len = strlen(de->d_name);

        if(strncmp(de->d_name + (len - 3), ".so", 3))
            continue;

        if(asprintf(&path, "%s/" HANDLERS_DIR "/%s", cwd, de->d_name) == -1) {
            print( ERROR, "asprintf: %s", strerror(errno) );
            continue;
        }

        if(!(handle = dlopen(path, RTLD_NOW))) {
            print( ERROR, "dlopen: %s", dlerror() );
            free(path);
            continue;
        }

        if(!(h = (handler *)dlsym(handle, "handler_info"))) {
            print( ERROR, "\"%s\": undefined reference to 'handler_info'", path );
            goto close;
        }

        if(check_handler(h)) {
            goto close;
        }

        h->dl_handle = handle;

        list_add(&(handlers), (node *) h);

        free(path);
        continue;

close:

        if(dlclose(handle))
            print( ERROR, "dlclose(\"%s\"): %s", path, dlerror() );

        free(path);
    }

    closedir(d);

    free(cwd);

    if(!handlers.head) {
        print( ERROR, "no handlers found" );
        return -1;
    }

    return 0;
}
Example #18
0
void
vcc_ParseImport(struct vcc *tl)
{
	void *hdl;
	char fn[1024];
	struct token *mod, *t1;
	const char *modname;
	const char *proto;
	const char *abi;
	const char **spec;
	struct symbol *sym;
	const struct symbol *osym;
	const char *p;
	// int *modlen;

	t1 = tl->t;
	SkipToken(tl, ID);		/* "import" */

	ExpectErr(tl, ID);
	mod = tl->t;
	vcc_NextToken(tl);

	osym = VCC_FindSymbol(tl, mod, SYM_NONE);
	if (osym != NULL && osym->kind != SYM_VMOD) {
		VSB_printf(tl->sb, "Module %.*s conflics with other symbol.\n",
		    PF(mod));
		vcc_ErrWhere2(tl, t1, tl->t);
		return;
	}
	if (osym != NULL) {
		VSB_printf(tl->sb, "Module %.*s already imported.\n",
		    PF(mod));
		vcc_ErrWhere2(tl, t1, tl->t);
		VSB_printf(tl->sb, "Previous import was here:\n");
		vcc_ErrWhere2(tl, osym->def_b, osym->def_e);
		return;
	}

	bprintf(fn, "%.*s", PF(mod));
	sym = VCC_AddSymbolStr(tl, fn, SYM_VMOD);
	ERRCHK(tl);
	AN(sym);
	sym->def_b = t1;
	sym->def_e = tl->t;

	if (tl->t->tok == ID) {
		if (!tl->unsafe_path) {
			VSB_printf(tl->sb,
			    "'import ... from path...'"
			    " not allowed.\nAt:");
			vcc_ErrToken(tl, tl->t);
			vcc_ErrWhere(tl, tl->t);
			return;
		}
		if (!vcc_IdIs(tl->t, "from")) {
			VSB_printf(tl->sb, "Expected 'from path...'\n");
			vcc_ErrWhere(tl, tl->t);
			return;
		}
		vcc_NextToken(tl);
		ExpectErr(tl, CSTR);
		bprintf(fn, "%s", tl->t->dec);
		vcc_NextToken(tl);
	} else {
		bprintf(fn, "%s/libvmod_%.*s.so", tl->vmod_dir, PF(mod));
	}

	Fh(tl, 0, "static void *VGC_vmod_%.*s;\n", PF(mod));

	Fi(tl, 0, "\tif (VRT_Vmod_Init(&VGC_vmod_%.*s,\n", PF(mod));
	Fi(tl, 0, "\t    &Vmod_Func_%.*s,\n", PF(mod));
	Fi(tl, 0, "\t    sizeof(Vmod_Func_%.*s),\n", PF(mod));
	Fi(tl, 0, "\t    \"%.*s\",\n", PF(mod));
	Fi(tl, 0, "\t    ");
	EncString(tl->fi, fn, NULL, 0);
	Fi(tl, 0, ",\n\t    ");
	Fi(tl, 0, "cli))\n");
	Fi(tl, 0, "\t\treturn(1);\n");

	SkipToken(tl, ';');

	hdl = dlopen(fn, RTLD_NOW | RTLD_LOCAL);
	if (hdl == NULL) {
		VSB_printf(tl->sb, "Could not load module %.*s\n\t%s\n\t%s\n",
		    PF(mod), fn, dlerror());
		vcc_ErrWhere(tl, mod);
		return;
	}

	modname = dlsym(hdl, "Vmod_Name");
	if (modname == NULL) {
		VSB_printf(tl->sb, "Could not load module %.*s\n\t%s\n\t%s\n",
		    PF(mod), fn, "Symbol Vmod_Name not found");
		vcc_ErrWhere(tl, mod);
		return;
	}
	if (!vcc_IdIs(mod, modname)) {
		VSB_printf(tl->sb, "Could not load module %.*s\n\t%s\n",
		    PF(mod), fn);
		VSB_printf(tl->sb, "\tModule has wrong name: <%s>\n", modname);
		vcc_ErrWhere(tl, mod);
		return;
	}

	abi = dlsym(hdl, "Vmod_Varnish_ABI");
	if (abi == NULL || strcmp(abi, VMOD_ABI_Version) != 0) {
		VSB_printf(tl->sb, "Could not load module %.*s\n\t%s\n",
		    PF(mod), fn);
		VSB_printf(tl->sb, "\tABI mismatch, expected <%s>, got <%s>\n",
			   VMOD_ABI_Version, abi);
		vcc_ErrWhere(tl, mod);
		return;
	}

	proto = dlsym(hdl, "Vmod_Proto");
	if (proto == NULL) {
		VSB_printf(tl->sb, "Could not load module %.*s\n\t%s\n\t%s\n",
		    PF(mod), fn, "Symbol Vmod_Proto not found");
		vcc_ErrWhere(tl, mod);
		return;
	}
	spec = dlsym(hdl, "Vmod_Spec");
	if (spec == NULL) {
		VSB_printf(tl->sb, "Could not load module %.*s\n\t%s\n\t%s\n",
		    PF(mod), fn, "Symbol Vmod_Spec not found");
		vcc_ErrWhere(tl, mod);
		return;
	}
	Fh(tl, 0, "static struct vmod_priv vmod_priv_%.*s;\n", PF(mod));
	for (; *spec != NULL; spec++) {
		p = *spec;
		if (!strcmp(p, "OBJ")) {
			p += strlen(p) + 1;
			sym = VCC_AddSymbolStr(tl, p, SYM_OBJECT);
			XXXAN(sym);
			sym->args = p;
		} else if (!strcmp(p, "FINI")) {
			p += strlen(p) + 1;
			// Nothing yet
		} else if (!strcmp(p, "INIT")) {
			p += strlen(p) + 1;
			Fi(tl, 0, "\t%s(&vmod_priv_%.*s, &VCL_conf);\n",
			    p, PF(mod));
		} else {
			sym = VCC_AddSymbolStr(tl, p, SYM_FUNC);
			ERRCHK(tl);
			AN(sym);
			sym->eval = vcc_Eval_SymFunc;
			p += strlen(p) + 1;
			sym->cfunc = p;
			p += strlen(p) + 1;
			sym->args = p;

			/* Functions which return VOID are procedures */
			if (!memcmp(p, "VOID\0", 5))
				sym->kind = SYM_PROC;
		}
	}
	Fh(tl, 0, "\n%s\n", proto);

	/* XXX: zero the function pointer structure ?*/
	Ff(tl, 0, "\tvmod_priv_fini(&vmod_priv_%.*s);\n", PF(mod));
	Ff(tl, 0, "\tVRT_Vmod_Fini(&VGC_vmod_%.*s);\n", PF(mod));
}
Example #19
0
static char * ll_dlerror(void)
{
  return dlerror();
}
Example #20
0
/*
==============
VID_LoadRefresh
==============
*/
qboolean VID_LoadRefresh( char *name )
{
	refimport_t	ri;
	GetRefAPI_t	GetRefAPI;
	char	fn[MAX_OSPATH];
	char	*path;
	struct stat st;
	extern uid_t saved_euid;
	
	if ( reflib_active )
	{
		if (KBD_Close_fp)
			KBD_Close_fp();
		if (RW_IN_Shutdown_fp)
			RW_IN_Shutdown_fp();
		KBD_Close_fp = NULL;
		RW_IN_Shutdown_fp = NULL;
		re.Shutdown();
		VID_FreeReflib ();
	}

	Com_Printf( "------- Loading %s -------\n", name );

	//regain root
	seteuid(saved_euid);

	path = Cvar_Get ("basedir", DEFAULT_BASEDIR, CVAR_NOSET)->string;

	snprintf (fn, MAX_OSPATH, "%s/%s", path, name );
	
	if (stat(fn, &st) == -1) {
		path = Cvar_Get ("libdir", DEFAULT_LIBDIR, CVAR_NOSET)->string;
		snprintf (fn, MAX_OSPATH, "%s/%s", path, name );
		if (stat(fn, &st) == -1) {
			Com_Printf( "LoadLibrary(\"%s\") failed: %s\n", name, strerror(errno));
			return false;
		}
	}
	
	// permission checking
	if (strstr(fn, "softx") == NULL &&
	    strstr(fn, "glx") == NULL &&
	    strstr(fn, "softsdl") == NULL &&
	    strstr(fn, "sdlgl") == NULL) { // softx doesn't require root	
#if 0
		if (st.st_uid != 0) {
			Com_Printf( "LoadLibrary(\"%s\") failed: ref is not owned by root\n", name);
			return false;
		}
		if ((st.st_mode & 0777) & ~0700) {
			Com_Printf( "LoadLibrary(\"%s\") failed: invalid permissions, must be 700 for security considerations\n", name);
			return false;
		}
#endif
	} else {
		// softx requires we give up root now
		setreuid(getuid(), getuid());
		setegid(getgid());
	}

	if ( ( reflib_library = dlopen( fn, RTLD_LAZY ) ) == 0 )
	{
		Com_Printf( "LoadLibrary(\"%s\") failed: %s\n", name , dlerror());
		return false;
	}

	Com_Printf( "LoadLibrary(\"%s\")\n", fn );

	ri.Cmd_AddCommand = Cmd_AddCommand;
	ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
	ri.Cmd_Argc = Cmd_Argc;
	ri.Cmd_Argv = Cmd_Argv;
	ri.Cmd_ExecuteText = Cbuf_ExecuteText;
	ri.Con_Printf = VID_Printf;
	ri.Sys_Error = VID_Error;
	ri.FS_LoadFile = FS_LoadFile;
	ri.FS_FreeFile = FS_FreeFile;
	ri.FS_Gamedir = FS_Gamedir;
	ri.Cvar_Get = Cvar_Get;
	ri.Cvar_Set = Cvar_Set;
	ri.Cvar_SetValue = Cvar_SetValue;
	ri.Vid_GetModeInfo = VID_GetModeInfo;
	ri.Vid_MenuInit = VID_MenuInit;
	ri.Vid_NewWindow = VID_NewWindow;

	#ifdef QMAX
	ri.SetParticlePics = SetParticleImages;
	#endif

	if ( ( GetRefAPI = (void *) dlsym( reflib_library, "GetRefAPI" ) ) == 0 )
		Com_Error( ERR_FATAL, "dlsym failed on %s", name );

	re = GetRefAPI( ri );

	if (re.api_version != API_VERSION)
	{
		VID_FreeReflib ();
		Com_Error (ERR_FATAL, "%s has incompatible api_version", name);
	}

	/* Init IN (Mouse) */
	in_state.IN_CenterView_fp = IN_CenterView;
	in_state.Key_Event_fp = Do_Key_Event;
	in_state.viewangles = cl.viewangles;
	in_state.in_strafe_state = &in_strafe.state;
	in_state.in_speed_state = &in_speed.state;

	if ((RW_IN_Init_fp = dlsym(reflib_library, "RW_IN_Init")) == NULL ||
		(RW_IN_Shutdown_fp = dlsym(reflib_library, "RW_IN_Shutdown")) == NULL ||
		(RW_IN_Activate_fp = dlsym(reflib_library, "RW_IN_Activate")) == NULL ||
		(RW_IN_Commands_fp = dlsym(reflib_library, "RW_IN_Commands")) == NULL ||
		(RW_IN_Move_fp = dlsym(reflib_library, "RW_IN_Move")) == NULL ||
		(RW_IN_Frame_fp = dlsym(reflib_library, "RW_IN_Frame")) == NULL)
		Sys_Error("No RW_IN functions in REF.\n");

	/* this one is optional */
	RW_Sys_GetClipboardData_fp = dlsym(reflib_library, "RW_Sys_GetClipboardData");
	
	Real_IN_Init();

	if ( re.Init( 0, 0 ) == -1 )
	{
		re.Shutdown();
		VID_FreeReflib ();
		return false;
	}

	/* Init KBD */
#if 1
	if ((KBD_Init_fp = dlsym(reflib_library, "KBD_Init")) == NULL ||
		(KBD_Update_fp = dlsym(reflib_library, "KBD_Update")) == NULL ||
		(KBD_Close_fp = dlsym(reflib_library, "KBD_Close")) == NULL)
		Sys_Error("No KBD functions in REF.\n");
#else
	{
		void KBD_Init(void);
		void KBD_Update(void);
		void KBD_Close(void);

		KBD_Init_fp = KBD_Init;
		KBD_Update_fp = KBD_Update;
		KBD_Close_fp = KBD_Close;
	}
#endif
	KBD_Init_fp(Do_Key_Event);

	Key_ClearStates();
	
	// give up root now
	setreuid(getuid(), getuid());
	setegid(getgid());

	Com_Printf( "------------------------------------\n");
	reflib_active = true;
	return true;
}
Example #21
0
void *oci8_find_symbol(const char *symbol_name)
{
#if defined _WIN32
    /* Windows */
    static HMODULE hModule = NULL;

    if (hModule == NULL) {
        hModule = LoadLibrary("OCI.DLL");
        if (hModule == NULL) {
            char message[512];
            int error = GetLastError();
            char *p;

            memset(message, 0, sizeof(message));
            FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), message, sizeof(message), NULL);
            for (p = message; *p; p++) {
                if (*p == '\n' || *p == '\r')
                    *p = ' ';
            }
            rb_raise(rb_eLoadError, "OCI.DLL: %d(%s)", error, message);
        }
    }
    return GetProcAddress(hModule, symbol_name);
#else
    /* UNIX */
    static void *handle = NULL;

    if (handle == NULL) {
        static const char * const sonames[] = {
#if defined(__CYGWIN__)
            /* Windows(Cygwin) */
            "OCI.DLL",
#elif defined(_AIX)
            /* AIX */
            "libclntsh.a(shr.o)",
#elif defined(__hppa)
            /* HP-UX(PA-RISC) */
            "libclntsh.sl.12.1",
            "libclntsh.sl.11.1",
            "libclntsh.sl.10.1",
            "libclntsh.sl.9.0",
            "libclntsh.sl.8.0",
#elif defined(__APPLE__)
            /* Mac OS X */
            "libclntsh.dylib.12.1",
            "libclntsh.dylib.11.1",
            "libclntsh.dylib.10.1",
#else
            /* Linux, Solaris and HP-UX(IA64) */
            "libclntsh.so.12.1",
            "libclntsh.so.11.1",
            "libclntsh.so.10.1",
            "libclntsh.so.9.0",
            "libclntsh.so.8.0",
#endif
        };
#define NUM_SONAMES (sizeof(sonames)/sizeof(sonames[0]))
        size_t idx;
        volatile VALUE err = rb_ary_new();

#ifdef _AIX
#define DLOPEN_FLAG (RTLD_LAZY|RTLD_GLOBAL|RTLD_MEMBER)
#else
#define DLOPEN_FLAG (RTLD_LAZY|RTLD_GLOBAL)
#endif
        for (idx = 0; idx < NUM_SONAMES; idx++) {
            handle = dlopen(sonames[idx], DLOPEN_FLAG);
            if (handle != NULL) {
                break;
            }
            rb_ary_push(err, rb_locale_str_new_cstr(dlerror()));
        }
        if (handle == NULL) {
            VALUE msg;
            const char *ary = RARRAY_CONST_PTR(err);

            msg = rb_str_buf_new(NUM_SONAMES * 50);
            for (idx = 0; idx < NUM_SONAMES; idx++) {
                const char *errmsg = RSTRING_PTR(arr[idx]);
                if (idx != 0) {
                    rb_str_buf_cat2(msg, " ");
                }
                if (strstr(errmsg, sonames[idx]) == NULL) {
                    /* prepend "soname: " if soname is not found in
                     * the error message.
                     */
                    rb_str_buf_cat2(msg, sonames[idx]);
                    rb_str_buf_cat2(msg, ": ");
                }
                rb_str_buf_append(msg, arr[idx]);
                rb_str_buf_cat2(msg, ";");
            }
            rb_exc_raise(rb_exc_new3(rb_eLoadError, msg));
        }
    }
    return dlsym(handle, symbol_name);
#endif /* defined _WIN32 */
}
Example #22
0
LWS_VISIBLE int
lws_plat_plugins_init(struct lws_context * context, const char * const *d)
{
	struct lws_plugin_capability lcaps;
	struct lws_plugin *plugin;
	lws_plugin_init_func initfunc;
	struct dirent **namelist;
	int n, i, m, ret = 0;
	char path[256];
	void *l;

	lwsl_notice("  Plugins:\n");

	while (d && *d) {
		n = scandir(*d, &namelist, filter, alphasort);
		if (n < 0) {
			lwsl_err("Scandir on %s failed\n", *d);
			return 1;
		}

		for (i = 0; i < n; i++) {
			if (strlen(namelist[i]->d_name) < 7)
				goto inval;

			lwsl_notice("   %s\n", namelist[i]->d_name);

			snprintf(path, sizeof(path) - 1, "%s/%s", *d,
				 namelist[i]->d_name);
			l = dlopen(path, RTLD_NOW);
			if (!l) {
				lwsl_err("Error loading DSO: %s\n", dlerror());
				while (i++ < n)
					free(namelist[i]);
				goto bail;
			}
			/* we could open it, can we get his init function? */
			m = snprintf(path, sizeof(path) - 1, "init_%s",
				     namelist[i]->d_name + 3 /* snip lib... */);
			path[m - 3] = '\0'; /* snip the .so */
			initfunc = dlsym(l, path);
			if (!initfunc) {
				lwsl_err("Failed to get init on %s: %s",
						namelist[i]->d_name, dlerror());
				dlclose(l);
			}
			lcaps.api_magic = LWS_PLUGIN_API_MAGIC;
			m = initfunc(context, &lcaps);
			if (m) {
				lwsl_err("Initializing %s failed %d\n",
					namelist[i]->d_name, m);
				dlclose(l);
				goto skip;
			}

			plugin = lws_malloc(sizeof(*plugin));
			if (!plugin) {
				lwsl_err("OOM\n");
				goto bail;
			}
			plugin->list = context->plugin_list;
			context->plugin_list = plugin;
			strncpy(plugin->name, namelist[i]->d_name, sizeof(plugin->name) - 1);
			plugin->name[sizeof(plugin->name) - 1] = '\0';
			plugin->l = l;
			plugin->caps = lcaps;
			context->plugin_protocol_count += lcaps.count_protocols;
			context->plugin_extension_count += lcaps.count_extensions;

			free(namelist[i]);
			continue;

	skip:
			dlclose(l);
	inval:
			free(namelist[i]);
		}
		free(namelist);
		d++;
	}

bail:
	free(namelist);

	return ret;
}
Example #23
0
const char *dynload_error(void)
{
	return dlerror();
}
Example #24
0
static void* ConcurrentDlErrorFn(void*) {
  dlopen("/child/thread", RTLD_NOW);
  return reinterpret_cast<void*>(strdup(dlerror()));
}
Example #25
0
KTPluginInfoEntry
*load_plugin_info (char *dir, char *file_name)
/*
Input:
	dir		- The directory where the plugin is located in
	file_name	- The file name of the plugin
Output:
	-
Returns:
	A pointer to the KTPluginInfoEntry structure if information was succesfully
	read from the plugin, otherwise NULL.
Description:
	This function loads the plugin which file name is 'file_name' and fills in
	the values of a new KTPluginInfoEntry that will be read from the plugin.
	The next element of the new KTPluginInfoEntry will point to NULL.
*/
{
	void			*plugin_file;
	KTPluginInfoEntry	*plugin_info = NULL;
	KeytouchPlugin		*plugin;
	char			*complete_file_name;
	int			function;
	
	complete_file_name = keytouch_malloc(strlen(file_name) + strlen(dir) + 2);
	strcpy (complete_file_name, dir);
	strcat (complete_file_name, "/");
	strcat (complete_file_name, file_name);
	/* Open the plugin */
	plugin_file = dlopen (complete_file_name, RTLD_LAZY);
	if (plugin_file)
	{
		/* Get the plugin structure */
		plugin = dlsym(plugin_file, "plugin_struct");
		/* If the plugin_struct symbol was successfully read */
		if (dlerror() == NULL)
		{
			plugin_info = (KTPluginInfoEntry *) keytouch_malloc( sizeof(KTPluginInfoEntry) );
			plugin_info->info.name =  keytouch_strdup (plugin->info.name);
			plugin_info->info.author =  keytouch_strdup (plugin->info.author);
			plugin_info->info.license =  keytouch_strdup (plugin->info.license);
			plugin_info->info.version =  keytouch_strdup (plugin->info.version);
			plugin_info->info.description =  keytouch_strdup (plugin->info.description);
			plugin_info->file_name = file_name;
			plugin_info->num_functions = plugin->num_functions;
			plugin_info->function_names = (char **) keytouch_malloc( sizeof(char *) * plugin->num_functions);
			for (function = 0; function < plugin->num_functions; function++)
			{
				plugin_info->function_names[function] = keytouch_strdup (plugin->function[function].name);
			}
			plugin_info->file_name = keytouch_strdup (plugin->file_name);
			plugin_info->complete_file_name = complete_file_name;
			plugin_info->next = NULL;
		}
		dlclose (plugin_file); /* Close the opened plugin */
	}
	if (plugin_info == NULL)
	{
		free (complete_file_name);
	}
	return (plugin_info);
}
/*
 * Get the linkmap from the dynlinker.  Try to load kernel modules
 * from all objects in the linkmap.
 */
void
rumpuser_dl_bootstrap(rump_modinit_fn domodinit,
	rump_symload_fn symload, rump_compload_fn compload)
{
	struct link_map *map, *origmap, *mainmap;
	void *mainhandle;
	int error;

	mainhandle = dlopen(NULL, RTLD_NOW);
	/* Will be null if statically linked so just return */
	if (mainhandle == NULL)
		return;
	if (dlinfo(mainhandle, RTLD_DI_LINKMAP, &mainmap) == -1) {
		fprintf(stderr, "warning: rumpuser module bootstrap "
		    "failed: %s\n", dlerror());
		return;
	}
	origmap = mainmap;

	/*
	 * Use a heuristic to determine if we are static linked.
	 * A dynamically linked binary should always have at least
	 * two objects: itself and ld.so.
	 *
	 * In a statically linked binary with glibc the linkmap
	 * contains some "info" that leads to a segfault.  Since we
	 * can't really do anything useful in here without ld.so, just
	 * simply bail and let the symbol references in librump do the
	 * right things.
	 */
	if (origmap->l_next == NULL && origmap->l_prev == NULL) {
		dlclose(mainhandle);
		return;
	}

	/*
	 * Process last->first because that's the most probable
	 * order for dependencies
	 */
	for (; origmap->l_next; origmap = origmap->l_next)
		continue;

	/*
	 * Build symbol table to hand to the rump kernel.  Do this by
	 * iterating over all rump libraries and collecting symbol
	 * addresses and relocation info.
	 */
	error = 0;
	for (map = origmap; map && !error; map = map->l_prev) {
		if (strstr(map->l_name, "librump") != NULL || map == mainmap)
			error = getsymbols(map, map == mainmap);
	}

	if (error == 0) {
		void *trimmedsym, *trimmedstr;

		/*
		 * Allocate optimum-sized memory for storing tables
		 * and feed to kernel.  If memory allocation fails,
		 * just give the ones with extra context (although
		 * I'm pretty sure we'll die moments later due to
		 * memory running out).
		 */
		if ((trimmedsym = malloc(symtaboff)) != NULL) {
			memcpy(trimmedsym, symtab, symtaboff);
		} else {
			trimmedsym = symtab;
			symtab = NULL;
		}
		if ((trimmedstr = malloc(strtaboff)) != NULL) {
			memcpy(trimmedstr, strtab, strtaboff);
		} else {
			trimmedstr = strtab;
			strtab = NULL;
		}
		symload(trimmedsym, symtaboff, trimmedstr, strtaboff);
	}
	free(symtab);
	free(strtab);

	/*
	 * Next, load modules and components.
	 *
	 * Simply loop through all objects, ones unrelated to rump kernels
	 * will not contain link_set_rump_components (well, not including
	 * "sabotage", but that needs to be solved at another level anyway).
	 */
	for (map = origmap; map; map = map->l_prev) {
		void *handle;

		if (map == mainmap) {
			handle = mainhandle;
		} else {
			handle = dlopen(map->l_name, RTLD_LAZY);
			if (handle == NULL)
				continue;
		}
		process_object(handle, domodinit, compload);
		if (map != mainmap)
			dlclose(handle);
	}
}
Example #27
0
int main (int argc, char **argv)
{
	/* master file descriptor list */
	fd_set used_fds, serv_fds, read_fds;

	/* working structs */
	struct addrinfo hints;
	struct sigaction sa;
	struct config conf;

	/* signal mask */
	sigset_t ss;

	/* maximum file descriptor number */
	int cur_fd, max_fd = 0;

#ifdef HAVE_TLS
	int tls = 0;
	int keys = 0;
#endif

	int bound = 0;
	int nofork = 0;

	/* args */
	int opt;
	char bind[128];
	char *port = NULL;

#if defined(HAVE_TLS) || defined(HAVE_LUA)
	/* library handle */
	void *lib;
#endif

	/* clear the master and temp sets */
	FD_ZERO(&used_fds);
	FD_ZERO(&serv_fds);
	FD_ZERO(&read_fds);

	/* handle SIGPIPE, SIGINT, SIGTERM, SIGCHLD */
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);

	sa.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sa, NULL);

	sa.sa_handler = uh_sigchld;
	sigaction(SIGCHLD, &sa, NULL);

	sa.sa_handler = uh_sigterm;
	sigaction(SIGINT,  &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);

	/* defer SIGCHLD */
	sigemptyset(&ss);
	sigaddset(&ss, SIGCHLD);
	sigprocmask(SIG_BLOCK, &ss, NULL);

	/* prepare addrinfo hints */
	memset(&hints, 0, sizeof(hints));
	hints.ai_family   = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags    = AI_PASSIVE;

	/* parse args */
	memset(&conf, 0, sizeof(conf));
	memset(bind, 0, sizeof(bind));

#ifdef HAVE_TLS
	/* load TLS plugin */
	if( ! (lib = dlopen("uhttpd_tls.so", RTLD_LAZY | RTLD_GLOBAL)) )
	{
		fprintf(stderr,
			"Notice: Unable to load TLS plugin - disabling SSL support! "
			"(Reason: %s)\n", dlerror()
		);
	}
	else
	{
		/* resolve functions */
		if( !(conf.tls_init   = dlsym(lib, "uh_tls_ctx_init"))      ||
		    !(conf.tls_cert   = dlsym(lib, "uh_tls_ctx_cert"))      ||
		    !(conf.tls_key    = dlsym(lib, "uh_tls_ctx_key"))       ||
		    !(conf.tls_free   = dlsym(lib, "uh_tls_ctx_free"))      ||
			!(conf.tls_accept = dlsym(lib, "uh_tls_client_accept")) ||
			!(conf.tls_close  = dlsym(lib, "uh_tls_client_close"))  ||
			!(conf.tls_recv   = dlsym(lib, "uh_tls_client_recv"))   ||
			!(conf.tls_send   = dlsym(lib, "uh_tls_client_send"))
		) {
			fprintf(stderr,
				"Error: Failed to lookup required symbols "
				"in TLS plugin: %s\n", dlerror()
			);
			exit(1);
		}

		/* init SSL context */
		if( ! (conf.tls = conf.tls_init()) )
		{
			fprintf(stderr, "Error: Failed to initalize SSL context\n");
			exit(1);
		}
	}
#endif

	while( (opt = getopt(argc, argv,
		"fSDRC:K:E:I:p:s:h:c:l:L:d:r:m:x:i:t:T:")) > 0
	) {
		switch(opt)
		{
			/* [addr:]port */
			case 'p':
			case 's':
				if( (port = strrchr(optarg, ':')) != NULL )
				{
					if( (optarg[0] == '[') && (port > optarg) && (port[-1] == ']') )
						memcpy(bind, optarg + 1,
							min(sizeof(bind), (int)(port - optarg) - 2));
					else
						memcpy(bind, optarg,
							min(sizeof(bind), (int)(port - optarg)));

					port++;
				}
				else
				{
					port = optarg;
				}

#ifdef HAVE_TLS
				if( opt == 's' )
				{
					if( !conf.tls )
					{
						fprintf(stderr,
							"Notice: TLS support is disabled, "
							"ignoring '-s %s'\n", optarg
						);
						continue;
					}

					tls = 1;
				}
#endif

				/* bind sockets */
				bound += uh_socket_bind(
					&serv_fds, &max_fd, bind[0] ? bind : NULL, port,
					&hints,	(opt == 's'), &conf
				);

				memset(bind, 0, sizeof(bind));
				break;

#ifdef HAVE_TLS
			/* certificate */
			case 'C':
				if( conf.tls )
				{
					if( conf.tls_cert(conf.tls, optarg) < 1 )
					{
						fprintf(stderr,
							"Error: Invalid certificate file given\n");
						exit(1);
					}

					keys++;
				}

				break;

			/* key */
			case 'K':
				if( conf.tls )
				{
					if( conf.tls_key(conf.tls, optarg) < 1 )
					{
						fprintf(stderr,
							"Error: Invalid private key file given\n");
						exit(1);
					}

					keys++;
				}

				break;
#endif

			/* docroot */
			case 'h':
				if( ! realpath(optarg, conf.docroot) )
				{
					fprintf(stderr, "Error: Invalid directory %s: %s\n",
						optarg, strerror(errno));
					exit(1);
				}
				break;

			/* error handler */
			case 'E':
				if( (strlen(optarg) == 0) || (optarg[0] != '/') )
				{
					fprintf(stderr, "Error: Invalid error handler: %s\n",
						optarg);
					exit(1);
				}
				conf.error_handler = optarg;
				break;

			/* index file */
			case 'I':
				if( (strlen(optarg) == 0) || (optarg[0] == '/') )
				{
					fprintf(stderr, "Error: Invalid index page: %s\n",
						optarg);
					exit(1);
				}
				conf.index_file = optarg;
				break;

			/* don't follow symlinks */
			case 'S':
				conf.no_symlinks = 1;
				break;

			/* don't list directories */
			case 'D':
				conf.no_dirlists = 1;
				break;

			case 'R':
				conf.rfc1918_filter = 1;
				break;

#ifdef HAVE_CGI
			/* cgi prefix */
			case 'x':
				conf.cgi_prefix = optarg;
				break;

			/* interpreter */
			case 'i':
				if( (optarg[0] == '.') && (port = strchr(optarg, '=')) )
				{
					*port++ = 0;
					uh_interpreter_add(optarg, port);
				}
				else
				{
					fprintf(stderr, "Error: Invalid interpreter: %s\n",
						optarg);
					exit(1);
				}
				break;
#endif

#ifdef HAVE_LUA
			/* lua prefix */
			case 'l':
				conf.lua_prefix = optarg;
				break;

			/* lua handler */
			case 'L':
				conf.lua_handler = optarg;
				break;
#endif

#if defined(HAVE_CGI) || defined(HAVE_LUA)
			/* script timeout */
			case 't':
				conf.script_timeout = atoi(optarg);
				break;
#endif

			/* network timeout */
			case 'T':
				conf.network_timeout = atoi(optarg);
				break;

			/* no fork */
			case 'f':
				nofork = 1;
				break;

			/* urldecode */
			case 'd':
				if( (port = malloc(strlen(optarg)+1)) != NULL )
				{
					memset(port, 0, strlen(optarg)+1);
					uh_urldecode(port, strlen(optarg), optarg, strlen(optarg));
					printf("%s", port);
					free(port);
					exit(0);
				}
				break;

			/* basic auth realm */
			case 'r':
				conf.realm = optarg;
				break;

			/* md5 crypt */
			case 'm':
				printf("%s\n", crypt(optarg, "$1$"));
				exit(0);
				break;

			/* config file */
			case 'c':
				conf.file = optarg;
				break;

			default:
				fprintf(stderr,
					"Usage: %s -p [addr:]port [-h docroot]\n"
					"	-f              Do not fork to background\n"
					"	-c file         Configuration file, default is '/etc/httpd.conf'\n"
					"	-p [addr:]port  Bind to specified address and port, multiple allowed\n"
#ifdef HAVE_TLS
					"	-s [addr:]port  Like -p but provide HTTPS on this port\n"
					"	-C file         ASN.1 server certificate file\n"
					"	-K file         ASN.1 server private key file\n"
#endif
					"	-h directory    Specify the document root, default is '.'\n"
					"	-E string       Use given virtual URL as 404 error handler\n"
					"	-I string       Use given filename as index page for directories\n"
					"	-S              Do not follow symbolic links outside of the docroot\n"
					"	-D              Do not allow directory listings, send 403 instead\n"
					"	-R              Enable RFC1918 filter\n"
#ifdef HAVE_LUA
					"	-l string       URL prefix for Lua handler, default is '/lua'\n"
					"	-L file         Lua handler script, omit to disable Lua\n"
#endif
#ifdef HAVE_CGI
					"	-x string       URL prefix for CGI handler, default is '/cgi-bin'\n"
					"	-i .ext=path    Use interpreter at path for files with the given extension\n"
#endif
#if defined(HAVE_CGI) || defined(HAVE_LUA)
					"	-t seconds      CGI and Lua script timeout in seconds, default is 60\n"
#endif
					"	-T seconds      Network timeout in seconds, default is 30\n"
					"	-d string       URL decode given string\n"
					"	-r string       Specify basic auth realm\n"
					"	-m string       MD5 crypt given string\n"
					"\n", argv[0]
				);

				exit(1);
		}
	}

#ifdef HAVE_TLS
	if( (tls == 1) && (keys < 2) )
	{
		fprintf(stderr, "Error: Missing private key or certificate file\n");
		exit(1);
	}
#endif

	if( bound < 1 )
	{
		fprintf(stderr, "Error: No sockets bound, unable to continue\n");
		exit(1);
	}

	/* default docroot */
	if( !conf.docroot[0] && !realpath(".", conf.docroot) )
	{
		fprintf(stderr, "Error: Can not determine default document root: %s\n",
			strerror(errno));
		exit(1);
	}

	/* default realm */
	if( ! conf.realm )
		conf.realm = "Protected Area";

	/* config file */
	uh_config_parse(&conf);

	/* default network timeout */
	if( conf.network_timeout <= 0 )
		conf.network_timeout = 30;

#if defined(HAVE_CGI) || defined(HAVE_LUA)
	/* default script timeout */
	if( conf.script_timeout <= 0 )
		conf.script_timeout = 60;
#endif

#ifdef HAVE_CGI
	/* default cgi prefix */
	if( ! conf.cgi_prefix )
		conf.cgi_prefix = "/cgi-bin";
#endif

#ifdef HAVE_LUA
	/* load Lua plugin */
	if( ! (lib = dlopen("uhttpd_lua.so", RTLD_LAZY | RTLD_GLOBAL)) )
	{
		fprintf(stderr,
			"Notice: Unable to load Lua plugin - disabling Lua support! "
			"(Reason: %s)\n", dlerror()
		);
	}
	else
	{
		/* resolve functions */
		if( !(conf.lua_init    = dlsym(lib, "uh_lua_init"))    ||
		    !(conf.lua_close   = dlsym(lib, "uh_lua_close"))   ||
		    !(conf.lua_request = dlsym(lib, "uh_lua_request"))
		) {
			fprintf(stderr,
				"Error: Failed to lookup required symbols "
				"in Lua plugin: %s\n", dlerror()
			);
			exit(1);
		}

		/* init Lua runtime if handler is specified */
		if( conf.lua_handler )
		{
			/* default lua prefix */
			if( ! conf.lua_prefix )
				conf.lua_prefix = "/lua";

			conf.lua_state = conf.lua_init(conf.lua_handler);
		}
	}
#endif

	/* fork (if not disabled) */
	if( ! nofork )
	{
		switch( fork() )
		{
			case -1:
				perror("fork()");
				exit(1);

			case 0:
				/* daemon setup */
				if( chdir("/") )
					perror("chdir()");

				if( (cur_fd = open("/dev/null", O_WRONLY)) > -1 )
					dup2(cur_fd, 0);

				if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
					dup2(cur_fd, 1);

				if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
					dup2(cur_fd, 2);

				break;

			default:
				exit(0);
		}
	}

	/* server main loop */
	uh_mainloop(&conf, serv_fds, max_fd);

#ifdef HAVE_LUA
	/* destroy the Lua state */
	if( conf.lua_state != NULL )
		conf.lua_close(conf.lua_state);
#endif

	return 0;
}
Example #28
0
int ExecuteManagedAssembly(
            const char* currentExeAbsolutePath,
            const char* clrFilesAbsolutePath,
            const char* managedAssemblyAbsolutePath,
            int managedAssemblyArgc,
            const char** managedAssemblyArgv)
{
    // Indicates failure
    int exitCode = -1;

    std::string coreClrDllPath(clrFilesAbsolutePath);
    coreClrDllPath.append("/");
    coreClrDllPath.append(coreClrDll);

    if (coreClrDllPath.length() >= PATH_MAX)
    {
        fprintf(stderr, "Absolute path to libcoreclr.so too long\n");
        return -1;
    }

    // Get just the path component of the managed assembly path
    std::string appPath;
    GetDirectory(managedAssemblyAbsolutePath, appPath);

    std::string nativeDllSearchDirs(appPath);
    nativeDllSearchDirs.append(":");
    nativeDllSearchDirs.append(clrFilesAbsolutePath);

    std::string tpaList;
    AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList);

    void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL);
    if (coreclrLib != nullptr)
    {
        ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, "ExecuteAssembly");
        if (executeAssembly != nullptr)
        {
            // Allowed property names:
            // APPBASE
            // - The base path of the application from which the exe and other assemblies will be loaded
            //
            // TRUSTED_PLATFORM_ASSEMBLIES
            // - The list of complete paths to each of the fully trusted assemblies
            //
            // APP_PATHS
            // - The list of paths which will be probed by the assembly loader
            //
            // APP_NI_PATHS
            // - The list of additional paths that the assembly loader will probe for ngen images
            //
            // NATIVE_DLL_SEARCH_DIRECTORIES
            // - The list of paths that will be probed for native DLLs called by PInvoke
            //
            const char *propertyKeys[] = {
                "TRUSTED_PLATFORM_ASSEMBLIES",
                "APP_PATHS",
                "APP_NI_PATHS",
                "NATIVE_DLL_SEARCH_DIRECTORIES",
                "AppDomainCompatSwitch"
            };
            const char *propertyValues[] = {
                // TRUSTED_PLATFORM_ASSEMBLIES
                tpaList.c_str(),
                // APP_PATHS
                appPath.c_str(),
                // APP_NI_PATHS
                appPath.c_str(),
                // NATIVE_DLL_SEARCH_DIRECTORIES
                nativeDllSearchDirs.c_str(),
                // AppDomainCompatSwitch
                "UseLatestBehaviorWhenTFMNotSpecified"
            };

            HRESULT st = executeAssembly(
                            currentExeAbsolutePath,
                            coreClrDllPath.c_str(),
                            "unixcorerun",
                            sizeof(propertyKeys) / sizeof(propertyKeys[0]),
                            propertyKeys,
                            propertyValues,
                            managedAssemblyArgc,
                            managedAssemblyArgv,
                            managedAssemblyAbsolutePath,
                            NULL,
                            NULL,
                            NULL,
                            (DWORD*)&exitCode);

            if (!SUCCEEDED(st))
            {
                fprintf(stderr, "ExecuteAssembly failed - status: 0x%08x\n", st);
                exitCode = -1;
            }
        }
        else
        {
            fprintf(stderr, "Function ExecuteAssembly not found in the libcoreclr.so\n");
        }

        if (dlclose(coreclrLib) != 0)
        {
            fprintf(stderr, "Warning - dlclose failed\n");
        }
    }
    else
    {
        char* error = dlerror();
        fprintf(stderr, "dlopen failed to open the libcoreclr.so with error %s\n", error);
    }

    return exitCode;
}
Example #29
0
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
  if (f == NULL) lua_pushstring(L, dlerror());
  return f;
}
Example #30
0
std::string DynamicLibraryLastError() {
    return std::string(dlerror());
}