void PlayerCharacterEntity::update()
{
  m_velocity = ((float)m_health + 10)/m_velocityModifier;

  if (m_controlledByAI == true)
  {
    // this is a bot character, here's the AI! :D

    // set check surroundings timer to one of two primes
    m_checkTimer--;
    if (m_checkTimer <= 0)
    {
      m_checkTimer = (rand()%2 > 0) ? 37 : 67;
      checkEnvironment();
    }

    if (m_goalList.empty() && m_insList.empty())
    {
      determineGoals();
    }

    if (m_insList.empty())
    {
      determineInstructionsFromGoal();
    }

    // add AI for important surroundings sensing whateverness

    processNextInstruction();
  }
}
Example #2
0
	void Device::setUserPreferredEnvironment(int env) {
		if (env < 0 || env >= m_envs.size()) {
			m_userEnv = -1;
		} else {
			m_userEnv = env;
		}
		checkEnvironment();
	}
Example #3
0
/* Stdio support to ensure the console file buffer is flushed */
void Re_FlushConsole()
{
    JNIEnv *lenv=checkEnvironment();
    jri_checkExceptions(lenv, 1);
    jmethodID mid=(*lenv)->GetMethodID(lenv, engineClass, "jriFlushConsole", "()V");
    jri_checkExceptions(lenv, 0);
#ifdef JRI_DEBUG
	printf("jriWriteconsole mid=%x\n", mid);
#endif
	if (!mid) return;
	(*lenv)->CallVoidMethod(lenv, engineObj, mid);
    jri_checkExceptions(lenv, 1);
}
Example #4
0
void Re_Busy(int which)
{
	jmethodID mid;
    JNIEnv *lenv=checkEnvironment();
    jri_checkExceptions(lenv, 1);
    mid=(*lenv)->GetMethodID(lenv, engineClass, "jriBusy", "(I)V");
    jri_checkExceptions(lenv, 0);
#ifdef JRI_DEBUG
	printf("jriBusy mid=%x\n", mid);
#endif
	if (!mid) return;
	(*lenv)->CallVoidMethod(lenv, engineObj, mid, which);
    jri_checkExceptions(lenv, 1);
}
Example #5
0
void Re_WriteConsole(char *buf, int len)
{
    JNIEnv *lenv=checkEnvironment();
    jri_checkExceptions(lenv, 1);
    jstring s=(*lenv)->NewStringUTF(lenv, buf);
    jmethodID mid=(*lenv)->GetMethodID(lenv, engineClass, "jriWriteConsole", "(Ljava/lang/String;)V");
    jri_checkExceptions(lenv, 0);
#ifdef JRI_DEBUG
	printf("jriWriteConsole mid=%x\n", mid);
#endif
    if (!mid) return;
	(*lenv)->CallVoidMethod(lenv, engineObj, mid, s);
    jri_checkExceptions(lenv, 1);
    (*lenv)->DeleteLocalRef(lenv, s);
}
Example #6
0
int Re_ReadConsole(char *prompt, unsigned char *buf, int len, int addtohistory)
{
	jstring r,s;
	jmethodID mid;
    JNIEnv *lenv=checkEnvironment();
	
    if (!lenv || !engineObj) return -1;
	
	jri_checkExceptions(lenv, 1);
	mid=(*lenv)->GetMethodID(eenv, engineClass, "jriReadConsole", "(Ljava/lang/String;I)Ljava/lang/String;");
#ifdef JRI_DEBUG
	printf("jriReadconsole mid=%x\n", mid);
#endif
	jri_checkExceptions(lenv, 0);
	if (!mid) return -1;
		
	s=(*lenv)->NewStringUTF(eenv, prompt);
	r=(jstring) (*lenv)->CallObjectMethod(lenv, engineObj, mid, s, addtohistory);
	jri_checkExceptions(lenv, 1);
	(*lenv)->DeleteLocalRef(lenv, s);
	jri_checkExceptions(lenv, 0);
	if (r) {
		const char *c=(*lenv)->GetStringUTFChars(lenv, r, 0);
		if (!c) return -1;
		{
			int l=strlen(c);
			strncpy(buf, c, (l>len-1)?len-1:l);
			buf[(l>len-1)?len-1:l]=0;
#ifdef JRI_DEBUG
			printf("Re_ReadConsole succeeded: \"%s\"\n",buf);
#endif
		}
		(*lenv)->ReleaseStringUTFChars(lenv, r, c);
		(*lenv)->DeleteLocalRef(lenv, r);
		return 1;
    }
    return -1;
}
Example #7
0
bool Application::OnInit()
{
#if wxUSE_ON_FATAL_EXCEPTION
    ::wxHandleFatalExceptions();
#endif

    std::set_terminate(parachute);
    checkEnvironment();
    parseCommandLine();

    // initialize IBPP library - if it fails: exit
    try
    {
        if (! IBPP::CheckVersion(IBPP::Version))
        {
            wxMessageBox(_("Wrong IBPP version."), _("Error."), wxOK | wxICON_ERROR);
            return false;
        }
    }
    catch (IBPP::Exception &e)
    {
        wxMessageBox(e.what(), _("Error initalizing IBPP library."), wxOK | wxICON_ERROR);
        return false;
    }

    wxImage::AddHandler(new wxPNGHandler);

    wxSystemOptions::SetOption("mac.listctrl.always_use_generic", true);

    MainFrame* main_frame = new MainFrame(0, -1, "");
    SetTopWindow(main_frame);
    main_frame->Show();

    openDatabasesFromParams(main_frame);
    return true;
}
Example #8
0
MAIN(appweb, int argc, char **argv, char **envp)
{
    Mpr     *mpr;
    cchar   *argp, *jail;
    char    *logSpec, *traceSpec;
    int     argind;

    jail = 0;
    logSpec = 0;
    traceSpec = 0;

    if ((mpr = mprCreate(argc, argv, MPR_USER_EVENTS_THREAD)) == NULL) {
        exit(1);
    }
    if ((app = mprAllocObj(AppwebApp, manageApp)) == NULL) {
        exit(2);
    }
    mprAddRoot(app);
    mprAddStandardSignals();
#if ME_ROM
    extern MprRomInode romFiles[];
    mprSetRomFileSystem(romFiles);
#endif

    if (httpCreate(HTTP_CLIENT_SIDE | HTTP_SERVER_SIDE) == 0) {
        exit(3);
    }
    app->mpr = mpr;
    app->workers = -1;
    app->home = sclone(ME_SERVER_ROOT);
    app->documents = app->home;
    argc = mpr->argc;
    argv = (char**) mpr->argv;

    for (argind = 1; argind < argc; argind++) {
        argp = argv[argind];
        if (*argp != '-') {
            break;
        }
        if (smatch(argp, "--config") || smatch(argp, "--conf")) {
            if (argind >= argc) {
                usageError();
            }
            app->configFile = sclone(argv[++argind]);

#if ME_UNIX_LIKE
        } else if (smatch(argp, "--chroot")) {
            if (argind >= argc) {
                usageError();
            }
            jail = mprGetAbsPath(argv[++argind]);
#endif

        } else if (smatch(argp, "--debugger") || smatch(argp, "-D")) {
            mprSetDebugMode(1);

        } else if (smatch(argp, "--exe")) {
            if (argind >= argc) {
                usageError();
            }
            mpr->argv[0] = mprGetAbsPath(argv[++argind]);
            mprSetAppPath(mpr->argv[0]);
            mprSetModuleSearchPath(NULL);

        } else if (smatch(argp, "--home")) {
            if (argind >= argc) {
                usageError();
            }
            app->home = sclone(argv[++argind]);
            if (chdir(app->home) < 0) {
                mprLog("error appweb", 0, "Cannot change directory to %s", app->home);
                exit(4);
            }

        } else if (smatch(argp, "--log") || smatch(argp, "-l")) {
            if (argind >= argc) {
                usageError();
            }
            logSpec = argv[++argind];

        } else if (smatch(argp, "--name") || smatch(argp, "-n")) {
            if (argind >= argc) {
                usageError();
            }
            mprSetAppName(argv[++argind], 0, 0);

        } else if (smatch(argp, "--threads")) {
            if (argind >= argc) {
                usageError();
            }
            app->workers = atoi(argv[++argind]);

        } else if (smatch(argp, "--show") || smatch(argp, "-s")) {
            app->show = 1;

        } else if (smatch(argp, "--trace") || smatch(argp, "-t")) {
            if (argind >= argc) {
                usageError();
            }
            traceSpec = argv[++argind];

        } else if (smatch(argp, "--verbose") || smatch(argp, "-v")) {
            if (!logSpec) {
                logSpec = sfmt("stderr:2");
            }
            if (!traceSpec) {
                traceSpec = sfmt("stderr:2");
            }

        } else if (smatch(argp, "--version") || smatch(argp, "-V")) {
            mprPrintf("%s\n", ME_VERSION);
            exit(0);

        } else if (*argp == '-' && isdigit((uchar) argp[1])) {
            if (!logSpec) {
                logSpec = sfmt("stderr:%d", (int) stoi(&argp[1]));
            }
            if (!traceSpec) {
                traceSpec = sfmt("stderr:%d", (int) stoi(&argp[1]));
            }

        } else if (smatch(argp, "-?") || scontains(argp, "-help")) {
            usageError();
            exit(5);

        } else if (*argp == '-') {
            mprLog("error appweb", 0, "Unknown switch \"%s\"", argp);
            usageError();
            exit(5);
        }
    }
    app->home = mprGetAbsPath(app->home);
    if (logSpec) {
        mprStartLogging(logSpec, MPR_LOG_DETAILED | MPR_LOG_CONFIG | MPR_LOG_CMDLINE);
    }
    if (traceSpec) {
        httpStartTracing(traceSpec);
    }
    if (mprStart() < 0) {
        mprLog("error appweb", 0, "Cannot start MPR");
        mprDestroy();
        return MPR_ERR_CANT_INITIALIZE;
    }
    if (checkEnvironment(argv[0]) < 0) {
        exit(6);
    }
    if (argc == argind && !app->configFile) {
        if (findAppwebConf() < 0) {
            exit(7);
        }
    }
    if (jail && changeRoot(jail) < 0) {
        exit(8);
    }
    if (createEndpoints(argc - argind, &argv[argind]) < 0) {
        return MPR_ERR_CANT_INITIALIZE;
    }
    if (maStartAppweb(app->appweb) < 0) {
        mprLog("error appweb", 0, "Cannot start HTTP service, exiting.");
        exit(9);
    }
    if (app->show) {
        httpLogRoutes(0, 0);
    }
    mprServiceEvents(-1, 0);

    mprLog("info appweb", 1, "Stopping Appweb ...");
    mprDestroy();
    return mprGetExitStatus();
}
Example #9
0
int main(int argc, char **argv)
{
	sbdclnt_t *sbdclnt;
	int port;
	int clicked;
	clock_t timeout;
	aeh_t aeh;
	int ninst;
	char comments[sendcrsh_COMMENT_MAXLEN];
	int len, lensent;
	char buf[sbd_MAXLEN];
	int pos;
	unsigned long crc;
	char signature[10];
	int i = 0;

	logprint_setFile("sendcrsh.log");

	if (!checkEnvironment()) {
		DPRINT(("anet2.dll did not set our environment!\n"));
		return 1;
	}
	if (!checkUnique()) {
		DPRINT(("Another instance of sendcrsh was running!\n"));
		return 1;
	}

	if (argc <= 3) { /* Usage: sendcrsh <host> <port> <hexdata> */
		DPRINT(("sendcrsh invoked with fewer than 3 arguments\n"));
		return 1;
	}
	DPRINT(("%s %s %s %s\n", argv[0], argv[1], argv[2], argv[3]));

	port = atoi(argv[2]);
	if ((port < 1024) || (port > 65536)) {
		DPRINT(("sendcrsh invoked with invalid port %d\n", port));
		return 1;
	}

	if (NULL == hex2buf(argv[3], buf, 2)) {
		DPRINT(("hex2buf(datalen) failed\n"));
		return 1;
	}
	len = dpMAKESHORT(buf[0], buf[1]);
	if (NULL == hex2buf(argv[3] + 4, buf, len)) {
		DPRINT(("hex2buf(data) failed\n"));
		return 1;
	}
	if (argv[3][4 + 2*len] != '\0') {
		DPRINT(("data does not end at datalen:%d\n", len));
		return 1;
	}
	if (len > sbd_MAXLEN) {
		DPRINT(("datalen:%d is greater than max:%d\n", len, sbd_MAXLEN));
		return 1;
	}
	pos = getLastRecord(buf, len, &aeh, &ninst);
	if (pos == -1) {
		DPRINT(("getLastRecord failed\n"));
		return 1;
	}
	if (aeh.nstk == 0) {
		DPRINT(("exception has 0 length stack trace\n"));
	}
	crc = aeh_getSignature(&aeh);
	if (crc == 0) {
		DPRINT(("aeh_getSignature returns 0 crc, error?\n"));
	}
	aeh_signature_toString(crc, signature);

	DPRINT(("%s to %s:%d len:%d data:%s\n", argv[0], argv[1], port, len,
		argv[3] + 4));
	sendbox_create(winCmdShow, signature, sendcrsh_COMMENT_MAXLEN, 120);
	while (1) {
		clock_t now = eclock();

		clicked = sendbox_poll(comments);
		if (clicked != sendbox_CLICKED_NONE) {
			DPRINT(("t:%d, clicked:%d, breaking\n", now, clicked));
			break;
		}
		Sleep(100);
		if (!((++i)%10)) {
			DPRINT(("%dth call to sendbox_poll at t:%d\n", i, now));
		}
	}
	sendbox_destroy();

	if (clicked != sendbox_CLICKED_OK) {
		DPRINT(("User cancelled send, clicked:%d\n", clicked));
		return 0;
	}

	timeout = eclock() + 30 * ECLOCKS_PER_SEC;
	/* add the comments to the buffer */
	if (comments[0]) {
		aeh_buf_t aehbuf;
		int commentlen = strlen(comments);
		int nwritten;

		if ((len + sizeof(unsigned int /* aeh_info_t.id */) + sizeof(commentlen) + commentlen) > sbd_MAXLEN) {
			DPRINT(("no room in buf for comment\n"));
			return 1;
		}
		/* stuff the comment into the info list */
		if (aeh_RES_OK != aeh_addComment(&aeh, comments)) {
			DPRINT(("aeh_addComment failed\n"));
			return 1;
		}
		/* convert it back to a buf */
		if (aeh_RES_OK != aeh_writeOutputStream(&aeh, &aehbuf)) {
			DPRINT(("can't convert aeh back to aehbuf\n"));
			return 1;
		}
		DPRINT(("writing new record at pos:%d buf:\n", pos));
		dumpbuf(aehbuf.buf, aehbuf.buflen);
		nwritten = aehlog_writetobuf(&aehbuf, ninst, buf+pos, sbd_MAXLEN-pos);
		if (-1 == nwritten) {
			DPRINT(("can't convert aehbuf back to buf\n"));
			return 1;
		}
		len = pos + nwritten;
	}
	aeh_Destroy(&aeh);

	/* send the buffer */
	sbdclnt = sbdclnt_create(buf, len, argv[1], (unsigned short)port);
	if (sbdclnt == NULL) {
		DPRINT(("sbdclnt_create failed\n"));
		return 1;
	}
	while ((long)(eclock() - timeout) < 0) {
		lensent = sbdclnt_poll(sbdclnt);
		if (lensent != 0)
			break;
		Sleep(100);
	}
	sbdclnt_destroy(sbdclnt);
	if (lensent != len) {
		DPRINT(("send only %d of %d bytes!\n", lensent, len));
		return 1;
	}
	DPRINT(("send completed successfully\n"));
	return 0;
}
Example #10
0
int Mhwd::launch(int argc, char *argv[])
{
    std::vector<std::string> missingDirs { checkEnvironment() };
    if (!missingDirs.empty())
    {
        consoleWriter_.printError("Following directories do not exist:");
        for (const auto& dir : missingDirs)
        {
            consoleWriter_.printStatus(dir);
        }
        return 1;
    }

    std::string operationType;
    bool autoConfigureNonFreeDriver = false;
    std::string autoConfigureClassID;

    try
    {
        tryToParseCmdLineOptions(argc, argv, autoConfigureNonFreeDriver, operationType,
                autoConfigureClassID);
    }
    catch(const std::runtime_error& e)
    {
        consoleWriter_.printError(e.what());
        consoleWriter_.printHelp();
        return 1;
    }

    if (!optionsDontInterfereWithEachOther())
    {
        return 1;
    }

    // Check for invalid configs
    for (auto&& invalidConfig : data_.invalidConfigs)
    {
        consoleWriter_.printWarning("config '" + invalidConfig->configPath_ + "' is invalid!");
    }

    // > Perform operations:

    // List all configs
    if (arguments_.LIST_ALL && arguments_.SHOW_PCI)
    {
        if (!data_.allPCIConfigs.empty())
        {
            consoleWriter_.listConfigs(data_.allPCIConfigs, "All PCI configs:");
        }
        else
        {
            consoleWriter_.printWarning("No PCI configs found!");
        }
    }
    if (arguments_.LIST_ALL && arguments_.SHOW_USB)
    {
        if (!data_.allUSBConfigs.empty())
        {
            consoleWriter_.listConfigs(data_.allUSBConfigs, "All USB configs:");
        }
        else
        {
            consoleWriter_.printWarning("No USB configs found!");
        }
    }

    // List installed configs
    if (arguments_.LIST_INSTALLED && arguments_.SHOW_PCI)
    {
        if (arguments_.DETAIL)
        {
            consoleWriter_.printInstalledConfigs("PCI", data_.installedPCIConfigs);
        }
        else
        {
            if (!data_.installedPCIConfigs.empty())
            {
                consoleWriter_.listConfigs(data_.installedPCIConfigs, "Installed PCI configs:");
            }
            else
            {
                consoleWriter_.printWarning("No installed PCI configs!");
            }
        }
    }
    if (arguments_.LIST_INSTALLED && arguments_.SHOW_USB)
    {
        if (arguments_.DETAIL)
        {
            consoleWriter_.printInstalledConfigs("USB", data_.installedUSBConfigs);
        }
        else
        {
            if (!data_.installedUSBConfigs.empty())
            {
                consoleWriter_.listConfigs(data_.installedUSBConfigs, "Installed USB configs:");
            }
            else
            {
                consoleWriter_.printWarning("No installed USB configs!");
            }
        }
    }

    // List available configs
    if (arguments_.LIST_AVAILABLE && arguments_.SHOW_PCI)
    {
        if (arguments_.DETAIL)
        {
            consoleWriter_.printAvailableConfigsInDetail("PCI", data_.PCIDevices);
        }
        else
        {
            for (auto&& PCIDevice : data_.PCIDevices)
            {
                if (!PCIDevice->availableConfigs_.empty())
                {
                    consoleWriter_.listConfigs(PCIDevice->availableConfigs_,
                            PCIDevice->sysfsBusID_ + " (" + PCIDevice->classID_ + ":"
                                    + PCIDevice->vendorID_ + ":" + PCIDevice->deviceID_ + ") "
                                    + PCIDevice->className_ + " " + PCIDevice->vendorName_ + ":");
                }
            }
        }
    }

    if (arguments_.LIST_AVAILABLE && arguments_.SHOW_USB)
    {
        if (arguments_.DETAIL)
        {
            consoleWriter_.printAvailableConfigsInDetail("USB", data_.USBDevices);
        }

        else
        {
            for (auto&& USBdevice : data_.USBDevices)
            {
                if (!USBdevice->availableConfigs_.empty())
                {
                    consoleWriter_.listConfigs(USBdevice->availableConfigs_,
                            USBdevice->sysfsBusID_ + " (" + USBdevice->classID_ + ":"
                            + USBdevice->vendorID_ + ":" + USBdevice->deviceID_ + ") "
                            + USBdevice->className_ + " " + USBdevice->vendorName_ + ":");
                }
            }
        }
    }

    // List hardware information
    if (arguments_.LIST_HARDWARE && arguments_.SHOW_PCI)
    {
        if (arguments_.DETAIL)
        {
            consoleWriter_.printDeviceDetails(hw_pci);
        }
        else
        {
            consoleWriter_.listDevices(data_.PCIDevices, "PCI");
        }
    }
    if (arguments_.LIST_HARDWARE && arguments_.SHOW_USB)
    {
        if (arguments_.DETAIL)
        {
            consoleWriter_.printDeviceDetails(hw_usb);
        }
        else
        {
            consoleWriter_.listDevices(data_.USBDevices, "USB");
        }
    }

    // Auto configuration
    if (arguments_.AUTOCONFIGURE)
    {
        std::vector<std::shared_ptr<Device>> *devices;
        std::vector<std::shared_ptr<Config>> *installedConfigs;

        if ("USB" == operationType)
        {
            devices = &data_.USBDevices;
            installedConfigs = &data_.installedUSBConfigs;
        }
        else
        {
            devices = &data_.PCIDevices;
            installedConfigs = &data_.installedPCIConfigs;
        }
        bool foundDevice = false;
        for (auto&& device : *devices)
        {
            if (device->classID_ != autoConfigureClassID)
            {
                continue;
            }
            else
            {
                foundDevice = true;
                std::shared_ptr<Config> config;

                for (auto&& availableConfig : device->availableConfigs_)
                {
                    if (autoConfigureNonFreeDriver || availableConfig->freedriver_)
                    {
                        config = availableConfig;
                        break;
                    }
                }

                if (nullptr == config)
                {
                    consoleWriter_.printWarning(
                            "No config found for device: " + device->sysfsBusID_ + " ("
                                    + device->classID_ + ":" + device->vendorID_ + ":"
                                    + device->deviceID_ + ") " + device->className_ + " "
                                    + device->vendorName_ + " " + device->deviceName_);
                    continue;
                }
                else
                {
                    // If force is not set then skip found config
                    bool skip = false;
                    if (!arguments_.FORCE)
                    {
                        skip = std::find_if(installedConfigs->begin(), installedConfigs->end(),
                                [&config](const std::shared_ptr<Config>& conf) -> bool {
                                    return conf->name_ == config->name_;
                                }) != installedConfigs->end();
                    }
                    // Print found config
                    if (skip)
                    {
                        consoleWriter_.printStatus(
                                "Skipping already installed config '" + config->name_ +
                                "' for device: " + device->sysfsBusID_ + " (" +
                                device->classID_ + ":" + device->vendorID_ + ":" +
                                device->deviceID_ + ") " + device->className_ + " " +
                                device->vendorName_ + " " + device->deviceName_);
                    }
                    else
                    {
                        consoleWriter_.printStatus(
                                "Using config '" + config->name_ + "' for device: " +
                                device->sysfsBusID_ + " (" + device->classID_ + ":" +
                                device->vendorID_ + ":" + device->deviceID_ + ") " +
                                device->className_ + " " + device->vendorName_ + " " +
                                device->deviceName_);
                    }

                    bool alreadyInList = std::find(configs_.begin(), configs_.end(), config->name_) != configs_.end();
                    if (!alreadyInList && !skip)
                    {
                        configs_.push_back(config->name_);
                    }
                }
            }
        }

        if (!foundDevice)
        {
            consoleWriter_.printWarning("No device of class " + autoConfigureClassID + " found!");
        }
        else if (!configs_.empty())
        {
            arguments_.INSTALL = true;
        }
    }

    // Transaction
    if (arguments_.INSTALL || arguments_.REMOVE)
    {
        if (!isUserRoot())
        {
            consoleWriter_.printError("You cannot perform this operation unless you are root!");
        }
        else
        {
            for (auto&& configName = configs_.begin();
                    configName != configs_.end(); configName++)
            {
                if (arguments_.CUSTOM_INSTALL)
                {
                    // Custom install -> get configs
                    struct stat filestatus;
                    std::string filepath = (*configName) + "/MHWDCONFIG";

                    if (0 != stat(filepath.c_str(), &filestatus))
                    {
                        consoleWriter_.printError("custom config '" + filepath + "' does not exist!");
                        return 1;
                    }
                    else if (!S_ISREG(filestatus.st_mode))
                    {
                        consoleWriter_.printError("custom config '" + filepath + "' is invalid!");
                        return 1;
                    }
                    else
                    {
                        config_.reset(new Config(filepath, operationType));
                        if (!config_->readConfigFile(filepath))
                        {
                            consoleWriter_.printError("failed to read custom config '" + filepath + "'!");
                            return 1;
                        }

                        else if (!performTransaction(config_, MHWD::TRANSACTIONTYPE::INSTALL))
                        {
                            return 1;
                        }
                    }
                }
                else if (arguments_.INSTALL)
                {
                    config_ = getAvailableConfig((*configName), operationType);
                    if (config_ == nullptr)
                    {
                        config_ = getDatabaseConfig((*configName), operationType);
                        if (config_ == nullptr)
                        {
                            consoleWriter_.printError("config '" + (*configName) + "' does not exist!");
                            return 1;
                        }
                        else
                        {
                            consoleWriter_.printWarning(
                                    "no matching device for config '" + (*configName) + "' found!");
                        }
                    }

                    if (!performTransaction(config_, MHWD::TRANSACTIONTYPE::INSTALL))
                    {
                        return 1;
                    }
                }
                else if (arguments_.REMOVE)
                {
                    config_ = getInstalledConfig((*configName), operationType);

                    if (nullptr == config_)
                    {
                        consoleWriter_.printError("config '" + (*configName) + "' is not installed!");
                        return 1;
                    }

                    else if (!performTransaction(config_, MHWD::TRANSACTIONTYPE::REMOVE))
                    {
                        return 1;
                    }
                }
            }
        }
    }
    return 0;
}
Example #11
0
MAIN(appweb, int argc, char **argv)
{
    Mpr         *mpr;
    MaHttp      *http;
    cchar       *ipAddrPort, *documentRoot, *argp, *logSpec;
    char        *configFile, *ipAddr, *homeDir, *timeText, *ejsPrefix, *ejsPath, *changeRoot;
    int         workers, outputVersion, argind, port;
    
    documentRoot = 0;
    changeRoot = ejsPrefix = ejsPath = 0;
    ipAddrPort = 0;
    ipAddr = 0;
    port = -1;
    logSpec = 0;
    server = 0;
    outputVersion = 0;
    workers = -1;

    configFile = BLD_FEATURE_CONFIG_FILE;
    homeDir = BLD_FEATURE_SERVER_ROOT;

    mpr = mprCreate(argc, argv, memoryFailure);
    argc = mpr->argc;
    argv = mpr->argv;

#if BLD_FEATURE_ROMFS
    extern MprRomInode romFiles[];
    mprSetRomFileSystem(mpr, romFiles);
#endif

    if (osInit(mpr) < 0) {
        exit(2);
    }
    if (mprStart(mpr, 0) < 0) {
        mprUserError(mpr, "Can't start MPR for %s", mprGetAppName(mpr));
        mprFree(mpr);
        return MPR_ERR_CANT_INITIALIZE;
    }

    for (argind = 1; argind < argc; argind++) {
        argp = argv[argind];
        if (*argp != '-') {
            break;
        }
        if (strcmp(argp, "--config") == 0) {
            if (argind >= argc) {
                return printUsage(mpr);
            }
            configFile = argv[++argind];

#if BLD_UNIX_LIKE
        } else if (strcmp(argp, "--chroot") == 0) {
            if (argind >= argc) {
                return printUsage(mpr);
            }
            changeRoot = mprGetAbsPath(mpr, argv[++argind]);
#endif

        } else if (strcmp(argp, "--debug") == 0 || strcmp(argp, "-D") == 0 || 
                strcmp(argp, "-d") == 0 || strcmp(argp, "--debugger") == 0) {
            mprSetDebugMode(mpr, 1);

        } else if (strcmp(argp, "--ejs") == 0) {
            if (argind >= argc) {
                return printUsage(mpr);
            }
            ejsPrefix = mprStrdup(mpr, argv[++argind]);
            if ((ejsPath = strchr(ejsPrefix, ':')) != 0) {
                *ejsPath++ = '\0';
            }
            ejsPath = mprGetAbsPath(mpr, ejsPath);

        } else if (strcmp(argp, "--home") == 0) {
            if (argind >= argc) {
                return printUsage(mpr);
            }
            homeDir = mprGetAbsPath(mpr, argv[++argind]);
            if (chdir((char*) homeDir) < 0) {
                mprPrintfError(mpr, "%s: Can't change directory to %s\n", mprGetAppName(mpr), homeDir);
                exit(2);
            }

        } else if (strcmp(argp, "--log") == 0 || strcmp(argp, "-l") == 0) {
            if (argind >= argc) {
                return printUsage(mpr);
            }
            logSpec = argv[++argind];
            maStartLogging(mpr, logSpec);

        } else if (strcmp(argp, "--name") == 0 || strcmp(argp, "-n") == 0) {
            if (argind >= argc) {
                return printUsage(mpr);
            }
            mprSetAppName(mpr, argv[++argind], 0, 0);

        } else if (strcmp(argp, "--threads") == 0) {
            if (argind >= argc) {
                return printUsage(mpr);
            }
            workers = atoi(argv[++argind]);

        } else if (strcmp(argp, "--verbose") == 0 || strcmp(argp, "-v") == 0) {
            maStartLogging(mpr, "stdout:2");

        } else if (strcmp(argp, "--version") == 0 || strcmp(argp, "-V") == 0) {
            outputVersion++;

        } else {
            mprPrintfError(mpr, "Unknown switch \"%s\"\n", argp);
            printUsage(mpr);
            exit(2);
        }
    }

    if (argc > argind) {
        if (argc > (argind + 2)) {
            return printUsage(mpr);
        }
        ipAddrPort = argv[argind++];
        if (argc > argind) {
            documentRoot = argv[argind++];
        } else {
            documentRoot = ".";
        }
    }

    if (outputVersion) {
        mprPrintf(mpr, "%s %s-%s\n", mprGetAppTitle(mpr), BLD_VERSION, BLD_NUMBER);
        exit(0);
    }

    if (ipAddrPort) {
        mprParseIp(mpr, ipAddrPort, &ipAddr, &port, MA_SERVER_DEFAULT_PORT_NUM);
    } else {
#if BLD_FEATURE_CONFIG_PARSE
        if (configFile == 0) {
            configFile = mprStrcat(mpr, -1, mprGetAppName(mpr), ".conf", NULL);
        }
        if (!mprPathExists(mpr, configFile, R_OK)) {
            mprPrintfError(mpr, "Can't open config file %s\n", configFile);
            exit(2);
        }
#else
        return printUsage(mpr);
#endif
#if !BLD_FEATURE_ROMFS
        if (homeDir == 0) {
            homeDir = mprGetPathParent(mpr, configFile);
            if (chdir((char*) homeDir) < 0) {
                mprPrintfError(mpr, "%s: Can't change directory to %s\n", mprGetAppName(mpr), homeDir);
                exit(2);
            }
        }
#endif
    }
    homeDir = mprGetCurrentPath(mpr);
    if (checkEnvironment(mpr, argv[0], homeDir) < 0) {
        exit(3);
    }

#if BLD_UNIX_LIKE
    if (changeRoot) {
        homeDir = mprGetAbsPath(mpr, changeRoot);
        if (chdir(homeDir) < 0) {
            mprError(mpr, "%s: Can't change directory to %s", homeDir);
            exit(4);
        }
        if (chroot(homeDir) < 0) {
            if (errno == EPERM) {
                mprError(mpr, "%s: Must be super user to use the --chroot option", mprGetAppName(mpr));
            } else {
                mprError(mpr, "%s: Can't change change root directory to %s, errno %d",
                    mprGetAppName(mpr), homeDir, errno);
            }
            exit(5);
        }
    }
#endif

    /*
     *  Create the top level HTTP service and default HTTP server. Set the initial server root to "."
     */
    http = maCreateHttp(mpr);
    if (http == 0) {
        mprUserError(mpr, "Can't create HTTP service for %s", mprGetAppName(mpr));
        return MPR_ERR_CANT_INITIALIZE;
    }
    server = maCreateServer(http, "default", ".", 0, -1);
    if (server == 0) {
        mprUserError(mpr, "Can't create HTTP server for %s", mprGetAppName(mpr));
        return MPR_ERR_CANT_INITIALIZE;
    }
    if (maConfigureServer(mpr, http, server, configFile, ipAddr, port, documentRoot) < 0) {
        /* mprUserError(mpr, "Can't configure the server, exiting."); */
        exit(6);
    }
    if (mpr->ipAddr) {
        mprLog(mpr, 2, "Server IP address %s", mpr->ipAddr);
    }
    timeText = mprFormatLocalTime(mpr, mprGetTime(mpr));
    mprLog(mpr, 1, "Started at %s", timeText);
    mprFree(timeText);

#if BLD_FEATURE_EJS
    if (ejsPrefix) {
        createEjsAlias(mpr, http, server, ejsPrefix, ejsPath);
    }
#endif

#if BLD_FEATURE_MULTITHREAD
    if (workers >= 0) {
        mprSetMaxWorkers(http, workers);
    }
#endif
#if BLD_WIN_LIKE
    if (!ejsPrefix) {
        writePort(server->defaultHost);
    }
#endif

    if (maStartHttp(http) < 0) {
        mprUserError(mpr, "Can't start HTTP service, exiting.");
        exit(7);
    }

#if BLD_FEATURE_MULTITHREAD
    mprLog(mpr, 1, "HTTP services are ready with max %d worker threads", mprGetMaxWorkers(mpr));
#else
    mprLog(mpr, 1, "HTTP services are ready (single-threaded)");
#endif

    /*
     *  Service I/O events until instructed to exit
     */
    while (!mprIsExiting(mpr)) {
        mprServiceEvents(mpr->dispatcher, -1, MPR_SERVICE_EVENTS | MPR_SERVICE_IO);
    }

    /*
     *  Signal a graceful shutdown
     */
    mprLog(http, 1, "Exiting ...");
    maStopHttp(http);
    mprLog(http, 1, "Exit complete");

#if VXWORKS
    if (mprStop(mpr)) {
        mprFree(mpr);
    }
#endif
    return 0;
}
Example #12
0
#ifdef JRI_DEBUG
	printf("jriWriteconsole mid=%x\n", mid);
#endif
	if (!mid) return;
	(*lenv)->CallVoidMethod(lenv, engineObj, mid);
    jri_checkExceptions(lenv, 1);
}

/* Reset stdin if the user types EOF on the console. */
void Re_ClearerrConsole()
{
}

int Re_ChooseFile(int new, char *buf, int len)
{
    JNIEnv *lenv=checkEnvironment();
	
    if (lenv && engineObj) {
		jmethodID mid;
		jri_checkExceptions(lenv, 1);
		mid=(*lenv)->GetMethodID(eenv, engineClass, "jriChooseFile", "(I)Ljava/lang/String;");
#ifdef JRI_DEBUG
		printf("jriChooseFile mid=%x\n", mid);
#endif
		jri_checkExceptions(lenv, 0);
		if (mid) {
			jstring r=(jstring) (*lenv)->CallObjectMethod(lenv, engineObj, mid, new);
			jri_checkExceptions(lenv, 1);
			if (r) {
				int slen=0;
				const char *c=(*lenv)->GetStringUTFChars(lenv, r, 0);
Example #13
0
MAIN(appweb, int argc, char **argv, char **envp)
{
    Mpr     *mpr;
    cchar   *ipAddrPort, *argp, *jail;
    char    *ip, *logSpec;
    int     argind, port, status, verbose;

    ipAddrPort = 0;
    ip = 0;
    jail = 0;
    port = -1;
    verbose = 0;
    logSpec = 0;
    argv[0] = BLD_APPWEB_PATH;

    if ((mpr = mprCreate(argc, argv, MPR_USER_EVENTS_THREAD)) == NULL) {
        exit(1);
    }
    mprSetAppName(BLD_PRODUCT, BLD_NAME, BLD_VERSION);

    if ((app = mprAllocObj(App, manageApp)) == NULL) {
        exit(2);
    }
    mprAddRoot(app);
    mprAddStandardSignals();

#if BLD_FEATURE_ROMFS
    extern MprRomInode romFiles[];
    mprSetRomFileSystem(romFiles);
#endif

    app->mpr = mpr;
    app->workers = -1;
    app->configFile = BLD_CONFIG_FILE;
    app->home = BLD_SERVER_ROOT;
    app->documents = app->home;
    argc = mpr->argc;
    argv = mpr->argv;

    for (argind = 1; argind < argc; argind++) {
        argp = argv[argind];
        if (*argp != '-') {
            break;
        }
        if (smatch(argp, "--config") || smatch(argp, "--conf")) {
            if (argind >= argc) {
                usageError();
            }
            app->configFile = sclone(argv[++argind]);

#if BLD_UNIX_LIKE
        } else if (smatch(argp, "--chroot")) {
            if (argind >= argc) {
                usageError();
            }
            jail = mprGetAbsPath(argv[++argind]);
#endif

        } else if (smatch(argp, "--debugger") || smatch(argp, "-D")) {
            mprSetDebugMode(1);

        } else if (smatch(argp, "--exe")) {
            if (argind >= argc) {
                usageError();
            }
            mpr->argv[0] = mprGetAbsPath(argv[++argind]);
            mprSetAppPath(mpr->argv[0]);
            mprSetModuleSearchPath(NULL);

        } else if (smatch(argp, "--home")) {
            if (argind >= argc) {
                usageError();
            }
            app->home = mprGetAbsPath(argv[++argind]);
#if UNUSED && KEEP
            if (chdir(app->home) < 0) {
                mprError("%s: Can't change directory to %s", mprGetAppName(), app->home);
                exit(4);
            }
#endif

        } else if (smatch(argp, "--log") || smatch(argp, "-l")) {
            if (argind >= argc) {
                usageError();
            }
            logSpec = argv[++argind];

        } else if (smatch(argp, "--name") || smatch(argp, "-n")) {
            if (argind >= argc) {
                usageError();
            }
            mprSetAppName(argv[++argind], 0, 0);

        } else if (smatch(argp, "--threads")) {
            if (argind >= argc) {
                usageError();
            }
            app->workers = atoi(argv[++argind]);

        } else if (smatch(argp, "--verbose") || smatch(argp, "-v")) {
            verbose++;

        } else if (smatch(argp, "--version") || smatch(argp, "-V")) {
            mprPrintf("%s %s-%s\n", mprGetAppTitle(), BLD_VERSION, BLD_NUMBER);
            exit(0);

        } else {
            mprError("Unknown switch \"%s\"", argp);
            usageError();
            exit(5);
        }
    }
    if (logSpec) {
        mprStartLogging(logSpec, 1);
        mprSetCmdlineLogging(1);
    } else if (verbose) {
        mprStartLogging(sfmt("stderr:%d", verbose + 1), 1);
        mprSetCmdlineLogging(1);
    }
    if (mprStart() < 0) {
        mprUserError("Can't start MPR for %s", mprGetAppName());
        mprDestroy(MPR_EXIT_DEFAULT);
        return MPR_ERR_CANT_INITIALIZE;
    }
    if (checkEnvironment(argv[0]) < 0) {
        exit(6);
    }
    if (argc > argind) {
        if (argc > (argind + 2)) {
            usageError();
        }
        ipAddrPort = argv[argind++];
        if (argc > argind) {
            app->documents = sclone(argv[argind++]);
        }
        mprParseSocketAddress(ipAddrPort, &ip, &port, HTTP_DEFAULT_PORT);
        
    } else if (findConfigFile() < 0) {
        exit(7);
    }
    if (jail && changeRoot(jail) < 0) {
        exit(8);
    }
    if (initialize(ip, port) < 0) {
        return MPR_ERR_CANT_INITIALIZE;
    }
    if (maStartAppweb(app->appweb) < 0) {
        mprUserError("Can't start HTTP service, exiting.");
        exit(9);
    }
    /*
        Service I/O events until instructed to exit
     */
    while (!mprIsStopping()) {
        mprServiceEvents(-1, 0);
    }
    status = mprGetExitStatus();
    mprLog(1, "Stopping Appweb ...");
    maStopAppweb(app->appweb);
    mprDestroy(MPR_EXIT_DEFAULT);
    return status;
}
Example #14
0
MAIN(appweb, int argc, char **argv, char **envp)
{
    Mpr     *mpr;
    cchar   *argp, *jail;
    char    *logSpec;
    int     argind, status, verbose;

    jail = 0;
    verbose = 0;
    logSpec = 0;

    if ((mpr = mprCreate(argc, argv, MPR_USER_EVENTS_THREAD)) == NULL) {
        exit(1);
    }
    mprSetAppName(BIT_PRODUCT, BIT_TITLE, BIT_VERSION);

    /*
        Allocate the top level application object. ManageApp is the GC manager function and is called
        by the GC to mark references in the app object.
     */
    if ((app = mprAllocObj(AppwebApp, manageApp)) == NULL) {
        exit(2);
    }
    mprAddRoot(app);
    mprAddStandardSignals();

    app->mpr = mpr;
    app->configFile = sclone("appweb.conf");
    app->home = mprGetCurrentPath();
    app->documents = app->home;
    argc = mpr->argc;
    argv = (char**) mpr->argv;

    for (argind = 1; argind < argc; argind++) {
        argp = argv[argind];
        if (*argp != '-') {
            break;
        }
        if (smatch(argp, "--config") || smatch(argp, "--conf")) {
            if (argind >= argc) {
                usageError();
            }
            app->configFile = sclone(argv[++argind]);

#if BIT_UNIX_LIKE
        } else if (smatch(argp, "--chroot")) {
            if (argind >= argc) {
                usageError();
            }
            jail = mprGetAbsPath(argv[++argind]);
#endif

        } else if (smatch(argp, "--debugger") || smatch(argp, "-D")) {
            mprSetDebugMode(1);

        } else if (smatch(argp, "--exe")) {
            if (argind >= argc) {
                usageError();
            }
            mpr->argv[0] = mprGetAbsPath(argv[++argind]);
            mprSetAppPath(mpr->argv[0]);
            mprSetModuleSearchPath(NULL);

        } else if (smatch(argp, "--home")) {
            if (argind >= argc) {
                usageError();
            }
            app->home = mprGetAbsPath(argv[++argind]);
            if (chdir(app->home) < 0) {
                mprError("%s: Cannot change directory to %s", mprGetAppName(), app->home);
                exit(4);
            }

        } else if (smatch(argp, "--log") || smatch(argp, "-l")) {
            if (argind >= argc) {
                usageError();
            }
            logSpec = argv[++argind];

        } else if (smatch(argp, "--name") || smatch(argp, "-n")) {
            if (argind >= argc) {
                usageError();
            }
            mprSetAppName(argv[++argind], 0, 0);

        } else if (smatch(argp, "--verbose") || smatch(argp, "-v")) {
            verbose++;

        } else if (smatch(argp, "--version") || smatch(argp, "-V")) {
            mprPrintf("%s-%s\n", BIT_VERSION, BIT_BUILD_NUMBER);
            exit(0);

        } else {
            if (!smatch(argp, "?")) {
                mprError("Unknown switch \"%s\"", argp);
            }
            usageError();
            exit(5);
        }
    }
    if (logSpec) {
        mprStartLogging(logSpec, 1);
        mprSetCmdlineLogging(1);

    } else if (verbose) {
        mprStartLogging(sfmt("stderr:%d", verbose + 1), 1);
        mprSetCmdlineLogging(1);
    }
    /*
        Start the multithreaded portable runtime (MPR)
     */
    if (mprStart() < 0) {
        mprError("Cannot start MPR for %s", mprGetAppName());
        mprDestroy(MPR_EXIT_DEFAULT);
        return MPR_ERR_CANT_INITIALIZE;
    }
    if (checkEnvironment(argv[0]) < 0) {
        exit(6);
    }
    if (findAppwebConf() < 0) {
        exit(7);
    }
    if (jail && changeRoot(jail) < 0) {
        exit(8);
    }
    /*
        Open the sockets to listen on
     */
    if (createEndpoints(argc - argind, &argv[argind]) < 0) {
        return MPR_ERR_CANT_INITIALIZE;
    }
    /*
        Start HTTP services
     */
    if (maStartAppweb(app->appweb) < 0) {
        mprError("Cannot start HTTP service, exiting.");
        exit(9);
    }
    /*
        Service I/O events until instructed to exit
     */
    while (!mprIsStopping()) {
        mprServiceEvents(-1, 0);
    }
    status = mprGetExitStatus();
    mprLog(1, "Stopping Appweb ...");
    maStopAppweb(app->appweb);
    mprDestroy(MPR_EXIT_DEFAULT);
    return status;
}
Example #15
0
int main(int argc, char **argv)
{
    // Setup Signal Handler, to exit gracefully on an INT signal
    signal(SIGINT, *sighandler);

    CONDITION
	cond;
    DUL_NETWORKKEY
	* network = NULL;
    DUL_ASSOCIATIONKEY
	* association = NULL;
    DUL_ASSOCIATESERVICEPARAMETERS *service;
    DUL_PRESENTATIONCONTEXT
	* requestedCtx;
    DUL_ABORTITEMS
	abortItems;

    MFileOperations f;
    char path[256];
    f.expandPath(path, "MESA_TARGET", "logs");
    MString logDir(path);            // Default is Storage Area
    f.expandPath(path, "MESA_STORAGE", "postproc");
    MString storageDir(path);            // Default is Storage Area
    char *dbName = "ppwf";            // Default database nameea

    int
        port,
        trips = 2048,		/* Trips through the main loop */
        classCount = 0,
        releaseDelay = 0,
        numBase = 100;		// msg number base for logging
    unsigned long
        maxPDU = 16384;
    CTNBOOLEAN
	verboseDUL = FALSE,
	verboseSRV = FALSE,
	verboseDCM = FALSE,
	abortFlag = FALSE,
	forgiveFlag = FALSE,
	forkFlag = FALSE,
	threadFlag = FALSE,
	paramsFlag = FALSE,
	acceptFlag,
	drop,
	done = FALSE,
	printConnectionStatistics = FALSE;
    DUL_SC_ROLE
	scRole;
    int associationRequests = 0;

    char *classArray[] = {
	DICOM_SOPCLASSVERIFICATION,
	DICOM_SOPGPWORKLIST_FIND,
	DICOM_SOPGPSPS,
	DICOM_SOPGPPPS,
    ""};

    char *serverTitle = POST_PROC_AE_TITLE;
    MLogClient::LOGLEVEL logLevel = MLogClient::MLOG_NONE;
    int fileMode = 0;
   
    while (--argc > 0 && (*++argv)[0] == '-') {
      int l1 = 0;
	switch (*(argv[0] + 1)) {
	case 'a':
	   argc--; argv++;
	   if (argc < 1)
	     usageerror();
	   logDir = MString(*argv);
	   break;
	case 'b':
	   argc--; argv++;
	   if (argc < 1)
	     usageerror();
	   if (sscanf(*argv, "%d", &numBase) != 1)
	     usageerror();
	   break;
	case 'c':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    serverTitle = *argv;
	    break;
	case 'd':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    if (strcmp(*argv, "DCM") == 0)
		verboseDCM = TRUE;
	    else if (strcmp(*argv, "DUL") == 0)
		verboseDUL = TRUE;
	    else if (strcmp(*argv, "SRV") == 0)
		verboseSRV = TRUE;
	    else
		usageerror();
	    break;
	case 'f':
	    forkFlag = TRUE;
	    break;
	case 'i':
	    forgiveFlag = TRUE;
	    break;
	case 'j':
#ifndef CTN_USE_THREADS
	    fprintf(stderr, "pp_dcmps was not compiled with threads\n");
	    return 1;
#else
	    //threadFlag = TRUE;
	    break;
#endif
	case 'l':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    if (sscanf(*argv, "%d", &l1) != 1)
		usageerror();
	    logLevel = (MLogClient::LOGLEVEL)l1;
	    break;
	case 'm':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    if (sscanf(*argv, "%lu", &maxPDU) != 1)
		usageerror();
	    break;
	case 'n':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    dbName = *argv;
	    break;
	case 'p':
	    paramsFlag = TRUE;
	    break;
	case 't':
	    argc--;
	    argv++;
	    if (argc < 1)
		usageerror();
	    if (sscanf(*argv, "%d", &trips) != 1)
		usageerror();
	    break;
	case 'v':
	    verboseDUL = TRUE;
	    verboseSRV = TRUE;
	    break;
	case 'y':
	    printConnectionStatistics = TRUE;
	    break;
	case 'z':
	    fileMode++;
	    break;
	default:
	    (void) fprintf(stderr, "Unrecognized option: %c\n", *(argv[0] + 1));
	    break;
	}
    }

    if (argc < 1)
	usageerror();

    // If in filemode, perform the query and exit
    if (fileMode) {
      ppwlQuery (*argv, logDir, numBase, dbName);
      return 0;
    }
    
    // Write PID file
    MServerAgent a("pp_dcmps");
    a.registerServerPID();

    if (sscanf(*argv, "%d", &port) != 1)
      usageerror();

    checkEnvironment();

    ::THR_Init();

    ::DCM_Debug(verboseDCM);
    ::DUL_Debug(verboseDUL);
    ::SRV_Debug(verboseSRV);

#ifndef _MSC_VER
    if (port < 1024) {
	if (geteuid() != 0) {
	    char errmsg[] =
	    "To use this port (%d), you must run as root or the application must be\n\
setuid root (see chmod)\n";

	    fprintf(stderr, errmsg, port);
	    perror("");
	    exit(1);
	}
    }
#endif

    if (logLevel != MLogClient::MLOG_NONE) {
      MLogClient logClient;
      logClient.initialize(logLevel, logDir + "/pp_dcmps.log");

      logClient.log(MLogClient::MLOG_ERROR,
		    "<no peer>", "pp_dcmps<main>", __LINE__,
		    "Begin server process");
      cout << "pp_dcmps logging messages at level "
	   << logLevel
	   << " to "
	   << logDir + "/pp_dcmps.log"
	   << endl;
    }

    cond = ::DUL_InitializeNetwork(DUL_NETWORK_TCP, DUL_AEBOTH,

		 (void *) &port, DUL_TIMEOUT, DUL_ORDERBIGENDIAN, &network);
    if (cond != DUL_NORMAL) {
	::COND_DumpConditions();
	::exit(1);
    }
/*  Go back to the proper uid so we don't mess with things we don't own.
*/

#ifndef _MSC_VER
    (void) setuid(getuid());
#endif

    done = FALSE;
    while (!done) {
	drop = FALSE;
	service = (DUL_ASSOCIATESERVICEPARAMETERS*)malloc(sizeof(*service));
	if (service == NULL) {
	    ::fprintf(stderr, "Could not allocate memory for association parameters\n");
	    ::exit(1);
	}
	(void) ::memset(service, 0, sizeof(*service));
	service->maxPDU = maxPDU;
	strcpy(service->calledImplementationClassUID,
	       MIR_IMPLEMENTATIONCLASSUID);
	strcpy(service->calledImplementationVersionName,
	       MIR_IMPLEMENTATIONVERSIONNAME);
	cond = ::DUL_ReceiveAssociationRQ(&network, DUL_BLOCK,
					service, &association);
	{
	  MLogClient logClient;
	  logClient.log(MLogClient::MLOG_CONVERSATION,
		    service->callingAPTitle,
			"pp_dcmps<main>", __LINE__,
			"Association Request");
	}

	acceptFlag = TRUE;
	if (cond != DUL_NORMAL) {
	    ::COND_DumpConditions();
	    if (cond == DUL_UNSUPPORTEDPEERPROTOCOL) {
		acceptFlag = FALSE;
		cond = APP_NORMAL;	/* Yes, this is normal */
	    } else
		::exit(0);
	}
	if (acceptFlag) {
	    cond = associationCheck(service, serverTitle,
				    forgiveFlag, &abortItems);
	    if (CTN_ERROR(cond)) {
		acceptFlag = FALSE;
		::fprintf(stderr, "Incorrect Association Request\n");
		::COND_DumpConditions();
		cond = ::DUL_RejectAssociationRQ(&association, &abortItems);
		if (cond != DUL_NORMAL) {
		    ::fprintf(stderr, "Unable to cleanly reject Association\n");
		    ::COND_DumpConditions();
		}
	    } else if (!CTN_SUCCESS(cond)) {
		::COND_DumpConditions();
	    }
	}
	if (acceptFlag) {
	    if (verboseDUL || paramsFlag) {
		fprintf(stdout,
			"Application is about to accept association.  The association parameters\n\
before the app has decided which presentation contexts to accept follow.\n");
		::DUL_DumpParams(service);
	    }
	    requestedCtx = (DUL_PRESENTATIONCONTEXT*)::LST_Head(&service->requestedPresentationContext);
	    if (requestedCtx != NULL)
		(void) ::LST_Position(&service->requestedPresentationContext,
				    requestedCtx);
	    classCount = 0;
	    while (requestedCtx != NULL) {
		if (strcmp(requestedCtx->abstractSyntax, MIR_SOPCLASSKILLSERVER) == 0)
		    done = TRUE;

		if (supportedClass(requestedCtx->abstractSyntax, classArray)) {
		    switch (requestedCtx->proposedSCRole) {
		    case DUL_SC_ROLE_DEFAULT:
			scRole = DUL_SC_ROLE_DEFAULT;
			break;
		    case DUL_SC_ROLE_SCU:
			scRole = DUL_SC_ROLE_SCU;
			break;
		    case DUL_SC_ROLE_SCP:
			scRole = DUL_SC_ROLE_DEFAULT;
			break;
		    case DUL_SC_ROLE_SCUSCP:
			scRole = DUL_SC_ROLE_SCU;
			break;
		    default:
			scRole = DUL_SC_ROLE_DEFAULT;
			break;
		    }
		    cond = ::SRV_AcceptServiceClass(requestedCtx, scRole,
						  service);
		    if (cond == SRV_NORMAL) {
			classCount++;
		    } else {
			::printf("SRV Facility rejected SOP Class: %s\n",
			       requestedCtx->abstractSyntax);
			::COND_DumpConditions();
		    }
		} else {
		    ::printf("Simple server rejects SOP Class with UID: %s\n",
			   requestedCtx->abstractSyntax);
		    dumpUIDDescription(requestedCtx->abstractSyntax);
		    cond = ::SRV_RejectServiceClass(requestedCtx,
				     DUL_PRESENTATION_REJECT_USER, service);
		    if (cond != SRV_NORMAL) {
			drop = TRUE;
		    }
		}
		requestedCtx = (DUL_PRESENTATIONCONTEXT*)::LST_Next(&service->requestedPresentationContext);
	    }
#if 0
	    ::printf("Supported classes: %d\n", classCount);
#endif
	    if (paramsFlag) {
		::fprintf(stdout,
			"Application has now decided which presentation contexts to accept.\n\
Association parameters now look like this.\n");
		::DUL_DumpParams(service);
	    }
	    if (drop) {
		(void) ::DUL_DropAssociation(&association);
		::COND_DumpConditions();
	    } else {
		if (printConnectionStatistics) {
		    printf("%6d: %16s %16s %s\n",
			   ++associationRequests,
			   service->calledAPTitle,
			   service->callingAPTitle,
			   service->callingPresentationAddress);
		}
		acceptManageAssociation(&network, association, service,
					forkFlag, threadFlag, abortFlag,
				verboseDUL, releaseDelay,
					logDir.strData(),
					storageDir.strData(),
                                        dbName );

	    }
	}
#if 0
	(void) ::DUL_ClearServiceParameters(service);
#endif
	if (CTN_ERROR(cond))
	    done = TRUE;
	if (trips >= 0) {
	    if (trips-- <= 0)
		done = TRUE;
	}
    }
Example #16
0
	void Device::selectDone(Environment*) {
		m_waitForEnvSelects--;
		checkEnvironment();
	}