bool SRAssembler::read_library_file() { ifstream lib_file(this->library_file.c_str()); string line; Library* lib = NULL; while (getline(lib_file, line)){ line = trim(line); if (line == "[LIBRARY]") { if (lib != NULL){ if (lib->get_left_read() == ""){ print_message("r1 file is expected in config file!"); return false; } this->libraries.push_back(*lib); } lib = new Library(this->libraries.size(), this->data_dir, this->tmp_dir, this->logger); } else { vector<string> tokens; tokenize(line, tokens, "="); if (tokens.size() == 2){ string param = trim(tokens[0]); string value = trim(tokens[1]); if (param == "r1" && lib != NULL) { lib->set_left_read(value); if (!file_exists(lib->get_left_read())) { print_message("r1 file in config file: " + lib->get_left_read() + " does not exist!"); return false; } } if (param == "r2" && lib != NULL) { lib->set_right_read(value); if (!file_exists(lib->get_right_read())) { print_message("r2 file in config file: " + lib->get_right_read() + " does not exist!"); return false; } lib->set_paired_end(true); } if (param == "insert_size" && lib != NULL) { lib->set_insert_size(str2int(value)); } if (param == "direction" && lib != NULL) { lib->set_reversed(str2int(value)); } if (param == "format" && lib != NULL) { if (value == "fastq") { lib->set_format(FORMAT_FASTQ); } else if (value == "fasta") { lib->set_format(FORMAT_FASTA); } else { print_message("format in config file should be 'fastq' or 'fasta'!"); return false; } } } } } if (lib != NULL){ if (lib->get_left_read() == ""){ print_message("r1 file is expected in config file!"); return false; } this->libraries.push_back(*lib); } if (this->libraries.size() == 0){ print_message(" No [LIBRARY] section found in config file!"); return false; } return true; }
int main() { int choice; Library myLibrary; cout << "Welcome to the Library Simulator!" << endl; //MENU //every option corresponds to a Library class member function //some require input before the function can be called //It is all very self-documenting do { cout << " Please make your choice: " << endl; cout << " [1] ADD BOOK" << endl; cout << " [2] ADD PATRON" << endl; cout << " [3] CHECK OUT BOOK" << endl; cout << " [4] RETURN BOOK" << endl; cout << " [5] REQUEST BOOK" << endl; cout << " [6] INCREASE DATE" << endl; cout << " [7] PAY FINE" << endl; cout << " [8] VIEW PATRON INFO" << endl; cout << " [9] VIEW BOOK INFO" << endl; cout << " [0] QUIT" << endl; cin >> choice; cin.ignore(); if(choice == 1) { myLibrary.addBook(); } else if(choice == 2) { myLibrary.addMember(); } else if(choice == 3) { string tempPatron, tempBook; cout << "Please enter the ID for the Patron." << endl; getline(cin, tempPatron); cout << "Please enter the ID for the Book." << endl; getline(cin, tempBook); myLibrary.checkOutBook(tempPatron, tempBook); } else if(choice == 4) { string tempBook; cout << "Please enter to Book ID that you wish to return: "; getline(cin, tempBook); myLibrary.returnBook(tempBook); } else if(choice == 5) { string tempPatron, tempBook; cout << "Please enter the ID for the Patron." << endl; getline(cin, tempPatron); cout << "Please enter the ID for the Book." << endl; getline(cin, tempBook); myLibrary.requestBook(tempPatron, tempBook); } else if(choice == 6) { myLibrary.incrementCurrentDate(); } else if(choice == 7) { string tempPatron; double tempPayment; cout << "Please enter the ID for the Patron." << endl; getline(cin, tempPatron); cout << "How much to pay? "; cin >> tempPayment; cin.ignore(); myLibrary.payFine(tempPatron, tempPayment); } else if(choice == 8) { string tempPatron; cout << "Please enter the ID of the Patron you wish to view: "; getline(cin, tempPatron); myLibrary.viewPatronInfo(tempPatron); } else if(choice == 9) { string tempBook; cout << "Please enter the ID of the Book you wish to view: "; getline(cin, tempBook); myLibrary.viewBookInfo(tempBook); } }
void container() const { const char xmldata[] = "<?xml version=\"1.0\"?>\n" "<def>\n" " <container id=\"A\" startPattern=\"std :: A <\" endPattern=\"> !!::\">\n" " <type templateParameter=\"1\"/>\n" " <size templateParameter=\"4\">\n" " <function name=\"resize\" action=\"resize\"/>\n" " <function name=\"clear\" action=\"clear\"/>\n" " <function name=\"size\" yields=\"size\"/>\n" " <function name=\"empty\" yields=\"empty\"/>\n" " <function name=\"push_back\" action=\"push\"/>\n" " <function name=\"pop_back\" action=\"pop\"/>\n" " </size>\n" " <access>\n" " <function name=\"at\" yields=\"at_index\"/>\n" " <function name=\"begin\" yields=\"start-iterator\"/>\n" " <function name=\"end\" yields=\"end-iterator\"/>\n" " <function name=\"data\" yields=\"buffer\"/>\n" " <function name=\"c_str\" yields=\"buffer-nt\"/>\n" " <function name=\"front\" yields=\"item\"/>\n" " <function name=\"find\" action=\"find\"/>\n" " </access>\n" " </container>\n" " <container id=\"B\" startPattern=\"std :: B <\" inherits=\"A\">\n" " <size templateParameter=\"3\"/>\n" // Inherits all but templateParameter " </container>\n" " <container id=\"C\">\n" " <type string=\"std-like\"/>\n" " <access indexOperator=\"array-like\"/>\n" " </container>\n" "</def>"; tinyxml2::XMLDocument doc; doc.Parse(xmldata, sizeof(xmldata)); Library library; library.load(doc); Library::Container& A = library.containers["A"]; Library::Container& B = library.containers["B"]; Library::Container& C = library.containers["C"]; ASSERT_EQUALS(A.type_templateArgNo, 1); ASSERT_EQUALS(A.size_templateArgNo, 4); ASSERT_EQUALS(A.startPattern, "std :: A <"); ASSERT_EQUALS(A.endPattern, "> !!::"); ASSERT_EQUALS(A.stdStringLike, false); ASSERT_EQUALS(A.arrayLike_indexOp, false); ASSERT_EQUALS(Library::Container::SIZE, A.getYield("size")); ASSERT_EQUALS(Library::Container::EMPTY, A.getYield("empty")); ASSERT_EQUALS(Library::Container::AT_INDEX, A.getYield("at")); ASSERT_EQUALS(Library::Container::START_ITERATOR, A.getYield("begin")); ASSERT_EQUALS(Library::Container::END_ITERATOR, A.getYield("end")); ASSERT_EQUALS(Library::Container::BUFFER, A.getYield("data")); ASSERT_EQUALS(Library::Container::BUFFER_NT, A.getYield("c_str")); ASSERT_EQUALS(Library::Container::ITEM, A.getYield("front")); ASSERT_EQUALS(Library::Container::NO_YIELD, A.getYield("foo")); ASSERT_EQUALS(Library::Container::RESIZE, A.getAction("resize")); ASSERT_EQUALS(Library::Container::CLEAR, A.getAction("clear")); ASSERT_EQUALS(Library::Container::PUSH, A.getAction("push_back")); ASSERT_EQUALS(Library::Container::POP, A.getAction("pop_back")); ASSERT_EQUALS(Library::Container::FIND, A.getAction("find")); ASSERT_EQUALS(Library::Container::NO_ACTION, A.getAction("foo")); ASSERT_EQUALS(B.type_templateArgNo, 1); ASSERT_EQUALS(B.size_templateArgNo, 3); ASSERT_EQUALS(B.startPattern, "std :: B <"); ASSERT_EQUALS(B.endPattern, "> !!::"); ASSERT_EQUALS(B.functions.size(), A.functions.size()); ASSERT(C.functions.empty()); ASSERT_EQUALS(C.type_templateArgNo, -1); ASSERT_EQUALS(C.size_templateArgNo, -1); ASSERT_EQUALS(C.stdStringLike, true); ASSERT_EQUALS(C.arrayLike_indexOp, true); }
virtual void setUp() { init = new Library; init->video().timer(); reached_callback = a = b = c = false; }
int main(){ Library myLib; int iChoice; char cChoice; string temp1, temp2; double tempDouble; do{ displayMenu(); iChoice = getChoice(); switch (iChoice){ case 0: //Quit break; case 1: //Add a book myLib.addBook(); break; case 2: //Add a member myLib.addMember(); break; case 3: //Check out a Book checkOutBook(myLib); cin.get(); break; case 4: //Return a Book std::cout << "What is the ID code of the book? "; std::getline(std::cin, temp1); myLib.returnBook(temp1); cin.get(); break; case 5: //Request a Book cout << "What is the member's ID number? "; getline(cin, temp1); cout << "What is the ID code of the book? "; getline(cin, temp2); myLib.requestBook(temp1,temp2); cin.get(); break; case 6: //Pay a Fine cout << "What is the member's ID number? "; getline(cin, temp1); cout << "How much would they like to pay? "; cin >> tempDouble; cin.get(); myLib.payFine(temp1,tempDouble); cin.get(); break; case 7: //Increment Date cout << "Current Date: " << myLib.getCurrentDate() << endl; cout << "Would you like to increment? (\'y\'/\'n\') "; cin >> cChoice; clearBuffer(); if (cChoice == 'y') myLib.incrementCurrentDate(); else cout << "Date not incremented." << endl; cin.get(); break; case 8: //View Member Information cout << "What is the member's ID number? "; getline(cin,temp1); myLib.viewPatronInfo(temp1); cin.get(); break; case 9: //View Book Information cout << "What is the book's ID code? "; getline(cin,temp1); myLib.viewBookInfo(temp1); cin.get(); break; } }while (iChoice > 0 && iChoice <= 9); return 0; }
BOOL LibraryFile::AddSpecificIndex(SuperGallery *ParentGal, PathName *Path, SGLibType Type, StringBase *Description, UINT32 bModified, BOOL bIsWebLib) { if(ParentGal == NULL || Path == NULL || !Libraries.IsEmpty() || !Path->IsValid()) { ERROR3("LibraryFile::AddSpecificIndex - Problems on entry"); return FALSE; } // Check the path for the library exists // if(!SGLibOil::FileExists(Path)) // return FALSE; // Remember the pathname and type MyPath = *Path; MyType = Type; ParentGallery = ParentGal; // Create the sub lib Library *NewSubLib = new Library; if (NewSubLib != NULL) { // Path = "C:\testlib\animals\xarainfo\animals.txt" // Path of files themselves... FilesPath = "C:\testlib\animals" NewSubLib->m_bIsWebLib = bIsWebLib; PathName TmpPath(Path->GetLocation(FALSE)); NewSubLib->SetModified(bModified); // If it's a root directory we need the slash... PathName FilesPath; String_256 TmpRootCheck(TmpPath.GetLocation(TRUE)); if(SGLibOil::IsRootDirectory(&TmpRootCheck)) FilesPath.SetPathName(TmpPath.GetLocation(TRUE)); else FilesPath.SetPathName(TmpPath.GetLocation(FALSE)); // Default title for the new group String_256 Desc256; String_64 Desc64; if(Description == NULL) Desc256 = Path->GetTruncatedPath(60); else Desc256 = *Description; Desc256.Left(&Desc64, 64); // The filename of the index String_64 IndexFilename(Path->GetFileName(TRUE)); // Add this new index to the library file and scan it in... if(NewSubLib->Init(ParentGal, &FilesPath, &Desc64, &IndexFilename, Type, FALSE, (Description != NULL))) { Libraries.AddTail(NewSubLib); // Keep track of libraries added for redraw purposes... AddNewFolderToScrollRedrawSystem(NewSubLib); return TRUE; } else { // if there was a problem, don't go round leaving memory everywhere... delete NewSubLib; NewSubLib = NULL; } } // Nothing added return FALSE; }
void SoMuchEvil(OnionEncryptor &oe) { int count = Random::GetInstance().GetInt(10, 20); int changed0 = Random::GetInstance().GetInt(0, count - 5); int changed1 = Random::GetInstance().GetInt(changed0 + 1, count + 1); int mchanged0 = Random::GetInstance().GetInt(0, count); int mchanged1 = Random::GetInstance().GetInt(0, count); Library *lib = CryptoFactory::GetInstance().GetLibrary(); QVector<QSharedPointer<AsymmetricKey> > private_keys; QVector<QSharedPointer<AsymmetricKey> > public_keys; for(int idx = 0; idx < count; idx++) { private_keys.append(QSharedPointer<AsymmetricKey>(lib->CreatePrivateKey())); public_keys.append(QSharedPointer<AsymmetricKey>(private_keys.last()->GetPublicKey())); } QVector<QByteArray> cleartexts; QVector<QByteArray> ciphertexts; QScopedPointer<Random> rand(lib->GetRandomNumberGenerator()); for(int idx = 0; idx < count; idx++) { QByteArray cleartext(1500, 0); rand->GenerateBlock(cleartext); QByteArray ciphertext; EXPECT_EQ(oe.Encrypt(public_keys, cleartext, ciphertext, 0), -1); cleartexts.append(cleartext); ciphertexts.append(ciphertext); } QVector<QVector<QByteArray> > onions(count + 1); onions.last() = ciphertexts; // Find first evil peer for(int idx = count - 1; idx >= changed1; idx--) { EXPECT_TRUE(oe.Decrypt(private_keys[idx], onions[idx + 1], onions[idx], 0)); oe.RandomizeBlocks(onions[idx]); } QVector<QSharedPointer<AsymmetricKey> > swap_keys(public_keys); swap_keys.resize(changed1); QByteArray cleartext(1500, 0); rand->GenerateBlock(cleartext); EXPECT_EQ(oe.Encrypt(swap_keys, cleartext, onions[changed1][mchanged1], 0), -1); // Find second evil peer for(int idx = changed1 - 1; idx >= changed0; idx--) { EXPECT_TRUE(oe.Decrypt(private_keys[idx], onions[idx + 1], onions[idx], 0)); oe.RandomizeBlocks(onions[idx]); } swap_keys.resize(changed0); rand->GenerateBlock(cleartext); EXPECT_EQ(oe.Encrypt(swap_keys, cleartext, onions[changed0][mchanged0], 0), -1); for(int idx = changed0 - 1; idx >= 0; idx--) { EXPECT_TRUE(oe.Decrypt(private_keys[idx], onions[idx + 1], onions[idx], 0)); oe.RandomizeBlocks(onions[idx]); } QBitArray bad; EXPECT_FALSE(oe.VerifyAll(private_keys, onions, bad)); int good_count = 0; int bad_count = 0; for(int idx = 0; idx < count; idx++) { if(idx == changed0 || idx == changed1) { EXPECT_TRUE(bad[idx]); } else { EXPECT_FALSE(bad[idx]); } onions.first().contains(cleartexts[idx]) ? good_count++ : bad_count++; } EXPECT_TRUE(good_count >= count - 2); EXPECT_TRUE(good_count < count); EXPECT_TRUE(bad_count > 0); EXPECT_TRUE(bad_count <= 2); }
void RoundTest_PeerDisconnectMiddle(CreateSessionCallback callback, CreateGroupGenerator cgg) { Timer::GetInstance().UseVirtualTime(); int count = Random::GetInstance().GetInt(TEST_RANGE_MIN, TEST_RANGE_MAX); int leader = Random::GetInstance().GetInt(0, count); int sender = Random::GetInstance().GetInt(0, count); int disconnecter = Random::GetInstance().GetInt(0, count); QVector<TestNode *> nodes; Group *group; ConstructOverlay(count, nodes, group); for(int idx = 0; idx < count; idx++) { for(int jdx = 0; jdx < count; jdx++) { if(idx == jdx) { continue; } EXPECT_TRUE(nodes[idx]->cm.GetConnectionTable().GetConnection(nodes[jdx]->cm.GetId())); } } for(int idx = 0; idx < count; idx++) { EXPECT_TRUE(nodes[idx]->sink.Count() == 0); } Id leader_id = nodes[leader]->cm.GetId(); Id session_id; CreateSessions(nodes, *group, leader_id, session_id, callback, cgg); Library *lib = CryptoFactory::GetInstance().GetLibrary(); QScopedPointer<Dissent::Utils::Random> rand(lib->GetRandomNumberGenerator()); QByteArray msg(512, 0); rand->GenerateBlock(msg); nodes[sender]->session->Send(msg); for(int idx = 0; idx < count; idx++) { nodes[idx]->session->Start(); } TestNode::calledback = 0; qint64 next = Timer::GetInstance().VirtualRun(); // XXX This needs to be improved, but what we are doing is issuing a // disconnect approximately 1 to count steps into the Round qint64 run_before_disc = Time::GetInstance().MSecsSinceEpoch() + Random::GetInstance().GetInt(10, 10 * count); while(next != -1 && TestNode::calledback < count && Time::GetInstance().MSecsSinceEpoch() < run_before_disc) { Time::GetInstance().IncrementVirtualClock(next); next = Timer::GetInstance().VirtualRun(); } if(Time::GetInstance().MSecsSinceEpoch() >= run_before_disc) { nodes[disconnecter]->cm.Disconnect(); } while(next != -1 && TestNode::calledback < count) { Time::GetInstance().IncrementVirtualClock(next); next = Timer::GetInstance().VirtualRun(); } if(Time::GetInstance().MSecsSinceEpoch() < run_before_disc) { std::cout << "RoundTest_PeerDisconnectMiddle never caused a disconnect, " "consider rerunning." << std::endl; for(int idx = 0; idx < count; idx++) { EXPECT_EQ(msg, nodes[idx]->sink.Last().first); } } else { foreach(TestNode *node, nodes) { EXPECT_TRUE(node->session->Stopped()); } }
/** This method exists only to allow the TraverseExtFuncLibrary function to make callbacks to the Library class from C. @NOTE there might be issues with C/C++ linking here? */ void Library::extMethodTraverse(void *a1, void *a2){ Library *self = (Library *)a2; self->appendToExtMethodVector(a1); }
void RoundTest_MultiRound(CreateSessionCallback callback, CreateGroupGenerator cgg) { Timer::GetInstance().UseVirtualTime(); int count = Random::GetInstance().GetInt(TEST_RANGE_MIN, TEST_RANGE_MAX); int leader = Random::GetInstance().GetInt(0, count); int sender0 = Random::GetInstance().GetInt(0, count); int sender1 = Random::GetInstance().GetInt(0, count); while(sender0 != sender1) { sender1 = Random::GetInstance().GetInt(0, count); } QVector<TestNode *> nodes; Group *group; ConstructOverlay(count, nodes, group); Id leader_id = nodes[leader]->cm.GetId(); Id session_id; CreateSessions(nodes, *group, leader_id, session_id, callback, cgg); Library *lib = CryptoFactory::GetInstance().GetLibrary(); QScopedPointer<Dissent::Utils::Random> rand(lib->GetRandomNumberGenerator()); QByteArray msg(512, 0); rand->GenerateBlock(msg); nodes[sender0]->session->Send(msg); SignalCounter sc; for(int idx = 0; idx < count; idx++) { QObject::connect(&nodes[idx]->sink, SIGNAL(DataReceived()), &sc, SLOT(Counter())); nodes[idx]->session->Start(); } TestNode::calledback = 0; qint64 next = Timer::GetInstance().VirtualRun(); while(next != -1 && sc.GetCount() < count && TestNode::calledback < count) { Time::GetInstance().IncrementVirtualClock(next); next = Timer::GetInstance().VirtualRun(); } sc.Reset(); for(int idx = 0; idx < count; idx++) { EXPECT_EQ(msg, nodes[idx]->sink.Last().first); } rand->GenerateBlock(msg); nodes[sender1]->session->Send(msg); TestNode::calledback = 0; next = Timer::GetInstance().VirtualRun(); while(next != -1 && sc.GetCount() < count && TestNode::calledback < count * 2) { Time::GetInstance().IncrementVirtualClock(next); next = Timer::GetInstance().VirtualRun(); } for(int idx = 0; idx < count; idx++) { EXPECT_EQ(msg, nodes[idx]->sink.Last().first); } CleanUp(nodes); delete group; }
void RoundTest_PeerDisconnectEnd(CreateSessionCallback callback, CreateGroupGenerator cgg) { Timer::GetInstance().UseVirtualTime(); int count = Random::GetInstance().GetInt(TEST_RANGE_MIN, TEST_RANGE_MAX); int leader = Random::GetInstance().GetInt(0, count); int disconnecter = Random::GetInstance().GetInt(0, count); while(leader != disconnecter) { disconnecter = Random::GetInstance().GetInt(0, count); } QVector<TestNode *> nodes; Group *group; ConstructOverlay(count, nodes, group); Id leader_id = nodes[leader]->cm.GetId(); Id session_id; CreateSessions(nodes, *group, leader_id, session_id, callback, cgg); for(int idx = 0; idx < count; idx++) { nodes[idx]->session->Start(); } TestNode::calledback = 0; qint64 next = Timer::GetInstance().VirtualRun(); while(next != -1 && TestNode::calledback < count) { Time::GetInstance().IncrementVirtualClock(next); next = Timer::GetInstance().VirtualRun(); } nodes[disconnecter]->session->Stop(); nodes[disconnecter]->cm.Disconnect(); EXPECT_TRUE(nodes[disconnecter]->session->Stopped()); TestNode::calledback = 0; next = Timer::GetInstance().VirtualRun(); while(next != -1 && TestNode::calledback < count) { Time::GetInstance().IncrementVirtualClock(next); next = Timer::GetInstance().VirtualRun(); } Library *lib = CryptoFactory::GetInstance().GetLibrary(); QScopedPointer<Dissent::Utils::Random> rand(lib->GetRandomNumberGenerator()); QByteArray msg(512, 0); rand->GenerateBlock(msg); nodes[(leader + disconnecter) % count]->session->Send(msg); TestNode::calledback = 0; next = Timer::GetInstance().VirtualRun(); while(next != -1 && TestNode::calledback < count) { Time::GetInstance().IncrementVirtualClock(next); next = Timer::GetInstance().VirtualRun(); } for(int idx = 0; idx < count; idx++) { EXPECT_TRUE(nodes[idx]->sink.Count() == 0); EXPECT_TRUE(nodes[idx]->session->Stopped()); } delete nodes[disconnecter]; nodes.remove(disconnecter); CleanUp(nodes); delete group; }
void Text::onDraw(const ParentDrawInfo& pdi, IDrawer& render) { Library* lib = getLibrary(); if(!lib) return; Bound absChildBound; Bound b = childBound(); b.min = b.min * pdi.scale + pdi.offset; b.max = b.max * pdi.scale + pdi.offset; if(!pdi.bound.intersection(absChildBound, b)) return; Font* fnt = lib->getFont(font); if(!fnt) return; int settedTex = -1; UnicodeReader ur(text); Vector locsize = childBound().size(); Vector locpos(Scalar(0), locsize.y - (fnt->characterHeight() + Scalar(0.5)) * fontScale); while(!ur.empty()) { uint firstChar = ur.getFirst(); if(firstChar == '\n'){ locpos.y -= fnt->characterHeight() * fontScale; locpos.x = 0; ur.str = ur.str.afterLeftTrim(1); continue; } if(firstChar == '\r'){ locpos.x = 0; ur.str = ur.str.afterLeftTrim(1); continue; } if(isSpace(firstChar)){ const Font::CharInfo* ci = fnt->charInfo(firstChar); if(ci) locpos.x += fontScale * ci->width() * fnt->characterHeight() / ci->fontHeight; ur.str = ur.str.afterLeftTrim(1); continue; } const utf8* wordFirst = ur.str.first(); const utf8* wordEnd = ur.str.first(); while(!ur.empty()) { ConstString prev = ur.str; if(isSpace(ur.pop())){ ur.str = prev; break; } wordEnd = ur.str.first(); } if(wrapping) { uint wordLenght = fnt->stringLineLenght(ConstString(wordFirst, wordEnd)); if(locpos.x + (Scalar(wordLenght) - Scalar(0.5)) * fontScale > locsize.x && Scalar(wordLenght) * fontScale <= locsize.x){ locpos.y -= fnt->characterHeight() * fontScale; locpos.x = 0; } } UnicodeReader u(ConstString(wordFirst, wordEnd)); uint prevChar = 0; while(!u.empty()) { uint ch = u.pop(); const Font::CharInfo* ci = fnt->charInfo(ch); if(!ci) continue; Scalar scale = fontScale * fnt->characterHeight() / ci->fontHeight; const Font::ImageInfo& imgInfo = fnt->imageInfo(ci->image); locpos.x += Scalar(fnt->charactersKerning(prevChar, ch)) * scale; Vector p = position + locpos + Vector((Scalar)ci->dx - Scalar(0.5), (Scalar)ci->dy - Scalar(0.5)) * scale; Vector s((ci->du + 1) * scale, (ci->dv + 1) * scale); Bound v; v.min = p * pdi.scale + pdi.offset; v.max = (p + s) * pdi.scale + pdi.offset; Bound t(Scalar(ci->u) - Scalar(0.5), Scalar(ci->v) - Scalar(0.5), Scalar(ci->u + ci->du) + Scalar(0.5), Scalar(ci->v + ci->dv) + Scalar(0.5)); t.min *= imgInfo.invSize; t.max *= imgInfo.invSize; Bound clipedV, clipedT; if(clip(clipedV, clipedT, absChildBound, v, t)) { if(ci->image != settedTex){ render.setTexture(imgInfo.name); settedTex = ci->image; } Vector s = clipedV.size(); clipedV.min.x = floor(clipedV.min.x / scale) * scale + Scalar(0.5) * scale; clipedV.min.y = floor(clipedV.min.y / scale) * scale + Scalar(0.5) * scale; s.x = floor(Scalar(s.x / scale) + Scalar(0.5)) * scale; s.y = floor(Scalar(s.y / scale) + Scalar(0.5)) * scale; clipedV.max = clipedV.min + s; if((shadowShift.x || shadowShift.y) && shadowColor.w) { Scalar shiftX = fontScale * fnt->characterHeight(); Bound v_Sh; v_Sh.min = v.min + shadowShift * shiftX * pdi.scale; v_Sh.max = v.max + shadowShift * shiftX * pdi.scale; Bound clipedV_Sh, clipedT_Sh; if(clip(clipedV_Sh, clipedT_Sh, absChildBound, v_Sh, t)) { render.drawFontQuad(clipedV_Sh.min, clipedV_Sh.max, clipedT_Sh.min, clipedT_Sh.max, shadowColor, ci->channel, ci->bit, imgInfo.bitCompressedLenght); } } render.drawFontQuad(clipedV.min, clipedV.max, clipedT.min, clipedT.max, color, ci->channel, ci->bit, imgInfo.bitCompressedLenght); } locpos.x += Scalar(ci->width()) * scale; prevChar = ch; } } }
void Text::updateLayout_FromParent(const Bound& parentBound) { Widget::updateLayout_FromParent(parentBound); if((autoSizeX | autoSizeY | autoFontScaleByX | autoFontScaleByY) == 0 || wrapping) return; Library* lib = getLibrary(); if(!lib) return; Font* fnt = lib->getFont(font); if(!fnt) return; screen->lenghts.tmpSet(parentBound.size()); Vector maxSize(screen->lenghts.lenghts[maxSizeXType].x * maxSizeX, screen->lenghts.lenghts[maxSizeXType].y * maxSizeY); Vector marginLow, marginHi; margin.getLowAndHi(marginLow, marginHi, parentBound.size(), screen->lenghts); maxSize -= marginLow + marginHi; Vector2i stringSize = fnt->stringSize(text); stringSize.x += 2; stringSize.y += 2; Scalar maxFontScaleByX = -1; if(autoFontScaleByX) { if(autoSizeX && maxSizeXType) maxFontScaleByX = maxSize.x / Scalar(stringSize.x); else maxFontScaleByX = size.x / Scalar(stringSize.x); } Scalar maxFontScaleByY = -1; if(autoFontScaleByY) { uint h = autoFontScaleByYConsiderateNewLines ? stringSize.y : fnt->characterHeight(); if(autoSizeY && maxSizeYType) maxFontScaleByY = maxSize.y / Scalar(h); else maxFontScaleByY = size.y / Scalar(h); } if(maxFontScaleByX > 0) { if(maxFontScaleByY > 0) fontScale = min(maxFontScaleByX, maxFontScaleByY); else fontScale = maxFontScaleByX; } else if(maxFontScaleByY > 0) { fontScale = maxFontScaleByY; } if(autoSizeX) { if(maxSizeXType) size.x = min(stringSize.x * fontScale, maxSize.x); else size.x = stringSize.x * fontScale; } if(autoSizeY) { if(maxSizeYType) size.y = min(stringSize.y * fontScale, maxSize.y); else size.y = stringSize.y * fontScale; } Widget::updateLayout_FromParent(parentBound); }
void SRAssembler::do_preprocessing(int lib_idx, int file_part){ Library lib = this->libraries[lib_idx]; logger->info("preprocessing lib " + int2str(lib_idx + 1) + ", reads file (" + int2str(file_part) + "/" + int2str(lib.get_num_parts()) + ")"); char suffixc[3]; suffixc[0] = (char)(((file_part-1) / 26) + 97); suffixc[1] = (char)(((file_part-1) % 26) + 97); suffixc[2] = '\0'; string suffix(suffixc); string left_src_read = lib.get_prefix_split_src_file(lib.get_left_read()) + suffix; string right_src_read = ""; if (lib.get_paired_end()) right_src_read = lib.get_prefix_split_src_file(lib.get_right_read()) + suffix; ifstream left_file(left_src_read.c_str()); ifstream right_file; if (lib.get_paired_end()){ right_file.open(right_src_read.c_str(), ios_base::in); } string left_header = ""; string right_header = ""; string left_seq = ""; string right_seq = ""; string left_qual = ""; string right_qual = ""; string plus; ofstream split_read_fasta_file; ofstream split_read_fastq_file; split_read_fasta_file.open(lib.get_split_file_name(file_part, FORMAT_FASTA).c_str(), ios_base::out); if (lib.get_format() == FORMAT_FASTQ) split_read_fastq_file.open(lib.get_split_file_name(file_part, FORMAT_FASTQ).c_str(), ios_base::out); while (getline(left_file, left_header)) { // get read data point, which includes 4 lines string lead_chr = (lib.get_format() == FORMAT_FASTQ)? "@" : ">"; if (left_header.substr(0,1) == lead_chr){ //save left-end reads getline(left_file, left_seq); if (lib.get_format() == FORMAT_FASTQ) { getline(left_file, plus); getline(left_file, left_qual); } if (lib.get_paired_end()){ //save right-end reads while (getline(right_file, right_header)) if (right_header.substr(0,1) == lead_chr) break; getline(right_file, right_seq); if (lib.get_format() == FORMAT_FASTQ) { getline(right_file, plus); getline(right_file, right_qual); } } if (lib.get_format() == FORMAT_FASTQ) { split_read_fastq_file << left_header << endl << left_seq << endl << "+" << endl << left_qual << endl; } split_read_fasta_file << ">" << left_header.substr(1) << endl << left_seq << endl; if (lib.get_paired_end()){ if (lib.get_format() == FORMAT_FASTQ) { split_read_fastq_file << right_header << endl << right_seq << endl << "+" << endl << right_qual << endl; } split_read_fasta_file << ">" << right_header.substr(1) << endl << right_seq << endl; } } } split_read_fasta_file.close(); if (lib.get_format() == FORMAT_FASTQ) split_read_fastq_file.close(); left_file.close(); if (lib.get_paired_end()) right_file.close(); string cmd = "rm " + left_src_read + " " + right_src_read; run_shell_command(cmd); }
INT32 LibraryFile::Init(SuperGallery *ParentGal, PathName *APath, SGLibType Type, BOOL Updated, BOOL DoScroll) { #ifndef EXCLUDE_GALS if(ParentGal == NULL || APath == NULL || !Libraries.IsEmpty()) { ERROR3("LibraryFile::Init - NULL parameters are illegal OR Init called > 1 times"); if(!Libraries.IsEmpty()) return(Libraries.GetCount()); else return 0; } BOOL ok = TRUE; // Tidy up Path a bit String_256 OurPath(APath->GetPath()); LibraryFile::TidyUpSubPath(&OurPath); // Now point Path to the new pathname PathName ModifiedPath(OurPath); PathName *Path = &ModifiedPath; if(!ModifiedPath.IsValid()) { ERROR3("LibraryFile::Init -> Modified library path is invalid"); return 0; } // Remember the pathname and type MyPath = *Path; MyType = Type; ParentGallery = ParentGal; if(ParentGallery->IsKindOf(CC_RUNTIME_CLASS(LibraryGallery))) ParentLibraryGallery = (LibraryGallery *)ParentGal; else { ERROR3("LibraryFile::Init passed a non-library gallery - yikes..."); return 0; } // Need to reset the Quiet status before a stream of Library::Init calls ParentLibraryGallery->SetQuietStatus(FALSE); BOOL Retry = TRUE; while(Retry) { Retry = FALSE; // Would be nice to have a way of adding a file to a path in PathName... Is there one ? if(!SGLibOil::FileExists(Path)) { // We're opening the font gallery, but can't find the font library path - don't warn if(Type == SGLib_Font) return 0; // tell the user that the directory doesn't exist String_256 WarnMsg; String_256 DefaultIndex; String_256 IndexDesc; BOOL CanGenerate; ok = LibraryFile::GetSubIndexDetails(ParentLibraryGallery, &DefaultIndex, &IndexDesc, &CanGenerate); String_256 TmpPath(Path->GetLocation(FALSE)); LibraryFile::TidyUpSubPath(&TmpPath); // Taken out by Graham 30/10/97: If the gallery had no directory specified, //we used to throw a warning which said "do you want to specify another folder?" //We don't do this any more, because the default is to open all galleries empty and //then download stuff from the Xara web site #if 0 WarnMsg.MakeMsg(_R(IDS_BROWSE_OR_SCAN), (TCHAR *)IndexDesc, (TCHAR *)TmpPath); Error::SetError(0, WarnMsg, 0); INT32 ButtonPressed = InformWarning(0, _R(IDS_BROWSE), _R(IDS_RETRY), _R(IDS_CANCEL)/*, _R(IDS_HELP)*/); #else // WEBSTER INT32 ButtonPressed = 3; #endif // WEBSTER TRACEUSER( "Richard", _T("ButtonPressed: %d\n"), ButtonPressed); Error::ClearError(); switch(ButtonPressed) { case 1: { // Open the Browse dialog (or the Add.. dialog as it seems to be called now) PathName ThePath(*Path); // This returns FALSE if Cancel was hit, or an error occurred. if(!SGLibOil::GetLibPath(ParentLibraryGallery, &ThePath, CanGenerate, Type)) { ERROR3("GetLibPath returned FALSE in LF::Init"); return 0; } else { ModifiedPath = ThePath; if(!ModifiedPath.IsValid()) { ERROR3("LibraryFile::Init -> scanned library path is invalid"); return 0; } // Remember the pathname MyPath = ThePath; switch(Type) { case SGLib_ClipArt: case SGLib_Bitmap: LibClipartSGallery::DefaultLibraryPath = MyPath.GetPath(); LibClipartSGallery::ClipartPath = LibClipartSGallery::DefaultLibraryPath; break; case SGLib_ClipArt_WebThemes: LibClipartSGallery::DefaultLibraryPath = MyPath.GetPath(); LibClipartSGallery::WebThemePath = LibClipartSGallery::DefaultLibraryPath; break; #ifndef STANDALONE case SGLib_Texture: case SGLib_Fractal: LibFillsSGallery::DefaultLibraryPath = MyPath.GetPath(); break; case SGLib_Font: // WEBSTER-Martin-09/01/97 - Put back by Ranbir. //#ifndef WEBSTER FontsSGallery::DefaultLibraryPath = MyPath.GetPath(); break; // Not in webster so we get the error below //#endif // WEBSTER #endif default: ERROR2(FALSE,"Library::ScanForLocation Type not present!"); break; } } break; } case 2: Retry = TRUE; #if 0 { // Scan String_256 Result; if(!Library::ScanForLocation(Type, &Result)) { ERROR3("No libraries found..."); return 0; } if(!ModifiedPath.SetPathName(Result)) { ERROR3("LibraryFile::Init -> scanned library path is invalid"); return 0; } // Remember the pathname and type MyPath = *Path; } #endif break; case 3: // Cancel return 0; } } } // Wipe libraries added to gallery for scroll / redraw purposes... InitScrollRedrawSystem(); // Check the actual path exists if(SGLibOil::FileExists(Path)) { // Would be nice to have a way of adding a file to a path in PathName... Is there one ? String_256 IndexFile((const TCHAR *)Path->GetPath(TRUE)); // "%s\\XaraInfo\\index.txt" IndexFile += String_16(_R(IDS_LIBRARIES_XARAINFO_DIRNAME)); IndexFile += TEXT("\\") + String_16(_R(IDS_LIBRARIES_INDEX_FILENAME)); PathName IndexFilePath(IndexFile); if(!IndexFilePath.IsValid()) { ERROR3("LibraryFile::Init indexfilepath is invalid"); return 0; } CCDiskFile MainIndex; if (!MainIndex.InitLexer(FALSE)) { // SetError! ERROR3("LibraryFile::LibraryFile InitLexer failed"); return(0); } if(SGLibOil::FileExists(&IndexFilePath)) { // Count lines in index file INT32 Count = CountLines(&IndexFilePath); TRACEUSER( "Richard", _T("%d lines in index file\n"), Count); // Used for the percentage display INT32 CurrentGroupNumber = 0; // Just in case there's a slow job already going on... SmashSlowJob(); String_64 SlowJob(_R(IDS_LIBRARY_SCANNING)); BeginSlowJob(Count, FALSE, &SlowJob); // Now use the index file to create each group in turn if (MainIndex.open(IndexFilePath, ios::in)) { MainIndex.SetWhitespace(""); // Setting this to blank lets us read non-"'d strings MainIndex.SetDelimiters(","); // ,s delimit our fields MainIndex.SetCommentMarker('#'); // #'d lines are commented out MainIndex.SetStringDelimiters(""); // No string delimiters String_64 Directory; String_64 Description; String_64 SubIndex; String_64 Kind; LexTokenType TT; BOOL EscapePressed = FALSE; while(ok && !EscapePressed) { if(!MainIndex.GetToken()) break; // Get SubLib directory name // Keep reading tokens until we hit a normal one... (skips line ends and // comments for us TT = MainIndex.GetTokenType(); while (TT != TOKEN_NORMAL && ok) { ok = MainIndex.GetToken(); if(!ok) break; TT = MainIndex.GetTokenType(); ok = (TT != TOKEN_EOF); if(!ok) break; } if(!ok) break; Directory = MainIndex.GetTokenBuf(); KillLeadingSpaces(&Directory); if(!MainIndex.GetToken()) break; // Get ',' if(!MainIndex.GetToken()) break; // Get Description String_256 Description256; Description256 = MainIndex.GetTokenBuf(); KillLeadingSpaces(&Description256); Description256.Left(&Description, 60); if(!MainIndex.GetToken()) break; // Get ',' if(!MainIndex.GetToken()) break; // Get Sub Library Index name SubIndex = MainIndex.GetTokenBuf(); KillLeadingSpaces(&SubIndex); if(!MainIndex.GetToken()) break; // Get ',' if(!MainIndex.GetToken()) break; // Get type of files in sublib Kind = MainIndex.GetTokenBuf(); KillLeadingSpaces(&Kind); BOOL Match = FALSE; Match = ParentLibraryGallery->CheckForIndexMatch(&Kind); if(Match) { // Show status of additions EscapePressed = !ContinueSlowJob(CurrentGroupNumber++); // Sort pathname of sublib directory out String_256 SubP(Path->GetPath(TRUE)); SubP += Directory; PathName SubPath(SubP); if(!SubPath.IsValid()) { ERROR3("LibraryFile::Init - invalid subpath"); if(MainIndex.isOpen()) MainIndex.close(); EndSlowJob(); return 0; } // Go ahead and add the new group if(ok) { // Create the sub lib Library *NewSubLib = new Library; if (NewSubLib != NULL) { // Create the new group in the gallery (note the TRUE for create a virtualised one if // we can to save time / memory) if(NewSubLib->Init(ParentGal, &SubPath, &Description, &SubIndex, Type, Updated, TRUE)) { Libraries.AddTail(NewSubLib); // Keep track of libraries added for redraw purposes... AddNewFolderToScrollRedrawSystem(NewSubLib); } else { // This check is new, should be ok... delete NewSubLib; NewSubLib = NULL; ERROR3("Library::Init failed in LibraryFile::Init"); ok = FALSE; } } } } } } else { // Failed to open the index file... // SetError?! ERROR3("LibraryFile::LibraryFile couldn't open index file"); ok = FALSE; } EndSlowJob(); } else { // The directory given had no XaraInfo\index.txt file, maybe it's a sublib, check // For defaults... ok = CheckForSubIndexes(ParentGal, Path, Type, Updated); } // reclaim lexer-buffer memory MainIndex.DeinitLexer(); // And close the file if(MainIndex.isOpen()) MainIndex.close(); // Scroll / redraw the newly added groups... if(DoScroll) DoScrollRedraw(); } else { TRACEUSER( "Richard", _T("Path doesn't exist\n")); } // And return the number of items created return(Libraries.GetCount()); #endif return 0; }
/*--------------------------------------------------------------------------*/ Function::ReturnValue sci_load(types::typed_list &in, int _iRetCount, types::typed_list &out) { if (in.size() < 1) { Scierror(999, _("%s: Wrong number of input argument(s): at least %d expected.\n"), fname.data(), 1); return types::Function::Error; } InternalType* pIT = in[0]; if (pIT->getId() != InternalType::IdScalarString) { Scierror(999, _("%s: Wrong type for input argument #%d: A string expected.\n"), fname.data(), 1); return Function::Error; } String *pS = pIT->getAs<types::String>(); wchar_t* pwstPathLib = expandPathVariableW(pS->get(0)); char* pstPath = wide_string_to_UTF8(pwstPathLib); if (FileExist(pstPath)) { if (isHDF5File(pstPath)) { FREE(pstPath); FREE(pwstPathLib); //call overload std::wstring wstFuncName = L"%_sodload"; ast::ExecVisitor exec; Callable::ReturnValue Ret = Callable::Error; Ret = Overload::call(wstFuncName, in, _iRetCount, out, &exec); return Ret; } else { int err = 0; Library* lib = loadlib(pS->get(0), &err); FREE(pstPath); switch (err) { case 0: //no error break; case 1: { char* pstPath = wide_string_to_UTF8(pS->get(0)); Scierror(999, _("%s: %s is not a valid module file.\n"), fname.data(), pstPath); FREE(pstPath); return Function::Error; } case 2: { Scierror(999, "%s: %s", fname.data(), _("Redefining permanent variable.\n")); return Function::Error; } default: { //nothing } } FREE(pwstPathLib); lib->killMe(); } } else { Scierror(999, _("%s: Unable to open file: \"%ls\".\n"), fname.data(), pwstPathLib); FREE(pstPath); FREE(pwstPathLib); return Function::Error; } return Function::OK; }
BOOL LibraryFile::CheckForSubIndexes(SuperGallery *ParentGal, PathName *Path, SGLibType Type, BOOL Updated) { // The directory given had no XaraInfo\index.txt file, maybe it's a sublib, check // For defaults... String_256 DefaultIndex; String_256 IndexDesc; BOOL CanGenerate; BOOL ok = TRUE; // Need to reset the Quiet status before a stream of Library::Init calls ParentLibraryGallery->SetQuietStatus(FALSE); if(GetSubIndexDetails(ParentLibraryGallery, &DefaultIndex, &IndexDesc, &CanGenerate)) { String_256 SubP(Path->GetPath(TRUE)); // "%s\\XaraInfo\\%s" SubP += String_16(_R(IDS_LIBRARIES_XARAINFO_DIRNAME)); SubP += TEXT("\\") + DefaultIndex; PathName SubPath(SubP); if(!SubPath.IsValid()) { ERROR3("LibraryFile::CheckForSubIndexes invalid subpath"); return FALSE; } BOOL Generate = FALSE; BOOL Found = FALSE; // Is there a default sub index ? Found = SGLibOil::FileExists(&SubPath); if(!Found && CanGenerate) { if(Library::RemoteIndexes && GenerateIndexFile::IsDirectoryReadOnly(Path)) { // Check whether there's a 'temporary' index for this directory, and // possibly use that instead of the read only directory... String_256 RemoteLocationOfIndex; BOOL Existing = GenerateIndexFile::CheckForRemote(Path, &RemoteLocationOfIndex); if(Existing) { String_256 SubP(RemoteLocationOfIndex); // %s\\XaraInfo\\%s SGLibOil::AppendSlashIfNotPresent(&SubP); SubP += String_16(_R(IDS_LIBRARIES_XARAINFO_DIRNAME)); SubP += TEXT("\\") + DefaultIndex; PathName TmpSubPath(SubP); Found = SGLibOil::FileExists(&TmpSubPath); // OK, so there's a remote index sitting pretty in the user's temporary // location... Use that and don't bother generating a new one... if(Found) { SubPath.SetPathName(SubP); Path->SetPathName(RemoteLocationOfIndex); } } } if(!Found) { // tell the user that there is no index file, and ask if they want one generating String_256 WarnMsg; String_256 TmpPath(SubPath.GetLocation(FALSE)); LibraryFile::TidyUpSubPath(&TmpPath); WarnMsg.MakeMsg(_R(IDS_LIBRARY_NO_INDEX_FILE_GEN), (TCHAR *)IndexDesc, (TCHAR *)TmpPath); Error::SetError(0, WarnMsg, 0); //INT32 ButtonPressed = InformMessage(0, _R(IDS_NOTHUMBNAILS), _R(IDS_THUMBNAILS), _R(IDS_CANCEL)/*, _R(IDS_HELP)*/); INT32 ButtonPressed = InformMessage(0, _R(IDS_CREATE), _R(IDS_CANCEL)); Error::ClearError(); if(ButtonPressed < 2) { // Generate an index... String_64 Author(PRODUCT_NAME); Generate = GenerateDefaultIndex(&SubPath, Path, &Author, Type, TRUE); ok = TRUE; } else { // Cancel or help clicked ok = FALSE; } } } if(!Found && !CanGenerate) { // tell the user that there is no index file, and give them a cancel... String_256 WarnMsg; String_256 TmpPath(SubPath.GetLocation(FALSE)); LibraryFile::TidyUpSubPath(&TmpPath); WarnMsg.MakeMsg(_R(IDS_LIBRARY_NO_INDEX_FILE), (TCHAR *)IndexDesc, (TCHAR *)TmpPath); Error::SetError(0, WarnMsg, 0); INT32 ButtonPressed = InformWarning(0, _R(IDS_CANCEL), NULL); Error::ClearError(); ok = FALSE; } // Check again... Found = SGLibOil::FileExists(&SubPath); if((Found && ok) || (!Found && Generate && ok)) { String_256 Description256 = Path->GetPath(); AbbreviateName(Description256, 60, TRUE); String_64 Description(Description256); BOOL DoAgain = TRUE; while (DoAgain) { DoAgain = FALSE; // Create the sub lib Library *NewSubLib = new Library; if (NewSubLib != NULL) { String_64 DefIndex64(DefaultIndex); String_256 PathToAdd256 = SubPath.GetLocation(FALSE); TidyUpSubPath(&PathToAdd256); PathName PathToAdd(PathToAdd256); Error::ClearError(); // Create the actual group itself if(NewSubLib->Init(ParentGal, &PathToAdd, &Description, &DefIndex64, Type, Updated)) { Libraries.AddTail(NewSubLib); ok = TRUE; // Keep track of libraries added for redraw purposes... AddNewFolderToScrollRedrawSystem(NewSubLib); } else { delete NewSubLib; NewSubLib = NULL; String_256 WarnMsg; String_256 SmallPath; PathToAdd256.Left(&SmallPath, 150); // "The index for '%s' seems to be invalid and requires updating." WarnMsg.MakeMsg(_R(IDS_LIBRARY_DODGY_INDEX), (TCHAR *)SmallPath); Error::SetError(0, WarnMsg, 0); INT32 Button = InformWarning(0, _R(IDS_GENERATE), _R(IDS_CANCEL)); Error::ClearError(); String_256 IPathToAdd256(PathToAdd256); SGLibOil::AppendSlashIfNotPresent(&IPathToAdd256); IPathToAdd256 += TEXT("indexfle.txt"); // This is just to check we can write ok... PathName IPathToAdd(IPathToAdd256); if(Button == 1) DoAgain = SGLibOil::GenerateClicked(ParentLibraryGallery, &IPathToAdd); if(!DoAgain) ok = FALSE; Error::ClearError(); } } } } } return ok; }
Module Process::getInjected(const Library& lib) { if (Module module = isInjected(lib)) return module; else BOOST_THROW_EXCEPTION(ex_injection() << e_text("failed to find injected library") << e_process(*this) << e_library(lib.path())); }
int main(int argc, char **argv) { QxtCommandOptions options; options.add(CL_HELP, "display this help message", QxtCommandOptions::NoValue); options.add(CL_NKEYS, "number of keys to generate", QxtCommandOptions::ValueRequired); options.add(CL_PUBDIR, "directory in which to put public keys (default=./keys/pub)", QxtCommandOptions::ValueRequired); options.add(CL_PRIVDIR, "directory in which to put private keys (default=./keys/priv)", QxtCommandOptions::ValueRequired); options.add(CL_KEYTYPE, "specify the key type (default=dsa, options=dsa|rsa)", QxtCommandOptions::ValueRequired); options.add(CL_LIB, "specify the library (default=cryptopp, options=cryptopp)", QxtCommandOptions::ValueRequired); options.add(CL_RAND, "specify the base properties for the key (default=NULL)", QxtCommandOptions::ValueRequired); options.add(CL_DEBUG, "enable debugging", QxtCommandOptions::NoValue); options.parse(argc, argv); if(options.count(CL_HELP) || options.showUnrecognizedWarning()) { options.showUsage(); return -1; } QMultiHash<QString, QVariant> params = options.parameters(); int key_count = params.value(CL_NKEYS, 1).toInt(); if(key_count < 1) { ExitWithWarning(options, "Invalid nkeys"); } QString pubdir_path = params.value(CL_PUBDIR, DEFAULT_PUBDIR).toString(); QDir pubdir(pubdir_path); if(!pubdir.exists()) { pubdir.mkpath("."); } if(!pubdir.exists()) { ExitWithWarning(options, "Unable to create pubdir"); } QString privdir_path = params.value(CL_PRIVDIR, DEFAULT_PRIVDIR).toString(); QDir privdir(privdir_path); if(!privdir.exists()) { privdir.mkpath("."); } if(!privdir.exists()) { ExitWithWarning(options, "Unable to create privdir"); } if(params.contains(CL_DEBUG)) { Logging::UseStderr(); } QString lib_name = params.value(CL_LIB, "cryptopp").toString(); QString key = params.value(CL_KEYTYPE, "dsa").toString(); CryptoFactory &cf = CryptoFactory::GetInstance(); QSharedPointer<CreateKey> ck(new CreateKey()); if(lib_name == "cryptopp") { if(key == "dsa") { cf.SetLibrary(CryptoFactory::CryptoPPDsa); if(params.contains(CL_RAND)) { ck = QSharedPointer<CreateKey>( new CreateSeededDsaKey(params.value(CL_RAND).toString())); } } else if (key == "rsa") { cf.SetLibrary(CryptoFactory::CryptoPP); } else { ExitWithWarning(options, "Invalid key type"); } } else { ExitWithWarning(options, "Invalid library"); } Library *lib = cf.GetLibrary(); QSharedPointer<Hash> hash(lib->GetHashAlgorithm()); int count = 0; while(count < key_count) { QSharedPointer<AsymmetricKey> key((*ck)()); QSharedPointer<AsymmetricKey> pubkey(key->GetPublicKey()); QByteArray hvalue = hash->ComputeHash(pubkey->GetByteArray()); QString id = Integer(hvalue).ToString(); if(!key->Save(privdir_path + QDir::separator() + id)) { qFatal("Could not save private key"); } if(!pubkey->Save(pubdir_path + QDir::separator() + id + ".pub")) { qFatal("Could not save private key"); } count++; } return 0; }
extern inline Http *ProtocolHttp( Socket* sock, char* data, unsigned int length ) { Http *response = NULL; DEBUG("HTTP Callback called\n"); if( length <= 0 ) { DEBUG("RESULT<0 http400\n"); struct TagItem tags[] = { { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicateN( "close", 5 ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_400_BAD_REQUEST, tags ); //HttpWriteAndFree( response ); } // Get the current request we're working on, or start a new one Http* request = (Http*)sock->data; if( !request ) { request = HttpNew( sock ); request->timestamp = time( NULL ); sock->data = (void*)request; } //DEBUG("Checking timeout, data %s\n", data ); //DEBUG("time %ld\nreqtimestamp %ld\nreqtimestamp %ld\n", // time( NULL ), request->timestamp, HTTP_REQUEST_TIMEOUT ); // Timeout if( time( NULL ) > request->timestamp + HTTP_REQUEST_TIMEOUT ) { struct TagItem tags[] = { { HTTP_HEADER_CONTENT_TYPE, (ULONG) StringDuplicate( "text/plain" ) }, { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicate( "close" ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_408_REQUEST_TIME_OUT, tags ); HttpAddTextContent( response, "408 Request Timeout\n" ); //HttpWriteAndFree( response ); HttpFreeRequest( request ); sock->data = NULL; DEBUG("HTTP TIMER\n"); return response; } // Continue parsing the request int result = HttpParsePartialRequest( request, data, length ); // Protocol error if( result < 0 ) { DEBUG("RESULT<0 http400\n"); struct TagItem tags[] = { { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicate( "close" ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_400_BAD_REQUEST, tags ); //HttpWriteAndFree( response ); } // Request not fully parsed yet. Return and wait for more data else if( result == -1 ) { DEBUG( " <- (%d): Waiting for more data\n", sock->fd ); HttpFreeRequest( request ); return response; } // Request parsed without errors! else if( result == 1 ) { Uri* uri = request->uri; // Disallow proxy requests if( uri && ( uri->scheme || uri->authority ) ) { struct TagItem tags[] = { { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicate( "close" ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_403_FORBIDDEN, tags ); result = 403; } // Cross-domain requests uses a pre-flight OPTIONS call if( !request->errorCode && request->method && strcmp( request->method, "OPTIONS" ) == 0 ) { struct TagItem tags[] = { { HTTP_HEADER_CONTROL_ALLOW_ORIGIN, (ULONG)StringDuplicateN( "*", 1 ) }, { HTTP_HEADER_CONTROL_ALLOW_HEADERS, (ULONG)StringDuplicateN( "Origin, X-Requested-With, Content-Type, Accept, Method", 54 ) }, { HTTP_HEADER_CONTROL_ALLOW_METHODS, (ULONG)StringDuplicateN( "GET, POST, OPTIONS", 18 ) }, { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicateN( "close", 5 ) }, {TAG_DONE, TAG_DONE} }; if( response != NULL ) ERROR("Response != NULL\n"); response = HttpNewSimple( HTTP_200_OK, tags ); result = 200; } // Check for connection upgrade else if( !request->errorCode && HttpHeaderContains( request, "connection", "Upgrade", false ) ) { struct TagItem tags[] = { { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicate( "close" ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_400_BAD_REQUEST, tags ); } else { Path* path = NULL; if( uri->path->raw ) { int nlen = 0; for( ; ; nlen++ ) { if( !uri->path->raw[nlen] ) break; } DEBUG("Want to parse path: %s (%d)\n", uri->path->raw, nlen ); path = PathNew( uri->path->raw ); if( path ) PathResolve( path ); // Resolve checks for "../"'s, and removes as many as it can. } if( !path || !path->resolved ) // If it cannot remove all, path->resolved == false. { DEBUG( "We have no path..\n" ); struct TagItem tags[] = { { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicate( "close" ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_403_FORBIDDEN, tags ); result = 403; } else { DEBUG( "We got through. %s\n", path->parts[ 0 ] ); if( path->size >= 2 && StringCheckExtension( path->parts[0], "library" ) == 0 ) { // system.library is main library and should be use for most things // we open it and close in main //DEBUG("systemlib found\n"); DEBUG("Calling systemlib\n"); if( strcmp( path->parts[ 0 ], "system.library" ) == 0 ) { DEBUG( "%s\n", path->parts[1] ); response = SLIB->SysWebRequest( SLIB, &(path->parts[1]), request ); if( response == NULL ) { struct TagItem tags[] = { { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicate( "close" ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_500_INTERNAL_SERVER_ERROR, tags ); result = 500; } } else { FriendCoreInstance_t *fci = (FriendCoreInstance_t *) sock->s_Data; Library* lib = FriendCoreGetLibrary( fci, path->parts[0], 1 ); if( lib && lib->WebRequest ) { response =(Http *) lib->WebRequest( lib, path->parts[1], request ); if( response == NULL ) { struct TagItem tags[] = { { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicate( "close" ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_500_INTERNAL_SERVER_ERROR, tags ); result = 500; } } else { struct TagItem tags[] = { { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicate( "close" ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_404_NOT_FOUND, tags ); result = 404; } } } // We're calling on a static file. else { //DEBUG("Getting resources\n"); // Read the file Path *base = PathNew( "resources" ); Path* complete = PathJoin( base, path ); BOOL freeFile = FALSE; LocFile* file = CacheManagerFileGet( SLIB->cm, complete->raw ); if( file == NULL ) { file = LocFileNew( complete->raw, FILE_READ_NOW | FILE_CACHEABLE ); if( file != NULL ) { if( CacheManagerFilePut( SLIB->cm, file ) != 0 ) { freeFile = TRUE; } } } // Send reply if( file != NULL ) { char* mime = NULL; if( file->buffer == NULL ) { ERROR("File is empty %s\n", complete->raw ); } if( complete->extension ) { mime = StringDuplicate( MimeFromExtension( complete->extension ) ); } else { mime = StringDuplicate( "text/plain" ); } struct TagItem tags[] = { { HTTP_HEADER_CONTENT_TYPE, (ULONG) mime }, { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicate( "close" ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_200_OK, tags ); //DEBUG("Before returning data\n"); HttpSetContent( response, file->buffer, file->bufferSize ); // write here and set data to NULL!!!!! // retusn response HttpWrite( response, sock ); result = 200; INFO("--------------------------------------------------------------%d\n", freeFile ); if( freeFile == TRUE ) { //ERROR("\n\n\n\nFREEEEEEFILE\n"); LocFileFree( file ); } response->content = NULL; response->sizeOfContent = 0; response->h_WriteType = FREE_ONLY; } else { DEBUG( "[ProtocolHttp] Going ahead with %s.\n", path->parts ? path->parts[0] : "No path part.." ); // Try to fall back on module // TODO: Make this behaviour configurable char command[255]; sprintf( command, "php \"php/catch_all.php\" \"%s\";", uri->path->raw ); DEBUG( "[ProtocolHttp] Executing %s\n", command ); ListString *bs = RunPHPScript( command ); int phpRun = FALSE; if( bs ) { if( bs->ls_Size > 0 ) { struct TagItem tags[] = { { HTTP_HEADER_CONTENT_TYPE, (ULONG) StringDuplicate( "text/html" ) }, { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicate( "close" ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_200_OK, tags ); HttpSetContent( response, bs->ls_Data, bs->ls_Size ); result = 200; phpRun = TRUE; bs->ls_Data = NULL; } ListStringDelete( bs ); } if( !phpRun ) { DEBUG("File do not exist\n"); struct TagItem tags[] = { { HTTP_HEADER_CONNECTION, (ULONG)StringDuplicate( "close" ) }, {TAG_DONE, TAG_DONE} }; response = HttpNewSimple( HTTP_404_NOT_FOUND, tags ); result = 404; } } PathFree( base ); PathFree( complete ); } } PathFree( path ); } // SPRING CLEANING!!! TIME TO CLEAN THE CASTLE!!! :) :) :) HttpFreeRequest( request ); if( result != 101 ) { sock->data = NULL; } return response; } // Winter cleaning HttpFreeRequest( request ); return response; }
Face(Library& lib, const std::string& filename, int face_index) :library_(lib) ,handle_(0) { KGASCII_FREETYPE_CALL(FT_New_Face, lib.handle(), filename.c_str(), face_index, &handle_); }
static bool AddLibsToCombo(int lang) { // First get the last used library for this language int lastUsed = -1; SqliteStatement stmt(g_db, "SELECT LibraryID FROM LangLastUsed WHERE Lang = @langid"); stmt.Bind("@langid", lang); if (stmt.GetNextRecord()) lastUsed = stmt.GetIntColumn("LibraryID"); stmt.Finalize(); // Get all the libraries for this language stmt.Prepare("SELECT Library.*, LibraryLang.Lang FROM Library INNER JOIN LibraryLang ON Library.LibraryID = LibraryLang.LibraryID WHERE (LibraryLang.Lang = @langid OR LibraryLang.Lang = -2) ORDER BY Library.Name"); stmt.Bind("@langid", lang); // Go through the rows int colLang = stmt.GetColumnCount() - 1; bool first = true; bool firstLanguage = false; bool selectedUsersChoice = false; // Did the user select a library? while (stmt.GetNextRecord()) { // Store the library data Library* lib = new Library(&stmt); // Add the item to the combo long item = (long) SendDlgItemMessage(s_hDlg, IDC_NAME, CB_ADDSTRING, (WPARAM) 0, (LPARAM) lib->WGetName()); SendDlgItemMessage(s_hDlg, IDC_NAME, CB_SETITEMDATA, (WPARAM) item, (LPARAM) lib); // Determine if we need to select this library? bool selectThisLib = first; // Did we run into the user selected library already? if (!selectedUsersChoice) { if (lib->GetLibraryID() == lastUsed) { selectedUsersChoice = true; selectThisLib = true; } else { if (!firstLanguage) { int libLang = stmt.GetIntColumn(colLang); if (libLang >= 0) { firstLanguage = true; selectThisLib = true; } } } } // Need to select this library? if (selectThisLib) { SendDlgItemMessage(s_hDlg, IDC_NAME, CB_SETCURSEL, (WPARAM) item, (LPARAM) 0); s_curLibrary = lib; } first = false; } stmt.Finalize(); return !first; }
bool isSameExpression(bool cpp, bool macro, const Token *tok1, const Token *tok2, const Library& library, bool pure, bool followVar, ErrorPath* errors) { if (tok1 == nullptr && tok2 == nullptr) return true; if (tok1 == nullptr || tok2 == nullptr) return false; if (cpp) { if (tok1->str() == "." && tok1->astOperand1() && tok1->astOperand1()->str() == "this") tok1 = tok1->astOperand2(); if (tok2->str() == "." && tok2->astOperand1() && tok2->astOperand1()->str() == "this") tok2 = tok2->astOperand2(); } // Skip double not if (Token::simpleMatch(tok1, "!") && Token::simpleMatch(tok1->astOperand1(), "!") && !Token::simpleMatch(tok1->astParent(), "=")) { return isSameExpression(cpp, macro, tok1->astOperand1()->astOperand1(), tok2, library, pure, followVar, errors); } if (Token::simpleMatch(tok2, "!") && Token::simpleMatch(tok2->astOperand1(), "!") && !Token::simpleMatch(tok2->astParent(), "=")) { return isSameExpression(cpp, macro, tok1, tok2->astOperand1()->astOperand1(), library, pure, followVar, errors); } // Follow variable if (followVar && tok1->str() != tok2->str() && (Token::Match(tok1, "%var%") || Token::Match(tok2, "%var%"))) { const Token * varTok1 = followVariableExpression(tok1, cpp, tok2); if (varTok1->str() == tok2->str()) { followVariableExpressionError(tok1, varTok1, errors); return isSameExpression(cpp, macro, varTok1, tok2, library, true, errors); } const Token * varTok2 = followVariableExpression(tok2, cpp, tok1); if (tok1->str() == varTok2->str()) { followVariableExpressionError(tok2, varTok2, errors); return isSameExpression(cpp, macro, tok1, varTok2, library, true, errors); } if (varTok1->str() == varTok2->str()) { followVariableExpressionError(tok1, varTok1, errors); followVariableExpressionError(tok2, varTok2, errors); return isSameExpression(cpp, macro, varTok1, varTok2, library, true, errors); } } if (tok1->varId() != tok2->varId() || tok1->str() != tok2->str() || tok1->originalName() != tok2->originalName()) { if ((Token::Match(tok1,"<|>") && Token::Match(tok2,"<|>")) || (Token::Match(tok1,"<=|>=") && Token::Match(tok2,"<=|>="))) { return isSameExpression(cpp, macro, tok1->astOperand1(), tok2->astOperand2(), library, pure, followVar, errors) && isSameExpression(cpp, macro, tok1->astOperand2(), tok2->astOperand1(), library, pure, followVar, errors); } return false; } if (macro && (tok1->isExpandedMacro() || tok2->isExpandedMacro() || tok1->isTemplateArg() || tok2->isTemplateArg())) return false; if (tok1->isComplex() != tok2->isComplex()) return false; if (tok1->isLong() != tok2->isLong()) return false; if (tok1->isUnsigned() != tok2->isUnsigned()) return false; if (tok1->isSigned() != tok2->isSigned()) return false; if (pure && tok1->isName() && tok1->next()->str() == "(" && tok1->str() != "sizeof") { if (!tok1->function()) { if (!Token::Match(tok1->previous(), ".|::") && !library.isFunctionConst(tok1) && !tok1->isAttributeConst() && !tok1->isAttributePure()) return false; if (Token::simpleMatch(tok1->previous(), ".")) { const Token *lhs = tok1->previous(); while (Token::Match(lhs, "(|.|[")) lhs = lhs->astOperand1(); const bool lhsIsConst = (lhs->variable() && lhs->variable()->isConst()) || (lhs->valueType() && lhs->valueType()->constness > 0) || (Token::Match(lhs, "%var% . %name% (") && library.isFunctionConst(lhs->tokAt(2))); if (!lhsIsConst) return false; } } else { if (tok1->function() && !tok1->function()->isConst() && !tok1->function()->isAttributeConst() && !tok1->function()->isAttributePure()) return false; } } // templates/casts if ((Token::Match(tok1, "%name% <") && tok1->next()->link()) || (Token::Match(tok2, "%name% <") && tok2->next()->link())) { // non-const template function that is not a dynamic_cast => return false if (pure && Token::simpleMatch(tok1->next()->link(), "> (") && !(tok1->function() && tok1->function()->isConst()) && tok1->str() != "dynamic_cast") return false; // some template/cast stuff.. check that the template arguments are same const Token *t1 = tok1->next(); const Token *t2 = tok2->next(); const Token *end1 = t1->link(); const Token *end2 = t2->link(); while (t1 && t2 && t1 != end1 && t2 != end2) { if (t1->str() != t2->str()) return false; t1 = t1->next(); t2 = t2->next(); } if (t1 != end1 || t2 != end2) return false; } if (tok1->tokType() == Token::eIncDecOp || tok1->isAssignmentOp()) return false; // bailout when we see ({..}) if (tok1->str() == "{") return false; // cast => assert that the casts are equal if (tok1->str() == "(" && tok1->previous() && !tok1->previous()->isName() && !(tok1->previous()->str() == ">" && tok1->previous()->link())) { const Token *t1 = tok1->next(); const Token *t2 = tok2->next(); while (t1 && t2 && t1->str() == t2->str() && t1->isLong() == t2->isLong() && t1->isUnsigned() == t2->isUnsigned() && t1->isSigned() == t2->isSigned() && (t1->isName() || t1->str() == "*")) { t1 = t1->next(); t2 = t2->next(); } if (!t1 || !t2 || t1->str() != ")" || t2->str() != ")") return false; } bool noncommutativeEquals = isSameExpression(cpp, macro, tok1->astOperand1(), tok2->astOperand1(), library, pure, followVar, errors); noncommutativeEquals = noncommutativeEquals && isSameExpression(cpp, macro, tok1->astOperand2(), tok2->astOperand2(), library, pure, followVar, errors); if (noncommutativeEquals) return true; // in c++, a+b might be different to b+a, depending on the type of a and b if (cpp && tok1->str() == "+" && tok1->isBinaryOp()) { const ValueType* vt1 = tok1->astOperand1()->valueType(); const ValueType* vt2 = tok1->astOperand2()->valueType(); if (!(vt1 && (vt1->type >= ValueType::VOID || vt1->pointer) && vt2 && (vt2->type >= ValueType::VOID || vt2->pointer))) return false; } const bool commutative = tok1->isBinaryOp() && Token::Match(tok1, "%or%|%oror%|+|*|&|&&|^|==|!="); bool commutativeEquals = commutative && isSameExpression(cpp, macro, tok1->astOperand2(), tok2->astOperand1(), library, pure, followVar, errors); commutativeEquals = commutativeEquals && isSameExpression(cpp, macro, tok1->astOperand1(), tok2->astOperand2(), library, pure, followVar, errors); return commutativeEquals; }
int main(int argc, char * const *argv) { operands ops; string objtype; string name; string object; string group; string parent; string comment_txt; bool list_children = false; bool recursive = false; string list_format = "%path%"; bool full_dump = false; string import_config; bool deduplicate = false; if (argc<=1) { usage(); exit(1); } /* * Command line format: * fwbedit command [options] * * argv[1] is always command */ cmd_str = string(argv[1]); cmd = NONE; if (cmd_str=="new") cmd = NEWOBJECT; if (cmd_str=="delete") cmd = DELOBJECT; if (cmd_str=="modify") cmd = MODOBJECT; if (cmd_str=="add") cmd = ADDGRP; if (cmd_str=="remove") cmd = REMGRP; if (cmd_str=="list") cmd = LIST; if (cmd_str=="upgrade") cmd = UPGRADE; if (cmd_str=="checktree") cmd = STRUCT; if (cmd_str=="merge") cmd = MERGE; if (cmd_str=="import") cmd = IMPORT; char * const *args = argv; args++; argc--; int opt; switch (cmd) { case NEWOBJECT: { // -f file.fwb -t objtype -n name -c comment -p parent [-a attrs] while( (opt=getopt(argc, args, "f:t:n:c:p:a:")) != EOF ) { switch(opt) { case 'f': filename = optarg; break; case 't': objtype = optarg; break; case 'n': name = optarg; break; case 'c': comment_txt = optarg; break; case 'p': parent = optarg; break; case 'a': int num=0; if (optarg!=NULL) { string str = optarg; num = splitStr(',', str, &ops); } break; } } if (filename=="") { usage_new(); exit(1); } break; } case DELOBJECT: // -f file.fwb -o object_def // object_def can be either full path or object ID while( (opt=getopt(argc, args, "f:o:")) != EOF ) { switch(opt) { case 'f': filename = optarg; break; case 'o': object = optarg; break; } } if (filename.empty() || object.empty()) { usage_delete(); exit(1); } break; case MODOBJECT: { // -f file.fwb -o object -c comment [-a attrs] while( (opt=getopt(argc, args, "f:o:c:a:")) != EOF ) { switch(opt) { case 'f': filename = optarg; break; case 'o': object = optarg; break; case 'c': comment_txt = optarg; break; case 'a': int num=0; if (optarg!=NULL) { string str = optarg; num = splitStr(',', str, &ops); } break; } } if (filename.empty() || object.empty()) { usage_modify(); exit(1); } break; } case ADDGRP: case REMGRP: // -f file.fwb -p group -o object // Add/remove object to group // both group and object can be either path or ID while( (opt=getopt(argc, args, "f:g:o:")) != EOF ) { switch(opt) { case 'f': filename = optarg; break; case 'g': group = optarg; break; case 'o': object = optarg; break; } } if (filename.empty() || group.empty() || object.empty()) { if (cmd == ADDGRP) usage_add(); if (cmd == REMGRP) usage_remove(); exit(1); } break; case LIST: // -f file.fwb -o object [-r] [-Fformat_string] [-d] // object can be either path or ID while( (opt=getopt(argc, args, "f:o:crdF:")) != EOF ) { switch(opt) { case 'f': filename = optarg; break; case 'o': object = optarg; break; case 'c': list_children = true; break; case 'r': recursive = true; break; case 'F': list_format = optarg; break; case 'd': full_dump = true; break; } } if (filename.empty() || object.empty()) { usage_list(); exit(1); } break; case UPGRADE: // -f file.fwb autoupgrade_flag = true; while( (opt=getopt(argc, args, "f:")) != EOF ) { switch(opt) { case 'f': filename = optarg; break; } } if (filename.empty()) { usage_upgrade(); exit(1); } break; case STRUCT: // -f file.fwb while( (opt=getopt(argc, args, "f:")) != EOF ) { switch(opt) { case 'f': filename = optarg; break; } } if (filename.empty()) { usage_checktree(); exit(1); } break; case MERGE: // -f file1.fwb -i file2.fwb while( (opt=getopt(argc, args, "f:i:c:")) != EOF ) { switch(opt) { case 'f': filename = optarg; break; case 'i': filemerge = optarg; break; case 'c': conflict_res = atoi(optarg); break; } } if (filename.empty() || filemerge.empty()) { usage_merge(); exit(1); } break; case IMPORT: // -f file.fwb -i config.txt -o /User/Firewalls/new_firewall while( (opt=getopt(argc, args, "f:i:o:d")) != EOF ) { switch(opt) { case 'f': filename = optarg; break; case 'i': import_config = optarg; break; case 'o': object = optarg; break; case 'd': deduplicate = true; break; } } if (filename.empty() || import_config.empty() || object.empty()) { usage_import(); exit(1); } break; case NONE: break; } if (cmd==NONE || filename=="") { usage(); exit(1); } init(argv); try { new Resources(Constants::getResourcesFilePath()); /* create database */ objdb = new FWObjectDatabase(); /* load the data file */ UpgradePredicate upgrade_predicate(autoupgrade_flag); objdb->load(filename, &upgrade_predicate, Constants::getDTDDirectory()); if (cmd == MERGE) { if (filemerge.empty()) { cerr << "The name of the file that should be merged is missing" << endl; usage_merge(); exit(1); } mergeTree(objdb, filemerge, conflict_res); } else if (cmd == IMPORT) { if (import_config.empty() || object.empty()) { cerr << "Configuration file name and path to the new firewall " "object are mandatory options for import" << endl; usage_import(); exit(1); } QStringList components = QString::fromUtf8(object.c_str()) .split("/", QString::SkipEmptyParts); string fw_name = components.last().toUtf8().constData(); Library *library = NULL; while (library == NULL) { components.pop_back(); string library_path = components.join("/").toUtf8().constData(); list<FWObject*> objects; findObjects(library_path, objdb, objects); if (objects.size() == 0) { cerr << "Library or folder '" << library_path << "' not found" << endl; usage_import(); exit(1); } library = Library::cast(objects.front()); } cout << "Import firewall configuration from file " << import_config << endl; cout << "New firewall object '" << fw_name << "' will be created in library '" << library->getName() << "'" << endl; importConfig(import_config, library, fw_name, deduplicate); } else if (cmd == STRUCT) { checkAndRepairTree(objdb); } else if (cmd == LIST) { listObject(objdb, object, list_children, recursive, list_format, full_dump); return(0); } else if (cmd == UPGRADE) { cout << "File upgraded; current data format version: " << libfwbuilder::Constants::getDataFormatVersion() << endl; } else if (cmd == NEWOBJECT) { newObject(objdb, objtype, name, comment_txt, parent, ops); } else if (cmd == DELOBJECT) { delObject(objdb, object); } else if (cmd == MODOBJECT) { modObject(objdb, object, comment_txt, ops); } else { list<FWObject*> objects; findObjects(object, objdb, objects); if (objects.size()==0) { cout << "Object " << object << " not found" << endl; exit(-1); } for (list<FWObject*>::iterator it=objects.begin(); it!=objects.end(); ++it) { FWObject *obj = *it; if (cmd==ADDGRP) { list<FWObject*> groups; findObjects(group, objdb, groups); if (groups.size()==0) { cout << "Group " << group << " not found" << endl; exit(-1); } FWObject *grp = groups.front(); cout << "Adding object '" << obj->getName() << "' to the group '" << grp->getName() << "'" << endl; grp->addRef(obj); } if (cmd==REMGRP) { list<FWObject*> groups; findObjects(group, objdb, groups); if (groups.size()==0) { cout << "Group " << group << " not found" << endl; exit(-1); } FWObject *grp = groups.front(); cout << "Removing object '" << obj->getName() << "' from the group '" << grp->getName() << "'" << endl; grp->removeRef(obj); } } } QString filename_qstr = QString::fromUtf8(filename.c_str()); QString bakfile = filename_qstr + ".bak"; QFile bakf(bakfile); if (bakf.exists()) bakf.remove(); QFile dataf(filename_qstr); if (dataf.rename(bakfile)) { objdb->saveFile(filename); } else { cout << "Could not rename data file, abroting operation" << endl; cout << dataf.errorString().toStdString() << endl; exit(-1); } } catch(FWException &ex) { cerr << ex.toString() << endl; exit(1); } catch (std::string s) { cerr << s; exit(1); } catch (std::exception ex) { cerr << ex.what(); exit(1); } catch (...) { cerr << "Unsupported exception"; exit(1); } return(0); }
bool LibraryInterception::onIntercept( XeCore::Intuicio::ParallelThreadVM* caller, uint32 code ) { if( !m_context || !m_owner ) return false; if( code == C_LOAD ) { Library lib; int64_t id = 0; int64_t ptrPath = 0; std::string path; if( !m_context->stackPop( caller, &id, sizeof( id ) ) ) return false; if( !m_context->stackPop( caller, &ptrPath, sizeof( ptrPath ) ) ) return false; if( m_libraries.count( id ) ) return false; if( !id || !ptrPath ) return false; path = (char*)ptrPath; lib.handle = loadLibrary( path ); if( !lib.handle ) { for( auto p : paths ) { lib.handle = loadLibrary( (p + "/" + path).c_str() ); if( lib.handle ) break; } } if( !lib.handle ) { int32_t v = 0; m_context->stackPush( caller, &v, sizeof( v ) ); return true; } lib.onLoad = (int32_t (*)())getFunction( lib.handle, "onLoad" ); lib.onUnload = (int32_t (*)())getFunction( lib.handle, "onUnload" ); lib.onCall = (int32_t (*)( Runtime*, int64_t, int64_t ))getFunction( lib.handle, "onCall" ); if( !lib.onLoad || !lib.onUnload || !lib.onCall ) { closeLibrary( lib.handle ); int32_t v = 0; m_context->stackPush( caller, &v, sizeof( v ) ); return true; } if( !lib.onLoad() ) { closeLibrary( lib.handle ); int32_t v = 0; m_context->stackPush( caller, &v, sizeof( v ) ); return true; } m_libraries[ id ] = lib; int32_t v = 1; m_context->stackPush( caller, &v, sizeof( v ) ); return true; } else if( code == C_UNLOAD ) { int64_t id = 0; if( !m_context->stackPop( caller, &id, sizeof( id ) ) ) return false; if( !m_libraries.count( id ) ) return false; m_libraries[ id ].onUnload(); closeLibrary( m_libraries[ id ].handle ); m_libraries.erase( id ); int32_t v = 1; m_context->stackPush( caller, &v, sizeof( v ) ); return true; } else if( code == C_CALL ) { int64_t id = 0; int64_t func = 0; if( !m_context->stackPop( caller, &id, sizeof( id ) ) ) return false; if( !m_context->stackPop( caller, &func, sizeof( func ) ) ) return false; if( !m_libraries.count( id ) ) return false; int32_t status = m_libraries[ id ].onCall( m_owner, (int64_t)caller, func ); return status; } return false; }
void CopyGui::on_btnBack_clicked() { Library *lib = new Library(); lib->show(); this->hide(); }
void function_arg_valid() const { const char xmldata[] = "<?xml version=\"1.0\"?>\n" "<def>\n" " <function name=\"foo\">\n" " <arg nr=\"1\"><valid>1:</valid></arg>\n" " <arg nr=\"2\"><valid>-7:0</valid></arg>\n" " <arg nr=\"3\"><valid>1:5,8</valid></arg>\n" " <arg nr=\"4\"><valid>-1,5</valid></arg>\n" " <arg nr=\"5\"><valid>:1,5</valid></arg>\n" " </function>\n" "</def>"; tinyxml2::XMLDocument doc; doc.Parse(xmldata, sizeof(xmldata)); Library library; library.load(doc); TokenList tokenList(nullptr); std::istringstream istr("foo();"); tokenList.createTokens(istr); tokenList.front()->next()->astOperand1(tokenList.front()); // 1- ASSERT_EQUALS(false, library.isargvalid(tokenList.front(), 1, -10)); ASSERT_EQUALS(false, library.isargvalid(tokenList.front(), 1, 0)); ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 1, 1)); ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 1, 10)); // -7-0 ASSERT_EQUALS(false, library.isargvalid(tokenList.front(), 2, -10)); ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 2, -7)); ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 2, -3)); ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 2, 0)); ASSERT_EQUALS(false, library.isargvalid(tokenList.front(), 2, 1)); // 1-5,8 ASSERT_EQUALS(false, library.isargvalid(tokenList.front(), 3, 0)); ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 3, 1)); ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 3, 3)); ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 3, 5)); ASSERT_EQUALS(false, library.isargvalid(tokenList.front(), 3, 6)); ASSERT_EQUALS(false, library.isargvalid(tokenList.front(), 3, 7)); ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 3, 8)); ASSERT_EQUALS(false, library.isargvalid(tokenList.front(), 3, 9)); // -1,5 ASSERT_EQUALS(false, library.isargvalid(tokenList.front(), 4, -10)); ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 4, -1)); // :1,5 ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 5, -10)); ASSERT_EQUALS(true, library.isargvalid(tokenList.front(), 5, 1)); ASSERT_EQUALS(false, library.isargvalid(tokenList.front(), 5, 2)); }
void SO_Group::add_executable (const char * path) { ACE_Process proc; ACE_Process_Options opts; ACE_HANDLE pipe[2]; ACE_Pipe io(pipe); opts.set_handles (ACE_STDIN,pipe[1]); int result = opts.command_line ("ldd %s",path); // Prevent compiler warning about "unused variable" if ACE_ASSERT is // an empty macro. ACE_UNUSED_ARG (result); ACE_ASSERT (result == 0); proc.spawn (opts); if (ACE_OS::close(pipe[1]) == -1) ACE_DEBUG ((LM_DEBUG, "%p\n", "close")); opts.release_handles(); const int max_line_length = 1000; char line[max_line_length]; while (1) { ACE_OS::memset (line,0,max_line_length); int len = 0; int nread = 0; int bogus = 0; // skip initial whitespace while ((nread = ACE_OS::read(pipe[0],line,1)) == 1 && (*line == ' ' || *line == '\t')); if (nread != 1) break; // read the library name len = 1; while ((nread = ACE_OS::read(pipe[0],line + len,1)) == 1 && (line[len] != ' ')) if (! bogus && ++len == max_line_length) { bogus = 1; break; } if (nread != 1 || bogus) break; line[len] = 0; char * dot = ACE_OS::strchr (line,'.'); if (dot) *dot = 0; char * libname = line + 3; // skip over "lib" // check to see if this is a new library int found = 0; for (int i = 0; !found && i < num_libs_; i++) found = (libs_[i]->name() == libname); if (!found) { Library *nlib = new Library(libname); ACE_OS::memset (line,0,max_line_length); // skip over '=> ' if (ACE_OS::read(pipe[0],line,3) != 3) break; // get library path len = 0; while ((nread = ACE_OS::read(pipe[0],line + len,1)) == 1 && (line[len] != ' ')) if (! bogus && ++len == max_line_length) { bogus = 1; break; } if (nread != 1 || bogus) break; line[len] = 0; nlib->set_path (line); libs_[num_libs_++] = nlib; ACE_ASSERT (num_libs_ < max_libs_); // grow max libs? } // skip the rest of the line while ((nread = ACE_OS::read(pipe[0],line,1)) == 1 && *line != '\n'); if (nread != 1) break; } proc.wait (); ACE_OS::close (pipe[0]); undef_wrapper_.add_source(path,1); // now do the ldd, iterate over the results to add new libs, etc. }
void function_arg_valid() const { const char xmldata[] = "<?xml version=\"1.0\"?>\n" "<def>\n" " <function name=\"foo\">\n" " <arg nr=\"1\"><valid>1:</valid></arg>\n" " <arg nr=\"2\"><valid>-7:0</valid></arg>\n" " <arg nr=\"3\"><valid>1:5,8</valid></arg>\n" " <arg nr=\"4\"><valid>-1,5</valid></arg>\n" " <arg nr=\"5\"><valid>:1,5</valid></arg>\n" " </function>\n" "</def>"; tinyxml2::XMLDocument doc; doc.Parse(xmldata, sizeof(xmldata)); Library library; library.load(doc); // 1- ASSERT_EQUALS(false, library.isargvalid("foo", 1, -10)); ASSERT_EQUALS(false, library.isargvalid("foo", 1, 0)); ASSERT_EQUALS(true, library.isargvalid("foo", 1, 1)); ASSERT_EQUALS(true, library.isargvalid("foo", 1, 10)); // -7-0 ASSERT_EQUALS(false, library.isargvalid("foo", 2, -10)); ASSERT_EQUALS(true, library.isargvalid("foo", 2, -7)); ASSERT_EQUALS(true, library.isargvalid("foo", 2, -3)); ASSERT_EQUALS(true, library.isargvalid("foo", 2, 0)); ASSERT_EQUALS(false, library.isargvalid("foo", 2, 1)); // 1-5,8 ASSERT_EQUALS(false, library.isargvalid("foo", 3, 0)); ASSERT_EQUALS(true, library.isargvalid("foo", 3, 1)); ASSERT_EQUALS(true, library.isargvalid("foo", 3, 3)); ASSERT_EQUALS(true, library.isargvalid("foo", 3, 5)); ASSERT_EQUALS(false, library.isargvalid("foo", 3, 6)); ASSERT_EQUALS(false, library.isargvalid("foo", 3, 7)); ASSERT_EQUALS(true, library.isargvalid("foo", 3, 8)); ASSERT_EQUALS(false, library.isargvalid("foo", 3, 9)); // -1,5 ASSERT_EQUALS(false, library.isargvalid("foo", 4, -10)); ASSERT_EQUALS(true, library.isargvalid("foo", 4, -1)); // :1,5 ASSERT_EQUALS(true, library.isargvalid("foo", 5, -10)); ASSERT_EQUALS(true, library.isargvalid("foo", 5, 1)); ASSERT_EQUALS(false, library.isargvalid("foo", 5, 2)); }
Library::Error readLibrary(Library& library, const char* xmldata) const { tinyxml2::XMLDocument doc; doc.Parse(xmldata); return library.load(doc); }