void URI::load_queries() { auto _ = query_; util::sview name {}; util::sview value {}; util::sview::size_type base {0U}; util::sview::size_type break_point {}; while (true) { if ((break_point = _.find('=')) not_eq util::sview::npos) { name = _.substr(base, break_point); //----------------------------------- _.remove_prefix(name.length() + 1U); } else { break; } if ((break_point = _.find('&')) not_eq util::sview::npos) { value = _.substr(base, break_point); query_map_.emplace(name, value); _.remove_prefix(value.length() + 1U); } else { query_map_.emplace(name, _); } } }
static size_t SkipInputToken(string_view const Str, subst_strings* const Strings = nullptr) { const auto cTail = tokens::skip(Str, tokens::input); if (!cTail) return 0; string_view Tail(cTail); auto Range = Tail; brackets TitleBrackets{}; const auto TitleSize = ProcessBrackets(Range, L'?', TitleBrackets); if (!TitleSize) return 0; Range.remove_prefix(TitleSize); brackets TextBrackets{}; const auto TextSize = ProcessBrackets(Range, L'!', TextBrackets); if (!TextSize) return 0; Range.remove_prefix(TextSize); if (Strings) { Strings->Title.All = Tail.substr(0, TitleSize - 1); Strings->Text.All = Tail.substr(TitleSize, TextSize - 1); Strings->Title.Sub = TitleBrackets.str(); Strings->Text.Sub = TextBrackets.str(); } return tokens::input.size() + TitleSize + TextSize; }
// ----------------------------------------------------------------------------- // Imports all files (including subdirectories) from [directory] into the // archive // ----------------------------------------------------------------------------- bool Archive::importDir(string_view directory) { // Get a list of all files in the directory vector<string> files; for (const auto& item : std::filesystem::recursive_directory_iterator{ directory }) if (item.is_regular_file()) files.push_back(item.path().string()); // Go through files for (const auto& file : files) { StrUtil::Path fn{ StrUtil::replace(file, directory, "") }; // Remove directory from entry name // Split filename into dir+name auto ename = fn.fileName(); auto edir = fn.path(); // Remove beginning \ or / from dir if (StrUtil::startsWith(edir, '\\') || StrUtil::startsWith(edir, '/')) edir.remove_prefix(1); // Add the entry auto dir = createDir(edir); auto entry = addNewEntry(ename, dir->numEntries() + 1, dir); // Load data entry->importFile(file); // Set unmodified entry->setState(ArchiveEntry::State::Unmodified); dir->dirEntry()->setState(ArchiveEntry::State::Unmodified); } return true; }
void CommandLineParser::parseArgs(const std::vector<StringView>& args, CommandLineFlags& result) const { size_t numPositionalConsumed = 0; size_t numFlagConsumed = 0; while (numFlagConsumed < args.size()) { auto flag = args[numFlagConsumed]; if (!isOption(flag)) // Positional arguments { if (numPositionalConsumed >= posFlagMap.size()) throw ParseException("too many positional arguments"); auto inserted = result.addFlag(posFlagMap[numPositionalConsumed].first, flag); assert(inserted && "Insertion failed"); ++numPositionalConsumed; } else // Optional arguments { flag.remove_prefix(1); // See if flag is "-help" if (flag == "help") throw HelpException(); auto itr = optFlagMap.find(flag); if (itr == optFlagMap.end()) throw ParseException("Option not recognized: " + flag.to_string()); if (itr->second.defaultValue) { ++numFlagConsumed; if (numFlagConsumed >= args.size()) throw ParseException("More argument needs to be provided after option " + flag.to_string()); auto flagArg = args[numFlagConsumed]; if (isOption(flagArg)) throw ParseException("Found another option instead of an argument after option " + flag.to_string()); auto inserted = result.addFlag(flag, flagArg); assert(inserted && "Insertion failed"); } else { auto inserted = result.addFlag(flag, ""); assert(inserted && "Insertion failed"); } } ++numFlagConsumed; } if (numPositionalConsumed < posFlagMap.size()) throw ParseException("Not enough positional arguments are provided"); for (auto const& mapping: optFlagMap) { if (mapping.second.defaultValue && result.lookup(mapping.first) == nullptr) result.addFlag(mapping.first, *mapping.second.defaultValue); } }
/** * This function moves outputs from final nodes to transitions leading to final nodes. */ static void subsequential_to_normal_transducer(struct dictionary_node* root, struct dictionary_node* node, struct string_hash* inf_codes, int pos,unichar* z, Ustring* normalizedOutput) { struct dictionary_node_transition* tmp=node->trans; int prefix_set=0; Ustring* prefix=new_Ustring(); while (tmp!=NULL) { z[pos]=tmp->letter; z[pos+1]='\0'; subsequential_to_normal_transducer(root,tmp->node,inf_codes,pos+1,z,normalizedOutput); /* First, if the destination state is final, we place its output on the output * of the current transition */ if (tmp->node->single_INF_code_list!=NULL) { //error("<%S>: output=<%S>\n",z,normalizedOutput->str); tmp->output=u_strdup(inf_codes->value[tmp->node->INF_code]); } if (normalizedOutput->len!=0) { /* Then, we add the normalized output obtained recursively, if any */ //error("<%S>: moving normalized output <%S>\n",z,normalizedOutput->str); if (tmp->output==NULL) { tmp->output=u_strdup(normalizedOutput->str); } else { tmp->output=(unichar*)realloc(tmp->output,sizeof(unichar)*(1+normalizedOutput->len+u_strlen(tmp->output))); } } if (!prefix_set) { prefix_set=1; u_strcpy(prefix,tmp->output); } else { get_longest_common_prefix(prefix,tmp->output); } tmp=tmp->next; } if (node==root || node->single_INF_code_list!=NULL) { /* If we are in the initial state or a final one, we let the transitions as they are, since * their outputs can not move more to the left */ z[pos]='\0'; free_Ustring(prefix); empty(normalizedOutput); return; } tmp=node->trans; while (tmp!=NULL) { //error("prefix removal: <%S> => ",tmp->output); remove_prefix(prefix->len,tmp->output); //error("<%S>\n",tmp->output); tmp=tmp->next; } z[pos]='\0'; u_strcpy(normalizedOutput,prefix); free_Ustring(prefix); }
std::string operator()(const utils::piece& word) { icu::UnicodeString uword = icu::UnicodeString::fromUTF8(icu::StringPiece(word.data(), word.size())); normalize_ya_alef_maqsoura(uword); normalize_aggressive(uword); remove_prefix(uword); remove_suffix(uword); std::string word_stemmed; uword.toUTF8String(word_stemmed); return word_stemmed; }
void RestServ::reset(HttpMessage& data) noexcept { state_ = 0; const auto method = data.method(); if (method == "GET") { state_ |= MethodGet; } else if (method == "POST") { state_ |= MethodPost; } else if (method == "PUT") { state_ |= MethodPut; } else if (method == "DELETE") { state_ |= MethodDelete; } auto uri = data.uri(); // Remove leading slash. if (uri.front() == '/') { uri.remove_prefix(1); } uri_.reset(uri); }
static int parse_date(struct universaltime *ut, Octstr *os) { if (remove_long(&ut->year, os) == -1 || remove_prefix(os, octstr_imm("-")) == -1 || remove_long(&ut->month, os) == -1 || remove_prefix(os, octstr_imm("-")) == -1 || remove_long(&ut->day, os) == -1 || remove_prefix(os, octstr_imm(" ")) == -1 || remove_long(&ut->hour, os) == -1 || remove_prefix(os, octstr_imm(":")) == -1 || remove_long(&ut->minute, os) == -1 || remove_prefix(os, octstr_imm(":")) == -1 || remove_long(&ut->second, os) == -1 || remove_prefix(os, octstr_imm(" ")) == -1) return -1; return 0; }
TokenType getNextToken(const util::FastInsertVector<string_view>& lines, size_t* line, size_t* offset, const string_view& whole, Location& pos, Token* out, bool crlf) { bool flag = true; if(*line == lines.size()) { out->loc = pos; out->type = TokenType::EndOfFile; return TokenType::EndOfFile; } string_view stream = lines[*line].substr(*offset); if(stream.empty()) { out->loc = pos; out->type = TokenType::EndOfFile; return TokenType::EndOfFile; } size_t read = 0; size_t unicodeLength = 0; // first eat all whitespace skipWhitespace(stream, pos, offset); Token& tok = *out; tok.loc = pos; tok.type = TokenType::Invalid; // check compound symbols first. if(hasPrefix(stream, "//")) { tok.type = TokenType::Comment; // stream = stream.substr(0, 0); (*line)++; pos.line++; pos.col = 0; (*offset) = 0; // don't assign lines[line] = stream, since over here we've changed 'line' to be the next one. flag = false; tok.text = ""; } else if(hasPrefix(stream, "==")) { tok.type = TokenType::EqualsTo; tok.text = "=="; read = 2; } else if(hasPrefix(stream, ">=")) { tok.type = TokenType::GreaterEquals; tok.text = ">="; read = 2; } else if(hasPrefix(stream, "<=")) { tok.type = TokenType::LessThanEquals; tok.text = "<="; read = 2; } else if(hasPrefix(stream, "!=")) { tok.type = TokenType::NotEquals; tok.text = "!="; read = 2; } else if(hasPrefix(stream, "||")) { tok.type = TokenType::LogicalOr; tok.text = "||"; read = 2; } else if(hasPrefix(stream, "&&")) { tok.type = TokenType::LogicalAnd; tok.text = "&&"; read = 2; } else if(hasPrefix(stream, "<-")) { tok.type = TokenType::LeftArrow; tok.text = "<-"; read = 2; } else if(hasPrefix(stream, "->")) { tok.type = TokenType::RightArrow; tok.text = "->"; read = 2; } else if(hasPrefix(stream, "<=")) { tok.type = TokenType::FatLeftArrow; tok.text = "<="; read = 2; } else if(hasPrefix(stream, "=>")) { tok.type = TokenType::FatRightArrow; tok.text = "=>"; read = 2; } else if(hasPrefix(stream, "++")) { tok.type = TokenType::DoublePlus; tok.text = "++"; read = 2; } else if(hasPrefix(stream, "--")) { tok.type = TokenType::DoubleMinus; tok.text = "--"; read = 2; } else if(hasPrefix(stream, "+=")) { tok.type = TokenType::PlusEq; tok.text = "+="; read = 2; } else if(hasPrefix(stream, "-=")) { tok.type = TokenType::MinusEq; tok.text = "-="; read = 2; } else if(hasPrefix(stream, "*=")) { tok.type = TokenType::MultiplyEq; tok.text = "*="; read = 2; } else if(hasPrefix(stream, "/=")) { tok.type = TokenType::DivideEq; tok.text = "/="; read = 2; } else if(hasPrefix(stream, "%=")) { tok.type = TokenType::ModEq; tok.text = "%="; read = 2; } else if(hasPrefix(stream, "&=")) { tok.type = TokenType::AmpersandEq; tok.text = "&="; read = 2; } else if(hasPrefix(stream, "|=")) { tok.type = TokenType::PipeEq; tok.text = "|="; read = 2; } else if(hasPrefix(stream, "^=")) { tok.type = TokenType::CaretEq; tok.text = "^="; read = 2; } else if(hasPrefix(stream, "::")) { tok.type = TokenType::DoubleColon; tok.text = "::"; read = 2; } else if(hasPrefix(stream, "...")) { tok.type = TokenType::Ellipsis; tok.text = "..."; read = 3; } else if(hasPrefix(stream, "..<")) { tok.type = TokenType::HalfOpenEllipsis; tok.text = "..<"; read = 3; } else if(hasPrefix(stream, "/*")) { int currentNest = 1; // support nested, so basically we have to loop until we find either a /* or a */ stream.remove_prefix(2); (*offset) += 2; pos.col += 2; Location opening = pos; Location curpos = pos; size_t k = 0; while(currentNest > 0) { // we can do this, because we know the closing token (*/) is 2 chars long // so if we have 1 char left, gg. if(k + 1 == stream.size() || stream[k] == '\n') { if(*line + 1 == lines.size()) error(opening, "expected closing */ (reached EOF), for block comment started here:"); // else, get the next line. // also note: if we're in this loop, we're inside a block comment. // since the ending token cannot be split across lines, we know that this last char // must also be part of the comment. hence, just skip over it. k = 0; curpos.line++; curpos.col = 0; (*offset) = 0; (*line)++; stream = lines[*line]; continue; } if(stream[k] == '/' && stream[k + 1] == '*') currentNest++, k++, curpos.col++, opening = curpos; else if(stream[k] == '*' && stream[k + 1] == '/') currentNest--, k++, curpos.col++; k++; curpos.col++; } if(currentNest != 0) error(opening, "expected closing */ (reached EOF), for block comment started here:"); pos = curpos; // don't actually store the text, because it's pointless and memory-wasting // tok.text = "/* I used to be a comment like you, until I took a memory-leak to the knee. */"; tok.type = TokenType::Comment; tok.text = ""; read = k; } else if(hasPrefix(stream, "*/")) { unexpected(tok.loc, "'*/'"); } // attrs else if(hasPrefix(stream, "@nomangle")) { tok.type = TokenType::Attr_NoMangle; tok.text = "@nomangle"; read = 9; } else if(hasPrefix(stream, "@entry")) { tok.type = TokenType::Attr_EntryFn; tok.text = "@entry"; read = 6; } else if(hasPrefix(stream, "@raw")) { tok.type = TokenType::Attr_Raw; tok.text = "@raw"; read = 4; } else if(hasPrefix(stream, "@operator")) { tok.type = TokenType::Attr_Operator; tok.text = "@operator"; read = 9; } // unicode stuff else if(hasPrefix(stream, "ƒ")) { tok.type = TokenType::Func; read = std::string("ƒ").length(); tok.text = "ƒ"; unicodeLength = 1; } else if(hasPrefix(stream, "fi")) { tok.type = TokenType::ForeignFunc; read = std::string("fi").length(); tok.text = "fi"; unicodeLength = 1; } else if(hasPrefix(stream, "÷")) { tok.type = TokenType::Divide; read = std::string("÷").length(); tok.text = "÷"; unicodeLength = 1; } else if(hasPrefix(stream, "≠")) { tok.type = TokenType::NotEquals; read = std::string("≠").length(); tok.text = "≠"; unicodeLength = 1; } else if(hasPrefix(stream, "≤")) { tok.type = TokenType::LessThanEquals; read = std::string("≤").length(); tok.text = "≤"; unicodeLength = 1; } else if(hasPrefix(stream, "≥")) { tok.type = TokenType::GreaterEquals; read = std::string("≥").length(); tok.text = "≥"; unicodeLength = 1; } // note some special-casing is needed to differentiate between unary +/- and binary +/- // cases where we want binary: // ...) + 3 // ...] + 3 // ident + 3 // number + 3 // string + 3 // so in every other case we want unary +/-. // note: this dumb '<=255' thing is because windows likes to assert useless things. else if((!stream.empty() && ((stream[0] >= 1 && (int) stream[0] <= 255 && isdigit(stream[0])) || shouldConsiderUnaryLiteral(stream, pos))) /* handle cases like '+ 3' or '- 14' (ie. space between sign and number) */ && ((isdigit(stream[0]) ? true : false) || (stream.size() > 1 && isdigit(stream[1])))) { // copy it. auto tmp = stream; if(tmp.find('-') == 0 || tmp.find('+') == 0) tmp.remove_prefix(1); int base = 10; if(tmp.find("0x") == 0 || tmp.find("0X") == 0) base = 16, tmp.remove_prefix(2); else if(tmp.find("0b") == 0 || tmp.find("0B") == 0) base = 2, tmp.remove_prefix(2); // find that shit auto end = std::find_if_not(tmp.begin(), tmp.end(), [base](const char& c) -> bool { if(base == 10) return isdigit(c); if(base == 16) return isdigit(c) || (toupper(c) >= 'A' && toupper(c) <= 'F'); else return (c == '0' || c == '1'); }); tmp.remove_prefix((end - tmp.begin())); // check if we have 'e' or 'E' bool hadExp = false; if(tmp.size() > 0 && (tmp[0] == 'e' || tmp[0] == 'E')) { if(base != 10) error("exponential form is supported with neither hexadecimal nor binary literals"); // find that shit auto next = std::find_if_not(tmp.begin() + 1, tmp.end(), isdigit); // this does the 'e' as well. tmp.remove_prefix(next - tmp.begin()); hadExp = true; } size_t didRead = stream.size() - tmp.size(); auto post = stream.substr(didRead); if(!post.empty() && post[0] == '.') { if(base != 10) error("invalid floating point literal; only valid in base 10"); else if(hadExp) error("invalid floating point literal; decimal point cannot occur after the exponent ('e' or 'E')."); // if the previous token was a '.' as well, then we're doing some tuple access // eg. x.0.1 (we would be at '0', having a period both ahead and behind us) // if the next token is not a number, then same thing, eg. // x.0.z, where the first tuple element of 'x' is a struct or something. // so -- lex a floating point *iff* the previous token was not '.', and the next token is a digit. if(prevType != TokenType::Period && post.size() > 1 && isdigit(post[1])) { // yes, parse a floating point post.remove_prefix(1), didRead++; while(post.size() > 0 && isdigit(post.front())) post.remove_prefix(1), didRead++; // ok. } else { // no, just return the integer token. // (which we do below, so just do nothing here) } } tok.text = stream.substr(0, didRead); tok.type = TokenType::Number; tok.loc.len = didRead; read = didRead; } else if(!stream.empty() && (stream[0] == '_' || utf8iscategory(stream.data(), stream.size(), UTF8_CATEGORY_LETTER) > 0)) { // get as many letters as possible first size_t identLength = utf8iscategory(stream.data(), stream.size(), UTF8_CATEGORY_LETTER | UTF8_CATEGORY_PUNCTUATION_CONNECTOR | UTF8_CATEGORY_NUMBER); read = identLength; tok.text = stream.substr(0, identLength); initKeywordMap(); if(auto it = keywordMap.find(tok.text); it != keywordMap.end()) tok.type = it->second; else
static void populate_multiboot(struct dirent *root, struct bootinfo *bi) { lvaddr_t data; size_t len; errval_t err; assert(root != NULL); // create bootscript file struct dirent *bootscript_f; err = ramfs_create(root, BOOTSCRIPT_FILE_NAME, &bootscript_f); if (err_is_fail(err)) { USER_PANIC_ERR(err, "error creating bootscript file"); } debug_printf("pre-populating from boot image...\n"); for (int i = 0; i < bi->regions_length; i++) { struct mem_region *region = &bi->regions[i]; if (region->mr_type != RegionType_Module) { /* Not of module type */ continue; } const char *name = remove_prefix(multiboot_module_name(region)); // is this a ramfs image we should unpack? if (strstr(name, "_ramfs.cpio.gz") != NULL) { debug_printf("unpacking Gzipped CPIO %s\n", name); err = spawn_map_module(region, &len, &data, NULL); if (err_is_fail(err)) { USER_PANIC_ERR(err, "error in spawn_map_module"); } err = unpack_cpiogz(root, (void *)data, len); if (err_is_fail(err)) { USER_PANIC_ERR(err, "error unpacking ramfs image"); } // TODO: unmap } else if (strstr(name, "_ramfs.cpio") != NULL) { debug_printf("unpacking CPIO %s\n", name); err = spawn_map_module(region, &len, &data, NULL); if (err_is_fail(err)) { USER_PANIC_ERR(err, "error in spawn_map_module"); } err = unpack_cpio(root, (void *)data, len); if (err_is_fail(err)) { USER_PANIC_ERR(err, "error unpacking ramfs image"); } // TODO: unmap } else { // map the image err = getimage(region, &len, &data); if (err_is_fail(err)) { USER_PANIC_ERR(err, "error in getimage"); } // copy to ramfs err = write_file(root, name, (void *)data, len); if (err_is_fail(err)) { if (err_no(err) == FS_ERR_EXISTS) { debug_printf("%s already exists, skipping it\n", name); } else { USER_PANIC_ERR(err, "error in write_file"); } } // TODO: unmap // append line to bootscript const char *args = remove_prefix(multiboot_module_rawstring(region)); err = append_to_file(bootscript_f, args); if (err_is_fail(err)) { USER_PANIC_ERR(err, "error appending to bootscript"); } } } debug_printf("ready\n"); }
void LLXferManager::processFileRequest (LLMessageSystem *mesgsys, void ** /*user_data*/) { U64 id; std::string local_filename; ELLPath local_path = LL_PATH_NONE; S32 result = LL_ERR_NOERR; LLUUID uuid; LLAssetType::EType type; S16 type_s16; BOOL b_use_big_packets; mesgsys->getBOOL("XferID", "UseBigPackets", b_use_big_packets); mesgsys->getU64Fast(_PREHASH_XferID, _PREHASH_ID, id); char U64_BUF[MAX_STRING]; /* Flawfinder : ignore */ llinfos << "xfer request id: " << U64_to_str(id, U64_BUF, sizeof(U64_BUF)) << " to " << mesgsys->getSender() << llendl; mesgsys->getStringFast(_PREHASH_XferID, _PREHASH_Filename, local_filename); { U8 local_path_u8; mesgsys->getU8("XferID", "FilePath", local_path_u8); local_path = (ELLPath)local_path_u8; } mesgsys->getUUIDFast(_PREHASH_XferID, _PREHASH_VFileID, uuid); mesgsys->getS16Fast(_PREHASH_XferID, _PREHASH_VFileType, type_s16); type = (LLAssetType::EType)type_s16; LLXfer *xferp; if (uuid != LLUUID::null) { if(NULL == LLAssetType::lookup(type)) { llwarns << "Invalid type for xfer request: " << uuid << ":" << type_s16 << " to " << mesgsys->getSender() << llendl; return; } llinfos << "starting vfile transfer: " << uuid << "," << LLAssetType::lookup(type) << " to " << mesgsys->getSender() << llendl; if (! mVFS) { llwarns << "Attempt to send VFile w/o available VFS" << llendl; return; } xferp = (LLXfer *)new LLXfer_VFile(mVFS, uuid, type); if (xferp) { xferp->mNext = mSendList; mSendList = xferp; result = xferp->startSend(id,mesgsys->getSender()); } else { llerrs << "Xfer allcoation error" << llendl; } } else if (!local_filename.empty()) { // See DEV-21775 for detailed security issues if (local_path == LL_PATH_NONE) { // this handles legacy simulators that are passing objects // by giving a filename that explicitly names the cache directory static const std::string legacy_cache_prefix = "data/"; if (remove_prefix(local_filename, legacy_cache_prefix)) { local_path = LL_PATH_CACHE; } } switch (local_path) { case LL_PATH_NONE: if(!validateFileForTransfer(local_filename)) { llwarns << "SECURITY: Unapproved filename '" << local_filename << llendl; return; } break; case LL_PATH_CACHE: if(!verify_cache_filename(local_filename)) { llwarns << "SECURITY: Illegal cache filename '" << local_filename << llendl; return; } break; default: llwarns << "SECURITY: Restricted file dir enum: " << (U32)local_path << llendl; return; } std::string expanded_filename = gDirUtilp->getExpandedFilename( local_path, local_filename ); llinfos << "starting file transfer: " << expanded_filename << " to " << mesgsys->getSender() << llendl; BOOL delete_local_on_completion = FALSE; mesgsys->getBOOL("XferID", "DeleteOnCompletion", delete_local_on_completion); // -1 chunk_size causes it to use the default xferp = (LLXfer *)new LLXfer_File(expanded_filename, delete_local_on_completion, b_use_big_packets ? LL_XFER_LARGE_PAYLOAD : -1); if (xferp) { xferp->mNext = mSendList; mSendList = xferp; result = xferp->startSend(id,mesgsys->getSender()); } else { llerrs << "Xfer allcoation error" << llendl; } } else { char U64_BUF[MAX_STRING]; /* Flawfinder : ignore */ llinfos << "starting memory transfer: " << U64_to_str(id, U64_BUF, sizeof(U64_BUF)) << " to " << mesgsys->getSender() << llendl; xferp = findXfer(id, mSendList); if (xferp) { result = xferp->startSend(id,mesgsys->getSender()); } else { llinfos << "Warning: " << U64_BUF << " not found." << llendl; result = LL_ERR_FILE_NOT_FOUND; } } if (result) { if (xferp) { xferp->abort(result); removeXfer(xferp,&mSendList); } else // can happen with a memory transfer not found { llinfos << "Aborting xfer to " << mesgsys->getSender() << " with error: " << result << llendl; mesgsys->newMessageFast(_PREHASH_AbortXfer); mesgsys->nextBlockFast(_PREHASH_XferID); mesgsys->addU64Fast(_PREHASH_ID, id); mesgsys->addS32Fast(_PREHASH_Result, result); mesgsys->sendMessage(mesgsys->getSender()); } } else if(xferp && (numActiveXfers(xferp->mRemoteHost) < mMaxOutgoingXfersPerCircuit)) { xferp->sendNextPacket(); changeNumActiveXfers(xferp->mRemoteHost,1); // llinfos << "***STARTING XFER IMMEDIATELY***" << llendl; } else { if(xferp) { llinfos << " queueing xfer request, " << numPendingXfers(xferp->mRemoteHost) << " ahead of this one" << llendl; } else { llwarns << "LLXferManager::processFileRequest() - no xfer found!" << llendl; } } }
NwaRefPtr assemble_nwa(ProcedureMap const & procedures, boost::function<void (Nwa &, State, State)> call_inserter, boost::function<void (Nwa &, State, State, State)> return_inserter) { NwaRefPtr finalnwa = new Nwa(); std::map<std::string, std::set<State> > entries_map; std::map<std::string, std::set<State> > exits_map; //////// // We will set up the states, then fix up the transitions. // First, combine all of the procedures (to get all the states // and transitions.) for (ProcedureMap::const_iterator proc = procedures.begin(); proc != procedures.end(); ++proc) { NwaRefPtr min = minimize_internal_nwa(proc->second); //NwaRefPtr min = proc->second; entries_map[proc->first] = min->getInitialStates(); exits_map[proc->first] = min->getFinalStates(); if (proc->first != "main") { min->clearInitialStates(); min->clearFinalStates(); } finalnwa->combineWith(*min); } //////// // Now set up the transitions // Now, find each of the transitions on a symbol __call__*. These // are the transitions we will replace. Nwa::Internals fake_call_transitions; for (Nwa::InternalIterator trans=finalnwa->beginInternalTrans(); trans != finalnwa->endInternalTrans(); ++trans) { std::string symbol = key2str(trans->second); if (string_starts_with(symbol, call_prefix)) { fake_call_transitions.insert(*trans); } } // Okay, now we have to do two things with each of those // transitions. The simpler one is to remove it. The more // complicated one is add a call and a return transition. The // call transition goes from the source to the entry of the // procedure that corresponds to the transition's symbol. The // return goes from the exit of that procedure to the return // node, with the call node as the predecessor. // // Schematically: // C ------------------> R // __call__foo // turns into // C R // | /\ . // call | | return (C as call predecessor) // | | // V | // entry_foo exit_foo // for (Nwa::Internals::iterator fake_call = fake_call_transitions.begin(); fake_call != fake_call_transitions.end(); ++fake_call) { // Remove the fake call. finalnwa->removeInternalTrans(*fake_call); // Prepare for the call and return transitions Key call_site = fake_call->first; Key return_site = fake_call->third; std::string symbol = key2str(fake_call->second); std::string callee_name = remove_prefix(symbol, call_prefix); assert(entries_map.find(callee_name) != entries_map.end()); assert(exits_map.find(callee_name) != exits_map.end()); std::set<State> const & entries = entries_map[callee_name]; std::set<State> const & exits = exits_map[callee_name]; // I don't think these assertions are necessary for the below // to work, but they do apply in my setting. TODO: consider // removing them when I make this code more general. -Evan // 3/10/11 (Actually change to >= 1 instead of remove // entirely.) assert(entries.size() == 1); // Now add the call transition(s) for (std::set<State>::const_iterator entry = entries.begin(); entry != entries.end(); ++entry) { call_inserter(*finalnwa, call_site, *entry); //finalnwa->addCallTrans(call_site, call_key, *entry); //finalnwa->addInternalTrans(call_site, EPSILON, *entry); } // Now add the return transition(s) for (std::set<State>::const_iterator exit = exits.begin(); exit != exits.end(); ++exit) { return_inserter(*finalnwa, *exit, call_site, return_site); //finalnwa->addReturnTrans(*exit, call_site, return_key, return_site); //finalnwa->addInternalTrans(*exit, EPSILON, return_site); } } // Finally, we remove the __call__ symbols from the automaton. std::set<Symbol> to_remove; for (Nwa::SymbolIterator symiter = finalnwa->beginSymbols(); symiter != finalnwa->endSymbols(); ++symiter) { Symbol symbol = *symiter; if (string_starts_with(key2str(symbol), call_prefix)) { // It shouldn't be used in any transitions. Check that. assert(query::getSources_Sym(*finalnwa, symbol).size() == 0); assert(query::getCallSites_Sym(*finalnwa, symbol).size() == 0); assert(query::getExits_Sym(*finalnwa, symbol).size() == 0); // Now schedule it for removal to_remove.insert(symbol); } } for (std::set<Symbol>::iterator s=to_remove.begin(); s!=to_remove.end(); ++s){ finalnwa->removeSymbol(*s); } return finalnwa; } // end assemble_nwa()
static char * get_session_file (void) { static const char prefix[] = "/" DBUS_DIR "/" DBUS_SESSION_BUS_DIR "/"; const char *machine; const char *home; char *display; char *result; char *p; machine = get_machine_uuid (); if (machine == NULL) return NULL; display = xstrdup (getenv ("DISPLAY")); if (display == NULL) { verbose ("X11 integration disabled because X11 is not running\n"); return NULL; } /* remove the screen part of the display name */ p = strrchr (display, ':'); if (p != NULL) { for ( ; *p; ++p) { if (*p == '.') { *p = '\0'; break; } } } /* Note that we leave the hostname in the display most of the * time. The idea is that we want to be per-(machine,display,user) * triplet to be extra-sure we get a bus we can connect to. Ideally * we'd recognize when the hostname matches the machine we're on in * all cases; we do try to drop localhost and localhost.localdomain * as a special common case so that alternate spellings of DISPLAY * don't result in extra bus instances. * * We also kill the ":" if there's nothing in front of it. This * avoids an ugly double underscore in the filename. */ remove_prefix (display, "localhost.localdomain:"); remove_prefix (display, "localhost:"); remove_prefix (display, ":"); /* replace the : in the display with _ if the : is still there. * use _ instead of - since it can't be in hostnames. */ for (p = display; *p; ++p) { if (*p == ':') *p = '_'; } home = get_homedir (); result = malloc (strlen (home) + strlen (prefix) + strlen (machine) + strlen (display) + 2); if (result == NULL) { /* out of memory */ free (display); return NULL; } strcpy (result, home); strcat (result, prefix); strcat (result, machine); strcat (result, "-"); strcat (result, display); free (display); verbose ("session file: %s\n", result); return result; }
/* Main server loop */ int server() { signal(SIGPIPE, SIG_IGN); int listenfd = socket(AF_INET, SOCK_STREAM, 0); // Keep socket open int option = 1; setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)); struct sockaddr_in serv_addr; memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = inet_addr("192.168.0.15"); serv_addr.sin_port = htons(5004); bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); if (listen(listenfd, 10) == -1) { printf("Failed to listen\n"); return -1; } for (;;) { int connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL); if (fork() == 0) { // receive requests char requestBuff[100]; recv(connfd, &requestBuff, 100, 0); // Our response to the client char responseBuffer[10]; // create the full path char *fullPath = pkg_path(remove_prefix(requestBuff)); // The request is for a package dl if (strstr(requestBuff, "PKG:")) { // check if packages exists on server if (pkg_exists(fullPath) == 1) { // tell the client that it exists strcpy(responseBuffer, "EXISTS"); send(connfd, &responseBuffer, 10, 0); // Open the file that we wish to transfer FILE *fp = fopen(fullPath, "rb"); if (fp == NULL) { printf("File open error"); return 1; } // calculate and send file size fseek(fp, 0L, SEEK_END); int fileSize = htonl(ftell(fp)); rewind(fp); send(connfd, &fileSize, sizeof(fileSize), 0); // Transfer the file for (;;) { // First read file in chunks of BUF_SIZE bytes unsigned char buff[BUF_SIZE]={0}; int nread = fread(buff,1,BUF_SIZE,fp); //printf("Bytes read %d\n", nread); // If read was success, send data if (nread > 0) { write(connfd, buff, nread); } if (nread < BUF_SIZE) { if (feof(fp)) //printf("End of file\n"); if (ferror(fp)) printf("Error reading\n"); break; } } fclose(fp); } else { strcpy(responseBuffer, "NOEXIST"); send(connfd, &responseBuffer, 10, 0); } } // The request is for package existence else if (strstr(requestBuff, "EXT:")) { // check if packages exists on server if (pkg_exists(fullPath) == 1) { // tell the client that it exists strcpy(responseBuffer, "EXISTS"); send(connfd, &responseBuffer, 10, 0); } else { // tell the client that it doesn't exist strcpy(responseBuffer, "NOEXIST"); send(connfd, &responseBuffer, 10, 0); } } // free memory free(fullPath); close(connfd); exit(0); } else { close(connfd); } } return 0; }