bool ViewHelper::doit(FILE * fp)
{
    if (globals->hasProp("WUID"))
    {
        const char* wuid = globals->queryProp("WUID");

        Owned<IClientWUInfoRequest> req = wuclient->createWUInfoRequest();
        req->setWuid(wuid);
        Owned<IClientWUInfoResponse> resp = wuclient->WUInfo(req);
        if(!resp)
            return false;

        const IMultiException* excep = &resp->getExceptions();
        if(excep != NULL && excep->ordinality() > 0)
        {
            StringBuffer msg;
            excep->errorMessage(msg);
            printf("%s\n", msg.str());
            return false;
        }

        IConstECLWorkunit* w = &resp->getWorkunit();
        if (w && fp)
        {
            bool xml = true;
            const char* fmt = globals->queryProp("format");
            if(fmt && (stricmp(fmt, "bin") == 0 || stricmp(fmt, "binary") == 0))
                xml = false;
            IArrayOf<IConstECLException>& exceptions = w->getExceptions();
            ForEachItemIn(ind, exceptions)
            {
                IConstECLException* excep = &exceptions.item(ind);
                if(!excep)
                    continue;

                bool skip = false;
                const char* severity = excep->getSeverity();
                if (severity != NULL && stricmp(severity, "Warning") == 0 && globals->getPropBool("noWarnings", false))
                    skip = true;
                if (severity != NULL && stricmp(severity, "Info") == 0 && globals->getPropBool("noInfo", false))
                    skip = true;
                if (severity != NULL && stricmp(severity, "Error") == 0 && globals->getPropBool("noErrors", false))
                    skip = true;
                if (!skip)
                {
                    int lineno = excep->getLineNo();
                    const char* source = excep->getSource();
                    const char* msg = excep->getMessage();
                    unsigned code = excep->getCode();
                    if (lineno && source != NULL)
                    {
                        if (xml)
                            fprintf(fp, "<%s><source>%s</source><line>%d</line><code>%d</code><message>%s</message></%s>\n", severity, source, lineno, code, msg, severity);
                        else
                            fprintf(fp, "%s: %s(%d) %s\n", severity, source, lineno, msg);
                    }
                    else if(source != NULL)
                    {
                        if (xml)
                            fprintf(fp, "<%s><source>%s</source><code>%d</code><message>%s</message></%s>\n", severity, source, code, msg, severity);
                        else
                            fprintf(fp, "%s: %s %s\n", severity, source, msg);
                    }
                    else
                    {
                        if (xml)
                            fprintf(fp, "<%s><code>%d</code><message>%s</message></%s>\n", severity, code, msg, severity);
                        else
                            fprintf(fp, "%s: %s\n", severity, msg);
                    }
                }
            }

            if (w->getStateID() == WUStateAborted)
            {
                fprintf(fp, "Aborted\n");
                return true;
            }
            if (w->getStateID() == WUStateFailed)
                return false;

            int queryid = 0;

            IArrayOf<IConstECLResult>& results = w->getResults();
            ForEachItemIn(res_ind, results)
            {
                IConstECLResult* result = &results.item(res_ind);
                
                if(!result)
                    continue;
                
                const char* value = result->getValue();
                if(value != NULL && stricmp(value, "[undefined]") == 0)
                    continue;

                if(format)
                    format->printHeader(fp, result->getName());

                const char* rfname = result->getFileName();
                if(!(rfname && *rfname  && (globals->getPropInt("viewFileResults") ==0)))
                {
                    int pagesize = 0;
                    if(globals->hasProp("pagesize"))
                        pagesize = atoi(globals->queryProp("pagesize"));
                    if(pagesize == 0)
                        pagesize = DEFAULT_PAGESIZE;
                    int curpos = 0;
                    int count = 0;
                    int total = 0;
                    do
                    {
                        Owned<IClientWUResultBinRequest> res_req = wuclient->createWUResultBinRequest();
                        res_req->setStart(curpos);
                        res_req->setWuid(wuid);
                        res_req->setSequence(result->getSequence());
                        res_req->setCount(pagesize);
                        if (xml)
                            res_req->setFormat("xml");
                        else
                            res_req->setFormat("raw");
                        Owned<IClientWUResultBinResponse> res_resp = wuclient->WUResultBin(res_req);

                        const IMultiException* excep = &res_resp->getExceptions();
                        if(excep != NULL && excep->ordinality() > 0)
                        {
                            StringBuffer errmsg;
                            excep->errorMessage(errmsg);
                            printf("%s\n", errmsg.str());
                            continue;
                        }

                        const MemoryBuffer& resultbuf = res_resp->getResult();
                        count = res_resp->getCount();
                        total = (int)res_resp->getTotal();
                        
                        if(format)
                        {
                            format->setStartRowNumber(curpos);
                            format->printBody(fp, resultbuf.length(), (char*)resultbuf.toByteArray());
                        }
                        else
                        {
                            // This should never happen
                            fprintf(fp, "%s", resultbuf.toByteArray());
                        }
                        
                        curpos += count;
                    }
                    while (count > 0 && curpos < total - 1);
                }
                
                if(format)
                    format->printFooter(fp);
            }
Exemple #2
0
char *CThorCodeContextBase::getJobOwner()
{
    StringBuffer out;
    out.append(job.queryUser());
    return out.detach();
}
Exemple #3
0
String DateInterval::format(const String& format_spec) {
  StringBuffer s;
  for(int i = 0; i < format_spec.length(); i++) {
    const int MAXLEN = 22; // 64bit signed int string length, plus terminating \0
    char buf[MAXLEN];
    int l;
    char c = format_spec.charAt(i);

    if (c != '%') {
      s.append(c);
      continue;
    }
    i++;
    if (i == format_spec.length()) {
      // End of format, use literal % and finish
      s.append(c);
      break;
    }
    c = format_spec.charAt(i);

    switch(c) {
      case 'Y': l = snprintf(buf, MAXLEN, "%02" PRId64, getYears()); break;
      case 'y': l = snprintf(buf, MAXLEN, "%" PRId64,   getYears()); break;

      case 'M': l = snprintf(buf, MAXLEN, "%02" PRId64, getMonths()); break;
      case 'm': l = snprintf(buf, MAXLEN, "%" PRId64,   getMonths()); break;

      case 'D': l = snprintf(buf, MAXLEN, "%02" PRId64, getDays()); break;
      case 'd': l = snprintf(buf, MAXLEN, "%" PRId64,   getDays()); break;

      case 'H': l = snprintf(buf, MAXLEN, "%02" PRId64, getHours()); break;
      case 'h': l = snprintf(buf, MAXLEN, "%" PRId64,   getHours()); break;

      case 'I': l = snprintf(buf, MAXLEN, "%02" PRId64, getMinutes()); break;
      case 'i': l = snprintf(buf, MAXLEN, "%" PRId64,   getMinutes()); break;

      case 'S': l = snprintf(buf, MAXLEN, "%02" PRId64, getSeconds()); break;
      case 's': l = snprintf(buf, MAXLEN, "%" PRId64,   getSeconds()); break;

      case 'a':
        if (haveTotalDays()) {
          l = snprintf(buf, MAXLEN, "%" PRId64, getTotalDays());
        } else {
          l = snprintf(buf, MAXLEN, "(unknown)");
        }
        break;

      case 'R':
        l = snprintf(buf, MAXLEN, "%c", isInverted() ? '-' : '+'); break;
      case 'r':
        l = snprintf(buf, MAXLEN, "%s", isInverted() ? "-" : "");  break;

      case '%':
      default:
        l = 0;
        s.append('%');
        break;
    }

    if (l > 0) {
      s.append(buf, l);
    }
  }
  return s.detach();
}
Exemple #4
0
TCHAR * CTaskModel::toXMLNoKids()
{
	StringBuffer sb;
	toXMLString(sb, false);
	return sb.toString();
}
Exemple #5
0
char *CThorCodeContextBase::getExpandLogicalName(const char * logicalName)
{
    StringBuffer lfn;
    expandLogicalName(lfn, logicalName);
    return lfn.detach();
}
Exemple #6
0
result_t querystring_base::stringify(v8::Local<v8::Object> obj, exlib::string sep,
    exlib::string eq, v8::Local<v8::Object> opt,
    exlib::string& retVal)
{
    StringBuffer bufs;

    v8::Local<v8::Array> ks = obj->GetPropertyNames();
    int32_t len = ks->Length();
    int32_t i;
    result_t hr;

    for (i = 0; i < len; i++) {
        exlib::string strKey, strValue, str;
        v8::Local<v8::Array> vs;
        v8::Local<v8::Value> k = ks->Get(i);
        v8::Local<v8::Value> v = obj->Get(k);

        GetArgumentValue(k, strKey);
        encoding_base::encodeURIComponent(strKey, strKey);

        hr = GetArgumentValue(v, vs, true);
        if (hr >= 0) {
            int32_t len1 = vs->Length();
            int32_t i1;

            for (i1 = 0; i1 < len1; i1++) {
                hr = GetArgumentValue(vs->Get(i1), strValue);
                if (hr < 0)
                    return hr;

                encoding_base::encodeURIComponent(strValue, strValue);

                if (bufs.size() > 0)
                    bufs.append(sep);

                bufs.append(strKey);
                bufs.append(eq);
                bufs.append(strValue);
            }
        } else {
            hr = GetArgumentValue(v, strValue);
            if (hr < 0)
                return hr;

            encoding_base::encodeURIComponent(strValue, strValue);

            if (bufs.size() > 0)
                bufs.append(sep);

            bufs.append(strKey);
            bufs.append(eq);
            bufs.append(strValue);
        }
    }

    retVal = bufs.str();

    return 0;
}
Exemple #7
0
String HHVM_FUNCTION(serialize, const Variant& value) {
  switch (value.getType()) {
    case KindOfUninit:
    case KindOfNull:
      return "N;";
    case KindOfBoolean:
      return value.getBoolean() ? "b:1;" : "b:0;";
    case KindOfInt64: {
      StringBuffer sb;
      sb.append("i:");
      sb.append(value.getInt64());
      sb.append(';');
      return sb.detach();
    }
    case KindOfStaticString:
    case KindOfString: {
      StringData *str = value.getStringData();
      StringBuffer sb;
      sb.append("s:");
      sb.append(str->size());
      sb.append(":\"");
      sb.append(str->data(), str->size());
      sb.append("\";");
      return sb.detach();
    }
    case KindOfArray: {
      ArrayData *arr = value.getArrayData();
      if (arr->empty()) return "a:0:{}";
      // fall-through
    }
    case KindOfDouble:
    case KindOfObject:
    case KindOfResource: {
      VariableSerializer vs(VariableSerializer::Type::Serialize);
      return vs.serialize(value, true);
    }
    case KindOfRef:
    case KindOfClass:
      break;
  }
  not_reached();
}
int ForceShrineMenuComponent::handleObjectMenuSelect(SceneObject* sceneObject, CreatureObject* creature, byte selectedID) {
	if (selectedID != 213)
		return 0;

	if (creature->getPosture() != CreaturePosture::CROUCHED){
		creature->sendSystemMessage("@jedi_trials:show_respect"); // Must show respect
		return 0;
	}

	ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();

	if (ghost == NULL)
		return 0;

	if (creature->getScreenPlayState("VillageJediProgression") && !creature->hasSkill("force_title_jedi_rank_02")){
		ManagedReference<SuiMessageBox*> box = new SuiMessageBox(creature, SuiWindowType::NONE);
		box->setPromptTitle("@jedi_trials:padawan_trials_title"); // Jedi Trials
		box->setPromptText("@jedi_trials:padawan_trials_completed");

		ghost->addSuiBox(box);
		creature->sendMessage(box->generateMessage());

		SkillManager::instance()->awardSkill("force_title_jedi_rank_02", creature, true, true, true);

		creature->playEffect("clienteffect/entertainer_dazzle_level_3.cef", ""); // Not sure if it's the right one for this.

		PlayMusicMessage* pmm = new PlayMusicMessage("sound/intro.snd");
		creature->sendMessage(pmm);

		ghost->setJediState(2);

		// Trainer number. Pick a random trainer, there are at least 600 in the galaxy.

		ZoneServer* zoneServer = ghost->getZoneServer();
		int randomZone = System::random(zoneServer->getZoneCount() - 1);

		ManagedReference<Zone*> zone = zoneServer->getZone(randomZone);
		Vector3 randomTrainer = zone->getCreatureManager()->getRandomJediTrainer();

		if ((randomTrainer.getX() == 0) && (randomTrainer.getY() == 0)) { // No trainers on the zone.
			ManagedReference<Zone*> zone = zoneServer->getZone(0);
			Vector3 randomTrainer = zone->getCreatureManager()->getRandomJediTrainer();
		}

		Vector3 trainerPositionFinal(randomTrainer.getX(), randomTrainer.getY(), 0);

		String zoneName = zone->getZoneName();

		ghost->setTrainerCoordinates(trainerPositionFinal);
		ghost->setTrainerZoneName(zoneName); // For the Waypoint.


		ManagedReference<SceneObject*> inventory = creature->getSlottedObject("inventory");

		//Check if inventory is full.
		if (inventory->hasFullContainerObjects()) {
			creature->sendSystemMessage("@jedi_spam:inventory_full_jedi_robe"); //	You have too many items in your inventory. In order to get your Padawan Robe you must clear out at least one free slot.
			return 0;
		}

		ZoneServer* zserv = creature->getZoneServer();

		String PadawanRobe = "object/tangible/wearables/robe/robe_jedi_padawan.iff";
		ManagedReference<SceneObject*> padawanRobe = zserv->createObject(PadawanRobe.hashCode(), 1);
		if (inventory->transferObject(padawanRobe, -1)) {
			inventory->broadcastObject(padawanRobe, true);
		} else {
			padawanRobe->destroyObjectFromDatabase(true);
		}
	}

	else if (!creature->hasSkill("force_title_jedi_novice")){

		int rand = System::random(14) + 1;

		StringBuffer sysmsg;

		sysmsg << "@jedi_trials:force_shrine_wisdom_" << rand;

		creature->sendSystemMessage(sysmsg.toString());

	}

	else if (creature->hasSkill("force_title_jedi_rank_02")){

		ManagedReference<SceneObject*> inventory = creature->getSlottedObject("inventory");

		//Check if inventory is full.
		if (inventory->hasFullContainerObjects()) {
			creature->sendSystemMessage("@jedi_spam:inventory_full_jedi_robe"); //	You have too many items in your inventory. In order to get your Padawan Robe you must clear out at least one free slot.
			return 0;
		}

		ZoneServer* zserv = creature->getZoneServer();

		String PadawanRobe = "object/tangible/wearables/robe/robe_jedi_padawan.iff";
		ManagedReference<SceneObject*> padawanRobe = zserv->createObject(PadawanRobe.hashCode(), 1);
		if (inventory->transferObject(padawanRobe, -1)) {
			inventory->broadcastObject(padawanRobe, true);
		} else {
			padawanRobe->destroyObjectFromDatabase(true);
		}

	}

	return 0;


}
Exemple #9
0
bool Cws_accountEx::onVerifyUser(IEspContext &context, IEspVerifyUserRequest &req, IEspVerifyUserResponse &resp)
{
    try
    {
        ISecUser* usr = context.queryUser();
        if(!usr || !usr->isAuthenticated())
        {
            resp.setRetcode(-1);
            return false;
        }

        const char* ver = req.getVersion();
        if (!ver || !*ver)
        {
            throw MakeStringException(ECLWATCH_OLD_CLIENT_VERSION, "Client version not found");
        }

        int minor = 0;
        int major = 0;
        const char* dot1 = strrchr(ver, '.');
        if (!dot1)
            minor = atoi(ver);
        else if (strlen(dot1) > 1)
        {
            minor = atoi(dot1 + 1);
            if(dot1 > ver)
            {
                const char* dot2 = dot1 - 1;

                while(dot2 > ver && *dot2 != '.')
                    dot2--;
                if(*dot2 == '.')
                    dot2++;
                if(dot2 < dot1)
                {
                    StringBuffer majorstr;
                    majorstr.append(dot1 - dot2, dot2);
                    major = atoi(majorstr.str());
                }
            }
        }

        if(major > CUTOFF_MAJOR || (major == CUTOFF_MAJOR && minor >= CUTOFF_MINOR))
        {
            resp.setRetcode(0);
            return true;
        }

        const char* build_ver = getBuildVersion();
        if (build_ver && *build_ver)
            throw MakeStringException(ECLWATCH_OLD_CLIENT_VERSION, "Client version %s (server %s) is out of date.", ver, build_ver);
        else
            throw MakeStringException(ECLWATCH_OLD_CLIENT_VERSION, "Client version %s is out of date.", ver);
    }
    catch(IException* e)
    {
        FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
    }

    return true;
}
Exemple #10
0
 inline bool fileExists(StringBuffer &filename)
 {
     return (checkFileExists(filename.str()) || checkFileExists(filename.toUpperCase().str()) || checkFileExists(filename.toLowerCase().str()));
 }
Exemple #11
0
bool HttpProtocol::ProxyRequest(Transport *transport, bool force,
                                const std::string &url,
                                int &code, std::string &error,
                                StringBuffer &response,
                                HeaderMap *extraHeaders /* = NULL */) {
    assert(transport);
    if (transport->headersSent()) {
        raise_warning("Cannot proxy request - headers already sent");
        return false;
    }

    HeaderMap requestHeaders;
    transport->getHeaders(requestHeaders);
    if (extraHeaders) {
        for (HeaderMap::const_iterator iter = extraHeaders->begin();
                iter != extraHeaders->end(); ++iter) {
            std::vector<std::string> &values = requestHeaders[iter->first];
            values.insert(values.end(), iter->second.begin(), iter->second.end());
        }
    }

    int size = 0;
    const char *data = nullptr;
    if (transport->getMethod() == Transport::Method::POST) {
        data = (const char *)transport->getPostData(size);
    }

    code = 0; // HTTP status of curl or 0 for "no server response code"
    std::vector<String> responseHeaders;
    HttpClient http;
    if (data && size) {
        code = http.post(url.c_str(), data, size, response, &requestHeaders,
                         &responseHeaders);
    } else {
        code = http.get(url.c_str(), response, &requestHeaders, &responseHeaders);
    }
    if (code == 0) {
        if (!force) return false; // so we can retry
        Logger::Error("Unable to proxy %s: %s", url.c_str(),
                      http.getLastError().c_str());
        error = http.getLastError();
        return true;
    }

    for (unsigned int i = 0; i < responseHeaders.size(); i++) {
        String &header = responseHeaders[i];
        if (header.find(":") != String::npos &&
                header.find("Content-Length: ") != 0 &&
                header.find("Client-Transfer-Encoding: ") != 0 &&
                header.find("Transfer-Encoding: ") != 0 &&
                header.find("Connection: ") != 0) {
            transport->addHeader(header.data());
        }
    }
    const char* respData = response.data();
    if (!respData) {
        respData = "";
    }
    Logger::Verbose("Response code was %d when proxying %s", code, url.c_str());
    return true;
}
Exemple #12
0
CEspConfig::CEspConfig(IProperties* inputs, IPropertyTree* envpt, IPropertyTree* procpt, bool isDali)
{
    hsami_=0;
    serverstatus=NULL;
    useDali=false;
    
    if(inputs)
        m_inputs.setown(inputs);

    if(!envpt || !procpt)
        return;

    m_envpt.setown(envpt);
    m_cfg.setown(procpt);

    loadBuiltIns();   
   
    // load options
    const char* level = m_cfg->queryProp("@logLevel");
    m_options.logLevel = level ? atoi(level) : LogMin;
    m_options.logReq = m_cfg->getPropBool("@logRequests", false);
    m_options.logResp = m_cfg->getPropBool("@logResponses", false);
    m_options.frameTitle.set(m_cfg->queryProp("@name"));
    m_options.slowProcessingTime = m_cfg->getPropInt("@slowProcessingTime", 30) * 1000; //in msec

#ifdef USE_ENV_CONF_FILE
    // load environment parameters
    StringBuffer envConfFile, envXMLFile;
    const char* configFile = m_cfg->queryProp("EnvironmentConfFile");
    if (configFile && *configFile)
    {
        envConfFile.append(configFile);
    }
    else
    {
        envConfFile.append("/etc/LexisNexis/environment.conf");
    }
    const char* envFromDali = m_cfg->queryProp("@environmentNotFromDali");
    if (envFromDali && !stricmp(envFromDali, "true"))
    {
        const char* envXML = m_cfg->queryProp("EnvironmentXMLFile");
        if (envXML && *envXML)
        {
            envXMLFile.append(envXML);
        }
        else
        {
            envXMLFile.append("environment.xml");
        }
    }

    Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
    factory->createEnvironmentByFile(envConfFile.str(), envXMLFile.str());
#endif

    if (!m_cfg->getProp("@name", m_process))
    {
        ERRLOG("EspProcess name not found");
    }
    else
    {
        DBGLOG("ESP process name [%s]", m_process.str());

        IPropertyTreeIterator *pt_iter = NULL;
        StringBuffer daliservers;
        if (m_cfg->getProp("@daliServers", daliservers))
            initDali(daliservers.str());

#ifndef _DEBUG
        startPerformanceMonitor(m_cfg->getPropInt("@perfReportDelay", 60)*1000);
#endif

        //get the local computer name:              
        m_cfg->getProp("@computer", m_computer);

        //get the local computer information:               
        StringBuffer xpath;
        xpath.appendf("Hardware/Computer[@name=\"%s\"]", m_computer.str());

        IPropertyTree *computer = m_envpt->queryPropTree(xpath.str());
        if (computer)
        {
            StringBuffer address;
            computer->getProp("@netAddress", address);

            int port = m_cfg->getPropInt("@port", 1500);
            if(strcmp(address.str(), ".") == 0)
            {
                GetHostName(address.clear());
            }
            m_address.set(address.str(), (unsigned short) port);
        }
      
        xpath.clear();
        xpath.append("EspService");
 
        pt_iter = m_cfg->getElements(xpath.str());

        if (pt_iter!=NULL)
        {
            IPropertyTree *ptree = NULL;

            pt_iter->first();

            while(pt_iter->isValid())
            {
                ptree = &pt_iter->query();
                if (ptree)
                {
                    srv_cfg *svcfg = new srv_cfg;

                    ptree->getProp("@name", svcfg->name);
                    ptree->getProp("@type", svcfg->type);
                    ptree->getProp("@plugin", svcfg->plugin);
                    fixPlugin(svcfg->plugin);

                    map<string, srv_cfg*>::value_type en(svcfg->name.str(), svcfg);
                    m_services.insert(en);
                }               
                pt_iter->next();
            }
    
            pt_iter->Release();
            pt_iter=NULL;
        }

        xpath.clear();
        xpath.append("EspProtocol");
 
        pt_iter = m_cfg->getElements(xpath.str());

        if (pt_iter!=NULL)
        {
            IPropertyTree *ptree = NULL;

            pt_iter->first();
    

            while(pt_iter->isValid())
            {
                ptree = &pt_iter->query();
                if (ptree)
                {
                    protocol_cfg *pcfg = new protocol_cfg;

                    ptree->getProp("@name", pcfg->name);
                    ptree->getProp("@plugin", pcfg->plugin);
                    fixPlugin(pcfg->plugin);
                    ptree->getProp("@type", pcfg->type);

                    map<string, protocol_cfg*>::value_type en(pcfg->name.str(), pcfg);
                    m_protocols.insert(en);
                }               

                pt_iter->next();
            }
    
            pt_iter->Release();
            pt_iter=NULL;
        }

        xpath.clear();
        xpath.append("EspBinding");
 
        pt_iter = m_cfg->getElements(xpath.str());

        if (pt_iter!=NULL)
        {
            IPropertyTree *ptree = NULL;

            pt_iter->first();
    

            while(pt_iter->isValid())
            {
                ptree = &pt_iter->query();
                if (ptree)
                {
                    binding_cfg *bcfg = new binding_cfg;
                    
                    ptree->getProp("@name", bcfg->name);
                    ptree->getProp("@type", bcfg->type);
                    ptree->getProp("@plugin", bcfg->plugin);
                    fixPlugin(bcfg->plugin);
                    bcfg->isDefault = ptree->getPropBool("@defaultBinding", false);
                    
                    StringBuffer addr;
                    ptree->getProp("@netAddress", addr);
                    if(strcmp(addr.str(), ".") == 0)
                    {
                        bcfg->address.append("0.0.0.0");
                    }
                    else
                    {
                        bcfg->address.append(addr.str());
                    }
                    
                    StringBuffer portstr;
                    ptree->getProp("@port", portstr);
                    bcfg->port = atoi(portstr.str());
                    ptree->getProp("@service", bcfg->service_name);
                    ptree->getProp("@protocol", bcfg->protocol_name);
                    
                    m_bindings.push_back(bcfg);
                }
                
                pt_iter->next();
            }
    
            pt_iter->Release();
            pt_iter=NULL;
        }
    }
}
//-----------------------------------------------------------------------
// SetEnvironment
//-----------------------------------------------------------------------
void CWizardInputs::setEnvironment()
{
  StringBuffer xpath;
  if(m_pXml->hasProp("@ipList"))
    formIPList(m_pXml->queryProp("@ipList"), m_ipaddress);

  if(m_pXml->hasProp("@supportNodes"))
  {
    m_supportNodes = atoi(m_pXml->queryProp("@supportNodes"));

    if (m_supportNodes)
    {
      if (m_ipaddress.length() > 0 && m_ipaddress.length() > m_supportNodes)
      {
        for(unsigned i = 0; i < m_supportNodes; i++)
          m_ipaddressSupport.append(m_ipaddress.item(i));

        m_ipaddress.removen(0, m_supportNodes);
      }
      else
        m_supportNodes = 0;
    }
  }

  if(m_pXml->hasProp("@roxieNodes"))
    m_roxieNodes = atoi(m_pXml->queryProp("@roxieNodes"));

  if(m_pXml->hasProp("@thorNodes"))
    m_thorNodes = atoi(m_pXml->queryProp("@thorNodes"));

  if(m_pXml->hasProp("@dbuser"))
    m_dbuser = m_pXml->queryProp("@dbuser");

  if(m_pXml->hasProp("@dbpassword"))
    m_dbpassword = m_pXml->queryProp("@dbpassword");

  m_thorSlavesPerNode = 1;
  if(m_pXml->hasProp("@slavesPerNode"))
    m_thorSlavesPerNode = atoi( m_pXml->queryProp("@slavesPerNode"));

  if (m_thorSlavesPerNode < 1)
    m_thorSlavesPerNode = 1;

  m_roxieOnDemand = m_pXml->getPropBool("@roxieOnDemand", true);

  xpath.clear().appendf("Software/EspProcess/EspService[@name='%s']/LocalConfFile", m_service.str());
  const char* pConfFile = m_cfg->queryProp(xpath.str());
  xpath.clear().appendf("Software/EspProcess/EspService[@name='%s']/LocalEnvConfFile",  m_service.str());
  const char* pEnvConfFile = m_cfg->queryProp(xpath.str());

  if (pConfFile && *pConfFile && pEnvConfFile && *pEnvConfFile)
  {
     Owned<IProperties> pParams = createProperties(pConfFile);
     Owned<IProperties> pEnvParams = createProperties(pEnvConfFile);
     StringBuffer sb, fileName;
     
     fileName.append((pEnvParams->queryProp("path")!= NULL ? (sb.clear().append(pEnvParams->queryProp("path")).append("/componentfiles/configxml/")) : STANDARD_CONFIGXMLDIR));
     fileName.append((pParams->queryProp("buildset") != NULL ? (sb.clear().append(pParams->queryProp("buildset"))) : STANDARD_CONFIG_BUILDSETFILE));

     if(fileName.length() && checkFileExists(fileName.str()))
       m_buildSetTree.setown(createPTreeFromXMLFile(fileName.str()));
     else
       throw MakeStringException( -1 , "The buildSetFile %s does not exists", fileName.str());
     
     fileName.clear().append((pEnvParams->queryProp("configs") != NULL ? (sb.clear().append(pEnvParams->queryProp("configs")).append("/")): STANDARD_CONFIG_DIR));
     fileName.append((pParams->queryProp("wizardalgorithm") != NULL ? (sb.clear().append(pParams->queryProp("wizardalgorithm"))) : STANDARD_CONFIG_ALGORITHMFILE));
     
     if(fileName.length() && checkFileExists(fileName.str()))
       m_algProp.setown(createProperties(fileName.str()));
     else
       throw MakeStringException( -1 , "The algorithm file %s does not exists", fileName.str());
  }
  setWizardRules();
  setTopologyParam();
}
Exemple #14
0
Variant f_icu_match(CStrRef pattern, CStrRef subject,
                    VRefParam matches /* = null */, int64_t flags /* = 0 */) {
    UErrorCode status = U_ZERO_ERROR;

    if (matches.isReferenced()) {
        matches = Array();
    }

    // Create hash map key by concatenating pattern and flags.
    StringBuffer bpattern;
    bpattern.append(pattern);
    bpattern.append(':');
    bpattern.append(flags);
    String spattern = bpattern.detach();

    // Find compiled pattern matcher in hash map or add it.
    PatternStringMap::accessor accessor;
    const RegexPattern* rpattern;
    if (s_patternCacheMap.find(accessor, spattern.get())) {
        rpattern = accessor->second;
    } else {
        // First 32 bits are reserved for ICU-specific flags.
        rpattern = RegexPattern::compile(
                       UnicodeString::fromUTF8(pattern.data()), (flags & 0xFFFFFFFF), status);
        if (U_FAILURE(status)) {
            return false;
        }

        if (s_patternCacheMap.insert(
                    accessor, makeStaticString(spattern.get()))) {
            accessor->second = rpattern;
        } else {
            delete rpattern;
            rpattern = accessor->second;
        }
    }

    // Build regex matcher from compiled pattern and passed-in subject.
    UnicodeString usubject = UnicodeString::fromUTF8(subject.data());
    boost::scoped_ptr<RegexMatcher> matcher(rpattern->matcher(usubject, status));
    if (U_FAILURE(status)) {
        return false;
    }

    // Return 0 or 1 depending on whether or not a match was found and
    // (optionally), set matched (sub-)patterns for passed-in reference.
    int matched = 0;
    if (matcher->find()) {
        matched = 1;

        if (matches.isReferenced()) {
            int32_t count = matcher->groupCount();

            for (int32_t i = 0; i <= count; i++) {
                UnicodeString ustring = matcher->group(i, status);
                if (U_FAILURE(status)) {
                    return false;
                }

                // Convert UnicodeString back to UTF-8.
                std::string string;
                ustring.toUTF8String(string);
                String match = String(string);

                if (flags & k_UREGEX_OFFSET_CAPTURE) {
                    // start() returns the index in UnicodeString, which
                    // normally means the index into an array of 16-bit
                    // code "units" (not "points").
                    int32_t start = matcher->start(i, status);
                    if (U_FAILURE(status)) {
                        return false;
                    }

                    start = usubject.countChar32(0, start);
                    matches->append(make_packed_array(match, start));
                } else {
                    matches->append(match);
                }
            }
        }
    }

    return matched;
}
 const char *  getParenttable() const
 {
     return parenttable.str();
 }
Exemple #16
0
bool Cws_accountEx::onUpdateUser(IEspContext &context, IEspUpdateUserRequest & req, IEspUpdateUserResponse & resp)
{
    try
    {
        CLdapSecManager* secmgr = dynamic_cast<CLdapSecManager*>(context.querySecManager());
        if(secmgr == NULL)
        {
            throw MakeStringException(ECLWATCH_INVALID_SEC_MANAGER, "Security manager can't be converted to LdapSecManager. Only LdapSecManager supports this function.");
        }

        ISecUser* user = context.queryUser();
        if(user == NULL)
        {
            resp.setRetcode(-1);
            resp.setMessage("Can't find user in esp context. Please check if the user was properly logged in.");
            return false;
        }
        if(req.getUsername() == NULL || strcmp(req.getUsername(), user->getName()) != 0)
        {
            resp.setRetcode(-1);
            resp.setMessage("Username/password don't match.");
            return false;
        }

        const char* oldpass = req.getOldpass();
        if(oldpass == NULL || strcmp(oldpass, user->credentials().getPassword()) != 0)
        {
            resp.setRetcode(-1);
            resp.setMessage("Username/password don't match.");
            return false;
        }

        const char* newpass1 = req.getNewpass1();
        const char* newpass2 = req.getNewpass2();
        if(newpass1 == NULL || newpass2 == NULL || strlen(newpass1) < 4 || strlen(newpass2) < 4)
        {
            resp.setRetcode(-1);
            resp.setMessage("New password must be 4 characters or longer.");
            return false;
        }
        if(strcmp(newpass1, newpass2) != 0)
        {
            resp.setRetcode(-1);
            resp.setMessage("Password and retype don't match.");
            return false;
        }
        if(strcmp(oldpass, newpass1) == 0)
        {
            resp.setRetcode(-1);
            resp.setMessage("New password can't be the same as current password.");
            return false;
        }

        const char* pwscheme = secmgr->getPasswordStorageScheme();
        bool isCrypt = pwscheme && (stricmp(pwscheme, "CRYPT") == 0);
        if(isCrypt && strncmp(oldpass, newpass1, 8) == 0)
        {
            resp.setRetcode(-1);
            resp.setMessage("The first 8 characters of the new password must be different from before.");
            return false;
        }

        bool ok = false;
        try
        {
            ok = secmgr->updateUser(*user, newpass1);
        }
        catch(IException* e)
        {
            StringBuffer emsg;
            e->errorMessage(emsg);
            resp.setRetcode(-1);
            resp.setMessage(emsg.str());
            return false;
        }
        catch(...)
        {
            ok = false;
        }

        if(!ok)
        {
            throw MakeStringException(ECLWATCH_CANNOT_CHANGE_PASSWORD, "Failed in changing password.");
        }

        resp.setRetcode(0);
        if(isCrypt && strlen(newpass1) > 8)
            resp.setMessage("Your password has been changed successfully, however, only the first 8 chars are effective.");
        else
            resp.setMessage("Your password has been changed successfully.");
    }
    catch(IException* e)
    {
        FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
    }
    return true;
}
 const char * getColumnType() const
 {
    return columnType.str();
 }
 HPCCColumnMetaData() : keyedField(false), decimalDigits(0), index(-1)
 {
     columnName.clear();
 }
Exemple #19
0
std::string CmdPrint::FormatResult(const char *format, CVarRef ret) {
  if (format == NULL) {
    String sret = DebuggerClient::FormatVariable(ret, -1);
    return string(sret.data(), sret.size());
  }

  if (strcmp(format, "v") == 0) {
    String sret = DebuggerClient::FormatVariable(ret, -1, true);
    return string(sret.data(), sret.size());
  }

  if (strcmp(format, "dec") == 0 ||
      strcmp(format, "unsigned") == 0 ||
      ret.isInteger()) {
    int64 nret = ret.toInt64();
    char buf[64];
    if (strcmp(format, "hex") == 0 || strcmp(format, "x") == 0) {
      snprintf(buf, sizeof(buf), "%llx", nret);
      return buf;
    }
    if (strcmp(format, "oct") == 0) {
      snprintf(buf, sizeof(buf), "%llo", nret);
      return buf;
    }
    if (strcmp(format, "dec") == 0) {
      snprintf(buf, sizeof(buf), "%lld", nret);
      return buf;
    }
    if (strcmp(format, "unsigned") == 0) {
      snprintf(buf, sizeof(buf), "%llu", (unsigned long long)nret);
      return buf;
    }
    if (strcmp(format, "time") == 0) {
      StringBuffer sb;
      DateTime dt(nret);
      sb.append("RFC822:            ");
      sb.append(dt.toString(DateTime::RFC822));
      sb.append("\nRFC850:            ");
      sb.append(dt.toString(DateTime::RFC850));
      sb.append("\nRFC1036:           ");
      sb.append(dt.toString(DateTime::RFC1036));
      sb.append("\nRFC1123/RSS:       ");
      sb.append(dt.toString(DateTime::RFC1123));
      sb.append("\nRFC2822:           ");
      sb.append(dt.toString(DateTime::RFC2822));
      sb.append("\nRFC3339/ATOM/W3C:  ");
      sb.append(dt.toString(DateTime::RFC3339));
      sb.append("\nISO8601:           ");
      sb.append(dt.toString(DateTime::ISO8601));
      sb.append("\nCookie:            ");
      sb.append(dt.toString(DateTime::Cookie));
      sb.append("\nHttpHeader:        ");
      sb.append(dt.toString(DateTime::HttpHeader));
      return sb.data();
    }

    ASSERT(false);
  }

  String sret = DebuggerClient::FormatVariable(ret, -1);
  if (strcmp(format, "hex") == 0 || strcmp(format, "x") == 0 ||
      strcmp(format, "oct") == 0) {
    StringBuffer sb;
    for (int i = 0; i < sret.size(); i++) {
      char ch = sret[i];
      if (isprint(ch)) {
        sb.append(ch);
      } else {
        char buf[6];
        if (strcmp(format, "oct") == 0) {
          snprintf(buf, sizeof(buf), "\\%03o", ch);
        } else {
          snprintf(buf, sizeof(buf), "\\x%02x", ch);
        }
        sb.append(buf);
      }
    }
    return sb.data();
  }
  if (strcmp(format, "time") == 0) {
    DateTime dt;
    int64 ts = -1;
    if (dt.fromString(ret.toString(), SmartObject<TimeZone>())) {
      bool err;
      ts = dt.toTimeStamp(err);
    }
    return String(ts).data();
  }

  ASSERT(false);
  return "";
}
 HPCCColumnMetaData(const char * colname) : keyedField(false), decimalDigits(0), index(-1)
 {
     columnName.set(colname);
 }
Exemple #21
0
Variant HHVM_FUNCTION(proc_open,
                      const String& cmd,
                      const Array& descriptorspec,
                      VRefParam pipesParam,
                      const Variant& cwd /* = uninit_variant */,
                      const Variant& env /* = uninit_variant */,
                      const Variant& other_options /* = uninit_variant */) {
  if (RuntimeOption::WhitelistExec && !check_cmd(cmd.data())) {
    return false;
  }
  if (cmd.size() != strlen(cmd.c_str())) {
    raise_warning("NULL byte detected. Possible attack");
    return false;
  }
  Variant pipes(pipesParam, Variant::WithRefBind{});

  std::vector<DescriptorItem> items;

  std::string scwd = "";
  if (!cwd.isNull() && cwd.isString() && !cwd.asCStrRef().empty()) {
    scwd = cwd.asCStrRef().c_str();
  } else if (!g_context->getCwd().empty()) {
    scwd = g_context->getCwd().c_str();
  }

  Array enva;

  if (env.isNull()) {
    if (is_cli_mode()) {
      enva = cli_env();
    } else {
      // Build out an environment that conceptually matches what we'd
      // see if we were to iterate the environment and call getenv()
      // for each name.

      // Env vars defined in the hdf file go in first
      for (const auto& envvar : RuntimeOption::EnvVariables) {
        enva.set(String(envvar.first), String(envvar.second));
      }

      // global environment overrides the hdf
      for (char **env = environ; env && *env; env++) {
        char *p = strchr(*env, '=');
        if (p) {
          String name(*env, p - *env, CopyString);
          String val(p + 1, CopyString);
          enva.set(name, val);
        }
      }
    }

    // and then any putenv() changes take precedence
    for (ArrayIter iter(g_context->getEnvs()); iter; ++iter) {
      enva.set(iter.first(), iter.second());
    }
  } else {
    enva = env.toArray();
  }


#ifdef _WIN32
  PROCESS_INFORMATION pi;
  HANDLE childHandle;
  STARTUPINFO si;
  BOOL newprocok;
  SECURITY_ATTRIBUTES security;
  DWORD dwCreateFlags = 0;
  char *command_with_cmd;
  UINT old_error_mode;
  char cur_cwd[MAXPATHLEN];
  bool suppress_errors = false;
  bool bypass_shell = false;

  if (!other_options.isNull() && other_options.isArray()) {
    auto arr = other_options.asCArrRef();
    if (arr.exists(String("suppress_errors", CopyString), true)) {
      auto v = arr[String("suppress_errors", CopyString)];
      if ((v.isBoolean() && v.asBooleanVal()) ||
          (v.isInteger() && v.asInt64Val())) {
        suppress_errors = true;
      }
    }

    if (arr.exists(String("bypass_shell", CopyString), true)) {
      auto v = arr[String("bypass_shell", CopyString)];
      if ((v.isBoolean() && v.asBooleanVal()) ||
          (v.isInteger() && v.asInt64Val())) {
        bypass_shell = true;
      }
    }
  }

  /* we use this to allow the child to inherit handles */
  memset(&security, 0, sizeof(security));
  security.nLength = sizeof(security);
  security.bInheritHandle = true;
  security.lpSecurityDescriptor = nullptr;

  memset(&si, 0, sizeof(si));
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESTDHANDLES;

  si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  si.hStdError = GetStdHandle(STD_ERROR_HANDLE);

  if (!pre_proc_open(descriptorspec, items)) return false;
  /* redirect stdin/stdout/stderr if requested */
  for (size_t i = 0; i < items.size(); i++) {
    switch (items[i].index) {
      case 0:
        si.hStdInput = items[i].childend;
        break;
      case 1:
        si.hStdOutput = items[i].childend;
        break;
      case 2:
        si.hStdError = items[i].childend;
        break;
    }
  }


  memset(&pi, 0, sizeof(pi));

  if (suppress_errors) {
    old_error_mode = SetErrorMode(
      SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
  }

  dwCreateFlags = NORMAL_PRIORITY_CLASS;
  if (!RuntimeOption::ServerExecutionMode()) {
    dwCreateFlags |= CREATE_NO_WINDOW;
  }

  char *envp = build_envp(enva);
  if (bypass_shell) {
    newprocok = CreateProcess(
      nullptr,
      strdup(cmd.c_str()),
      &security,
      &security,
      TRUE,
      dwCreateFlags,
      envp,
      scwd.c_str(),
      &si,
      &pi);
  } else {
    std::string command_with = "cmd.exe /c ";
    command_with += cmd.toCppString();

    newprocok = CreateProcess(
      nullptr,
      strdup(command_with.c_str()),
      &security,
      &security,
      TRUE,
      dwCreateFlags,
      envp,
      scwd.c_str(),
      &si,
      &pi);
  }
  free(envp);

  if (suppress_errors) {
    SetErrorMode(old_error_mode);
  }

  if (newprocok == FALSE) {
    DWORD dw = GetLastError();
    char* msg;
    FormatMessageA(
      FORMAT_MESSAGE_ALLOCATE_BUFFER
        | FORMAT_MESSAGE_FROM_SYSTEM
        | FORMAT_MESSAGE_IGNORE_INSERTS,
      nullptr,
      dw,
      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
      (LPSTR)&msg,
      0,
      nullptr);

    /* clean up all the descriptors */
    for (size_t i = 0; i < items.size(); i++) {
      CloseHandle(items[i].childend);
      if (items[i].parentend) {
        CloseHandle(items[i].parentend);
      }
    }
    raise_warning("CreateProcess failed, error code - %u: %s", dw, msg);
    LocalFree(msg);
    return false;
  }

  childHandle = pi.hProcess;
  DWORD child = pi.dwProcessId;
  CloseHandle(pi.hThread);
  return post_proc_open(cmd, pipes, enva, items, (pid_t)child, childHandle);
#else
  pid_t child;

  if (LightProcess::Available()) {
    // light process available
    // there is no need to do any locking, because the forking is delegated
    // to the light process
    if (!pre_proc_open(descriptorspec, items)) return false;
    const int item_size = items.size();
    std::vector<int> created;
    created.reserve(item_size);
    std::vector<int> intended;
    intended.reserve(item_size);
    for (int i = 0; i < item_size; i++) {
      const auto& item = items[i];
      created.push_back(item.childend);
      intended.push_back(item.index);
    }

    std::vector<std::string> envs;
    for (ArrayIter iter(enva); iter; ++iter) {
      StringBuffer nvpair;
      nvpair.append(iter.first().toString());
      nvpair.append('=');
      nvpair.append(iter.second().toString());
      std::string tmp = nvpair.detach().c_str();
      if (tmp.find('\n') == std::string::npos) {
        envs.push_back(tmp);
      }
    }

    child = LightProcess::proc_open(cmd.c_str(), created, intended,
                                    scwd.c_str(), envs);
    assert(child);
    return post_proc_open(cmd, pipes, enva, items, child);
  } else {
    /* the unix way */
    Lock lock(DescriptorItem::s_mutex);
    if (!pre_proc_open(descriptorspec, items)) return false;
    child = fork();
    if (child) {
      // the parent process
      return post_proc_open(cmd, pipes, enva, items, child);
    }
  }

  assert(child == 0);
  /* this is the child process */

  /* close those descriptors that we just opened for the parent stuff,
   * dup new descriptors into required descriptors and close the original
   * cruft */
  for (auto& item : items) {
    item.dupChild();
  }
  if (scwd.length() > 0 && chdir(scwd.c_str())) {
    // chdir failed, the working directory remains unchanged
  }
  std::vector<String> senvs; // holding those char *
  char **envp = build_envp(enva, senvs);
  execle("/bin/sh", "sh", "-c", cmd.data(), nullptr, envp);
  free(envp);
  _exit(127);
#endif
}
 const char * getTableName() const
 {
     return tableName.str();
 }
Exemple #23
0
static void doSetCompilerPath(const char * path, const char * includes, const char * libs, const char * tmpdir, unsigned targetCompiler, bool verbose)
{
    if (!includes)
        includes = INCLUDEPATH[targetCompiler];
    if (!libs)
        libs = LIB_DIR[targetCompiler];
    if (verbose)
    {
        PrintLog("Include directory set to %s", includes);
        PrintLog("Library directory set to %s", libs);
    }
    compilerRoot.set(path ? path : targetCompiler==GccCppCompiler ? "/usr" : ".\\CL");
    stdIncludes.set(includes);
    stdLibs.clear();
    for (;;)
    {
        StringBuffer thislib;
        while (*libs && *libs != ';')
            thislib.append(*libs++);
        if (thislib.length())
        {
            stdLibs.append(" ").append(USE_LIBPATH_FLAG[targetCompiler]).append(thislib).append(USE_LIBPATH_TAIL[targetCompiler]);
            if (USE_LIBRPATH_FLAG[targetCompiler])
                stdLibs.append(" ").append(USE_LIBRPATH_FLAG[targetCompiler]).append(thislib);
        }
        if (!*libs)
            break;
        libs++;
    }
    StringBuffer fname;
    if (path)
    {
        const char *finger = CC_NAME[targetCompiler];
        while (*finger)
        {
            if (*finger == '#')
                fname.append(path);
            else
                fname.append(*finger);
            finger++;
        }

#if defined(__linux__)
        StringBuffer clbin_dir;
        const char* dir_end = strrchr(fname, '/');
        if(dir_end == NULL)
            clbin_dir.append(".");
        else
            clbin_dir.append((dir_end - fname.str()) + 1, fname.str());
        
        StringBuffer pathenv(clbin_dir.str());
        const char* oldpath = getenv("PATH");
        if(oldpath != NULL && *oldpath != '\0')
        pathenv.append(":").append(oldpath);
        setenv("PATH", pathenv.str(), 1);
#endif
    }
    else
    {
        fname.append(compilerRoot).append(CC_NAME[targetCompiler]);
        fname.replaceString("#",NULL);
    }
    if (verbose)
        PrintLog("Compiler path set to %s", fname.str());

    dequote(fname);
#ifdef _WIN32
    if (_access(fname.str(), 4))
    {
#else
#if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
    struct stat filestatus;
    int r = stat(fname.str(), &filestatus);
    if (    (r != 0)
        ||  (!S_ISREG(filestatus.st_mode))
        ||  (filestatus.st_mode&(S_IXOTH|S_IXGRP|S_IXUSR)==0))
    {
        if (r == -1) errno = ENOENT;
#endif
#endif
        if (verbose)
            PrintLog("SetCompilerPath - no compiler found");
        throw MakeOsException(GetLastError(), "setCompilerPath could not locate compiler %s", fname.str());
    }

    if(tmpdir && *tmpdir)
    {
        //MORE: this should be done for the child process instead of the parent but invoke does not let me do it
#if defined(__linux__)
        setenv("TMPDIR", tmpdir, 1);
#endif

#ifdef _WIN32
        StringBuffer tmpbuf;
        tmpbuf.append("TMP=").append(tmpdir);
        _putenv(tmpbuf.str());
#endif
    }
}

//===========================================================================

class CCompilerThreadParam : CInterface
{
public:
    IMPLEMENT_IINTERFACE;
    CCompilerThreadParam(const StringBuffer & _cmdline, Semaphore & _finishedCompiling, const StringBuffer & _logfile) : cmdline(_cmdline), finishedCompiling(_finishedCompiling), logfile(_logfile) {};

    StringBuffer        cmdline;
    StringBuffer        logfile;
    Semaphore       &   finishedCompiling;
};

//===========================================================================

static void setDirectoryPrefix(StringAttr & target, const char * source)
{
    if (source && *source)
    {
        StringBuffer temp;
        target.set(addDirectoryPrefix(temp, source));
    }
}

CppCompiler::CppCompiler(const char * _coreName, const char * _sourceDir, const char * _targetDir, unsigned _targetCompiler, bool _verbose)
{
#define CORE_NAME allSources.item(0)
    if (_coreName)
        addSourceFile(_coreName);
    targetCompiler = _targetCompiler;
    createDLL = true;
#ifdef _DEBUG
    setDebug(true);
    setDebugLibrary(true);
#else
    setDebug(false);
    setDebugLibrary(false);
#endif
    
    setDirectoryPrefix(sourceDir, _sourceDir);
    setDirectoryPrefix(targetDir, _targetDir);
    maxCompileThreads = 1;
    onlyCompile = false;
    verbose = _verbose;
    saveTemps = false;
    abortChecker = NULL;
}

void CppCompiler::addCompileOption(const char * option)
{
    compilerOptions.append(' ').append(option);
}
 const char * getColumnName() const
 {
     return columnName.str();
 }
Exemple #25
0
char *CThorCodeContextBase::getWuid()
{
    StringBuffer out;
    out.append(job.queryWuid());
    return out.detach();
}
 const char * getAlias() const
 {
     return alias.str();
 }
static void getOldXPath(StringBuffer & path, const char * name)
{
    path.append("/GeneratedDlls/GeneratedDll[@uid=\"").append(name).append("\"]");
}
 const char * getName()
 {
     return name.str();
 }
Exemple #29
0
bool CmdExtension::processList(DebuggerProxy &proxy) {
  IDebuggable::InfoVec info;

  Array exts = ExtensionRegistry::getLoaded();

  std::set<std::string, string_lessi> names;
  for (ArrayIter iter(exts); iter; ++iter) {
    names.insert(iter.second().toString().data());
  }
  for (auto const& name : names) {
    auto ext = ExtensionRegistry::get(name);
    assert(ext);
    if (ext) {
      int support = ext->debuggerSupport();
      std::string line;
      line += (support & IDebuggable::SupportInfo) ? "Yes     " : "        ";
      line += (support & IDebuggable::SupportDump) ? "Yes     " : "        ";
      line += (support & IDebuggable::SupportVerb) ? "Yes     " : "        ";
      line += ext->getVersion();
      IDebuggable::Add(info, name.c_str(), line);
    }
  }
  int nameLen;
  String body = DebuggerClient::FormatInfoVec(info, &nameLen);
  int hrLen = nameLen + 42;
  if (hrLen > DebuggerClient::LineWidth) hrLen = DebuggerClient::LineWidth;

  StringBuffer sb;
  for (int i = 0; i < hrLen; i++) sb.append(BOX_H); sb.append("\n");
  sb.append(StringUtil::Pad("Name\\Support", nameLen));
  sb.append("Info    Dump    Verb    Version\n");
  for (int i = 0; i < hrLen; i++) sb.append(BOX_H); sb.append("\n");
  sb.append(body);
  for (int i = 0; i < hrLen; i++) sb.append(BOX_H); sb.append("\n");

  m_out = sb.detach();
  return proxy.sendToClient(this);
}
Exemple #30
0
void RichPara::UnpackParts(Stream& in, const RichPara::CharFormat& chrstyle,
                           Array<RichPara::Part>& part, const Array<RichObject>& obj,
                           int& oi) {
	part.Add();
	part.Top().format = format;
	int c;
	while((c = in.Term()) >= 0)
		if(c < 31 && c != 9 && c != FIELD) {
			do
				switch(in.Get()) {
				case BOLD0:
					format.NoBold();
					break;
				case BOLD1:
					format.Bold();
					break;
				case BOLDS:
					format.Bold(chrstyle.IsBold());
					break;
				case ITALIC0:
					format.NoItalic();
					break;
				case ITALIC1:
					format.Italic();
					break;
				case ITALICS:
					format.Italic(chrstyle.IsItalic());
					break;
				case UNDERLINE0:
					format.NoUnderline();
					break;
				case UNDERLINE1:
					format.Underline();
					break;
				case UNDERLINES:
					format.Underline(chrstyle.IsUnderline());
					break;
				case STRIKEOUT0:
					format.NoStrikeout();
					break;
				case STRIKEOUT1:
					format.Strikeout();
					break;
				case STRIKEOUTS:
					format.Strikeout(chrstyle.IsStrikeout());
					break;
				case CAPITALS0:
					format.capitals = false;
					break;
				case CAPITALS1:
					format.capitals = true;
					break;
				case CAPITALSS:
					format.capitals = chrstyle.capitals;
					break;
				case DASHED0:
					format.dashed = false;
					break;
				case DASHED1:
					format.dashed = true;
					break;
				case DASHEDS:
					format.dashed = chrstyle.dashed;
					break;
				case SSCRIPT:
					format.sscript = in.Get();
					if(format.sscript == 3)
						format.sscript = chrstyle.sscript;
					break;
				case FACE:
					c = in.Get16();
					format.Face(c == 0xffff ? chrstyle.GetFace() : c);
					break;
				case HEIGHT:
					c = in.Get16();
					format.Height(c == 0xffff ? chrstyle.GetHeight() : c);
					break;
				case LINK:
					in % format.link;
					break;
				case INDEXENTRY:
					in % format.indexentry;
					break;
				case INK:
					in % format.ink;
					break;
				case PAPER:
					in % format.paper;
					break;
				case LANGUAGE:
					format.language = in.Get32();
					break;
				case EXT:
					switch(in.Get()) {
					case NONAA0:
						format.NonAntiAliased(false);
						break;
					case NONAA1:
						format.NonAntiAliased(true);
						break;
					case NONAAS:
						format.NonAntiAliased(chrstyle.IsNonAntiAliased());
						break;
					}
				}
			while((c = in.Term()) < 31 && c != 9 && c != FIELD && c >= 0);
			if(part.Top().text.GetLength())
				part.Add();
			part.Top().format = format;
		}
		else
		if(in.Term() == FIELD) {
			RichPara::Format pformat = format;
			if(part.Top().text.GetLength()) {
				part.Add();
				part.Top().format = pformat;
			}
			in.Get();
			Part& p = part.Top();
			String id;
			in % id;
			p.field = id;
			in % p.fieldparam;
			String s;
			in % s;
			StringStream sn(s);
			UnpackParts(sn, chrstyle, p.fieldpart, obj, oi);
			part.Add();
			part.Top().format = format = pformat;
		}
		else
		if(in.Term() == OBJECT) {
			if(part.Top().text.GetLength()) {
				part.Add();
				part.Top().format = format;
			}
			part.Top().object = obj[oi++];
			part.Top().format = format;
			part.Add();
			part.Top().format = format;
			in.Get();
		}
		else {
			StringBuffer b;
			b.Reserve(512);
			while(in.Term() >= 32 || in.Term() == 9)
				b.Cat(in.Get());
			part.Top().text.Cat(FromUtf8(~b));
		}
	if(part.Top().text.GetLength() == 0 && part.Top().IsText())
		part.Drop();
}