/** * Индексный оператор * * Ищет первый тег по указанному пути * * если найден, то возвращает для него хелпер * если не найден, то создает все необходимые * промежуточные элементы и возращает хелпер * созданного элемента. */ TagHelper TagHelper::operator [] (const char *path) { XmlTag *cur = tag; XmlTag *child; const char *remain = strchr(path, '/'); while ( remain ) { std::string name(path, remain); child = cur->firstChild(name.c_str()); if ( child == 0 ) { child = new XmlTag(name); cur->insertChildElement(child); } cur = child; path = remain + 1; remain = strchr(path, '/'); } child = tag->firstChild(path); if ( child == 0 ) { child = new XmlTag(path); cur->insertChildElement(child); } return child; }
/** * Найти следующий узел * @param path путь к узлу * @return найденый узел или 0 если узлов больше нет */ XmlTag* XmlTag::findNext(const char *path, XmlTag *from) { const char *remain = strchr(path, '/'); if ( remain == 0 ) return nextChild(path, from); // TODO выделять строку во временном буфере string name(path, remain++); //XmlTag *parent = from->parent; for(XmlTag *child = firstChild(name.c_str()); child; child = nextChild(name.c_str(), child)) { if ( child->hasChild(from) ) { XmlTag *result = child->findNext(remain, from); if ( result ) return result; child = nextChild(name.c_str(), child); for(; child; child = nextChild(name.c_str(), child)) { XmlTag *result = child->find(remain); if ( result ) return result; } return 0; } } return 0; }
XmlErr XmlProfile::XmlStartHandler(char *element, char **attr_names, char **attr_values) { XmlTag *newTag = new XmlTag(element,cTag); func("new tag found %s\n",element); if(cTag) { if(!cTag->addChild(newTag)) error("Can't add new child %s for element %s\n",newTag->name(),cTag->name()); else func("Added new child %s for element %s\n",newTag->name(),cTag->name()); } else { if(!addRootElement(newTag)) error("Can't add new root element\n%s",newTag->name()); else func("Added new root element %s\n",newTag->name()); } cTag = newTag; unsigned int offset = 0; if(attr_names && attr_values) { while(attr_names[offset]!=NULL) { if(!newTag->addAttribute(attr_names[offset],attr_values[offset])) { func("Added new attr %s => %s for element %s\n", attr_names[offset],attr_values[offset],newTag->name()); } else { error("Can't add new attr %s => %s for element %s\n", attr_names[offset],attr_values[offset],newTag->name()); } offset++; } } return XML_NOERR; }
/** * Найти первого потомка по указанному пути */ XmlTag* XmlTag::find(const char *path) { const char *remain = strchr(path, '/'); if ( remain == 0 ) return firstChild(path); // TODO выделять строку во временном буфере string name(path, remain++); for(XmlTag *child = firstChild(name.c_str()); child; child = nextChild(name.c_str(), child)) { XmlTag *result = child->find(remain); if ( result ) return result; } return 0; }
void FeatureEncoder::WriteXML (const KKStr& varName, ostream& o ) const { XmlTag tagStart ("TrainingClassList", XmlTag::TagTypes::tagStart); if (!varName.Empty ()) tagStart.AddAtribute ("VarName", varName); tagStart.WriteXML (o); o << endl; XmlElementInt32::WriteXML (codedNumOfFeatures, "CodedNumOfFeatures", o); XmlElementDouble::WriteXML (c_Param, "c_Param", o); XmlElementInt32::WriteXML (numEncodedFeatures, "NumEncodedFeatures", o); XmlElementInt32::WriteXML (numOfFeatures, "NumOfFeatures", o); XmlElementInt32::WriteXML (xSpaceNeededPerExample, "xSpaceNeededPerExample", o); if (cardinalityDest) XmlElementArrayInt32::WriteXML (numOfFeatures, cardinalityDest, "CardinalityDest", o); if (class1) class1->Name ().WriteXML ("Class1", o); if (class2) class2->Name ().WriteXML ("Class2", o); if (destFeatureNums) XmlElementArrayInt32::WriteXML (numOfFeatures, destFeatureNums, "DestFeatureNums", o); if (fileDesc) fileDesc->WriteXML ("FileDesc", o); if (destFileDesc) destFileDesc->WriteXML ("DestFileDesc", o); if (destWhatToDo) { VectorInt32 v; for (kkint32 x = 0; x < numOfFeatures; ++x) v.push_back ((kkint32)(destWhatToDo[x])); XmlElementVectorInt32::WriteXML (v, "DestWhatToDo", o); } EncodingMethodToStr (encodingMethod).WriteXML ("EncodingMethod", o); selectedFeatures.WriteXML ("selectedFeatures", o); if (srcFeatureNums) XmlElementArrayInt32::WriteXML (numOfFeatures, srcFeatureNums, "SrcFeatureNums", o); XmlTag tagEnd ("TrainingClassList", XmlTag::TagTypes::tagEnd); tagEnd.WriteXML (o); o << endl; }
void ModelUsfCasCor::WriteXML (const KKStr& varName, ostream& o ) const { XmlTag startTag ("ModelUsfCasCor", XmlTag::TagTypes::tagStart); if (!varName.Empty ()) startTag.AddAtribute ("VarName", varName); startTag.WriteXML (o); o << endl; WriteModelXMLFields (o); // Write the base class data fields 1st. usfCasCorClassifier->WriteXML ("UsfCasCorClassifier", o); XmlTag endTag ("ModelUsfCasCor", XmlTag::TagTypes::tagEnd); endTag.WriteXML (o); o << endl; } /* WriteXML */
void ModelParamUsfCasCor::WriteXML (const KKStr& varName, ostream& o ) const { XmlTag startTag ("ModelParamUsfCasCor", XmlTag::TagTypes::tagStart); if (!varName.Empty ()) startTag.AddAtribute ("VarName", varName); startTag.WriteXML (o); o << endl; WriteXMLFields (o); XmlElementInt32::WriteXML (in_limit, "in_limit", o); XmlElementInt32::WriteXML (number_of_rounds, "number_of_rounds", o); XmlElementInt32::WriteXML (number_of_trials, "number_of_trials", o); XmlElementInt64::WriteXML (random_seed, "random_seed", o); XmlElementBool::WriteXML (useCache, "useCache", o); XmlTag endTag ("ModelParamUsfCasCor", XmlTag::TagTypes::tagEnd); endTag.WriteXML (o); o << endl; } /* WriteXML */
void Component::handleStanza(Stanza *stanza) { if(strcmp(stanza->name(), "message") == 0) { if(message_handler) { message_handler->handleMessage(stanza); } else { std::cerr << " [JCE] Got a message, but have no handler for it.\n"; } } if(strcmp(stanza->name(), "presence") == 0) { if(presence_handler) { presence_handler->handlePresence(stanza); } else { std::cerr << " [JCE] Got a presence, but have no handler for it.\n"; } } if(strcmp(stanza->name(), "stream:error") == 0) { if(stream_error_handler) { stream_error_handler->handleStreamError(); } else { std::cerr << " [JCE] Got a stream error, but have no handler for it.\n"; } } if(strcmp(stanza->name(), "handshake") == 0) { if(auth_success_handler) { auth_success_handler->handleHandshake(); } else { std::cerr << " [JCE] Got a successful handshake, but have no handler for it.\n"; } } if(strcmp(stanza->name(), "iq") == 0) { XmlTag *query = stanza->query(); if(query) { const char *query_xmlns = query->getAttribute("xmlns"); } } delete stanza; }
void FeatureNumList::WriteXML (const KKStr& varName, ostream& o ) const { XmlTag startTag ("FeatureNumList", XmlTag::TagTypes::tagStart); if (!varName.Empty ()) startTag.AddAtribute ("VarName", varName); startTag.AddAtribute ("MaxFeatureNum", maxFeatureNum); startTag.AddAtribute ("NumOfFeatures", numOfFeatures); startTag.WriteXML (o); o << ToString (); XmlTag endTag ("FeatureNumList", XmlTag::TagTypes::tagEnd); endTag.WriteXML (o); o << endl; }
int main(int argc, const char **argv) { // Конфигурация ConfigFile *config = new ConfigFile(PATH_CONFIG); // открыть лог файлы до смены пользователя open_access_log(PATH_ACCESS_LOG); open_error_log(PATH_ERROR_LOG); FILE *fpid = fopen(PATH_PID, "w"); // установить лимиты до смены пользователя if ( getuid() == 0 ) { struct rlimit rl; rl.rlim_cur = config->filesLimit(); rl.rlim_max = config->filesLimit(); if ( setrlimit(RLIMIT_NOFILE, &rl) == -1 ) { fprintf(stderr, "setrlimit fault: %s\n", strerror(errno)); } } else { struct rlimit rl; if ( getrlimit(RLIMIT_NOFILE, &rl) == -1 ) { fprintf(stderr, "getrlimit fault: %s\n", strerror(errno)); } else { rl.rlim_cur = config->filesLimit(); if ( config->filesLimit() > rl.rlim_max ) { fprintf(stderr, "only root can increase over hard limit (RLIMIT_NOFILE)\ntry to increase up to hard limit (%lu)\n", rl.rlim_max); rl.rlim_cur = rl.rlim_max; } if ( setrlimit(RLIMIT_NOFILE, &rl) == -1 ) { fprintf(stderr, "setrlimit fault: %s\n", strerror(errno)); } } } // если запущены под root, то сменить пользователя if ( getuid() == 0 ) { fprintf(stdout, "Trying to switch to user: "******"\n"); struct passwd *pw = getpwnam(config->user()); if(pw) { if(setgid(pw->pw_gid) != 0) fprintf(stderr, "Failed to setgid!\n"); if(setuid(pw->pw_uid) != 0 ) fprintf(stderr, "Failed to setuid!\n"); } else { fprintf(stderr, "user %s not found\n", config->user()); } } if ( argc > 1 && strcmp(argv[1], "-d") == 0 ) { printf("try fork\n"); pid_t parpid; if((parpid = fork()) < 0) { mawarError("Failed to fork!", 99); } else if(parpid != 0) { exit(0); // успешно создан дочерний процесс, основной можно завершить } setsid(); } // после форка записать pid if ( fpid ) { fprintf(fpid, "%d", getpid()); fclose(fpid); fpid = 0; } // демон управляющий воркерами вводом-выводом struct rlimit rl; if ( getrlimit(RLIMIT_NOFILE, &rl) == -1 ) { fprintf(stderr, "getrlimit fault: %s\n", strerror(errno)); return 1; } printf("files limit: %lu\n", rl.rlim_cur); NetDaemon daemon(rl.rlim_cur, config->getOutputBuffers()); // устанавливаем скорректированное число воркеров daemon.setWorkerCount(config->workers() - 1); // XMPP-сервер server = new XMPPServer(&daemon); server->config = config; // подключемся к c2s-порту из конфига server->bind(config->c2s()); // не более 10 ожидающих соединений server->listen(10); // добавляем виртуальные хосты printf("[main] loading virtual hosts\n"); for(XmlTag *vhost = config->firstHost(); vhost; vhost = config->nextHost(vhost)) { printf("[main] load vhost: %s\n", vhost->getAttribute("name").c_str()); server->addHost(vhost->getAttribute("name"), vhost); } printf("[main] virtual hosts loaded\n"); // асинхронный резолвер nanosoft::ptr<AsyncDNS> dns = new AsyncDNS(&daemon); daemon.addObject(dns); server->adns = dns; // добавляем сервер в демона daemon.addObject(server); int port = config->xep0114(); if ( port > 0 ) { nanosoft::ptr<XEP0114Listener> xep0114 = new XEP0114Listener(server.getObject()); xep0114->bind(port); xep0114->listen(10); daemon.addObject(xep0114); } port = config->s2s(); if ( port > 0 ) { server->s2s = new S2SListener(server.getObject()); server->s2s->bind(port); server->s2s->listen(10); daemon.addObject(server->s2s); } string path = config->status(); if ( path != "" ) { nanosoft::ptr<ServerStatus> status = new ServerStatus(server.getObject()); status->bind(path.c_str()); status->listen(1); daemon.addObject(status); } // консоль управления сервером //MyConsole console(&daemon, 0); //daemon.addObject(&console); struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = on_signal; sigaction(SIGTERM, &sa, 0); sigaction(SIGHUP, &sa, 0); sigaction(SIGINT, &sa, 0); // запускаем демона fprintf(stderr, "[main] run daemon\n"); daemon.run(); fprintf(stderr, "[main] daemon exited\n"); cleanup(); return 0; }