id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
592
view_information.hpp
WerWolv_ImHex/plugins/builtin/include/content/views/view_information.hpp
#pragma once #include <hex/api/content_registry.hpp> #include <hex/api/task_manager.hpp> #include <hex/ui/view.hpp> #include <ui/widgets.hpp> namespace hex::plugin::builtin { class ViewInformation : public View::Window { public: explicit ViewInformation(); ~ViewInformation() override = default; void drawContent() override; private: void analyze(); struct AnalysisData { bool valid = false; TaskHolder task; const prv::Provider *analyzedProvider = nullptr; Region analysisRegion = { 0, 0 }; ui::RegionType selectionType = ui::RegionType::EntireData; std::list<std::unique_ptr<ContentRegistry::DataInformation::InformationSection>> informationSections; }; PerProvider<AnalysisData> m_analysisData; }; }
859
C++
.h
24
28.333333
113
0.658981
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
593
view_pattern_data.hpp
WerWolv_ImHex/plugins/builtin/include/content/views/view_pattern_data.hpp
#pragma once #include <hex/ui/view.hpp> #include <ui/pattern_drawer.hpp> namespace hex::plugin::builtin { class ViewPatternData : public View::Window { public: ViewPatternData(); ~ViewPatternData() override; void drawContent() override; private: bool m_rowColoring = false; ui::PatternDrawer::TreeStyle m_treeStyle = ui::PatternDrawer::TreeStyle::Default; PerProvider<std::unique_ptr<ui::PatternDrawer>> m_patternDrawer; Region m_hoveredPatternRegion = Region::Invalid(); }; }
556
C++
.h
16
28.8125
89
0.688555
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
594
view_data_processor.hpp
WerWolv_ImHex/plugins/builtin/include/content/views/view_data_processor.hpp
#pragma once #include <imgui.h> #include <hex/ui/view.hpp> #include <hex/data_processor/node.hpp> #include <hex/data_processor/link.hpp> #include <imnodes_internal.h> #include <string> #include <hex/api/task_manager.hpp> #include <nlohmann/json.hpp> namespace hex::plugin::builtin { class ViewDataProcessor : public View::Window { public: struct Workspace { Workspace() = default; std::unique_ptr<ImNodesContext, void(*)(ImNodesContext*)> context = { []{ ImNodesContext *ctx = ImNodes::CreateContext(); ctx->Style = ImNodes::GetStyle(); ctx->Io = ImNodes::GetIO(); ctx->AttributeFlagStack = GImNodes->AttributeFlagStack; return ctx; }(), ImNodes::DestroyContext }; std::list<std::unique_ptr<dp::Node>> nodes; std::list<dp::Node*> endNodes; std::list<dp::Link> links; std::vector<hex::prv::Overlay *> dataOverlays; std::optional<dp::Node::NodeError> currNodeError; }; public: ViewDataProcessor(); ~ViewDataProcessor() override; void drawContent() override; static nlohmann::json saveNode(const dp::Node *node); static nlohmann::json saveNodes(const Workspace &workspace); static std::unique_ptr<dp::Node> loadNode(nlohmann::json data); void loadNodes(Workspace &workspace, nlohmann::json data); static void eraseLink(Workspace &workspace, int id); static void eraseNodes(Workspace &workspace, const std::vector<int> &ids); void processNodes(Workspace &workspace); void reloadCustomNodes(); void updateNodePositions(); std::vector<Workspace*> &getWorkspaceStack() { return *m_workspaceStack; } private: void drawContextMenus(ViewDataProcessor::Workspace &workspace); void drawNode(dp::Node &node) const; private: bool m_updateNodePositions = false; int m_rightClickedId = -1; ImVec2 m_rightClickedCoords; bool m_continuousEvaluation = false; struct CustomNode { std::string name; nlohmann::json data; }; std::vector<CustomNode> m_customNodes; PerProvider<Workspace> m_mainWorkspace; PerProvider<std::vector<Workspace*>> m_workspaceStack; TaskHolder m_evaluationTask; }; }
2,431
C++
.h
59
32.389831
85
0.639302
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
595
view_provider_settings.hpp
WerWolv_ImHex/plugins/builtin/include/content/views/view_provider_settings.hpp
#pragma once #include <hex/ui/view.hpp> namespace hex::plugin::builtin { class ViewProviderSettings : public View::Modal { public: ViewProviderSettings(); ~ViewProviderSettings() override; void drawContent() override; [[nodiscard]] bool hasViewMenuItemEntry() const override; [[nodiscard]] bool shouldDraw() const override { return true; } ImVec2 getMinSize() const override { return { -1, -1 }; } ImVec2 getMaxSize() const override { return this->getMinSize(); } bool hasCloseButton() const override { return false; } }; }
628
C++
.h
17
29.823529
73
0.648425
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
596
view_theme_manager.hpp
WerWolv_ImHex/plugins/builtin/include/content/views/view_theme_manager.hpp
#pragma once #include <hex/ui/view.hpp> #include <string> namespace hex::plugin::builtin { class ViewThemeManager : public View::Floating { public: ViewThemeManager(); ~ViewThemeManager() override = default; void drawContent() override; [[nodiscard]] bool shouldDraw() const override { return true; } [[nodiscard]] bool hasViewMenuItemEntry() const override { return false; } private: std::string m_themeName; std::optional<ImColor> m_startingColor; std::optional<u32> m_hoveredColorId; std::optional<std::string> m_hoveredHandlerName; }; }
637
C++
.h
18
29.055556
82
0.672668
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
597
view_pattern_editor.hpp
WerWolv_ImHex/plugins/builtin/include/content/views/view_pattern_editor.hpp
#pragma once #include <hex/api/achievement_manager.hpp> #include <hex/ui/view.hpp> #include <hex/ui/popup.hpp> #include <hex/providers/provider.hpp> #include <hex/helpers/default_paths.hpp> #include <pl/pattern_language.hpp> #include <pl/core/errors/error.hpp> #include <ui/hex_editor.hpp> #include <ui/pattern_drawer.hpp> #include <filesystem> #include <functional> #include <TextEditor.h> #include <popups/popup_file_chooser.hpp> namespace pl::ptrn { class Pattern; } namespace hex::plugin::builtin { constexpr static auto textEditorView = "/Pattern editor_"; constexpr static auto consoleView = "/##console_"; constexpr static auto variablesView = "/##env_vars_"; constexpr static auto settingsView = "/##settings_"; constexpr static auto sectionsView = "/##sections_table_"; constexpr static auto virtualFilesView = "/Virtual File Tree_"; constexpr static auto debuggerView = "/##debugger_"; class PatternSourceCode { public: const std::string& get(prv::Provider *provider) { if (m_synced) return m_sharedSource; return m_perProviderSource.get(provider); } void set(prv::Provider *provider, std::string source) { source = wolv::util::trim(source); m_perProviderSource.set(source, provider); m_sharedSource = std::move(source); } bool isSynced() const { return m_synced; } void enableSync(bool enabled) { m_synced = enabled; } private: bool m_synced = false; PerProvider<std::string> m_perProviderSource; std::string m_sharedSource; }; class ViewPatternEditor : public View::Window { public: ViewPatternEditor(); ~ViewPatternEditor() override; void drawAlwaysVisibleContent() override; void drawContent() override; [[nodiscard]] ImGuiWindowFlags getWindowFlags() const override { return ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; } public: struct VirtualFile { std::fs::path path; std::vector<u8> data; Region region; }; enum class DangerousFunctionPerms : u8 { Ask, Allow, Deny }; private: class PopupAcceptPattern : public Popup<PopupAcceptPattern> { public: explicit PopupAcceptPattern(ViewPatternEditor *view) : Popup("hex.builtin.view.pattern_editor.accept_pattern"), m_view(view) {} void drawContent() override { std::scoped_lock lock(m_view->m_possiblePatternFilesMutex); auto* provider = ImHexApi::Provider::get(); ImGuiExt::TextFormattedWrapped("{}", static_cast<const char *>("hex.builtin.view.pattern_editor.accept_pattern.desc"_lang)); if (ImGui::BeginListBox("##patterns_accept", ImVec2(400_scaled, 0))) { u32 index = 0; for (const auto &[path, author, description] : m_view->m_possiblePatternFiles.get(provider)) { auto fileName = wolv::util::toUTF8String(path.filename()); std::string displayValue; if (!description.empty()) { displayValue = fmt::format("{} ({})", description, fileName); } else { displayValue = fileName; } if (ImGui::Selectable(displayValue.c_str(), index == m_selectedPatternFile, ImGuiSelectableFlags_NoAutoClosePopups)) m_selectedPatternFile = index; if (ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal)) { if (ImGui::BeginTooltip()) { ImGui::TextUnformatted(fileName.c_str()); if (!author.empty()) { ImGui::SameLine(); ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); ImGui::SameLine(); ImGui::TextUnformatted(author.c_str()); } if (!description.empty()) { ImGui::Separator(); ImGui::TextUnformatted(description.c_str()); } ImGui::EndTooltip(); } } if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0)) m_view->loadPatternFile(m_view->m_possiblePatternFiles.get(provider)[m_selectedPatternFile].path, provider); ImGuiExt::InfoTooltip(wolv::util::toUTF8String(path).c_str()); index++; } // Close the popup if there aren't any patterns available if (index == 0) this->close(); ImGui::EndListBox(); } ImGui::NewLine(); ImGui::TextUnformatted("hex.builtin.view.pattern_editor.accept_pattern.question"_lang); ImGui::NewLine(); ImGuiExt::ConfirmButtons("hex.ui.common.yes"_lang, "hex.ui.common.no"_lang, [this, provider] { m_view->loadPatternFile(m_view->m_possiblePatternFiles.get(provider)[m_selectedPatternFile].path, provider); this->close(); }, [this] { this->close(); } ); if (ImGui::IsKeyPressed(ImGuiKey_Escape)) this->close(); } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize; } private: ViewPatternEditor *m_view; u32 m_selectedPatternFile = 0; }; private: struct PatternVariable { bool inVariable; bool outVariable; pl::core::Token::ValueType type; pl::core::Token::Literal value; }; enum class EnvVarType { Integer, Float, String, Bool }; struct EnvVar { u64 id; std::string name; pl::core::Token::Literal value; EnvVarType type; bool operator==(const EnvVar &other) const { return this->id == other.id; } }; struct AccessData { float progress; u32 color; }; struct PossiblePattern { std::fs::path path; std::string author; std::string description; }; std::unique_ptr<pl::PatternLanguage> m_editorRuntime; std::mutex m_possiblePatternFilesMutex; PerProvider<std::vector<PossiblePattern>> m_possiblePatternFiles; bool m_runAutomatically = false; bool m_triggerEvaluation = false; std::atomic<bool> m_triggerAutoEvaluate = false; volatile bool m_lastEvaluationProcessed = true; bool m_lastEvaluationResult = false; std::atomic<u32> m_runningEvaluators = 0; std::atomic<u32> m_runningParsers = 0; bool m_hasUnevaluatedChanges = false; std::chrono::time_point<std::chrono::steady_clock> m_lastEditorChangeTime; TextEditor m_textEditor, m_consoleEditor; std::atomic<bool> m_consoleNeedsUpdate = false; std::atomic<bool> m_dangerousFunctionCalled = false; std::atomic<DangerousFunctionPerms> m_dangerousFunctionsAllowed = DangerousFunctionPerms::Ask; bool m_autoLoadPatterns = true; std::map<prv::Provider*, std::function<void()>> m_sectionWindowDrawer; ui::HexEditor m_sectionHexEditor; PatternSourceCode m_sourceCode; PerProvider<std::vector<std::string>> m_console; PerProvider<bool> m_executionDone; std::mutex m_logMutex; PerProvider<TextEditor::Coordinates> m_cursorPosition; PerProvider<std::optional<pl::core::err::PatternLanguageError>> m_lastEvaluationError; PerProvider<std::vector<pl::core::err::CompileError>> m_lastCompileError; PerProvider<const std::vector<std::unique_ptr<pl::core::ast::ASTNode>>*> m_callStack; PerProvider<std::map<std::string, pl::core::Token::Literal>> m_lastEvaluationOutVars; PerProvider<std::map<std::string, PatternVariable>> m_patternVariables; PerProvider<std::map<u64, pl::api::Section>> m_sections; PerProvider<std::vector<VirtualFile>> m_virtualFiles; PerProvider<std::list<EnvVar>> m_envVarEntries; PerProvider<TaskHolder> m_analysisTask; PerProvider<bool> m_shouldAnalyze; PerProvider<bool> m_breakpointHit; PerProvider<std::unique_ptr<ui::PatternDrawer>> m_debuggerDrawer; std::atomic<bool> m_resetDebuggerVariables; int m_debuggerScopeIndex = 0; std::array<AccessData, 512> m_accessHistory = {}; u32 m_accessHistoryIndex = 0; bool m_parentHighlightingEnabled = true; bool m_replaceMode = false; bool m_openFindReplacePopUp = false; std::map<std::fs::path, std::string> m_patternNames; ImRect m_textEditorHoverBox; ImRect m_consoleHoverBox; std::string m_focusedSubWindowName; static inline std::array<std::string,256> m_findHistory; static inline u32 m_findHistorySize = 0; static inline u32 m_findHistoryIndex = 0; static inline std::array<std::string,256> m_replaceHistory; static inline u32 m_replaceHistorySize = 0; static inline u32 m_replaceHistoryIndex = 0; private: void drawConsole(ImVec2 size); void drawEnvVars(ImVec2 size, std::list<EnvVar> &envVars); void drawVariableSettings(ImVec2 size, std::map<std::string, PatternVariable> &patternVariables); void drawSectionSelector(ImVec2 size, const std::map<u64, pl::api::Section> &sections); void drawVirtualFiles(ImVec2 size, const std::vector<VirtualFile> &virtualFiles) const; void drawDebugger(ImVec2 size); void drawPatternTooltip(pl::ptrn::Pattern *pattern); void drawFindReplaceDialog(TextEditor *textEditor, std::string &findWord, bool &requestFocus, u64 &position, u64 &count, bool &updateCount, bool canReplace); void historyInsert(std::array<std::string, 256> &history, u32 &size, u32 &index, const std::string &value); void loadPatternFile(const std::fs::path &path, prv::Provider *provider); void parsePattern(const std::string &code, prv::Provider *provider); void evaluatePattern(const std::string &code, prv::Provider *provider); TextEditor *getEditorFromFocusedWindow(); void setupFindReplace(TextEditor *editor); void registerEvents(); void registerMenuItems(); void registerHandlers(); std::function<void()> m_importPatternFile = [this] { auto provider = ImHexApi::Provider::get(); const auto basePaths = paths::Patterns.read(); std::vector<std::fs::path> paths; for (const auto &imhexPath : basePaths) { if (!wolv::io::fs::exists(imhexPath)) continue; std::error_code error; for (auto &entry : std::fs::recursive_directory_iterator(imhexPath, error)) { if (entry.is_regular_file() && entry.path().extension() == ".hexpat") paths.push_back(entry.path()); } } ui::PopupNamedFileChooser::open( basePaths, paths, std::vector<hex::fs::ItemFilter>{ { "Pattern File", "hexpat" } }, false, [this, provider](const std::fs::path &path, const std::fs::path &adjustedPath) mutable -> std::string { auto it = m_patternNames.find(path); if (it != m_patternNames.end()) { return it->second; } const auto fileName = wolv::util::toUTF8String(adjustedPath.filename()); m_patternNames[path] = fileName; pl::PatternLanguage runtime; ContentRegistry::PatternLanguage::configureRuntime(runtime, provider); runtime.addPragma("description", [&](pl::PatternLanguage &, const std::string &value) -> bool { m_patternNames[path] = hex::format("{} ({})", value, fileName); return true; }); wolv::io::File file(path, wolv::io::File::Mode::Read); hex::unused(runtime.preprocessString(file.readString(), pl::api::Source::DefaultSource)); return m_patternNames[path]; }, [this, provider](const std::fs::path &path) { this->loadPatternFile(path, provider); AchievementManager::unlockAchievement("hex.builtin.achievement.patterns", "hex.builtin.achievement.patterns.load_existing.name"); } ); }; std::function<void()> m_exportPatternFile = [this] { fs::openFileBrowser( fs::DialogMode::Save, { {"Pattern", "hexpat"} }, [this](const auto &path) { wolv::io::File file(path, wolv::io::File::Mode::Create); file.writeString(wolv::util::trim(m_textEditor.GetText())); } ); }; void appendEditorText(const std::string &text); void appendVariable(const std::string &type); void appendArray(const std::string &type, size_t size); }; }
14,227
C++
.h
288
35.621528
165
0.575007
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
598
popup_crash_recovered.hpp
WerWolv_ImHex/plugins/builtin/include/content/popups/popup_crash_recovered.hpp
#pragma once #include <hex/ui/popup.hpp> #include <hex/api/localization_manager.hpp> #include <llvm/Demangle/Demangle.h> #include <string> namespace hex::plugin::builtin { class PopupCrashRecovered : public Popup<PopupCrashRecovered> { public: PopupCrashRecovered(const std::exception &e) : hex::Popup<PopupCrashRecovered>("hex.builtin.popup.crash_recover.title", false), m_errorType(typeid(e).name()), m_errorMessage(e.what()) { } void drawContent() override { ImGuiExt::TextFormattedWrapped("hex.builtin.popup.crash_recover.message"_lang); ImGuiExt::TextFormattedWrapped(hex::format("Error: {}: {}", llvm::itaniumDemangle(this->m_errorType), this->m_errorMessage)); if (ImGui::Button("hex.ui.common.okay"_lang)) { this->close(); } } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_AlwaysAutoResize; } [[nodiscard]] ImVec2 getMinSize() const override { return scaled({ 400, 100 }); } [[nodiscard]] ImVec2 getMaxSize() const override { return scaled({ 600, 300 }); } private: std::string m_errorType, m_errorMessage; }; }
1,306
C++
.h
32
32.03125
137
0.624901
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
599
popup_docs_question.hpp
WerWolv_ImHex/plugins/builtin/include/content/popups/popup_docs_question.hpp
#pragma once #include <hex/ui/popup.hpp> #include <hex/ui/imgui_imhex_extensions.h> #include <hex/api/localization_manager.hpp> #include <hex/helpers/http_requests.hpp> #include <functional> #include <string> namespace hex::plugin::builtin { class PopupDocsQuestion : public Popup<PopupDocsQuestion> { public: PopupDocsQuestion(const std::string &input = "") : hex::Popup<PopupDocsQuestion>("hex.builtin.popup.docs_question.title", true, true) { if (!input.empty()) { m_inputBuffer = input; this->executeQuery(); } } enum class TextBlockType { Text, Code }; void drawContent() override { ImGui::PushItemWidth(600_scaled); ImGui::BeginDisabled(m_requestTask.isRunning()); if (ImGui::InputText("##input", m_inputBuffer, ImGuiInputTextFlags_EnterReturnsTrue)) { this->executeQuery(); } ImGui::EndDisabled(); ImGui::PopItemWidth(); if (ImGui::BeginChild("##answer", scaled(ImVec2(600, 350)), true, ImGuiWindowFlags_AlwaysVerticalScrollbar)) { if (!m_requestTask.isRunning()) { if (m_answer.empty()) { if (m_noAnswer) ImGuiExt::TextFormattedCentered("{}", "hex.builtin.popup.docs_question.no_answer"_lang); else ImGuiExt::TextFormattedCentered("{}", "hex.builtin.popup.docs_question.prompt"_lang); } else { int id = 1; for (auto &[type, text] : m_answer) { ImGui::PushID(id); switch (type) { case TextBlockType::Text: ImGuiExt::TextFormattedWrapped("{}", text); break; case TextBlockType::Code: ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyle().Colors[ImGuiCol_WindowBg]); auto textWidth = 400_scaled - ImGui::GetStyle().FramePadding.x * 4 - ImGui::GetStyle().ScrollbarSize; auto textHeight = ImGui::CalcTextSize(text.c_str(), nullptr, false, textWidth).y + ImGui::GetStyle().FramePadding.y * 6; if (ImGui::BeginChild("##code", ImVec2(textWidth, textHeight), true)) { ImGuiExt::TextFormattedWrapped("{}", text); ImGui::EndChild(); } ImGui::PopStyleColor(); break; } ImGui::PopID(); id += 1; } } } else { ImGuiExt::TextFormattedCentered("{}", "hex.builtin.popup.docs_question.thinking"_lang); } } ImGui::EndChild(); if (ImGui::IsKeyPressed(ImGuiKey_Escape)) this->close(); } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize; } private: void executeQuery() { m_requestTask = TaskManager::createBackgroundTask("hex.builtin.task.query_docs"_lang, [this, input = m_inputBuffer](Task &) { m_noAnswer = false; for (auto space : { "xj7sbzGbHH260vbpZOu1", "WZzDdGjxmgMSIE3xly6o" }) { m_answer.clear(); auto request = HttpRequest("POST", hex::format("https://api.gitbook.com/v1/spaces/{}/search/ask", space)); // Documentation API often takes a long time to respond, so we set a timeout of 30 seconds request.setTimeout(30'000); const nlohmann::json body = { { "query", input } }; request.setBody(body.dump()); request.addHeader("Content-Type", "application/json"); auto response = request.execute().get(); if (!response.isSuccess()) continue; try { auto json = nlohmann::json::parse(response.getData()); if (!json.contains("answer")) continue; auto answer = json["answer"]["text"].get<std::string>(); if (answer.empty()) break; auto blocks = wolv::util::splitString(answer, "```"); for (auto &block : blocks) { if (block.empty()) continue; block = wolv::util::trim(block); if (block.starts_with("rust\n")) { block = block.substr(5); m_answer.emplace_back(TextBlockType::Code, block); } else if (block.starts_with("cpp\n")) { block = block.substr(4); m_answer.emplace_back(TextBlockType::Code, block); } else { m_answer.emplace_back(TextBlockType::Text, block); } } } catch(...) { continue; } } m_noAnswer = m_answer.empty(); }); } private: std::string m_inputBuffer; std::vector<std::pair<TextBlockType, std::string>> m_answer; TaskHolder m_requestTask; bool m_noAnswer = false; }; }
6,044
C++
.h
121
30.049587
156
0.459803
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
600
popup_blocking_task.hpp
WerWolv_ImHex/plugins/builtin/include/content/popups/popup_blocking_task.hpp
#pragma once #include <hex/ui/popup.hpp> #include <hex/api/localization_manager.hpp> #include <string> namespace hex::plugin::builtin { class PopupBlockingTask : public Popup<PopupBlockingTask> { public: PopupBlockingTask(TaskHolder &&task) : hex::Popup<PopupBlockingTask>("hex.builtin.popup.blocking_task.title", false), m_task(std::move(task)) { } void drawContent() override { ImGui::TextUnformatted("hex.builtin.popup.blocking_task.desc"_lang); ImGui::Separator(); if (m_task.getProgress() == 0) ImGuiExt::TextSpinner(""); else ImGui::ProgressBar(m_task.getProgress() / 100.0F); ImGui::NewLine(); if (ImGui::ButtonEx("hex.ui.common.cancel"_lang, ImVec2(ImGui::GetContentRegionAvail().x, 0)) || ImGui::IsKeyDown(ImGuiKey_Escape)) m_task.interrupt(); if (!m_task.isRunning()) { ImGui::CloseCurrentPopup(); } } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove; } private: TaskHolder m_task; }; }
1,249
C++
.h
29
33.551724
153
0.622829
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
601
popup_tasks_waiting.hpp
WerWolv_ImHex/plugins/builtin/include/content/popups/popup_tasks_waiting.hpp
#pragma once #include <hex/ui/popup.hpp> #include <hex/api/localization_manager.hpp> #include <string> namespace hex::plugin::builtin { class PopupTasksWaiting : public Popup<PopupTasksWaiting> { public: PopupTasksWaiting() : hex::Popup<PopupTasksWaiting>("hex.builtin.popup.waiting_for_tasks.title", false) { } void drawContent() override { ImGui::TextUnformatted("hex.builtin.popup.waiting_for_tasks.desc"_lang); ImGui::Separator(); ImGui::SetCursorPosX((ImGui::GetWindowWidth() - ImGui::CalcTextSize("[-]").x) / 2); ImGuiExt::TextSpinner(""); ImGui::NewLine(); ImGui::SetCursorPosX((ImGui::GetWindowWidth() - 150_scaled) / 2); if (ImGui::ButtonEx("hex.ui.common.cancel"_lang, ImVec2(150, 0)) || ImGui::IsKeyDown(ImGuiKey_Escape)) ImGui::CloseCurrentPopup(); if (TaskManager::getRunningTaskCount() == 0 && TaskManager::getRunningBackgroundTaskCount() == 0) { ImGui::CloseCurrentPopup(); ImHexApi::System::closeImHex(); } } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove; } }; }
1,328
C++
.h
28
37.821429
114
0.632068
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
602
popup_unsaved_changes.hpp
WerWolv_ImHex/plugins/builtin/include/content/popups/popup_unsaved_changes.hpp
#pragma once #include <hex/ui/popup.hpp> #include <hex/api/localization_manager.hpp> #include <functional> #include <string> namespace hex::plugin::builtin { class PopupUnsavedChanges : public Popup<PopupUnsavedChanges> { public: PopupUnsavedChanges(std::string message, std::function<void()> yesFunction, std::function<void()> noFunction, std::function<void()> cancelFunction) : hex::Popup<PopupUnsavedChanges>("hex.ui.common.question", false), m_message(std::move(message)), m_yesFunction(std::move(yesFunction)), m_noFunction(std::move(noFunction)), m_cancelFunction(std::move(cancelFunction)) { } void drawContent() override { ImGuiExt::TextFormattedWrapped("{}", m_message.c_str()); ImGui::NewLine(); if (ImGui::BeginTable("##unsaved_providers", 1, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 4))) { for (const auto &provider : ImHexApi::Provider::impl::getClosingProviders()) { ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::TextUnformatted(provider->getName().c_str()); } ImGui::EndTable(); } ImGui::NewLine(); ImGui::Separator(); auto width = ImGui::GetWindowWidth(); ImGui::SetCursorPosX((width / 10) * 0.5); if (ImGui::Button("hex.ui.common.yes"_lang, ImVec2(width / 4, 0))) { m_yesFunction(); this->close(); } ImGui::SameLine(); ImGui::SetCursorPosX((width / 10) * 3.75); if (ImGui::Button("hex.ui.common.no"_lang, ImVec2(width / 4, 0)) || ImGui::IsKeyPressed(ImGuiKey_Escape)) { m_noFunction(); this->close(); } ImGui::SameLine(); ImGui::SetCursorPosX((width / 10) * 7); if (ImGui::Button("hex.ui.common.cancel"_lang, ImVec2(width / 4, 0)) || ImGui::IsKeyPressed(ImGuiKey_Escape)) { m_cancelFunction(); this->close(); } ImGui::SetWindowPos((ImHexApi::System::getMainWindowSize() - ImGui::GetWindowSize()) / 2, ImGuiCond_Appearing); } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; } [[nodiscard]] ImVec2 getMinSize() const override { return scaled({ 400, 100 }); } [[nodiscard]] ImVec2 getMaxSize() const override { return scaled({ 600, 600 }); } private: std::string m_message; std::function<void()> m_yesFunction, m_noFunction, m_cancelFunction; }; }
2,889
C++
.h
59
37.152542
165
0.583097
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
603
popup_hex_editor_find.hpp
WerWolv_ImHex/plugins/builtin/include/content/popups/hex_editor/popup_hex_editor_find.hpp
#pragma once #include "content/views/view_hex_editor.hpp" #include "hex/api/task_manager.hpp" #include <atomic> #include <optional> #include <string> namespace hex::plugin::builtin { class PopupFind : public ViewHexEditor::Popup { public: explicit PopupFind(ViewHexEditor *editor) noexcept; ~PopupFind() override; void draw(ViewHexEditor *editor) override; private: void drawSearchDirectionButtons(); void drawTabContents(); std::optional<Region> findByteSequence(const std::vector<u8> &sequence) const; std::vector<u8> m_searchByteSequence; std::optional<Region> m_foundRegion = std::nullopt; bool m_requestFocus = true; std::atomic<bool> m_requestSearch = false; std::atomic<bool> m_searchBackwards = false; std::atomic<bool> m_reachedEnd = false; enum class Encoding { UTF8, UTF16, UTF32 }; enum class Endianness { Little, Big }; enum class SearchMode : bool { ByteSequence, String }; static PerProvider<std::string> s_inputString; static PerProvider<SearchMode> s_searchMode; std::atomic<Encoding> m_stringEncoding = Encoding::UTF8; std::atomic<Endianness> m_stringEndianness = Endianness::Little; TaskHolder m_searchTask; void processInputString(); [[nodiscard]] UnlocalizedString getTitle() const override; }; } // namespace hex::plugin::builtin
1,628
C++
.h
44
27.454545
87
0.624113
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
604
toast_notification.hpp
WerWolv_ImHex/plugins/ui/include/toasts/toast_notification.hpp
#pragma once #include <hex/ui/imgui_imhex_extensions.h> #include <hex/ui/toast.hpp> #include <fonts/codicons_font.h> #include <hex/helpers/utils.hpp> #include <hex/helpers/logger.hpp> #include <popups/popup_notification.hpp> namespace hex::ui { namespace impl { template<typename T> struct ToastNotification : Toast<T> { ToastNotification(ImColor color, const char *icon, UnlocalizedString unlocalizedTitle, std::string message) : Toast<T>(color), m_icon(icon), m_unlocalizedTitle(std::move(unlocalizedTitle)), m_message(std::move(message)) {} void drawContent() final { if (ImGui::IsWindowHovered()) { if (ImGui::BeginTooltip()) { ImGuiExt::Header(Lang(m_unlocalizedTitle), true); ImGui::PushTextWrapPos(300_scaled); ImGui::TextUnformatted(m_message.c_str()); ImGui::PopTextWrapPos(); ImGui::EndTooltip(); } } ImGuiExt::TextFormattedColored(this->getColor(), "{}", m_icon); ImGui::SameLine(); ImGuiExt::TextFormatted("{}", hex::limitStringLength(Lang(m_unlocalizedTitle).get(), 30)); ImGui::Separator(); ImGuiExt::TextFormattedWrapped("{}", hex::limitStringLength(m_message, 60)); } private: const char *m_icon; UnlocalizedString m_unlocalizedTitle; std::string m_message; }; } struct ToastInfo : impl::ToastNotification<ToastInfo> { explicit ToastInfo(std::string message) : ToastNotification(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_LoggerInfo), ICON_VS_INFO, "hex.ui.common.info", message) { log::info("{}", message); } }; struct ToastWarning : impl::ToastNotification<ToastWarning> { explicit ToastWarning(std::string message) : ToastNotification(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_LoggerWarning), ICON_VS_WARNING, "hex.ui.common.warning", message) { log::warn("{}", message); } }; struct ToastError : impl::ToastNotification<ToastError> { explicit ToastError(std::string message) : ToastNotification(ImGuiExt::GetCustomColorVec4(ImGuiCustomCol_LoggerError), ICON_VS_ERROR, "hex.ui.common.error", message) { log::error("{}", message); } }; }
2,520
C++
.h
54
35.277778
144
0.604328
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
605
pattern_drawer.hpp
WerWolv_ImHex/plugins/ui/include/ui/pattern_drawer.hpp
#pragma once #include <hex/api/task_manager.hpp> #include <hex/api/content_registry.hpp> #include <pl/patterns/pattern.hpp> #include <pl/pattern_visitor.hpp> #include <pl/formatters.hpp> #include <set> struct ImGuiTableSortSpecs; namespace hex::ui { class PatternDrawer : public pl::PatternVisitor { public: PatternDrawer() { m_formatters = pl::gen::fmt::createFormatters(); } virtual ~PatternDrawer() = default; void draw(const std::vector<std::shared_ptr<pl::ptrn::Pattern>> &patterns, const pl::PatternLanguage *runtime = nullptr, float height = 0.0F); enum class TreeStyle : u8 { Default = 0, AutoExpanded = 1, Flattened = 2 }; void setTreeStyle(TreeStyle style) { m_treeStyle = style; } void setSelectionCallback(std::function<void(const pl::ptrn::Pattern *)> callback) { m_selectionCallback = std::move(callback); } void setHoverCallback(std::function<void(const pl::ptrn::Pattern *)> callback) { m_hoverCallback = std::move(callback); } void enableRowColoring(bool enabled) { m_rowColoring = enabled; } void enablePatternEditing(bool enabled) { m_editingEnabled = enabled; } void reset(); void jumpToPattern(const pl::ptrn::Pattern *pattern) { m_jumpToPattern = pattern; } private: void draw(pl::ptrn::Pattern& pattern); public: void visit(pl::ptrn::PatternArrayDynamic& pattern) override; void visit(pl::ptrn::PatternArrayStatic& pattern) override; void visit(pl::ptrn::PatternBitfieldField& pattern) override; void visit(pl::ptrn::PatternBitfieldArray& pattern) override; void visit(pl::ptrn::PatternBitfield& pattern) override; void visit(pl::ptrn::PatternBoolean& pattern) override; void visit(pl::ptrn::PatternCharacter& pattern) override; void visit(pl::ptrn::PatternEnum& pattern) override; void visit(pl::ptrn::PatternFloat& pattern) override; void visit(pl::ptrn::PatternPadding& pattern) override; void visit(pl::ptrn::PatternPointer& pattern) override; void visit(pl::ptrn::PatternSigned& pattern) override; void visit(pl::ptrn::PatternString& pattern) override; void visit(pl::ptrn::PatternStruct& pattern) override; void visit(pl::ptrn::PatternUnion& pattern) override; void visit(pl::ptrn::PatternUnsigned& pattern) override; void visit(pl::ptrn::PatternWideCharacter& pattern) override; void visit(pl::ptrn::PatternWideString& pattern) override; private: constexpr static auto ChunkSize = 512; constexpr static auto DisplayEndStep = 64; void drawArray(pl::ptrn::Pattern& pattern, pl::ptrn::IIterable &iterable, bool isInlined); u64& getDisplayEnd(const pl::ptrn::Pattern& pattern); void makeSelectable(const pl::ptrn::Pattern &pattern); void drawValueColumn(pl::ptrn::Pattern& pattern); void drawVisualizer(const std::map<std::string, ContentRegistry::PatternLanguage::impl::Visualizer> &visualizers, const std::vector<pl::core::Token::Literal> &arguments, pl::ptrn::Pattern &pattern, bool reset); void drawFavoriteColumn(const pl::ptrn::Pattern& pattern); bool drawNameColumn(const pl::ptrn::Pattern &pattern, bool leaf = false); void drawColorColumn(const pl::ptrn::Pattern& pattern); void drawCommentColumn(const pl::ptrn::Pattern& pattern); bool beginPatternTable(const std::vector<std::shared_ptr<pl::ptrn::Pattern>> &patterns, std::vector<pl::ptrn::Pattern*> &sortedPatterns, float height) const; bool createTreeNode(const pl::ptrn::Pattern& pattern, bool leaf = false); void createDefaultEntry(const pl::ptrn::Pattern &pattern); void closeTreeNode(bool inlined) const; bool sortPatterns(const ImGuiTableSortSpecs* sortSpecs, const pl::ptrn::Pattern * left, const pl::ptrn::Pattern * right) const; [[nodiscard]] bool isEditingPattern(const pl::ptrn::Pattern& pattern) const; void resetEditing(); void traversePatternTree(pl::ptrn::Pattern &pattern, std::vector<std::string> &patternPath, const std::function<void(pl::ptrn::Pattern&)> &callback); [[nodiscard]] std::string getDisplayName(const pl::ptrn::Pattern& pattern) const; struct Filter { std::vector<std::string> path; std::optional<pl::core::Token::Literal> value; }; [[nodiscard]] static bool matchesFilter(const std::vector<std::string> &filterPath, const std::vector<std::string> &patternPath, bool fullMatch); [[nodiscard]] static std::optional<Filter> parseRValueFilter(const std::string &filter); void updateFilter(); private: std::map<const pl::ptrn::Pattern*, u64> m_displayEnd; std::vector<pl::ptrn::Pattern*> m_sortedPatterns; const pl::ptrn::Pattern *m_editingPattern = nullptr; u64 m_editingPatternOffset = 0; TreeStyle m_treeStyle = TreeStyle::Default; bool m_rowColoring = false; bool m_editingEnabled = false; pl::ptrn::Pattern *m_currVisualizedPattern = nullptr; const pl::ptrn::Pattern *m_jumpToPattern = nullptr; std::set<pl::ptrn::Pattern*> m_visualizedPatterns; std::string m_lastVisualizerError; std::string m_filterText; Filter m_filter; std::vector<pl::ptrn::Pattern*> m_filteredPatterns; std::vector<std::string> m_currPatternPath; std::map<std::vector<std::string>, std::unique_ptr<pl::ptrn::Pattern>> m_favorites; std::map<std::string, std::vector<std::unique_ptr<pl::ptrn::Pattern>>> m_groups; bool m_showFavoriteStars = false; bool m_filtersUpdated = false; bool m_showSpecName = false; TaskHolder m_favoritesUpdateTask; std::function<void(const pl::ptrn::Pattern *)> m_selectionCallback = [](const pl::ptrn::Pattern *) { }; std::function<void(const pl::ptrn::Pattern *)> m_hoverCallback = [](const pl::ptrn::Pattern *) { }; pl::gen::fmt::FormatterArray m_formatters; u64 m_lastRunId = 0; }; }
6,209
C++
.h
105
50.657143
218
0.676543
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
606
widgets.hpp
WerWolv_ImHex/plugins/ui/include/ui/widgets.hpp
#pragma once #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> namespace pl::ptrn { class Pattern; } namespace hex::prv { class Provider; } namespace hex::ui { enum class RegionType : int { EntireData, Selection, Region }; inline void regionSelectionPicker(Region *region, prv::Provider *provider, RegionType *type, bool showHeader = true, bool firstEntry = false) { if (showHeader) ImGuiExt::Header("hex.ui.common.range"_lang, firstEntry); if (ImGui::RadioButton("hex.ui.common.range.entire_data"_lang, *type == RegionType::EntireData)) *type = RegionType::EntireData; if (ImGui::RadioButton("hex.ui.common.range.selection"_lang, *type == RegionType::Selection)) *type = RegionType::Selection; if (ImGui::RadioButton("hex.ui.common.region"_lang, *type == RegionType::Region)) *type = RegionType::Region; switch (*type) { case RegionType::EntireData: *region = { provider->getBaseAddress(), provider->getActualSize() }; break; case RegionType::Selection: *region = ImHexApi::HexEditor::getSelection().value_or( ImHexApi::HexEditor::ProviderRegion { { 0, 1 }, provider } ).getRegion(); break; case RegionType::Region: ImGui::SameLine(); const auto width = ImGui::GetContentRegionAvail().x / 2 - ImGui::CalcTextSize(" - ").x / 2; u64 start = region->getStartAddress(), end = region->getEndAddress(); ImGui::PushItemWidth(width); ImGuiExt::InputHexadecimal("##start", &start); ImGui::PopItemWidth(); ImGui::SameLine(0, 0); ImGui::TextUnformatted(" - "); ImGui::SameLine(0, 0); ImGui::PushItemWidth(width); ImGuiExt::InputHexadecimal("##end", &end); ImGui::PopItemWidth(); *region = { start, (end - start) + 1 }; break; } } }
2,197
C++
.h
49
32.346939
147
0.552644
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
607
hex_editor.hpp
WerWolv_ImHex/plugins/ui/include/ui/hex_editor.hpp
#pragma once #include <hex.hpp> #include <hex/api/imhex_api.hpp> #include <hex/api/content_registry.hpp> #include <hex/providers/provider.hpp> #include <hex/helpers/encoding_file.hpp> #include <imgui.h> #include <hex/ui/view.hpp> namespace hex::ui { class ScrollPosition { public: ScrollPosition() = default; // We explicitly don't assign any data during copy and move operations so that each instance of the // Hex Editor will get its own independent scroll position ScrollPosition(const ScrollPosition&) { } ScrollPosition(ScrollPosition&&) noexcept { } ScrollPosition& operator=(const ScrollPosition&) { return *this; } ScrollPosition& operator=(ScrollPosition&&) noexcept { return *this; } void setSynced(bool synced) { m_synced = synced; } void setProvider(prv::Provider *provider) { m_provider = provider; } ImS64& get() { if (m_synced) return m_syncedPosition; else return m_unsyncedPosition.get(m_provider); } [[nodiscard]] const ImS64& get() const { if (m_synced) return m_syncedPosition; else return m_unsyncedPosition.get(m_provider); } operator ImS64&() { return this->get(); } operator const ImS64&() const { return this->get(); } ScrollPosition& operator=(ImS64 value) { this->get() = value; return *this; } auto operator<=>(const ScrollPosition &other) const { return this->get() <=> other.get(); } private: bool m_synced = false; prv::Provider *m_provider = nullptr; ImS64 m_syncedPosition = 0; PerProvider<ImS64> m_unsyncedPosition; }; class HexEditor { public: explicit HexEditor(prv::Provider *provider = nullptr); void draw(float height = ImGui::GetContentRegionAvail().y); HexEditor(const HexEditor&) = default; HexEditor& operator=(const HexEditor&) = default; HexEditor(HexEditor &&editor) noexcept = default; HexEditor& operator=(HexEditor &&) noexcept = default; void setProvider(prv::Provider *provider) { m_provider = provider; m_currValidRegion = { Region::Invalid(), false }; m_scrollPosition.setProvider(provider); } [[nodiscard]] prv::Provider* getProvider() const { return m_provider; } void setUnknownDataCharacter(char character) { m_unknownDataCharacter = character; } private: enum class CellType : u8 { None, Hex, ASCII }; void drawCell(u64 address, const u8 *data, size_t size, bool hovered, CellType cellType); void drawSelectionFrame(u32 x, u32 y, Region selection, u64 byteAddress, u16 bytesPerCell, const ImVec2 &cellPos, const ImVec2 &cellSize, const ImColor &backgroundColor) const; void drawEditor(const ImVec2 &size); void drawFooter(const ImVec2 &size); void drawTooltip(u64 address, const u8 *data, size_t size) const; void drawScrollbar(ImVec2 characterSize); void drawMinimap(ImVec2 characterSize); void handleSelection(u64 address, u32 bytesPerCell, const u8 *data, bool cellHovered); std::optional<color_t> applySelectionColor(u64 byteAddress, std::optional<color_t> color); public: void setSelectionUnchecked(std::optional<u64> start, std::optional<u64> end) { m_selectionStart = start; m_selectionEnd = end; m_cursorPosition = end; } void setSelection(const Region &region) { this->setSelection(region.getStartAddress(), region.getEndAddress()); } void setSelection(u128 start, u128 end) { if (!ImHexApi::Provider::isValid() || m_provider == nullptr) return; if (start > m_provider->getBaseAddress() + m_provider->getActualSize()) return; if (start < m_provider->getBaseAddress()) return; if (m_provider->getActualSize() == 0) return; const size_t maxAddress = m_provider->getActualSize() + m_provider->getBaseAddress() - 1; constexpr static auto alignDown = [](u128 value, u128 alignment) { return value & ~(alignment - 1); }; m_selectionChanged = m_selectionStart != start || m_selectionEnd != end; if (!m_selectionStart.has_value()) m_selectionStart = start; if (!m_selectionEnd.has_value()) m_selectionEnd = end; if (auto bytesPerCell = m_currDataVisualizer->getBytesPerCell(); bytesPerCell > 1) { if (end > start) { start = alignDown(start, bytesPerCell); end = alignDown(end, bytesPerCell) + (bytesPerCell - 1); } else { start = alignDown(start, bytesPerCell) + (bytesPerCell - 1); end = alignDown(end, bytesPerCell); } } m_selectionStart = std::clamp<u128>(start, 0, maxAddress); m_selectionEnd = std::clamp<u128>(end, 0, maxAddress); m_cursorPosition = m_selectionEnd; if (m_selectionChanged) { auto selection = this->getSelection(); EventRegionSelected::post(ImHexApi::HexEditor::ProviderRegion{ { selection.address, selection.size }, m_provider }); m_shouldModifyValue = true; } if (m_mode == Mode::Insert) { m_selectionStart = m_selectionEnd; m_cursorBlinkTimer = -0.3F; } } [[nodiscard]] Region getSelection() const { if (!isSelectionValid()) return Region::Invalid(); const auto start = std::min(m_selectionStart.value(), m_selectionEnd.value()); const auto end = std::max(m_selectionStart.value(), m_selectionEnd.value()); const size_t size = end - start + 1; return { start, size }; } [[nodiscard]] std::optional<u64> getCursorPosition() const { return m_cursorPosition; } void setCursorPosition(u64 cursorPosition) { m_cursorPosition = cursorPosition; } [[nodiscard]] bool isSelectionValid() const { return m_selectionStart.has_value() && m_selectionEnd.has_value(); } void jumpToSelection(float pivot = 0.0F) { m_shouldJumpToSelection = true; m_jumpPivot = pivot; } void scrollToSelection() { m_shouldScrollToSelection = true; } void jumpIfOffScreen() { m_shouldScrollToSelection = true; m_shouldJumpWhenOffScreen = true; } [[nodiscard]] u16 getBytesPerRow() const { return m_bytesPerRow; } [[nodiscard]] u16 getBytesPerCell() const { return m_currDataVisualizer->getBytesPerCell(); } void setBytesPerRow(u16 bytesPerRow) { m_bytesPerRow = bytesPerRow; } [[nodiscard]] u16 getVisibleRowCount() const { return m_visibleRowCount; } void setSelectionColor(color_t color) { m_selectionColor = color; } void enableUpperCaseHex(bool upperCaseHex) { m_upperCaseHex = upperCaseHex; } void enableGrayOutZeros(bool grayOutZeros) { m_grayOutZero = grayOutZeros; } void enableShowAscii(bool showAscii) { m_showAscii = showAscii; } void enableSyncScrolling(bool syncScrolling) { m_scrollPosition.setSynced(syncScrolling); } void setByteCellPadding(u32 byteCellPadding) { m_byteCellPadding = byteCellPadding; } void setCharacterCellPadding(u32 characterCellPadding) { m_characterCellPadding = characterCellPadding; } [[nodiscard]] const std::optional<EncodingFile>& getCustomEncoding() const { return m_currCustomEncoding; } void setCustomEncoding(const EncodingFile &encoding) { m_currCustomEncoding = encoding; m_encodingLineStartAddresses.clear(); } void setCustomEncoding(EncodingFile &&encoding) { m_currCustomEncoding = std::move(encoding); m_encodingLineStartAddresses.clear(); } void forceUpdateScrollPosition() { m_shouldUpdateScrollPosition = true; } void setForegroundHighlightCallback(const std::function<std::optional<color_t>(u64, const u8 *, size_t)> &callback) { m_foregroundColorCallback = callback; } void setBackgroundHighlightCallback(const std::function<std::optional<color_t>(u64, const u8 *, size_t)> &callback) { m_backgroundColorCallback = callback; } void setHoverChangedCallback(const std::function<void(u64, size_t)> &callback) { m_hoverChangedCallback = callback; } void setTooltipCallback(const std::function<void(u64, const u8 *, size_t)> &callback) { m_tooltipCallback = callback; } [[nodiscard]] i64 getScrollPosition() { return m_scrollPosition.get(); } void setScrollPosition(i64 scrollPosition) { m_scrollPosition.get() = scrollPosition; } void setEditingAddress(u64 address) { m_editingAddress = address; m_shouldModifyValue = false; m_enteredEditingMode = true; m_editingBytes.resize(m_currDataVisualizer->getBytesPerCell()); m_provider->read(address + m_provider->getBaseAddress(), m_editingBytes.data(), m_editingBytes.size()); m_editingCellType = CellType::Hex; } void clearEditingAddress() { m_editingAddress = std::nullopt; } enum class Mode : u8 { Overwrite, Insert }; void setMode(Mode mode) { if (mode == Mode::Insert) { // Don't enter insert mode if the provider doesn't support resizing the underlying data if (!m_provider->isResizable()) return; // Get rid of any selection in insert mode m_selectionStart = m_selectionEnd; m_cursorPosition = m_selectionEnd; m_selectionChanged = true; } m_mode = mode; } [[nodiscard]] Mode getMode() const { return m_mode; } private: prv::Provider *m_provider = nullptr; std::optional<u64> m_selectionStart; std::optional<u64> m_selectionEnd; std::optional<u64> m_cursorPosition; ScrollPosition m_scrollPosition; Region m_frameStartSelectionRegion = Region::Invalid(); Region m_hoveredRegion = Region::Invalid(); u16 m_bytesPerRow = 16; std::endian m_dataVisualizerEndianness = std::endian::little; std::shared_ptr<ContentRegistry::HexEditor::DataVisualizer> m_currDataVisualizer; char m_unknownDataCharacter = '?'; bool m_shouldJumpToSelection = false; float m_jumpPivot = 0.0F; bool m_shouldScrollToSelection = false; bool m_shouldJumpWhenOffScreen = false; bool m_shouldUpdateScrollPosition = false; bool m_selectionChanged = false; u16 m_visibleRowCount = 0; CellType m_editingCellType = CellType::None; std::optional<u64> m_editingAddress; bool m_shouldModifyValue = false; bool m_enteredEditingMode = false; bool m_shouldUpdateEditingValue = false; std::vector<u8> m_editingBytes; std::shared_ptr<ContentRegistry::HexEditor::MiniMapVisualizer> m_miniMapVisualizer; color_t m_selectionColor = 0x60C08080; bool m_upperCaseHex = true; bool m_grayOutZero = true; bool m_showAscii = true; bool m_showCustomEncoding = true; bool m_showMiniMap = false; int m_miniMapWidth = 5; u32 m_byteCellPadding = 0, m_characterCellPadding = 0; bool m_footerCollapsed = true; std::optional<EncodingFile> m_currCustomEncoding; std::vector<u64> m_encodingLineStartAddresses; std::pair<Region, bool> m_currValidRegion = { Region::Invalid(), false }; static std::optional<color_t> defaultColorCallback(u64, const u8 *, size_t) { return std::nullopt; } static void defaultTooltipCallback(u64, const u8 *, size_t) { } std::function<std::optional<color_t>(u64, const u8 *, size_t)> m_foregroundColorCallback = defaultColorCallback, m_backgroundColorCallback = defaultColorCallback; std::function<void(u64, size_t)> m_hoverChangedCallback = [](auto, auto){ }; std::function<void(u64, const u8 *, size_t)> m_tooltipCallback = defaultTooltipCallback; Mode m_mode = Mode::Overwrite; float m_cursorBlinkTimer = -0.3F; }; }
13,295
C++
.h
298
33.718121
184
0.608227
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
608
popup_question.hpp
WerWolv_ImHex/plugins/ui/include/popups/popup_question.hpp
#pragma once #include <hex/ui/popup.hpp> #include <hex/api/localization_manager.hpp> #include <functional> #include <string> namespace hex::ui { class PopupQuestion : public Popup<PopupQuestion> { public: PopupQuestion(std::string message, std::function<void()> yesFunction, std::function<void()> noFunction) : hex::Popup<PopupQuestion>("hex.ui.common.question", false), m_message(std::move(message)), m_yesFunction(std::move(yesFunction)), m_noFunction(std::move(noFunction)) { } void drawContent() override { ImGuiExt::TextFormattedWrapped("{}", m_message.c_str()); ImGui::NewLine(); ImGui::Separator(); auto width = ImGui::GetWindowWidth(); ImGui::SetCursorPosX(width / 9); if (ImGui::Button("hex.ui.common.yes"_lang, ImVec2(width / 3, 0))) { m_yesFunction(); this->close(); } ImGui::SameLine(); ImGui::SetCursorPosX(width / 9 * 5); if (ImGui::Button("hex.ui.common.no"_lang, ImVec2(width / 3, 0))) { m_noFunction(); this->close(); } ImGui::SetWindowPos((ImHexApi::System::getMainWindowSize() - ImGui::GetWindowSize()) / 2, ImGuiCond_Appearing); } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_AlwaysAutoResize; } [[nodiscard]] ImVec2 getMinSize() const override { return scaled({ 400, 100 }); } [[nodiscard]] ImVec2 getMaxSize() const override { return scaled({ 600, 300 }); } private: std::string m_message; std::function<void()> m_yesFunction, m_noFunction; }; class PopupCancelableQuestion : public Popup<PopupCancelableQuestion> { public: PopupCancelableQuestion(std::string message, std::function<void()> yesFunction, std::function<void()> noFunction) : hex::Popup<PopupCancelableQuestion>("hex.ui.common.question", false), m_message(std::move(message)), m_yesFunction(std::move(yesFunction)), m_noFunction(std::move(noFunction)) { } void drawContent() override { ImGuiExt::TextFormattedWrapped("{}", m_message.c_str()); ImGui::NewLine(); ImGui::Separator(); auto width = ImGui::GetWindowWidth(); ImGui::SetCursorPosX(width / 9); if (ImGui::Button("hex.ui.common.yes"_lang, ImVec2(width / 3, 0))) { m_yesFunction(); this->close(); } ImGui::SameLine(); if (ImGui::Button("hex.ui.common.no"_lang, ImVec2(width / 3, 0))) { m_noFunction(); this->close(); } ImGui::SameLine(); if (ImGui::Button("hex.ui.common.cancel"_lang, ImVec2(width / 3, 0))) { this->close(); } ImGui::SetWindowPos((ImHexApi::System::getMainWindowSize() - ImGui::GetWindowSize()) / 2, ImGuiCond_Appearing); } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_AlwaysAutoResize; } [[nodiscard]] ImVec2 getMinSize() const override { return scaled({ 400, 100 }); } [[nodiscard]] ImVec2 getMaxSize() const override { return scaled({ 600, 300 }); } private: std::string m_message; std::function<void()> m_yesFunction, m_noFunction; }; }
3,636
C++
.h
84
32.047619
123
0.565968
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
609
popup_notification.hpp
WerWolv_ImHex/plugins/ui/include/popups/popup_notification.hpp
#pragma once #include <hex/ui/popup.hpp> #include <hex/api/localization_manager.hpp> #include <hex/api/imhex_api.hpp> #include <functional> #include <string> namespace hex::ui { namespace impl { template<typename T> class PopupNotification : public Popup<T> { public: PopupNotification(UnlocalizedString unlocalizedName, std::string message, std::function<void()> function) : hex::Popup<T>(std::move(unlocalizedName), false), m_message(std::move(message)), m_function(std::move(function)) { } void drawContent() override { ImGuiExt::TextFormattedWrapped("{}", m_message.c_str()); ImGui::NewLine(); ImGui::Separator(); if (ImGui::Button("hex.ui.common.okay"_lang) || ImGui::IsKeyDown(ImGuiKey_Escape)) m_function(); ImGui::SetWindowPos((ImHexApi::System::getMainWindowSize() - ImGui::GetWindowSize()) / 2, ImGuiCond_Appearing); if (ImGui::IsKeyPressed(ImGuiKey_Escape)) this->close(); } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_AlwaysAutoResize; } [[nodiscard]] ImVec2 getMinSize() const override { return scaled({ 400, 100 }); } [[nodiscard]] ImVec2 getMaxSize() const override { return scaled({ 600, 300 }); } private: std::string m_message; std::function<void()> m_function; }; } class PopupInfo : public impl::PopupNotification<PopupInfo> { public: explicit PopupInfo(std::string message) : PopupNotification("hex.ui.common.info", std::move(message), [this] { Popup::close(); }) { } }; class PopupWarning : public impl::PopupNotification<PopupWarning> { public: explicit PopupWarning(std::string message) : PopupNotification("hex.ui.common.warning", std::move(message), [this] { Popup::close(); }) { } }; class PopupError : public impl::PopupNotification<PopupError> { public: explicit PopupError(std::string message) : PopupNotification("hex.ui.common.error", std::move(message), [this] { Popup::close(); }) { } }; class PopupFatal : public impl::PopupNotification<PopupFatal> { public: explicit PopupFatal(std::string message) : PopupNotification("hex.ui.common.fatal", std::move(message), [this] { ImHexApi::System::closeImHex(); Popup::close(); }) { } }; }
2,727
C++
.h
68
29.970588
127
0.584091
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
610
popup_text_input.hpp
WerWolv_ImHex/plugins/ui/include/popups/popup_text_input.hpp
#pragma once #include <hex/ui/popup.hpp> #include <hex/api/imhex_api.hpp> #include <hex/api/localization_manager.hpp> #include <functional> #include <string> #include <fonts/codicons_font.h> namespace hex::ui { class PopupTextInput : public Popup<PopupTextInput> { public: PopupTextInput(UnlocalizedString unlocalizedName, UnlocalizedString message, std::function<void(std::string)> function) : hex::Popup<PopupTextInput>(std::move(unlocalizedName), false), m_message(std::move(message)), m_function(std::move(function)) { } void drawContent() override { ImGuiExt::TextFormattedWrapped("{}", Lang(m_message)); ImGui::NewLine(); ImGui::PushItemWidth(-1); if (m_justOpened) { ImGui::SetKeyboardFocusHere(); m_justOpened = false; } ImGuiExt::InputTextIcon("##input", ICON_VS_SYMBOL_KEY, m_input); ImGui::PopItemWidth(); ImGui::NewLine(); ImGui::Separator(); auto width = ImGui::GetWindowWidth(); ImGui::SetCursorPosX(width / 9); if (ImGui::Button("hex.ui.common.okay"_lang, ImVec2(width / 3, 0)) || ImGui::IsKeyPressed(ImGuiKey_Enter)) { m_function(m_input); this->close(); } ImGui::SameLine(); ImGui::SetCursorPosX(width / 9 * 5); if (ImGui::Button("hex.ui.common.cancel"_lang, ImVec2(width / 3, 0)) || ImGui::IsKeyPressed(ImGuiKey_Escape)) { this->close(); } ImGui::SetWindowPos((ImHexApi::System::getMainWindowSize() - ImGui::GetWindowSize()) / 2, ImGuiCond_Appearing); } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_AlwaysAutoResize; } [[nodiscard]] ImVec2 getMinSize() const override { return scaled({ 400, 100 }); } [[nodiscard]] ImVec2 getMaxSize() const override { return scaled({ 600, 300 }); } private: std::string m_input; UnlocalizedString m_message; std::function<void(std::string)> m_function; bool m_justOpened = true; }; }
2,270
C++
.h
54
31.851852
127
0.590992
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
611
popup_file_chooser.hpp
WerWolv_ImHex/plugins/ui/include/popups/popup_file_chooser.hpp
#pragma once #include <hex/ui/popup.hpp> #include <hex/api/localization_manager.hpp> #include <wolv/utils/string.hpp> #include <fonts/codicons_font.h> #include <functional> #include <string> #include <vector> #include <set> namespace hex::ui { template<typename T> class PopupNamedFileChooserBase : public Popup<T> { public: PopupNamedFileChooserBase(const std::vector<std::fs::path> &basePaths, const std::vector<std::fs::path> &files, const std::vector<hex::fs::ItemFilter> &validExtensions, bool multiple, const std::function<void(std::fs::path)> &callback) : hex::Popup<T>("hex.ui.common.choose_file"), m_files(files), m_selectedFiles({ }), m_openCallback(callback), m_validExtensions(validExtensions), m_multiple(multiple) { for (const auto &path : files) { std::fs::path adjustedPath; for (const auto &basePath : basePaths) { if (isSubpath(basePath, path)) { adjustedPath = std::fs::relative(path, basePath); break; } } if (adjustedPath.empty()) adjustedPath = path.filename(); m_adjustedPaths[path] = adjustedPath; } std::sort(m_files.begin(), m_files.end(), [](const auto &a, const auto &b) { return a < b; }); } void drawContent() override { bool doubleClicked = false; if (m_justOpened) { ImGui::SetKeyboardFocusHere(); m_justOpened = false; } ImGui::PushItemWidth(-1); ImGuiExt::InputTextIcon("##search", ICON_VS_FILTER, m_filter); ImGui::PopItemWidth(); if (ImGui::BeginListBox("##files", scaled(ImVec2(500, 400)))) { for (auto fileIt = m_files.begin(); fileIt != m_files.end(); ++fileIt) { const auto &path = *fileIt; const auto &pathNameString = getEntryName(path); if (!m_filter.empty() && !pathNameString.contains(m_filter)) continue; ImGui::PushID(&*fileIt); bool selected = m_selectedFiles.contains(fileIt); if (ImGui::Selectable(pathNameString.c_str(), selected, ImGuiSelectableFlags_NoAutoClosePopups)) { if (!m_multiple) { m_selectedFiles.clear(); m_selectedFiles.insert(fileIt); } else { if (selected) { m_selectedFiles.erase(fileIt); } else { m_selectedFiles.insert(fileIt); } } } if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0)) doubleClicked = true; ImGuiExt::InfoTooltip(wolv::util::toUTF8String(path).c_str()); ImGui::PopID(); } ImGui::EndListBox(); } if (ImGui::Button("hex.ui.common.open"_lang) || doubleClicked) { for (const auto &it : m_selectedFiles) m_openCallback(*it); Popup<T>::close(); } ImGui::SameLine(); if (ImGui::Button("hex.ui.common.browse"_lang)) { fs::openFileBrowser(fs::DialogMode::Open, m_validExtensions, [this](const auto &path) { m_openCallback(path); Popup<T>::close(); }, {}, m_multiple); } if (ImGui::IsKeyPressed(ImGuiKey_Escape)) this->close(); } [[nodiscard]] ImGuiWindowFlags getFlags() const override { return ImGuiWindowFlags_AlwaysAutoResize; } protected: const std::fs::path& getAdjustedPath(const std::fs::path &path) const { return m_adjustedPaths.at(path); } virtual std::string getEntryName(const std::fs::path &path) = 0; private: static bool isSubpath(const std::fs::path &basePath, const std::fs::path &path) { auto relativePath = std::fs::relative(path, basePath); return !relativePath.empty() && relativePath.native()[0] != '.'; } private: std::string m_filter; std::vector<std::fs::path> m_files; std::map<std::fs::path, std::fs::path> m_adjustedPaths; std::set<std::vector<std::fs::path>::const_iterator> m_selectedFiles; std::function<void(std::fs::path)> m_openCallback; std::vector<hex::fs::ItemFilter> m_validExtensions; bool m_multiple = false; bool m_justOpened = true; }; class PopupNamedFileChooser : public PopupNamedFileChooserBase<PopupNamedFileChooser> { public: PopupNamedFileChooser(const std::vector<std::fs::path> &basePaths, const std::vector<std::fs::path> &files, const std::vector<hex::fs::ItemFilter> &validExtensions, bool multiple, const std::function<std::string(std::fs::path, std::fs::path)> &nameCallback, const std::function<void(std::fs::path)> &callback) : PopupNamedFileChooserBase(basePaths, files, validExtensions, multiple, callback), m_nameCallback(nameCallback) { } std::string getEntryName(const std::fs::path &path) override { return m_nameCallback(path, getAdjustedPath(path)); } private: std::function<std::string(std::fs::path, std::fs::path)> m_nameCallback; }; class PopupFileChooser : public PopupNamedFileChooserBase<PopupFileChooser> { public: PopupFileChooser(const std::vector<std::fs::path> &basePaths, const std::vector<std::fs::path> &files, const std::vector<hex::fs::ItemFilter> &validExtensions, bool multiple, const std::function<void(std::fs::path)> &callback) : PopupNamedFileChooserBase(basePaths, files, validExtensions, multiple, callback) { } std::string getEntryName(const std::fs::path &path) override { return wolv::util::toUTF8String(getAdjustedPath(path)); } }; }
6,380
C++
.h
129
35.565891
317
0.556003
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
612
visualizer_helpers.hpp
WerWolv_ImHex/plugins/visualizers/include/content/visualizer_helpers.hpp
#pragma once #include <pl/pattern_language.hpp> #include <pl/patterns/pattern.hpp> namespace hex::plugin::visualizers { template<typename T> std::vector<T> patternToArray(pl::ptrn::Pattern *pattern){ const auto bytes = pattern->getBytes(); std::vector<T> result; result.resize(bytes.size() / sizeof(T)); for (size_t i = 0; i < result.size(); i++) std::memcpy(&result[i], &bytes[i * sizeof(T)], sizeof(T)); return result; } }
494
C++
.h
14
29.357143
70
0.625263
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
613
yara_rule.hpp
WerWolv_ImHex/plugins/yara_rules/include/content/yara_rule.hpp
#pragma once #include <hex/providers/provider.hpp> #include <string> #include <vector> #include <wolv/utils/expected.hpp> namespace hex::plugin::yara { class YaraRule { public: YaraRule() = default; explicit YaraRule(const std::string& content); explicit YaraRule(const std::fs::path& path); static void init(); static void cleanup(); struct Match { std::string variable; Region region; bool wholeDataMatch; }; struct Rule { std::string identifier; std::map<std::string, std::string> metadata; std::vector<std::string> tags; std::vector<Match> matches; }; struct Result { std::vector<Rule> matchedRules; std::vector<std::string> consoleMessages; }; struct Error { enum class Type { CompileError, RuntimeError, Interrupted } type; std::string message; }; wolv::util::Expected<Result, Error> match(prv::Provider *provider, Region region); void interrupt(); [[nodiscard]] bool isInterrupted() const; private: std::string m_content; std::fs::path m_filePath; std::atomic<bool> m_interrupted = false; }; }
1,375
C++
.h
45
21.244444
90
0.56307
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
614
view_yara.hpp
WerWolv_ImHex/plugins/yara_rules/include/content/views/view_yara.hpp
#pragma once #include <hex.hpp> #include <hex/ui/view.hpp> #include <hex/api/task_manager.hpp> #include <content/yara_rule.hpp> #include <wolv/container/interval_tree.hpp> namespace hex::plugin::yara { class ViewYara : public View::Window { public: ViewYara(); ~ViewYara() override; void drawContent() override; private: PerProvider<std::vector<std::pair<std::fs::path, std::fs::path>>> m_rulePaths; PerProvider<std::vector<YaraRule::Rule>> m_matchedRules; PerProvider<std::vector<std::string>> m_consoleMessages; PerProvider<u32> m_selectedRule; PerProvider<wolv::container::IntervalTree<std::string>> m_highlights; TaskHolder m_matcherTask; void applyRules(); void clearResult(); }; }
802
C++
.h
23
28.869565
86
0.675781
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
615
view_hashes.hpp
WerWolv_ImHex/plugins/hashes/include/content/views/view_hashes.hpp
#pragma once #include <hex/api/content_registry.hpp> #include <hex/ui/view.hpp> namespace hex::plugin::hashes { class ViewHashes : public View::Window { public: explicit ViewHashes(); ~ViewHashes() override; void drawContent() override; private: bool importHashes(prv::Provider *provider, const nlohmann::json &json); bool exportHashes(prv::Provider *provider, nlohmann::json &json); private: ContentRegistry::Hashes::Hash *m_selectedHash = nullptr; std::string m_newHashName; PerProvider<std::vector<ContentRegistry::Hashes::Hash::Function>> m_hashFunctions; }; }
659
C++
.h
18
30.388889
90
0.687797
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
616
view_tty_console.hpp
WerWolv_ImHex/plugins/windows/include/views/view_tty_console.hpp
#pragma once #include <hex/ui/view.hpp> #include <mutex> #include <thread> #include <jthread.hpp> #include <vector> namespace hex::plugin::windows { class ViewTTYConsole : public View::Window { public: ViewTTYConsole(); ~ViewTTYConsole() override = default; void drawContent() override; private: std::vector<std::pair<std::wstring, std::wstring>> m_comPorts; std::vector<std::pair<std::wstring, std::wstring>> getAvailablePorts() const; bool connect(); bool disconnect(); void transmitData(std::vector<char> &data); void* m_portHandle = reinterpret_cast<void*>(-1); std::jthread m_receiveThread; int m_selectedPort = 0; int m_selectedBaudRate = 11; // 115200 int m_selectedNumBits = 3; // 8 int m_selectedStopBits = 0; // 1 int m_selectedParityBits = 0; // None bool m_hasCTSFlowControl = false; // No bool m_shouldAutoScroll = true; std::mutex m_receiveBufferMutex; std::vector<char> m_receiveDataBuffer, m_transmitDataBuffer; std::vector<u32> m_wrapPositions; bool m_transmitting = false; constexpr static std::array BaudRates = { "110", "300", "600", "1200", "2400", "4800", "9600", "14400", "19200", "38400", "57600", "115200", "128000", "256000" }; constexpr static std::array NumBits = { "5", "6", "7", "8" }; constexpr static std::array StopBits = { "1", "1.5", "2.0" }; constexpr static std::array ParityBits = { "None", "Odd", "Even", "Mark", "Space" }; }; }
1,987
C++
.h
67
20.059701
85
0.501576
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
617
view_diff.hpp
WerWolv_ImHex/plugins/diffing/include/content/views/view_diff.hpp
#pragma once #include <hex.hpp> #include <hex/ui/view.hpp> #include <hex/api/task_manager.hpp> #include <array> #include <vector> #include "ui/hex_editor.hpp" namespace hex::plugin::diffing { class ViewDiff : public View::Window { public: ViewDiff(); ~ViewDiff() override; void drawContent() override; void drawAlwaysVisibleContent() override; ImGuiWindowFlags getWindowFlags() const override { return ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; } public: struct Column { ui::HexEditor hexEditor; ContentRegistry::Diffing::DiffTree diffTree; std::vector<ContentRegistry::Diffing::DiffTree::Data> differences; int provider = -1; i32 scrollLock = 0; }; private: std::function<std::optional<color_t>(u64, const u8*, size_t)> createCompareFunction(size_t otherIndex) const; void analyze(prv::Provider *providerA, prv::Provider *providerB); void reset(); private: std::array<Column, 2> m_columns; TaskHolder m_diffTask; std::atomic<bool> m_analyzed = false; ContentRegistry::Diffing::Algorithm *m_algorithm = nullptr; }; }
1,250
C++
.h
34
29.617647
134
0.663342
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
618
window.hpp
WerWolv_ImHex/main/gui/include/window.hpp
#pragma once #include <filesystem> #include <memory> #include <string> #include <list> #include <vector> #include <hex/ui/view.hpp> struct GLFWwindow; struct ImGuiSettingsHandler; namespace hex { void nativeErrorMessage(const std::string &message); class Window { public: Window(); ~Window(); void loop(); void fullFrame(); static void initNative(); void resize(i32 width, i32 height); private: void configureGLFW(); void setupNativeWindow(); void beginNativeWindowFrame(); void endNativeWindowFrame(); void drawTitleBar(); void frameBegin(); void frame(); void frameEnd(); void initGLFW(); void initImGui(); void exitGLFW(); void exitImGui(); void registerEventHandlers(); GLFWwindow *m_window = nullptr; std::string m_windowTitle, m_windowTitleFull; double m_lastStartFrameTime = 0; double m_lastFrameTime = 0; ImGuiExt::Texture m_logoTexture; std::mutex m_popupMutex; std::list<std::string> m_popupsToOpen; std::vector<int> m_pressedKeys; bool m_unlockFrameRate = false; ImGuiExt::ImHexCustomData m_imguiCustomData; u32 m_searchBarPosition = 0; bool m_emergencyPopupOpen = false; }; }
1,378
C++
.h
47
22.148936
56
0.6356
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
619
stacktrace.hpp
WerWolv_ImHex/main/gui/include/stacktrace.hpp
#pragma once #include <hex.hpp> #include <string> #include <vector> namespace hex::stacktrace { struct StackFrame { std::string file; std::string function; u32 line; }; void initialize(); struct StackTraceResult { std::vector<StackFrame> stackFrames; std::string implementationName; }; StackTraceResult getStackTrace(); }
394
C++
.h
17
17.941176
44
0.664865
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
620
messaging.hpp
WerWolv_ImHex/main/gui/include/messaging.hpp
#pragma once #include <string> #include <vector> #include <hex/helpers/types.hpp> /** * Cross-instance (cross-process) messaging system * As of now, this system may not be stable for use beyond its current use: * forwarding providers opened in new instances */ namespace hex::messaging { /** * @brief Setup everything to be able to send/receive messages */ void setupMessaging(); /** * @brief Internal method - setup platform-specific things to be able to send messages * @return if this instance has been determined to be the main instance */ bool setupNative(); /** * @brief Internal method - send a message to another Imhex instance in a platform-specific way */ void sendToOtherInstance(const std::string &eventName, const std::vector<u8> &args); /** * @brief Internal method - called by platform-specific code when a event has been received */ void messageReceived(const std::string &eventName, const std::vector<u8> &args); }
1,025
C++
.h
28
32.285714
99
0.708629
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
621
tasks.hpp
WerWolv_ImHex/main/gui/include/init/tasks.hpp
#pragma once #include <vector> #include <init/splash_window.hpp> namespace hex::init { /** * @brief Runs the exit tasks and print them to console */ void runExitTasks(); std::vector<Task> getInitTasks(); std::vector<Task> getExitTasks(); }
270
C++
.h
11
20.818182
59
0.678431
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
622
splash_window.hpp
WerWolv_ImHex/main/gui/include/init/splash_window.hpp
#pragma once #include <functional> #include <future> #include <list> #include <ranges> #include <string> #include <mutex> #include <imgui.h> #include <hex/ui/imgui_imhex_extensions.h> struct GLFWwindow; namespace hex::init { using TaskFunction = std::function<bool()>; struct Task { std::string name; std::function<bool()> callback; bool async; }; enum FrameResult{ Success, Failure, Running }; struct Highlight { ImVec2 start; size_t count; ImColor color; }; class WindowSplash { public: WindowSplash(); ~WindowSplash(); bool loop(); FrameResult fullFrame(); void startStartupTasks(); void createTask(const Task &task); void addStartupTask(const std::string &taskName, const TaskFunction &function, bool async) { std::scoped_lock lock(m_tasksMutex); m_tasks.emplace_back(taskName, function, async); } private: GLFWwindow *m_window; std::mutex m_progressMutex; std::atomic<float> m_progress = 0; std::list<std::string> m_currTaskNames; void initGLFW(); void initImGui(); void loadAssets(); void exitGLFW() const; void exitImGui() const; std::future<bool> processTasksAsync(); std::atomic<u32> m_totalTaskCount, m_completedTaskCount; std::atomic<bool> m_taskStatus = true; std::list<Task> m_tasks; std::mutex m_tasksMutex; std::string m_gpuVendor; ImGuiExt::Texture m_splashBackgroundTexture; ImGuiExt::Texture m_splashTextTexture; std::future<bool> m_tasksSucceeded; std::array<Highlight, 4> m_highlights; float m_progressLerp = 0.0F; }; }
1,803
C++
.h
58
23.827586
100
0.630966
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
623
run.hpp
WerWolv_ImHex/main/gui/include/init/run.hpp
#pragma once #include <init/splash_window.hpp> namespace hex::init { void handleFileOpenRequest(); std::unique_ptr<WindowSplash> initializeImHex(); void deinitializeImHex(); }
193
C++
.h
7
24.142857
52
0.756906
WerWolv/ImHex
43,494
1,905
221
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
765
UtilTest1.cc
aria2_aria2/test/UtilTest1.cc
#include "util.h" #include <cmath> #include <cstring> #include <string> #include <cassert> #include <iostream> #include <cppunit/extensions/HelperMacros.h> #include "FixedNumberRandomizer.h" #include "DlAbortEx.h" #include "BitfieldMan.h" #include "ByteArrayDiskWriter.h" #include "FileEntry.h" #include "File.h" #include "array_fun.h" #include "BufferedFile.h" #include "TestUtil.h" #include "SocketCore.h" namespace aria2 { class UtilTest1 : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(UtilTest1); CPPUNIT_TEST(testStrip); CPPUNIT_TEST(testStripIter); CPPUNIT_TEST(testLstripIter); CPPUNIT_TEST(testLstripIter_char); CPPUNIT_TEST(testDivide); CPPUNIT_TEST(testSplit); CPPUNIT_TEST(testSplitIter); CPPUNIT_TEST(testSplitIterM); CPPUNIT_TEST(testStreq); CPPUNIT_TEST(testStrieq); CPPUNIT_TEST(testStrifind); CPPUNIT_TEST(testEndsWith); CPPUNIT_TEST(testIendsWith); CPPUNIT_TEST(testReplace); CPPUNIT_TEST(testStartsWith); CPPUNIT_TEST(testIstartsWith); // may be moved to other helper class in the future. CPPUNIT_TEST(testGetContentDispositionFilename); CPPUNIT_TEST(testParseContentDisposition1); CPPUNIT_TEST(testParseContentDisposition2); CPPUNIT_TEST_SUITE_END(); private: public: void setUp() {} void testStrip(); void testStripIter(); void testLstripIter(); void testLstripIter_char(); void testDivide(); void testSplit(); void testSplitIter(); void testSplitIterM(); void testStreq(); void testStrieq(); void testStrifind(); void testEndsWith(); void testIendsWith(); void testReplace(); void testStartsWith(); void testIstartsWith(); // may be moved to other helper class in the future. void testGetContentDispositionFilename(); void testParseContentDisposition1(); void testParseContentDisposition2(); }; CPPUNIT_TEST_SUITE_REGISTRATION(UtilTest1); void UtilTest1::testStrip() { std::string str1 = "aria2"; CPPUNIT_ASSERT_EQUAL(str1, util::strip("aria2")); CPPUNIT_ASSERT_EQUAL(str1, util::strip(" aria2")); CPPUNIT_ASSERT_EQUAL(str1, util::strip("aria2 ")); CPPUNIT_ASSERT_EQUAL(str1, util::strip(" aria2 ")); CPPUNIT_ASSERT_EQUAL(str1, util::strip(" aria2 ")); std::string str2 = "aria2 debut"; CPPUNIT_ASSERT_EQUAL(str2, util::strip("aria2 debut")); CPPUNIT_ASSERT_EQUAL(str2, util::strip(" aria2 debut ")); std::string str3 = ""; CPPUNIT_ASSERT_EQUAL(str3, util::strip("")); CPPUNIT_ASSERT_EQUAL(str3, util::strip(" ")); CPPUNIT_ASSERT_EQUAL(str3, util::strip(" ")); std::string str4 = "A"; CPPUNIT_ASSERT_EQUAL(str4, util::strip("A")); CPPUNIT_ASSERT_EQUAL(str4, util::strip(" A ")); CPPUNIT_ASSERT_EQUAL(str4, util::strip(" A ")); } void UtilTest1::testStripIter() { Scip p; std::string str1 = "aria2"; std::string s = "aria2"; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str1, std::string(p.first, p.second)); s = " aria2"; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str1, std::string(p.first, p.second)); s = "aria2 "; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str1, std::string(p.first, p.second)); s = " aria2 "; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str1, std::string(p.first, p.second)); s = " aria2 "; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str1, std::string(p.first, p.second)); std::string str2 = "aria2 debut"; s = "aria2 debut"; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str2, std::string(p.first, p.second)); s = " aria2 debut "; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str2, std::string(p.first, p.second)); std::string str3 = ""; s = ""; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str3, std::string(p.first, p.second)); s = " "; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str3, std::string(p.first, p.second)); s = " "; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str3, std::string(p.first, p.second)); std::string str4 = "A"; s = "A"; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str4, std::string(p.first, p.second)); s = " A "; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str4, std::string(p.first, p.second)); s = " A "; p = util::stripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(str4, std::string(p.first, p.second)); } void UtilTest1::testLstripIter() { std::string::iterator r; std::string s = "foo"; r = util::lstripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(std::string("foo"), std::string(r, s.end())); s = " foo bar "; r = util::lstripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(std::string("foo bar "), std::string(r, s.end())); s = "f"; r = util::lstripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(std::string("f"), std::string(r, s.end())); s = "foo "; r = util::lstripIter(s.begin(), s.end()); CPPUNIT_ASSERT_EQUAL(std::string("foo "), std::string(r, s.end())); } void UtilTest1::testLstripIter_char() { std::string::iterator r; std::string s = "foo"; r = util::lstripIter(s.begin(), s.end(), '$'); CPPUNIT_ASSERT_EQUAL(std::string("foo"), std::string(r, s.end())); s = "$$foo$bar$$"; r = util::lstripIter(s.begin(), s.end(), '$'); CPPUNIT_ASSERT_EQUAL(std::string("foo$bar$$"), std::string(r, s.end())); s = "f"; r = util::lstripIter(s.begin(), s.end(), '$'); CPPUNIT_ASSERT_EQUAL(std::string("f"), std::string(r, s.end())); s = "foo$$"; r = util::lstripIter(s.begin(), s.end(), '$'); CPPUNIT_ASSERT_EQUAL(std::string("foo$$"), std::string(r, s.end())); } void UtilTest1::testDivide() { std::string s = "name=value"; auto p1 = util::divide(std::begin(s), std::end(s), '='); CPPUNIT_ASSERT_EQUAL(std::string("name"), std::string(p1.first.first, p1.first.second)); CPPUNIT_ASSERT_EQUAL(std::string("value"), std::string(p1.second.first, p1.second.second)); s = " name = value "; p1 = util::divide(std::begin(s), std::end(s), '='); CPPUNIT_ASSERT_EQUAL(std::string("name"), std::string(p1.first.first, p1.first.second)); CPPUNIT_ASSERT_EQUAL(std::string("value"), std::string(p1.second.first, p1.second.second)); s = "=value"; p1 = util::divide(std::begin(s), std::end(s), '='); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(p1.first.first, p1.first.second)); CPPUNIT_ASSERT_EQUAL(std::string("value"), std::string(p1.second.first, p1.second.second)); s = "name="; p1 = util::divide(std::begin(s), std::end(s), '='); CPPUNIT_ASSERT_EQUAL(std::string("name"), std::string(p1.first.first, p1.first.second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(p1.second.first, p1.second.second)); s = "name"; p1 = util::divide(std::begin(s), std::end(s), '='); CPPUNIT_ASSERT_EQUAL(std::string("name"), std::string(p1.first.first, p1.first.second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(p1.second.first, p1.second.second)); } void UtilTest1::testSplit() { std::vector<std::string> v; std::string s = "k1; k2;; k3"; util::split(s.begin(), s.end(), std::back_inserter(v), ';', true); CPPUNIT_ASSERT_EQUAL((size_t)3, v.size()); std::vector<std::string>::iterator itr = v.begin(); CPPUNIT_ASSERT_EQUAL(std::string("k1"), *itr++); CPPUNIT_ASSERT_EQUAL(std::string("k2"), *itr++); CPPUNIT_ASSERT_EQUAL(std::string("k3"), *itr++); v.clear(); s = "k1; k2; k3"; util::split(s.begin(), s.end(), std::back_inserter(v), ';'); CPPUNIT_ASSERT_EQUAL((size_t)3, v.size()); itr = v.begin(); CPPUNIT_ASSERT_EQUAL(std::string("k1"), *itr++); CPPUNIT_ASSERT_EQUAL(std::string(" k2"), *itr++); CPPUNIT_ASSERT_EQUAL(std::string(" k3"), *itr++); v.clear(); s = "k=v"; util::split(s.begin(), s.end(), std::back_inserter(v), ';', false, true); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); itr = v.begin(); CPPUNIT_ASSERT_EQUAL(std::string("k=v"), *itr++); v.clear(); s = ";;k1;;k2;"; util::split(s.begin(), s.end(), std::back_inserter(v), ';', false, true); CPPUNIT_ASSERT_EQUAL((size_t)6, v.size()); itr = v.begin(); CPPUNIT_ASSERT_EQUAL(std::string(""), *itr++); CPPUNIT_ASSERT_EQUAL(std::string(""), *itr++); CPPUNIT_ASSERT_EQUAL(std::string("k1"), *itr++); CPPUNIT_ASSERT_EQUAL(std::string(""), *itr++); CPPUNIT_ASSERT_EQUAL(std::string("k2"), *itr++); CPPUNIT_ASSERT_EQUAL(std::string(""), *itr++); v.clear(); s = ";;k1;;k2;"; util::split(s.begin(), s.end(), std::back_inserter(v), ';'); CPPUNIT_ASSERT_EQUAL((size_t)2, v.size()); itr = v.begin(); CPPUNIT_ASSERT_EQUAL(std::string("k1"), *itr++); CPPUNIT_ASSERT_EQUAL(std::string("k2"), *itr++); v.clear(); s = "k; "; util::split(s.begin(), s.end(), std::back_inserter(v), ';'); CPPUNIT_ASSERT_EQUAL((size_t)2, v.size()); itr = v.begin(); CPPUNIT_ASSERT_EQUAL(std::string("k"), *itr++); CPPUNIT_ASSERT_EQUAL(std::string(" "), *itr++); v.clear(); s = " "; util::split(s.begin(), s.end(), std::back_inserter(v), ';', true, true); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(""), v[0]); v.clear(); s = " "; util::split(s.begin(), s.end(), std::back_inserter(v), ';', true); CPPUNIT_ASSERT_EQUAL((size_t)0, v.size()); v.clear(); s = " "; util::split(s.begin(), s.end(), std::back_inserter(v), ';'); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(" "), v[0]); v.clear(); s = ";"; util::split(s.begin(), s.end(), std::back_inserter(v), ';'); CPPUNIT_ASSERT_EQUAL((size_t)0, v.size()); v.clear(); s = ";"; util::split(s.begin(), s.end(), std::back_inserter(v), ';', false, true); CPPUNIT_ASSERT_EQUAL((size_t)2, v.size()); itr = v.begin(); CPPUNIT_ASSERT_EQUAL(std::string(""), *itr++); CPPUNIT_ASSERT_EQUAL(std::string(""), *itr++); v.clear(); s = ""; util::split(s.begin(), s.end(), std::back_inserter(v), ';', false, true); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(""), v[0]); } void UtilTest1::testSplitIter() { std::vector<Scip> v; std::string s = "k1; k2;; k3"; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';', true); CPPUNIT_ASSERT_EQUAL((size_t)3, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k1"), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string("k2"), std::string(v[1].first, v[1].second)); CPPUNIT_ASSERT_EQUAL(std::string("k3"), std::string(v[2].first, v[2].second)); v.clear(); s = "k1; k2; k3"; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';'); CPPUNIT_ASSERT_EQUAL((size_t)3, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k1"), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string(" k2"), std::string(v[1].first, v[1].second)); CPPUNIT_ASSERT_EQUAL(std::string(" k3"), std::string(v[2].first, v[2].second)); v.clear(); s = "k=v"; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';', false, true); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k=v"), std::string(v[0].first, v[0].second)); v.clear(); s = ";;k1;;k2;"; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';', false, true); CPPUNIT_ASSERT_EQUAL((size_t)6, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[1].first, v[1].second)); CPPUNIT_ASSERT_EQUAL(std::string("k1"), std::string(v[2].first, v[2].second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[3].first, v[3].second)); CPPUNIT_ASSERT_EQUAL(std::string("k2"), std::string(v[4].first, v[4].second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[5].first, v[5].second)); v.clear(); s = ";;k1;;k2;"; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';'); CPPUNIT_ASSERT_EQUAL((size_t)2, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k1"), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string("k2"), std::string(v[1].first, v[1].second)); v.clear(); s = "k; "; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';'); CPPUNIT_ASSERT_EQUAL((size_t)2, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k"), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string(" "), std::string(v[1].first, v[1].second)); v.clear(); s = " "; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';', true, true); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[0].first, v[0].second)); v.clear(); s = " "; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';', true); CPPUNIT_ASSERT_EQUAL((size_t)0, v.size()); v.clear(); s = " "; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';'); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(" "), std::string(v[0].first, v[0].second)); v.clear(); s = ";"; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';'); CPPUNIT_ASSERT_EQUAL((size_t)0, v.size()); v.clear(); s = ";"; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';', false, true); CPPUNIT_ASSERT_EQUAL((size_t)2, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[1].first, v[1].second)); v.clear(); s = ""; util::splitIter(s.begin(), s.end(), std::back_inserter(v), ';', false, true); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[0].first, v[0].second)); } void UtilTest1::testSplitIterM() { const char d[] = ";"; const char md[] = "; "; std::vector<Scip> v; std::string s = "k1; k2;; k3"; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d, true); CPPUNIT_ASSERT_EQUAL((size_t)3, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k1"), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string("k2"), std::string(v[1].first, v[1].second)); CPPUNIT_ASSERT_EQUAL(std::string("k3"), std::string(v[2].first, v[2].second)); v.clear(); s = "k1; k2; k3"; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d); CPPUNIT_ASSERT_EQUAL((size_t)3, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k1"), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string(" k2"), std::string(v[1].first, v[1].second)); CPPUNIT_ASSERT_EQUAL(std::string(" k3"), std::string(v[2].first, v[2].second)); v.clear(); s = "k1; k2; k3"; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), md); CPPUNIT_ASSERT_EQUAL((size_t)3, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k1"), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string("k2"), std::string(v[1].first, v[1].second)); CPPUNIT_ASSERT_EQUAL(std::string("k3"), std::string(v[2].first, v[2].second)); v.clear(); s = "k1; k2; k3;"; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), md, false, true); CPPUNIT_ASSERT_EQUAL((size_t)6, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k1"), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[1].first, v[1].second)); CPPUNIT_ASSERT_EQUAL(std::string("k2"), std::string(v[2].first, v[2].second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[3].first, v[3].second)); CPPUNIT_ASSERT_EQUAL(std::string("k3"), std::string(v[4].first, v[4].second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[5].first, v[5].second)); v.clear(); s = "k=v"; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d, false, true); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k=v"), std::string(v[0].first, v[0].second)); v.clear(); s = ";;k1;;k2;"; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d, false, true); CPPUNIT_ASSERT_EQUAL((size_t)6, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[1].first, v[1].second)); CPPUNIT_ASSERT_EQUAL(std::string("k1"), std::string(v[2].first, v[2].second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[3].first, v[3].second)); CPPUNIT_ASSERT_EQUAL(std::string("k2"), std::string(v[4].first, v[4].second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[5].first, v[5].second)); v.clear(); s = ";;k1;;k2;"; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d); CPPUNIT_ASSERT_EQUAL((size_t)2, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k1"), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string("k2"), std::string(v[1].first, v[1].second)); v.clear(); s = "k; "; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d); CPPUNIT_ASSERT_EQUAL((size_t)2, v.size()); CPPUNIT_ASSERT_EQUAL(std::string("k"), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string(" "), std::string(v[1].first, v[1].second)); v.clear(); s = " "; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d, true, true); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[0].first, v[0].second)); v.clear(); s = " "; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d, true); CPPUNIT_ASSERT_EQUAL((size_t)0, v.size()); v.clear(); s = " "; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(" "), std::string(v[0].first, v[0].second)); v.clear(); s = ";"; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d); CPPUNIT_ASSERT_EQUAL((size_t)0, v.size()); v.clear(); s = ";"; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d, false, true); CPPUNIT_ASSERT_EQUAL((size_t)2, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[0].first, v[0].second)); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[1].first, v[1].second)); v.clear(); s = ""; util::splitIterM(s.begin(), s.end(), std::back_inserter(v), d, false, true); CPPUNIT_ASSERT_EQUAL((size_t)1, v.size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(v[0].first, v[0].second)); } void UtilTest1::testEndsWith() { std::string target = "abcdefg"; std::string part = "fg"; CPPUNIT_ASSERT( util::endsWith(target.begin(), target.end(), part.begin(), part.end())); target = "abdefg"; part = "g"; CPPUNIT_ASSERT( util::endsWith(target.begin(), target.end(), part.begin(), part.end())); target = "abdefg"; part = "eg"; CPPUNIT_ASSERT( !util::endsWith(target.begin(), target.end(), part.begin(), part.end())); target = "g"; part = "eg"; CPPUNIT_ASSERT( !util::endsWith(target.begin(), target.end(), part.begin(), part.end())); target = "g"; part = "g"; CPPUNIT_ASSERT( util::endsWith(target.begin(), target.end(), part.begin(), part.end())); target = "g"; part = ""; CPPUNIT_ASSERT( util::endsWith(target.begin(), target.end(), part.begin(), part.end())); target = ""; part = ""; CPPUNIT_ASSERT( util::endsWith(target.begin(), target.end(), part.begin(), part.end())); target = ""; part = "g"; CPPUNIT_ASSERT( !util::endsWith(target.begin(), target.end(), part.begin(), part.end())); } void UtilTest1::testIendsWith() { std::string target = "abcdefg"; std::string part = "Fg"; CPPUNIT_ASSERT( util::iendsWith(target.begin(), target.end(), part.begin(), part.end())); target = "abdefg"; part = "ef"; CPPUNIT_ASSERT( !util::iendsWith(target.begin(), target.end(), part.begin(), part.end())); } void UtilTest1::testStreq() { std::string s1, s2; s1 = "foo"; s2 = "foo"; CPPUNIT_ASSERT(util::streq(s1.begin(), s1.end(), s2.begin(), s2.end())); CPPUNIT_ASSERT(util::streq(s1.begin(), s1.end(), s2.c_str())); s2 = "fooo"; CPPUNIT_ASSERT(!util::streq(s1.begin(), s1.end(), s2.begin(), s2.end())); CPPUNIT_ASSERT(!util::streq(s1.begin(), s1.end(), s2.c_str())); s2 = "fo"; CPPUNIT_ASSERT(!util::streq(s1.begin(), s1.end(), s2.begin(), s2.end())); CPPUNIT_ASSERT(!util::streq(s1.begin(), s1.end(), s2.c_str())); s2 = ""; CPPUNIT_ASSERT(!util::streq(s1.begin(), s1.end(), s2.begin(), s2.end())); CPPUNIT_ASSERT(!util::streq(s1.begin(), s1.end(), s2.c_str())); s1 = ""; CPPUNIT_ASSERT(util::streq(s1.begin(), s1.end(), s2.begin(), s2.end())); CPPUNIT_ASSERT(util::streq(s1.begin(), s1.end(), s2.c_str())); } void UtilTest1::testStrieq() { std::string s1, s2; s1 = "foo"; s2 = "foo"; CPPUNIT_ASSERT(util::strieq(s1.begin(), s1.end(), s2.begin(), s2.end())); CPPUNIT_ASSERT(util::strieq(s1.begin(), s1.end(), s2.c_str())); s1 = "FoO"; s2 = "fOo"; CPPUNIT_ASSERT(util::strieq(s1.begin(), s1.end(), s2.begin(), s2.end())); CPPUNIT_ASSERT(util::strieq(s1.begin(), s1.end(), s2.c_str())); s2 = "fooo"; CPPUNIT_ASSERT(!util::strieq(s1.begin(), s1.end(), s2.begin(), s2.end())); CPPUNIT_ASSERT(!util::strieq(s1.begin(), s1.end(), s2.c_str())); s2 = "fo"; CPPUNIT_ASSERT(!util::strieq(s1.begin(), s1.end(), s2.begin(), s2.end())); CPPUNIT_ASSERT(!util::strieq(s1.begin(), s1.end(), s2.c_str())); s2 = ""; CPPUNIT_ASSERT(!util::strieq(s1.begin(), s1.end(), s2.begin(), s2.end())); CPPUNIT_ASSERT(!util::strieq(s1.begin(), s1.end(), s2.c_str())); s1 = ""; CPPUNIT_ASSERT(util::strieq(s1.begin(), s1.end(), s2.begin(), s2.end())); CPPUNIT_ASSERT(util::strieq(s1.begin(), s1.end(), s2.c_str())); } void UtilTest1::testStrifind() { std::string s1, s2; s1 = "yamagakani mukashi wo toheba hARU no tuki"; s2 = "HaRu"; CPPUNIT_ASSERT(util::strifind(s1.begin(), s1.end(), s2.begin(), s2.end()) != s1.end()); s2 = "aki"; CPPUNIT_ASSERT(util::strifind(s1.begin(), s1.end(), s2.begin(), s2.end()) == s1.end()); s1 = "h"; s2 = "HH"; CPPUNIT_ASSERT(util::strifind(s1.begin(), s1.end(), s2.begin(), s2.end()) == s1.end()); } void UtilTest1::testReplace() { CPPUNIT_ASSERT_EQUAL(std::string("abc\n"), util::replace("abc\r\n", "\r", "")); CPPUNIT_ASSERT_EQUAL(std::string("abc"), util::replace("abc\r\n", "\r\n", "")); CPPUNIT_ASSERT_EQUAL(std::string(""), util::replace("", "\r\n", "")); CPPUNIT_ASSERT_EQUAL(std::string("abc"), util::replace("abc", "", "a")); CPPUNIT_ASSERT_EQUAL(std::string("xbc"), util::replace("abc", "a", "x")); } void UtilTest1::testStartsWith() { std::string target; std::string part; target = "abcdefg"; part = "abc"; CPPUNIT_ASSERT( util::startsWith(target.begin(), target.end(), part.begin(), part.end())); CPPUNIT_ASSERT(util::startsWith(target.begin(), target.end(), part.c_str())); target = "abcdefg"; part = "abx"; CPPUNIT_ASSERT(!util::startsWith(target.begin(), target.end(), part.begin(), part.end())); CPPUNIT_ASSERT(!util::startsWith(target.begin(), target.end(), part.c_str())); target = "abcdefg"; part = "bcd"; CPPUNIT_ASSERT(!util::startsWith(target.begin(), target.end(), part.begin(), part.end())); CPPUNIT_ASSERT(!util::startsWith(target.begin(), target.end(), part.c_str())); target = ""; part = "a"; CPPUNIT_ASSERT(!util::startsWith(target.begin(), target.end(), part.begin(), part.end())); CPPUNIT_ASSERT(!util::startsWith(target.begin(), target.end(), part.c_str())); target = ""; part = ""; CPPUNIT_ASSERT( util::startsWith(target.begin(), target.end(), part.begin(), part.end())); CPPUNIT_ASSERT(util::startsWith(target.begin(), target.end(), part.c_str())); target = "a"; part = ""; CPPUNIT_ASSERT( util::startsWith(target.begin(), target.end(), part.begin(), part.end())); CPPUNIT_ASSERT(util::startsWith(target.begin(), target.end(), part.c_str())); target = "a"; part = "a"; CPPUNIT_ASSERT( util::startsWith(target.begin(), target.end(), part.begin(), part.end())); CPPUNIT_ASSERT(util::startsWith(target.begin(), target.end(), part.c_str())); } void UtilTest1::testIstartsWith() { std::string target; std::string part; target = "abcdefg"; part = "aBc"; CPPUNIT_ASSERT(util::istartsWith(target.begin(), target.end(), part.begin(), part.end())); CPPUNIT_ASSERT(util::istartsWith(target.begin(), target.end(), part.c_str())); target = "abcdefg"; part = "abx"; CPPUNIT_ASSERT(!util::istartsWith(target.begin(), target.end(), part.begin(), part.end())); CPPUNIT_ASSERT( !util::istartsWith(target.begin(), target.end(), part.c_str())); } void UtilTest1::testGetContentDispositionFilename() { std::string val; val = "attachment; filename=\"aria2.tar.bz2\""; CPPUNIT_ASSERT_EQUAL(std::string("aria2.tar.bz2"), util::getContentDispositionFilename(val, false)); val = "attachment; filename=\"\""; CPPUNIT_ASSERT_EQUAL(std::string(""), util::getContentDispositionFilename(val, false)); val = "attachment; filename=\""; CPPUNIT_ASSERT_EQUAL(std::string(""), util::getContentDispositionFilename(val, false)); val = "attachment; filename= \" aria2.tar.bz2 \""; CPPUNIT_ASSERT_EQUAL(std::string(" aria2.tar.bz2 "), util::getContentDispositionFilename(val, false)); val = "attachment; filename=dir/file"; CPPUNIT_ASSERT_EQUAL(std::string(""), util::getContentDispositionFilename(val, false)); val = "attachment; filename=dir\\file"; CPPUNIT_ASSERT_EQUAL(std::string(""), util::getContentDispositionFilename(val, false)); val = "attachment; filename=\"dir/file\""; CPPUNIT_ASSERT_EQUAL(std::string(""), util::getContentDispositionFilename(val, false)); val = "attachment; filename=\"dir\\\\file\""; CPPUNIT_ASSERT_EQUAL(std::string(""), util::getContentDispositionFilename(val, false)); val = "attachment; filename=\"/etc/passwd\""; CPPUNIT_ASSERT_EQUAL(std::string(""), util::getContentDispositionFilename(val, false)); val = "attachment; filename=\"..\""; CPPUNIT_ASSERT_EQUAL(std::string(""), util::getContentDispositionFilename(val, false)); val = "attachment; filename=.."; CPPUNIT_ASSERT_EQUAL(std::string(""), util::getContentDispositionFilename(val, false)); // Unescaping %2E%2E%2F produces "../". But since we won't unescape, // we just accept it as is. val = "attachment; filename=\"%2E%2E%2Ffoo.html\""; CPPUNIT_ASSERT_EQUAL(std::string("%2E%2E%2Ffoo.html"), util::getContentDispositionFilename(val, false)); // iso-8859-1 string will be converted to utf-8. val = "attachment; filename*=iso-8859-1''foo-%E4.html"; CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), util::getContentDispositionFilename(val, false)); val = "attachment; filename*= UTF-8''foo-%c3%a4.html"; CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), util::getContentDispositionFilename(val, false)); // iso-8859-1 string will be converted to utf-8. val = "attachment; filename=\"foo-%E4.html\""; val = util::percentDecode(val.begin(), val.end()); CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), util::getContentDispositionFilename(val, false)); // allow utf-8 in filename if default_utf8 is set. val = "attachment; filename=\"foo-ä.html\""; CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), util::getContentDispositionFilename(val, true)); // return empty if default_utf8 is set but invalid utf8. val = "attachment; filename=\"foo-\xc2\x02.html\""; CPPUNIT_ASSERT_EQUAL(std::string(""), util::getContentDispositionFilename(val, true)); } void UtilTest1::testParseContentDisposition1() { char dest[1_k]; size_t destlen = sizeof(dest); const char* cs; size_t cslen; std::string val; // test cases from http://greenbytes.de/tech/tc2231/ // inlonly val = "inline"; CPPUNIT_ASSERT_EQUAL((ssize_t)0, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // inlonlyquoted val = "\"inline\""; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // inlwithasciifilename val = "inline; filename=\"foo.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); // inlwithfnattach val = "inline; filename=\"Not an attachment!\""; CPPUNIT_ASSERT_EQUAL((ssize_t)18, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("Not an attachment!"), std::string(&dest[0], &dest[18])); // inlwithasciifilenamepdf val = "inline; filename=\"foo.pdf\""; CPPUNIT_ASSERT_EQUAL((ssize_t)7, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.pdf"), std::string(&dest[0], &dest[7])); // attwithasciifilename25 val = "attachment; filename=\"0000000000111111111122222\""; CPPUNIT_ASSERT_EQUAL((ssize_t)25, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("0000000000111111111122222"), std::string(&dest[0], &dest[25])); // attwithasciifilename35 val = "attachment; filename=\"00000000001111111111222222222233333\""; CPPUNIT_ASSERT_EQUAL((ssize_t)35, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("00000000001111111111222222222233333"), std::string(&dest[0], &dest[35])); // attwithasciifnescapedchar val = "attachment; filename=\"f\\oo.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); // attwithasciifnescapedquote val = "attachment; filename=\"\\\"quoting\\\" tested.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)21, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("\"quoting\" tested.html"), std::string(&dest[0], &dest[21])); // attwithquotedsemicolon val = "attachment; filename=\"Here's a semicolon;.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)24, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("Here's a semicolon;.html"), std::string(&dest[0], &dest[24])); // attwithfilenameandextparam val = "attachment; foo=\"bar\"; filename=\"foo.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); // attwithfilenameandextparamescaped val = "attachment; foo=\"\\\"\\\\\";filename=\"foo.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); // attwithasciifilenameucase val = "attachment; FILENAME=\"foo.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); // attwithasciifilenamenq val = "attachment; filename=foo.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); // attwithtokfncommanq val = "attachment; filename=foo,bar.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithasciifilenamenqs val = "attachment; filename=foo.html ;"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attemptyparam val = "attachment; ;filename=foo"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithasciifilenamenqws val = "attachment; filename=foo bar.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithfntokensq val = "attachment; filename='foo.bar'"; CPPUNIT_ASSERT_EQUAL((ssize_t)9, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("'foo.bar'"), std::string(&dest[0], &dest[9])); // attwithisofnplain // attachment; filename="foo-ä.html" val = "attachment; filename=\"foo-%E4.html\""; val = util::percentDecode(val.begin(), val.end()); CPPUNIT_ASSERT_EQUAL((ssize_t)10, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), util::iso8859p1ToUtf8(std::string(&dest[0], &dest[10]))); // attwithutf8fnplain // attachment; filename="foo-ä.html" val = "attachment; filename=\"foo-%C3%A4.html\""; val = util::percentDecode(val.begin(), val.end()); CPPUNIT_ASSERT_EQUAL((ssize_t)11, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), util::iso8859p1ToUtf8(std::string(&dest[0], &dest[11]))); // attwithfnrawpctenca val = "attachment; filename=\"foo-%41.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)12, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo-%41.html"), std::string(&dest[0], &dest[12])); // attwithfnusingpct val = "attachment; filename=\"50%.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("50%.html"), std::string(&dest[0], &dest[8])); // attwithfnrawpctencaq val = "attachment; filename=\"foo-%\\41.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)12, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo-%41.html"), std::string(&dest[0], &dest[12])); // attwithnamepct val = "attachment; name=\"foo-%41.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)0, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithfilenamepctandiso // attachment; filename="ä-%41.html" val = "attachment; filename=\"%E4-%2541.html\""; val = util::percentDecode(val.begin(), val.end()); CPPUNIT_ASSERT_EQUAL((ssize_t)10, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("ä-%41.html"), util::iso8859p1ToUtf8(std::string(&dest[0], &dest[10]))); // attwithfnrawpctenclong val = "attachment; filename=\"foo-%c3%a4-%e2%82%ac.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)25, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo-%c3%a4-%e2%82%ac.html"), std::string(&dest[0], &dest[25])); // attwithasciifilenamews1 val = "attachment; filename =\"foo.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); // attwith2filenames val = "attachment; filename=\"foo.html\"; filename=\"bar.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attfnbrokentoken val = "attachment; filename=foo[1](2).html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attfnbrokentokeniso val = "attachment; filename=foo-%E4.html"; val = util::percentDecode(val.begin(), val.end()); CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attfnbrokentokenutf // attachment; filename=foo-ä.html val = "attachment; filename=foo-ä.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attmissingdisposition val = "filename=foo.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attmissingdisposition2 val = "x=y; filename=foo.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attmissingdisposition3 val = "\"foo; filename=bar;baz\"; filename=qux"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attmissingdisposition4 val = "filename=foo.html, filename=bar.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // emptydisposition val = "; filename=foo.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // doublecolon val = ": inline; attachment; filename=foo.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attandinline val = "inline; attachment; filename=foo.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attandinline2 val = "attachment; inline; filename=foo.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attbrokenquotedfn val = "attachment; filename=\"foo.html\".txt"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attbrokenquotedfn2 val = "attachment; filename=\"bar"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attbrokenquotedfn3 val = "attachment; filename=foo\"bar;baz\"qux"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attmultinstances val = "attachment; filename=foo.html, attachment; filename=bar.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); } void UtilTest1::testParseContentDisposition2() { char dest[1_k]; size_t destlen = sizeof(dest); const char* cs; size_t cslen; std::string val; // test cases from http://greenbytes.de/tech/tc2231/ // attmissingdelim val = "attachment; foo=foo filename=bar"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attmissingdelim2 val = "attachment; filename=bar foo=foo "; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attmissingdelim3 val = "attachment filename=bar"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attreversed val = "filename=foo.html; attachment"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attconfusedparam val = "attachment; xfilename=foo.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)0, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attabspath val = "attachment; filename=\"/foo.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)9, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("/foo.html"), std::string(&dest[0], &dest[9])); // attabspathwin val = "attachment; filename=\"\\\\foo.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)9, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("\\foo.html"), std::string(&dest[0], &dest[9])); // attcdate val = "attachment; creation-date=\"Wed, 12 Feb 1997 16:29:51 -0500\""; CPPUNIT_ASSERT_EQUAL((ssize_t)0, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // dispext val = "foobar"; CPPUNIT_ASSERT_EQUAL((ssize_t)0, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // dispextbadfn val = "attachment; example=\"filename=example.txt\""; CPPUNIT_ASSERT_EQUAL((ssize_t)0, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithisofn2231iso val = "attachment; filename*=iso-8859-1''foo-%E4.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)10, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("iso-8859-1"), std::string(cs, cslen)); CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), util::iso8859p1ToUtf8(std::string(&dest[0], &dest[10]))); // attwithfn2231utf8 val = "attachment; filename*=UTF-8''foo-%c3%a4-%e2%82%ac.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)15, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("UTF-8"), std::string(cs, cslen)); CPPUNIT_ASSERT_EQUAL(std::string("foo-ä-€.html"), std::string(&dest[0], &dest[15])); // attwithfn2231noc val = "attachment; filename*=''foo-%c3%a4-%e2%82%ac.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithfn2231utf8comp val = "attachment; filename*=UTF-8''foo-a%cc%88.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)12, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); val = "foo-a%cc%88.html"; CPPUNIT_ASSERT_EQUAL(std::string(util::percentDecode(val.begin(), val.end())), std::string(&dest[0], &dest[12])); // attwithfn2231utf8-bad val = "attachment; filename*=iso-8859-1''foo-%c3%a4-%e2%82%ac.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithfn2231iso-bad val = "attachment; filename*=utf-8''foo-%E4.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithfn2231ws1 val = "attachment; filename *=UTF-8''foo-%c3%a4.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithfn2231ws2 val = "attachment; filename*= UTF-8''foo-%c3%a4.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)11, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), std::string(&dest[0], &dest[11])); // attwithfn2231ws3 val = "attachment; filename* =UTF-8''foo-%c3%a4.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)11, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), std::string(&dest[0], &dest[11])); // attwithfn2231quot val = "attachment; filename*=\"UTF-8''foo-%c3%a4.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithfn2231quot2 val = "attachment; filename*=\"foo%20bar.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithfn2231singleqmissing val = "attachment; filename*=UTF-8'foo-%c3%a4.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithfn2231nbadpct1 val = "attachment; filename*=UTF-8''foo%"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithfn2231nbadpct2 val = "attachment; filename*=UTF-8''f%oo.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attwithfn2231dpct val = "attachment; filename*=UTF-8''A-%2541.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)10, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("A-%41.html"), std::string(&dest[0], &dest[10])); // attwithfn2231abspathdisguised val = "attachment; filename*=UTF-8''%5cfoo.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)9, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("\\foo.html"), std::string(&dest[0], &dest[9])); // attfnboth val = "attachment; filename=\"foo-ae.html\"; filename*=UTF-8''foo-%c3%a4.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)11, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), std::string(&dest[0], &dest[11])); // attfnboth2 val = "attachment; filename*=UTF-8''foo-%c3%a4.html; filename=\"foo-ae.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)11, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), std::string(&dest[0], &dest[11])); // attfnboth3 val = "attachment; filename*0*=ISO-8859-15''euro-sign%3d%a4; " "filename*=ISO-8859-1''currency-sign%3d%a4"; CPPUNIT_ASSERT_EQUAL((ssize_t)15, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("ISO-8859-1"), std::string(cs, cslen)); CPPUNIT_ASSERT_EQUAL(std::string("currency-sign=¤"), util::iso8859p1ToUtf8(std::string(&dest[0], &dest[15]))); // attnewandfn val = "attachment; foobar=x; filename=\"foo.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); // attrfc2047token val = "attachment; filename==?ISO-8859-1?Q?foo-=E4.html?="; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // attrfc2047quoted val = "attachment; filename=\"=?ISO-8859-1?Q?foo-=E4.html?=\""; CPPUNIT_ASSERT_EQUAL((ssize_t)29, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("=?ISO-8859-1?Q?foo-=E4.html?="), std::string(&dest[0], &dest[29])); // aria2 original testcases // zero-length filename. token cannot be empty, so this is invalid. val = "attachment; filename="; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // zero-length filename. quoted-string can be empty string, so this // is ok. val = "attachment; filename=\"\""; CPPUNIT_ASSERT_EQUAL((ssize_t)0, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // empty value is not allowed val = "attachment; filename=;"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // / is not valid char in token. val = "attachment; filename=dir/file"; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); // value-chars is *(pct-encoded / attr-char), so empty string is // allowed. val = "attachment; filename*=UTF-8''"; CPPUNIT_ASSERT_EQUAL((ssize_t)0, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("UTF-8"), std::string(cs, cslen)); val = "attachment; filename*=UTF-8''; filename=foo"; CPPUNIT_ASSERT_EQUAL((ssize_t)0, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("UTF-8"), std::string(cs, cslen)); val = "attachment; filename*=UTF-8'' ; filename=foo"; CPPUNIT_ASSERT_EQUAL((ssize_t)0, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("UTF-8"), std::string(cs, cslen)); // with language val = "attachment; filename*=UTF-8'japanese'konnichiwa"; CPPUNIT_ASSERT_EQUAL((ssize_t)10, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("konnichiwa"), std::string(&dest[0], &dest[10])); // lws before and after "=" val = "attachment; filename = foo.html"; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); // lws before and after "=" with quoted-string val = "attachment; filename = \"foo.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); // lws after parm val = "attachment; filename=foo.html "; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); val = "attachment; filename=foo.html ; hello=world"; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); val = "attachment; filename=\"foo.html\" "; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); val = "attachment; filename=\"foo.html\" ; hello=world"; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); val = "attachment; filename*=UTF-8''foo.html ; hello=world"; CPPUNIT_ASSERT_EQUAL((ssize_t)8, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), false)); CPPUNIT_ASSERT_EQUAL(std::string("foo.html"), std::string(&dest[0], &dest[8])); // allow utf8 if content-disposition-default-utf8 is set val = "attachment; filename=\"foo-ä.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)11, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), true)); CPPUNIT_ASSERT_EQUAL(std::string("foo-ä.html"), std::string(&dest[0], &dest[11])); // incomplete utf8 sequence must be rejected val = "attachment; filename=\"foo-\xc3.html\""; CPPUNIT_ASSERT_EQUAL((ssize_t)-1, util::parse_content_disposition( dest, destlen, &cs, &cslen, val.c_str(), val.size(), true)); } } // namespace aria2
61,368
C++
.cc
1,268
38.271293
80
0.561181
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
772
HttpRequestTest.cc
aria2_aria2/test/HttpRequestTest.cc
#include "HttpRequest.h" #include <sstream> #include <cppunit/extensions/HelperMacros.h> #include "prefs.h" #include "AuthConfigFactory.h" #include "PiecedSegment.h" #include "Piece.h" #include "Range.h" #include "Request.h" #include "Option.h" #include "array_fun.h" #include "CookieStorage.h" #include "util.h" #include "AuthConfig.h" #include "TestUtil.h" #include "MessageDigest.h" namespace aria2 { class HttpRequestTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(HttpRequestTest); CPPUNIT_TEST(testGetStartByte); CPPUNIT_TEST(testGetEndByte); CPPUNIT_TEST(testCreateRequest); CPPUNIT_TEST(testCreateRequest_ftp); CPPUNIT_TEST(testCreateRequest_with_cookie); CPPUNIT_TEST(testCreateRequest_query); CPPUNIT_TEST(testCreateRequest_head); CPPUNIT_TEST(testCreateRequest_ipv6LiteralAddr); CPPUNIT_TEST(testCreateRequest_endOffsetOverride); CPPUNIT_TEST(testCreateRequest_wantDigest); CPPUNIT_TEST(testCreateProxyRequest); CPPUNIT_TEST(testIsRangeSatisfied); CPPUNIT_TEST(testUserAgent); CPPUNIT_TEST(testAddHeader); CPPUNIT_TEST(testAcceptMetalink); CPPUNIT_TEST(testEnableAcceptEncoding); CPPUNIT_TEST(testConditionalRequest); CPPUNIT_TEST_SUITE_END(); private: std::unique_ptr<Option> option_; std::unique_ptr<AuthConfigFactory> authConfigFactory_; public: void setUp() { option_.reset(new Option()); option_->put(PREF_HTTP_AUTH_CHALLENGE, A2_V_TRUE); authConfigFactory_.reset(new AuthConfigFactory()); } void testGetStartByte(); void testGetEndByte(); void testCreateRequest(); void testCreateRequest_ftp(); void testCreateRequest_with_cookie(); void testCreateRequest_query(); void testCreateRequest_head(); void testCreateRequest_ipv6LiteralAddr(); void testCreateRequest_endOffsetOverride(); void testCreateRequest_wantDigest(); void testCreateProxyRequest(); void testIsRangeSatisfied(); void testUserAgent(); void testAddHeader(); void testAcceptMetalink(); void testEnableAcceptEncoding(); void testConditionalRequest(); }; CPPUNIT_TEST_SUITE_REGISTRATION(HttpRequestTest); void HttpRequestTest::testGetStartByte() { HttpRequest httpRequest; auto p = std::make_shared<Piece>(1, 1_k); auto segment = std::make_shared<PiecedSegment>(1_k, p); auto fileEntry = std::make_shared<FileEntry>("file", 10_k, 0); CPPUNIT_ASSERT_EQUAL((int64_t)0LL, httpRequest.getStartByte()); httpRequest.setSegment(segment); httpRequest.setFileEntry(fileEntry); CPPUNIT_ASSERT_EQUAL((int64_t)1_k, httpRequest.getStartByte()); } void HttpRequestTest::testGetEndByte() { size_t index = 1; size_t length = 1_m - 1_k; size_t segmentLength = 1_m; HttpRequest httpRequest; auto piece = std::make_shared<Piece>(index, length); auto segment = std::make_shared<PiecedSegment>(segmentLength, piece); auto fileEntry = std::make_shared<FileEntry>("file", segmentLength * 10, 0); CPPUNIT_ASSERT_EQUAL((int64_t)0LL, httpRequest.getEndByte()); httpRequest.setSegment(segment); CPPUNIT_ASSERT_EQUAL((int64_t)0LL, httpRequest.getEndByte()); auto request = std::make_shared<Request>(); request->supportsPersistentConnection(true); request->setPipeliningHint(true); httpRequest.setRequest(request); httpRequest.setFileEntry(fileEntry); CPPUNIT_ASSERT_EQUAL((int64_t)(segmentLength * index + length - 1), httpRequest.getEndByte()); // The end byte of FileEntry are placed inside segment fileEntry->setLength(segmentLength + 100); CPPUNIT_ASSERT_EQUAL((int64_t)(segmentLength * index + 100 - 1), httpRequest.getEndByte()); request->setPipeliningHint(false); CPPUNIT_ASSERT_EQUAL((int64_t)0LL, httpRequest.getEndByte()); } void HttpRequestTest::testCreateRequest() { auto request = std::make_shared<Request>(); request->supportsPersistentConnection(true); request->setUri("http://localhost:8080/archives/aria2-1.0.0.tar.bz2"); auto p = std::make_shared<Piece>(0, 1_k); auto segment = std::make_shared<PiecedSegment>(1_k, p); auto fileEntry = std::make_shared<FileEntry>("file", 10_m, 0); HttpRequest httpRequest; httpRequest.disableContentEncoding(); httpRequest.setRequest(request); httpRequest.setSegment(segment); httpRequest.setFileEntry(fileEntry); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); httpRequest.setNoWantDigest(true); // remove "Connection: close" and add end byte range request->setPipeliningHint(true); std::string expectedText = "GET /archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Range: bytes=0-1023\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); request->setPipeliningHint(false); expectedText = "GET /archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); p.reset(new Piece(1, 1_m)); segment.reset(new PiecedSegment(1_m, p)); httpRequest.setSegment(segment); expectedText = "GET /archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Range: bytes=1048576-\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); request->setPipeliningHint(true); expectedText = "GET /archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Range: bytes=1048576-2097151\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); // redirection set persistent connection flag to true request->redirectUri( "http://localhost:8080/archives/download/aria2-1.0.0.tar.bz2"); expectedText = "GET /archives/download/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Range: bytes=1048576-2097151\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); request->supportsPersistentConnection(true); request->setPipeliningHint(false); // this only removes "Connection: close". request->setKeepAliveHint(true); expectedText = "GET /archives/download/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Range: bytes=1048576-\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); request->setKeepAliveHint(false); request->resetUri(); p.reset(new Piece(0, 1_m)); segment.reset(new PiecedSegment(1_m, p)); httpRequest.setSegment(segment); // enable http auth option_->put(PREF_HTTP_USER, "aria2user"); option_->put(PREF_HTTP_PASSWD, "aria2passwd"); CPPUNIT_ASSERT(authConfigFactory_->activateBasicCred("localhost", 8080, "/", option_.get())); expectedText = "GET /archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Authorization: Basic YXJpYTJ1c2VyOmFyaWEycGFzc3dk\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); // enable http proxy auth auto proxyRequest = std::make_shared<Request>(); CPPUNIT_ASSERT(proxyRequest->setUri( "http://aria2proxyuser:aria2proxypasswd@localhost:9000")); httpRequest.setProxyRequest(proxyRequest); expectedText = "GET http://localhost:8080/archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Proxy-Authorization: Basic " "YXJpYTJwcm94eXVzZXI6YXJpYTJwcm94eXBhc3N3ZA==\r\n" "Authorization: Basic YXJpYTJ1c2VyOmFyaWEycGFzc3dk\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); request->setPipeliningHint(true); expectedText = "GET http://localhost:8080/archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Range: bytes=0-1048575\r\n" "Connection: Keep-Alive\r\n" "Proxy-Authorization: Basic " "YXJpYTJwcm94eXVzZXI6YXJpYTJwcm94eXBhc3N3ZA==\r\n" "Authorization: Basic YXJpYTJ1c2VyOmFyaWEycGFzc3dk\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); request->setPipeliningHint(false); // turn off proxy auth CPPUNIT_ASSERT(proxyRequest->setUri("http://localhost:9000")); expectedText = "GET http://localhost:8080/archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Authorization: Basic YXJpYTJ1c2VyOmFyaWEycGFzc3dk\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); } void HttpRequestTest::testCreateRequest_ftp() { option_->put(PREF_FTP_USER, "aria2user"); option_->put(PREF_FTP_PASSWD, "aria2passwd"); auto request = std::make_shared<Request>(); request->setUri("ftp://localhost:8080/archives/aria2-1.0.0.tar.bz2"); auto proxyRequest = std::make_shared<Request>(); CPPUNIT_ASSERT(proxyRequest->setUri("http://localhost:9000")); HttpRequest httpRequest; auto p = std::make_shared<Piece>(0, 1_m); auto segment = std::make_shared<PiecedSegment>(1_m, p); auto fileEntry = std::make_shared<FileEntry>("file", 10_m, 0); httpRequest.disableContentEncoding(); httpRequest.setRequest(request); httpRequest.setSegment(segment); httpRequest.setFileEntry(fileEntry); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); httpRequest.setProxyRequest(proxyRequest); httpRequest.setNoWantDigest(true); std::string expectedText = "GET ftp://aria2user@localhost:8080/archives/aria2-1.0.0.tar.bz2" " HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Authorization: Basic YXJpYTJ1c2VyOmFyaWEycGFzc3dk\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); // test proxy authorization CPPUNIT_ASSERT(proxyRequest->setUri( "http://aria2proxyuser:aria2proxypasswd@localhost:9000")); expectedText = "GET ftp://aria2user@localhost:8080/archives/aria2-1.0.0.tar.bz2" " HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Proxy-Authorization: Basic " "YXJpYTJwcm94eXVzZXI6YXJpYTJwcm94eXBhc3N3ZA==\r\n" "Authorization: Basic YXJpYTJ1c2VyOmFyaWEycGFzc3dk\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); } template <typename InputIterator> void foo(CookieStorage& st, InputIterator first, InputIterator last, time_t t) { for (; first != last; ++first) { st.store(*first, t); } } void HttpRequestTest::testCreateRequest_with_cookie() { auto request = std::make_shared<Request>(); request->setUri("http://localhost/archives/aria2-1.0.0.tar.bz2"); auto p = std::make_shared<Piece>(0, 1_m); auto segment = std::make_shared<PiecedSegment>(1_m, p); auto fileEntry = std::make_shared<FileEntry>("file", 10_m, 0); auto st = CookieStorage{}; CPPUNIT_ASSERT(st.store( createCookie("name1", "value1", "localhost", true, "/archives", false), 0)); CPPUNIT_ASSERT(st.store(createCookie("name2", "value2", "localhost", true, "/archives/download", false), 0)); CPPUNIT_ASSERT(st.store(createCookie("name3", "value3", "aria2.org", false, "/archives/download", false), 0)); CPPUNIT_ASSERT(st.store( createCookie("name4", "value4", "aria2.org", false, "/archives/", true), 0)); CPPUNIT_ASSERT(st.store( createCookie("name5", "value5", "example.org", false, "/", false), 0)); HttpRequest httpRequest; httpRequest.disableContentEncoding(); httpRequest.setRequest(request); httpRequest.setSegment(segment); httpRequest.setFileEntry(fileEntry); httpRequest.setCookieStorage(&st); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); httpRequest.setNoWantDigest(true); std::string expectedText = "GET /archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Cookie: name1=value1;\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); request->setUri("http://localhost/archives/download/aria2-1.0.0.tar.bz2"); expectedText = "GET /archives/download/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Cookie: name2=value2;name1=value1;\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); request->setUri("http://www.aria2.org/archives/download/aria2-1.0.0.tar.bz2"); expectedText = "GET /archives/download/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: www.aria2.org\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Cookie: name3=value3;\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); request->setUri("https://www.aria2.org/archives/download/" "aria2-1.0.0.tar.bz2"); expectedText = "GET /archives/download/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: www.aria2.org\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Cookie: name3=value3;name4=value4;\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); // The path of cookie4 ends with '/' request->setUri("https://www.aria2.org/archives/aria2-1.0.0.tar.bz2"); expectedText = "GET /archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: www.aria2.org\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Cookie: name4=value4;\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); request->setUri("http://example.org/aria2-1.0.0.tar.bz2"); expectedText = "GET /aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: example.org\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Cookie: name5=value5;\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); } void HttpRequestTest::testCreateRequest_query() { auto request = std::make_shared<Request>(); request->setUri( "http://localhost/wiki?id=9ad5109a-b8a5-4edf-9373-56a1c34ae138"); HttpRequest httpRequest; httpRequest.disableContentEncoding(); httpRequest.setRequest(request); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); httpRequest.setNoWantDigest(true); std::string expectedText = "GET /wiki?id=9ad5109a-b8a5-4edf-9373-56a1c34ae138 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); } void HttpRequestTest::testCreateRequest_head() { auto request = std::make_shared<Request>(); request->setMethod(Request::METHOD_HEAD); request->setUri("http://localhost/aria2-1.0.0.tar.bz2"); HttpRequest httpRequest; httpRequest.setRequest(request); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); std::stringstream result(httpRequest.createRequest()); std::string line; CPPUNIT_ASSERT(getline(result, line)); line = util::strip(line); CPPUNIT_ASSERT_EQUAL(std::string("HEAD /aria2-1.0.0.tar.bz2 HTTP/1.1"), line); } void HttpRequestTest::testCreateRequest_endOffsetOverride() { auto request = std::make_shared<Request>(); request->setUri("http://localhost/myfile"); HttpRequest httpRequest; httpRequest.disableContentEncoding(); httpRequest.setRequest(request); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); httpRequest.setNoWantDigest(true); auto p = std::make_shared<Piece>(0, 1_m); auto segment = std::make_shared<PiecedSegment>(1_m, p); httpRequest.setSegment(segment); httpRequest.setEndOffsetOverride(1_g); auto fileEntry = std::make_shared<FileEntry>("file", 10_g, 0); httpRequest.setFileEntry(fileEntry); // End byte is passed if it is not 0 std::string expectedText = "GET /myfile HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Range: bytes=0-1073741823\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); segment->updateWrittenLength(1); expectedText = "GET /myfile HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Range: bytes=1-1073741823\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); } void HttpRequestTest::testCreateRequest_wantDigest() { auto request = std::make_shared<Request>(); request->setUri("http://localhost/"); HttpRequest httpRequest; httpRequest.setRequest(request); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); std::string wantDigest; if (MessageDigest::supports("sha-512")) { wantDigest += "SHA-512;q=1, "; } if (MessageDigest::supports("sha-256")) { wantDigest += "SHA-256;q=1, "; } if (MessageDigest::supports("sha-1")) { wantDigest += "SHA;q=0.1, "; } if (!wantDigest.empty()) { wantDigest.erase(wantDigest.size() - 2); } std::string expectedText = "GET / HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n" "Host: localhost\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Want-Digest: " + wantDigest + "\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); } void HttpRequestTest::testCreateProxyRequest() { auto request = std::make_shared<Request>(); request->setUri("http://localhost/archives/aria2-1.0.0.tar.bz2"); auto p = std::make_shared<Piece>(0, 1_m); auto segment = std::make_shared<PiecedSegment>(1_m, p); auto proxyRequest = std::make_shared<Request>(); CPPUNIT_ASSERT(proxyRequest->setUri("http://localhost:9000")); HttpRequest httpRequest; httpRequest.setRequest(request); httpRequest.setSegment(segment); httpRequest.setProxyRequest(proxyRequest); request->supportsPersistentConnection(true); std::string expectedText = "CONNECT localhost:80 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Host: localhost:80\r\n" //"Proxy-Connection: close\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createProxyRequest()); // adds Keep-Alive header. request->setKeepAliveHint(true); expectedText = "CONNECT localhost:80 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Host: localhost:80\r\n" //"Proxy-Connection: Keep-Alive\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createProxyRequest()); request->setKeepAliveHint(false); // pipelining also adds Keep-Alive header. request->setPipeliningHint(true); expectedText = "CONNECT localhost:80 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Host: localhost:80\r\n" //"Proxy-Connection: Keep-Alive\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createProxyRequest()); // test proxy authorization CPPUNIT_ASSERT(proxyRequest->setUri( "http://aria2proxyuser:aria2proxypasswd@localhost:9000")); expectedText = "CONNECT localhost:80 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Host: localhost:80\r\n" //"Proxy-Connection: Keep-Alive\r\n" "Proxy-Authorization: Basic " "YXJpYTJwcm94eXVzZXI6YXJpYTJwcm94eXBhc3N3ZA==\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createProxyRequest()); } void HttpRequestTest::testIsRangeSatisfied() { auto request = std::make_shared<Request>(); request->supportsPersistentConnection(true); request->setUri("http://localhost:8080/archives/aria2-1.0.0.tar.bz2"); request->setPipeliningHint(false); // default: false auto p = std::make_shared<Piece>(0, 1_m); auto segment = std::make_shared<PiecedSegment>(1_m, p); auto fileEntry = std::make_shared<FileEntry>("file", 0, 0); HttpRequest httpRequest; httpRequest.setRequest(request); httpRequest.setSegment(segment); httpRequest.setFileEntry(fileEntry); Range range; CPPUNIT_ASSERT(httpRequest.isRangeSatisfied(range)); p.reset(new Piece(1, 1_m)); segment.reset(new PiecedSegment(1_m, p)); httpRequest.setSegment(segment); CPPUNIT_ASSERT(!httpRequest.isRangeSatisfied(range)); uint64_t entityLength = segment->getSegmentLength() * 10; range = Range(segment->getPosition(), 0, entityLength); CPPUNIT_ASSERT(httpRequest.isRangeSatisfied(range)); fileEntry->setLength(entityLength - 1); CPPUNIT_ASSERT(!httpRequest.isRangeSatisfied(range)); fileEntry->setLength(entityLength); CPPUNIT_ASSERT(httpRequest.isRangeSatisfied(range)); request->setPipeliningHint(true); CPPUNIT_ASSERT(!httpRequest.isRangeSatisfied(range)); range = Range(segment->getPosition(), segment->getPosition() + segment->getLength() - 1, entityLength); CPPUNIT_ASSERT(httpRequest.isRangeSatisfied(range)); range = Range(segment->getPosition(), segment->getPosition() + segment->getLength() - 1, 0); CPPUNIT_ASSERT(!httpRequest.isRangeSatisfied(range)); range = Range(0, segment->getPosition() + segment->getLength() - 1, entityLength); CPPUNIT_ASSERT(!httpRequest.isRangeSatisfied(range)); } void HttpRequestTest::testUserAgent() { auto request = std::make_shared<Request>(); request->setUri("http://localhost:8080/archives/aria2-1.0.0.tar.bz2"); // std::shared_ptr<Piece> p(new Piece(0, 1_k)); // std::shared_ptr<Segment> segment(new PiecedSegment(1_k, p)); HttpRequest httpRequest; httpRequest.disableContentEncoding(); httpRequest.setRequest(request); // httpRequest.setSegment(segment); httpRequest.setUserAgent("aria2 (Linux)"); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); httpRequest.setNoWantDigest(true); std::string expectedText = "GET /archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2 (Linux)\r\n" "Accept: */*\r\n" "Host: localhost:8080\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); auto proxyRequest = std::make_shared<Request>(); CPPUNIT_ASSERT(proxyRequest->setUri("http://localhost:9000")); httpRequest.setProxyRequest(proxyRequest); std::string expectedTextForProxy = "CONNECT localhost:8080 HTTP/1.1\r\n" "User-Agent: aria2 (Linux)\r\n" "Host: localhost:8080\r\n" //"Proxy-Connection: close\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedTextForProxy, httpRequest.createProxyRequest()); } void HttpRequestTest::testAddHeader() { auto request = std::make_shared<Request>(); request->setUri("http://localhost/archives/aria2-1.0.0.tar.bz2"); HttpRequest httpRequest; httpRequest.disableContentEncoding(); httpRequest.setRequest(request); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); httpRequest.addHeader("X-ARIA2: v0.13\nX-ARIA2-DISTRIBUTE: enabled\n"); httpRequest.addHeader("Accept: text/html"); httpRequest.setNoWantDigest(true); std::string expectedText = "GET /archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Host: localhost\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "X-ARIA2: v0.13\r\n" "X-ARIA2-DISTRIBUTE: enabled\r\n" "Accept: text/html\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); } void HttpRequestTest::testAcceptMetalink() { auto request = std::make_shared<Request>(); request->setUri("http://localhost/archives/aria2-1.0.0.tar.bz2"); HttpRequest httpRequest; httpRequest.disableContentEncoding(); httpRequest.setRequest(request); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); httpRequest.setAcceptMetalink(true); httpRequest.setNoWantDigest(true); std::string expectedText = "GET /archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*,application/metalink4+xml,application/metalink+xml\r\n" "Host: localhost\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "\r\n"; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); } void HttpRequestTest::testEnableAcceptEncoding() { auto request = std::make_shared<Request>(); request->setUri("http://localhost/archives/aria2-1.0.0.tar.bz2"); HttpRequest httpRequest; httpRequest.setRequest(request); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); httpRequest.setNoWantDigest(true); std::string acceptEncodings; #ifdef HAVE_ZLIB acceptEncodings += "deflate, gzip"; #endif // HAVE_ZLIB std::string expectedTextHead = "GET /archives/aria2-1.0.0.tar.bz2 HTTP/1.1\r\n" "User-Agent: aria2\r\n" "Accept: */*\r\n"; std::string expectedTextTail = "Host: localhost\r\n" "Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "\r\n"; std::string expectedText = expectedTextHead; expectedText += expectedTextTail; CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); expectedText = expectedTextHead; if (!acceptEncodings.empty()) { expectedText += "Accept-Encoding: "; expectedText += acceptEncodings; expectedText += "\r\n"; } expectedText += expectedTextTail; httpRequest.enableAcceptGZip(); CPPUNIT_ASSERT_EQUAL(expectedText, httpRequest.createRequest()); } void HttpRequestTest::testCreateRequest_ipv6LiteralAddr() { auto request = std::make_shared<Request>(); request->setUri("http://[::1]/path"); HttpRequest httpRequest; httpRequest.disableContentEncoding(); httpRequest.setRequest(request); httpRequest.setAuthConfigFactory(authConfigFactory_.get()); httpRequest.setOption(option_.get()); CPPUNIT_ASSERT(httpRequest.createRequest().find("Host: [::1]") != std::string::npos); auto proxy = std::make_shared<Request>(); proxy->setUri("http://proxy"); httpRequest.setProxyRequest(proxy); std::string proxyRequest = httpRequest.createProxyRequest(); CPPUNIT_ASSERT(proxyRequest.find("Host: [::1]:80") != std::string::npos); CPPUNIT_ASSERT(proxyRequest.find("CONNECT [::1]:80 ") != std::string::npos); } void HttpRequestTest::testConditionalRequest() { HttpRequest httpRequest; CPPUNIT_ASSERT(!httpRequest.conditionalRequest()); httpRequest.setIfModifiedSinceHeader("dummy"); CPPUNIT_ASSERT(httpRequest.conditionalRequest()); httpRequest.setIfModifiedSinceHeader(""); CPPUNIT_ASSERT(!httpRequest.conditionalRequest()); httpRequest.addHeader("If-None-Match: *"); CPPUNIT_ASSERT(httpRequest.conditionalRequest()); httpRequest.clearHeader(); httpRequest.addHeader("If-Modified-Since: dummy"); CPPUNIT_ASSERT(httpRequest.conditionalRequest()); } } // namespace aria2
32,113
C++
.cc
756
34.271164
80
0.642623
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
779
SimpleRandomizerTest.cc
aria2_aria2/test/SimpleRandomizerTest.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2022 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "SimpleRandomizer.h" #include <set> #include <array> #include <cppunit/extensions/HelperMacros.h> namespace aria2 { class SimpleRandomizerTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SimpleRandomizerTest); CPPUNIT_TEST(testGetRandomBytes); CPPUNIT_TEST_SUITE_END(); public: void testGetRandomBytes(); }; CPPUNIT_TEST_SUITE_REGISTRATION(SimpleRandomizerTest); void SimpleRandomizerTest::testGetRandomBytes() { std::set<std::string> set; constexpr size_t n = 5000; for (size_t i = 0; i < 5000; ++i) { std::array<unsigned char, 257> buf; SimpleRandomizer::getInstance()->getRandomBytes(buf.data(), buf.size()); set.emplace(std::begin(buf), std::end(buf)); } CPPUNIT_ASSERT_EQUAL(n, set.size()); } } // namespace aria2
2,372
C++
.cc
59
37.983051
79
0.755864
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
794
TimeTest.cc
aria2_aria2/test/TimeTest.cc
#include "TimeA2.h" #include <iostream> #include <cppunit/extensions/HelperMacros.h> #include "Exception.h" #include "util.h" namespace aria2 { class TimeTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TimeTest); CPPUNIT_TEST(testParseRFC1123); CPPUNIT_TEST(testParseRFC850); CPPUNIT_TEST(testParseRFC850Ext); CPPUNIT_TEST(testParseAsctime); CPPUNIT_TEST(testParseHTTPDate); CPPUNIT_TEST(testOperatorLess); CPPUNIT_TEST(testToHTTPDate); CPPUNIT_TEST_SUITE_END(); public: void setUp() {} void tearDown() {} void testParseRFC1123(); void testParseRFC1123Alt(); void testParseRFC850(); void testParseRFC850Ext(); void testParseAsctime(); void testParseHTTPDate(); void testOperatorLess(); void testToHTTPDate(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TimeTest); void TimeTest::testParseRFC1123() { Time t1 = Time::parseRFC1123("Sat, 06 Sep 2008 15:26:33 GMT"); CPPUNIT_ASSERT_EQUAL((time_t)1220714793, t1.getTimeFromEpoch()); } void TimeTest::testParseRFC1123Alt() { Time t1 = Time::parseRFC1123Alt("Sat, 06 Sep 2008 15:26:33 +0000"); CPPUNIT_ASSERT_EQUAL((time_t)1220714793, t1.getTimeFromEpoch()); } void TimeTest::testParseRFC850() { Time t1 = Time::parseRFC850("Saturday, 06-Sep-08 15:26:33 GMT"); CPPUNIT_ASSERT_EQUAL((time_t)1220714793, t1.getTimeFromEpoch()); } void TimeTest::testParseRFC850Ext() { Time t1 = Time::parseRFC850Ext("Saturday, 06-Sep-2008 15:26:33 GMT"); CPPUNIT_ASSERT_EQUAL((time_t)1220714793, t1.getTimeFromEpoch()); } void TimeTest::testParseAsctime() { Time t1 = Time::parseAsctime("Sun Sep 6 15:26:33 2008"); CPPUNIT_ASSERT_EQUAL((time_t)1220714793, t1.getTimeFromEpoch()); } void TimeTest::testParseHTTPDate() { CPPUNIT_ASSERT_EQUAL( (time_t)1220714793, Time::parseHTTPDate("Sat, 06 Sep 2008 15:26:33 GMT").getTimeFromEpoch()); CPPUNIT_ASSERT_EQUAL( (time_t)1220714793, Time::parseHTTPDate("Sat, 06-Sep-2008 15:26:33 GMT").getTimeFromEpoch()); CPPUNIT_ASSERT_EQUAL( (time_t)1220714793, Time::parseHTTPDate("Sat, 06-Sep-08 15:26:33 GMT").getTimeFromEpoch()); CPPUNIT_ASSERT_EQUAL( (time_t)1220714793, Time::parseHTTPDate("Sun Sep 6 15:26:33 2008").getTimeFromEpoch()); CPPUNIT_ASSERT(Time::parseHTTPDate("Sat, 2008-09-06 15:26:33 GMT").bad()); } void TimeTest::testOperatorLess() { CPPUNIT_ASSERT(Time(1) < Time(2)); CPPUNIT_ASSERT(!(Time(1) < Time(1))); CPPUNIT_ASSERT(!(Time(2) < Time(1))); } void TimeTest::testToHTTPDate() { // This test disabled for MinGW32, because the garbage will be // displayed and it hides real errors. #ifndef __MINGW32__ Time t(1220714793); CPPUNIT_ASSERT_EQUAL(std::string("Sat, 06 Sep 2008 15:26:33 GMT"), t.toHTTPDate()); #endif // !__MINGW32__ } } // namespace aria2
2,800
C++
.cc
87
29.252874
79
0.729399
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
800
CookieBoxTest.cc
aria2_aria2/test/CookieBoxTest.cc
#include "CookieBox.h" #include <string> #include <cppunit/extensions/HelperMacros.h> namespace aria2 { class CookieBoxTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(CookieBoxTest); CPPUNIT_TEST(testCriteriaFind); CPPUNIT_TEST_SUITE_END(); private: public: void setUp() {} void testCriteriaFind(); }; CPPUNIT_TEST_SUITE_REGISTRATION(CookieBoxTest); void CookieBoxTest::testCriteriaFind() { // 1181473200 = Sun Jun 10 11:00:00 2007 GMT Cookie c1("SESSIONID1", "1", 1181473200, "/downloads", "rednoah.com", false); Cookie c2("SESSIONID2", "2", 1181473200, "/downloads", "rednoah.com", false); Cookie c3("USER", "user", "/home", "aria.rednoah.com", false); Cookie c4("PASS", "pass", "/downloads", "rednoah.com", true); CookieBox box; box.add(c1); box.add(c2); box.add(c3); box.add(c4); Cookies result1 = box.criteriaFind("rednoah.com", "/downloads", 1181473100, false); CPPUNIT_ASSERT_EQUAL(2, (int)result1.size()); Cookies::iterator itr = result1.begin(); CPPUNIT_ASSERT_EQUAL(std::string("SESSIONID1=1"), (*itr).toString()); itr++; CPPUNIT_ASSERT_EQUAL(std::string("SESSIONID2=2"), (*itr).toString()); result1 = box.criteriaFind("rednoah.com", "/downloads", 1181473100, true); CPPUNIT_ASSERT_EQUAL(3, (int)result1.size()); itr = result1.begin(); CPPUNIT_ASSERT_EQUAL(std::string("SESSIONID1=1"), (*itr).toString()); itr++; CPPUNIT_ASSERT_EQUAL(std::string("SESSIONID2=2"), (*itr).toString()); itr++; CPPUNIT_ASSERT_EQUAL(std::string("PASS=pass"), (*itr).toString()); result1 = box.criteriaFind("aria.rednoah.com", "/", 1181473100, false); CPPUNIT_ASSERT_EQUAL(0, (int)result1.size()); result1 = box.criteriaFind("aria.rednoah.com", "/home", 1181473100, false); CPPUNIT_ASSERT_EQUAL(1, (int)result1.size()); itr = result1.begin(); CPPUNIT_ASSERT_EQUAL(std::string("USER=user"), (*itr).toString()); result1 = box.criteriaFind("rednoah.com", "/downloads", 1181473200, false); CPPUNIT_ASSERT_EQUAL(0, (int)result1.size()); } } // namespace aria2
2,044
C++
.cc
51
37.235294
79
0.70187
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
819
File.cc
aria2_aria2/src/File.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "File.h" #include <stdlib.h> #include <sys/types.h> #ifdef HAVE_UTIME_H # include <utime.h> #endif // HAVE_UTIME_H #include <unistd.h> #include <vector> #include <cstring> #include <cstdio> #include "util.h" #include "A2STR.h" #include "array_fun.h" #include "Logger.h" #include "LogFactory.h" #include "fmt.h" namespace aria2 { File::File(const std::string& name) : name_(name) {} File::File(const File& c) = default; File::~File() = default; File& File::operator=(const File& c) { if (this != &c) { name_ = c.name_; } return *this; } int File::fillStat(a2_struct_stat& fstat) { return a2stat(utf8ToWChar(name_).c_str(), &fstat); } bool File::exists() { a2_struct_stat fstat; return fillStat(fstat) == 0; } bool File::exists(std::string& err) { a2_struct_stat fstat; if (fillStat(fstat) != 0) { err = fmt("Could not get file status: %s", strerror(errno)); return false; } return true; } bool File::isFile() { a2_struct_stat fstat; if (fillStat(fstat) < 0) { return false; } return S_ISREG(fstat.st_mode) == 1; } bool File::isDir() { a2_struct_stat fstat; if (fillStat(fstat) < 0) { return false; } return S_ISDIR(fstat.st_mode) == 1; } bool File::remove() { if (isFile()) { return a2unlink(utf8ToWChar(name_).c_str()) == 0; } else if (isDir()) { return a2rmdir(utf8ToWChar(name_).c_str()) == 0; } else { return false; } } #ifdef __MINGW32__ namespace { HANDLE openFile(const std::string& filename, bool readOnly = true) { DWORD desiredAccess = GENERIC_READ | (readOnly ? 0 : GENERIC_WRITE); DWORD sharedMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; DWORD creationDisp = OPEN_EXISTING; return CreateFileW(utf8ToWChar(filename).c_str(), desiredAccess, sharedMode, /* lpSecurityAttributes */ nullptr, creationDisp, FILE_ATTRIBUTE_NORMAL, /* hTemplateFile */ nullptr); } } // namespace #endif // __MINGW32__ int64_t File::size() { #ifdef __MINGW32__ // _wstat cannot be used for symlink. It always returns 0. Quoted // from https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx: // // _wstat does not work with Windows Vista symbolic links. In // these cases, _wstat will always report a file size of 0. _stat // does work correctly with symbolic links. auto hn = openFile(name_); if (hn == INVALID_HANDLE_VALUE) { return 0; } LARGE_INTEGER fileSize; const auto rv = GetFileSizeEx(hn, &fileSize); CloseHandle(hn); return rv ? fileSize.QuadPart : 0; #else // !__MINGW32__ a2_struct_stat fstat; if (fillStat(fstat) < 0) { return 0; } return fstat.st_size; #endif // !__MINGW32__ } bool File::mkdirs() { if (isDir()) { return false; } #ifdef __MINGW32__ std::string path = name_; for (std::string::iterator i = path.begin(), eoi = path.end(); i != eoi; ++i) { if (*i == '\\') { *i = '/'; } } std::string::iterator dbegin; if (util::startsWith(path, "//")) { // UNC path std::string::size_type hostEnd = path.find('/', 2); if (hostEnd == std::string::npos) { // UNC path with only hostname considered as an error. return false; } else if (hostEnd == 2) { // If path starts with "///", it is not considered as UNC. dbegin = path.begin(); } else { std::string::iterator i = path.begin() + hostEnd; std::string::iterator eoi = path.end(); // //host/mount/dir/... // | | // i (at this point) // | // dbegin (will be) // Skip to after first directory part. This is because // //host/dir appears to be non-directory and mkdir it fails. for (; i != eoi && *i == '/'; ++i) ; for (; i != eoi && *i != '/'; ++i) ; dbegin = i; A2_LOG_DEBUG( fmt("UNC Prefix %s", std::string(path.begin(), dbegin).c_str())); } } else { dbegin = path.begin(); } std::string::iterator begin = path.begin(); std::string::iterator end = path.end(); for (std::string::iterator i = dbegin; i != end;) { #else // !__MINGW32__ std::string::iterator begin = name_.begin(); std::string::iterator end = name_.end(); for (std::string::iterator i = begin; i != end;) { #endif // !__MINGW32__ std::string::iterator j = std::find(i, end, '/'); if (std::distance(i, j) == 0) { ++i; continue; } i = j; if (i != end) { ++i; } #ifdef __MINGW32__ if (*(j - 1) == ':') { // This is a drive letter, e.g. C:, so skip it. continue; } #endif // __MINGW32__ std::string dir(begin, j); A2_LOG_DEBUG(fmt("Making directory %s", dir.c_str())); if (File(dir).isDir()) { A2_LOG_DEBUG(fmt("%s exists and is a directory.", dir.c_str())); continue; } if (a2mkdir(utf8ToWChar(dir).c_str(), DIR_OPEN_MODE) == -1) { A2_LOG_DEBUG(fmt("Failed to create %s", dir.c_str())); return false; } } return true; } // namespace aria2 mode_t File::mode() { a2_struct_stat fstat; if (fillStat(fstat) < 0) { return 0; } return fstat.st_mode; } std::string File::getBasename() const { std::string::size_type lastSlashIndex = name_.find_last_of(getPathSeparators()); if (lastSlashIndex == std::string::npos) { return name_; } else { return name_.substr(lastSlashIndex + 1); } } std::string File::getDirname() const { std::string::size_type lastSlashIndex = name_.find_last_of(getPathSeparators()); if (lastSlashIndex == std::string::npos) { if (name_.empty()) { return A2STR::NIL; } else { return "."; } } else if (lastSlashIndex == 0) { return "/"; } else { return name_.substr(0, lastSlashIndex); } } bool File::isDir(const std::string& filename) { return File(filename).isDir(); } bool File::renameTo(const std::string& dest) { #ifdef __MINGW32__ // MinGW's rename() doesn't delete an existing destination. Better // to use MoveFileEx, which usually provides atomic move in aria2 // usecase. if (MoveFileExW(utf8ToWChar(name_).c_str(), utf8ToWChar(dest).c_str(), MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING)) { name_ = dest; return true; } return false; #else // !__MINGW32__ if (rename(name_.c_str(), dest.c_str()) == 0) { name_ = dest; return true; } else { return false; } #endif // !__MINGW32__ } bool File::utime(const Time& actime, const Time& modtime) const { #if defined(HAVE_UTIMES) && !defined(__MINGW32__) struct timeval times[2] = {{actime.getTimeFromEpoch(), 0}, {modtime.getTimeFromEpoch(), 0}}; return utimes(name_.c_str(), times) == 0; #elif defined(__MINGW32__) auto hn = openFile(name_, false); if (hn == INVALID_HANDLE_VALUE) { auto errNum = GetLastError(); A2_LOG_ERROR(fmt(EX_FILE_OPEN, name_.c_str(), util::formatLastError(errNum).c_str())); return false; } // Use SetFileTime because Windows _wutime takes DST into // consideration. // // std::chrono::time_point::time_since_epoch returns the amount of // time between it and epoch Jan 1, 1970. OTOH, FILETIME structure // expects the epoch as Jan 1, 1601. The resolution is 100 // nanoseconds. constexpr auto offset = 116444736000000000LL; uint64_t at = std::chrono::duration_cast<std::chrono::nanoseconds>( actime.getTime().time_since_epoch()) .count() / 100 + offset; uint64_t mt = std::chrono::duration_cast<std::chrono::nanoseconds>( modtime.getTime().time_since_epoch()) .count() / 100 + offset; FILETIME att{static_cast<DWORD>(at & 0xffffffff), static_cast<DWORD>(at >> 32)}; FILETIME mtt{static_cast<DWORD>(mt & 0xffffffff), static_cast<DWORD>(mt >> 32)}; auto rv = SetFileTime(hn, nullptr, &att, &mtt); if (!rv) { auto errNum = GetLastError(); A2_LOG_ERROR(fmt("SetFileTime failed, cause: %s", util::formatLastError(errNum).c_str())); } CloseHandle(hn); return rv; #else // !defined(HAVE_UTIMES) && !defined(__MINGW32__) a2utimbuf ub; ub.actime = actime.getTimeFromEpoch(); ub.modtime = modtime.getTimeFromEpoch(); return a2utime(utf8ToWChar(name_).c_str(), &ub) == 0; #endif // !defined(HAVE_UTIMES) && !defined(__MINGW32__) } Time File::getModifiedTime() { a2_struct_stat fstat; if (fillStat(fstat) < 0) { return 0; } return Time(fstat.st_mtime); } std::string File::getCurrentDir() { #ifdef __MINGW32__ const size_t buflen = 2048; wchar_t buf[buflen]; if (_wgetcwd(buf, buflen)) { return wCharToUtf8(buf); } else { return "."; } #else // !__MINGW32__ const size_t buflen = 2048; char buf[buflen]; if (getcwd(buf, buflen)) { return std::string(buf); } else { return "."; } #endif // !__MINGW32__ } const char* File::getPathSeparators() { #ifdef __MINGW32__ return "/\\"; #else // !__MINGW32__ return "/"; #endif // !__MINGW32__ } } // namespace aria2
10,809
C++
.cc
379
24.604222
80
0.629783
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
835
AbstractSingleDiskAdaptor.cc
aria2_aria2/src/AbstractSingleDiskAdaptor.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "AbstractSingleDiskAdaptor.h" #include "File.h" #include "AdaptiveFileAllocationIterator.h" #include "DiskWriter.h" #include "FileEntry.h" #include "TruncFileAllocationIterator.h" #include "WrDiskCacheEntry.h" #include "LogFactory.h" #ifdef HAVE_SOME_FALLOCATE # include "FallocFileAllocationIterator.h" #endif // HAVE_SOME_FALLOCATE namespace aria2 { AbstractSingleDiskAdaptor::AbstractSingleDiskAdaptor() : totalLength_(0), readOnly_(false) { } AbstractSingleDiskAdaptor::~AbstractSingleDiskAdaptor() = default; void AbstractSingleDiskAdaptor::initAndOpenFile() { diskWriter_->initAndOpenFile(totalLength_); } void AbstractSingleDiskAdaptor::openFile() { diskWriter_->openFile(totalLength_); } void AbstractSingleDiskAdaptor::closeFile() { diskWriter_->closeFile(); } void AbstractSingleDiskAdaptor::openExistingFile() { diskWriter_->openExistingFile(totalLength_); } void AbstractSingleDiskAdaptor::writeData(const unsigned char* data, size_t len, int64_t offset) { diskWriter_->writeData(data, len, offset); } ssize_t AbstractSingleDiskAdaptor::readData(unsigned char* data, size_t len, int64_t offset) { return diskWriter_->readData(data, len, offset); } ssize_t AbstractSingleDiskAdaptor::readDataDropCache(unsigned char* data, size_t len, int64_t offset) { auto rv = readData(data, len, offset); if (rv > 0) { diskWriter_->dropCache(len, offset); } return rv; } void AbstractSingleDiskAdaptor::writeCache(const WrDiskCacheEntry* entry) { for (auto& d : entry->getDataSet()) { A2_LOG_DEBUG(fmt("Cache flush goff=%" PRId64 ", len=%lu", d->goff, static_cast<unsigned long>(d->len))); writeData(d->data + d->offset, d->len, d->goff); } } void AbstractSingleDiskAdaptor::flushOSBuffers() { diskWriter_->flushOSBuffers(); } bool AbstractSingleDiskAdaptor::fileExists() { return File(getFilePath()).exists(); } int64_t AbstractSingleDiskAdaptor::size() { return File(getFilePath()).size(); } void AbstractSingleDiskAdaptor::truncate(int64_t length) { diskWriter_->truncate(length); } std::unique_ptr<FileAllocationIterator> AbstractSingleDiskAdaptor::fileAllocationIterator() { switch (getFileAllocationMethod()) { #ifdef HAVE_SOME_FALLOCATE case (DiskAdaptor::FILE_ALLOC_FALLOC): return make_unique<FallocFileAllocationIterator>(diskWriter_.get(), size(), totalLength_); #endif // HAVE_SOME_FALLOCATE case (DiskAdaptor::FILE_ALLOC_TRUNC): return make_unique<TruncFileAllocationIterator>(diskWriter_.get(), size(), totalLength_); default: return make_unique<AdaptiveFileAllocationIterator>(diskWriter_.get(), size(), totalLength_); } } void AbstractSingleDiskAdaptor::enableReadOnly() { diskWriter_->enableReadOnly(); readOnly_ = true; } void AbstractSingleDiskAdaptor::disableReadOnly() { diskWriter_->disableReadOnly(); readOnly_ = false; } void AbstractSingleDiskAdaptor::enableMmap() { diskWriter_->enableMmap(); } void AbstractSingleDiskAdaptor::cutTrailingGarbage() { if (File(getFilePath()).size() > totalLength_) { diskWriter_->truncate(totalLength_); } } void AbstractSingleDiskAdaptor::setDiskWriter( std::unique_ptr<DiskWriter> diskWriter) { diskWriter_ = std::move(diskWriter); } void AbstractSingleDiskAdaptor::setTotalLength(int64_t totalLength) { totalLength_ = totalLength; } } // namespace aria2
5,254
C++
.cc
148
31.351351
80
0.725054
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
836
BtSeederStateChoke.cc
aria2_aria2/src/BtSeederStateChoke.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "BtSeederStateChoke.h" #include <algorithm> #include "Peer.h" #include "Logger.h" #include "LogFactory.h" #include "SimpleRandomizer.h" #include "wallclock.h" #include "fmt.h" namespace aria2 { BtSeederStateChoke::BtSeederStateChoke() : round_(0), lastRound_(Timer::zero()) { } BtSeederStateChoke::~BtSeederStateChoke() = default; namespace { constexpr auto TIME_FRAME = 20_s; } // namespace BtSeederStateChoke::PeerEntry::PeerEntry(const std::shared_ptr<Peer>& peer) : peer_(peer), outstandingUpload_(peer->countOutstandingUpload()), lastAmUnchoking_(peer->getLastAmUnchoking()), recentUnchoking_(lastAmUnchoking_.difference(global::wallclock()) < TIME_FRAME), uploadSpeed_(peer->calculateUploadSpeed()) { } BtSeederStateChoke::PeerEntry::PeerEntry(const PeerEntry& c) = default; BtSeederStateChoke::PeerEntry::~PeerEntry() = default; void BtSeederStateChoke::PeerEntry::swap(PeerEntry& c) { using std::swap; swap(peer_, c.peer_); swap(outstandingUpload_, c.outstandingUpload_); swap(lastAmUnchoking_, c.lastAmUnchoking_); swap(recentUnchoking_, c.recentUnchoking_); swap(uploadSpeed_, c.uploadSpeed_); } BtSeederStateChoke::PeerEntry& BtSeederStateChoke::PeerEntry::operator=(const PeerEntry& c) { if (this != &c) { peer_ = c.peer_; outstandingUpload_ = c.outstandingUpload_; lastAmUnchoking_ = c.lastAmUnchoking_; recentUnchoking_ = c.recentUnchoking_; uploadSpeed_ = c.uploadSpeed_; } return *this; } bool BtSeederStateChoke::PeerEntry::operator<(const PeerEntry& rhs) const { if (this->outstandingUpload_ && !rhs.outstandingUpload_) { return true; } else if (!this->outstandingUpload_ && rhs.outstandingUpload_) { return false; } if (this->recentUnchoking_ && (this->lastAmUnchoking_ > rhs.lastAmUnchoking_)) { return true; } else if (rhs.recentUnchoking_) { return false; } else { return this->uploadSpeed_ > rhs.uploadSpeed_; } } void BtSeederStateChoke::PeerEntry::disableOptUnchoking() { peer_->optUnchoking(false); } void BtSeederStateChoke::unchoke( std::vector<BtSeederStateChoke::PeerEntry>& peers) { int count = (round_ == 2) ? 4 : 3; std::sort(std::begin(peers), std::end(peers)); auto r = std::begin(peers); for (; r != std::end(peers) && count; ++r, --count) { auto& peer = (*r).getPeer(); peer->chokingRequired(false); A2_LOG_INFO(fmt("RU: %s:%u, ulspd=%d", peer->getIPAddress().c_str(), peer->getPort(), (*r).getUploadSpeed())); } if (round_ < 2) { std::for_each(std::begin(peers), std::end(peers), std::mem_fn(&PeerEntry::disableOptUnchoking)); if (r != std::end(peers)) { std::shuffle(r, std::end(peers), *SimpleRandomizer::getInstance()); auto& peer = (*r).getPeer(); peer->optUnchoking(true); A2_LOG_INFO( fmt("POU: %s:%u", peer->getIPAddress().c_str(), peer->getPort())); } } } void BtSeederStateChoke::executeChoke(const PeerSet& peerSet) { A2_LOG_INFO(fmt("Seeder state, %d choke round started", round_)); lastRound_ = global::wallclock(); std::vector<PeerEntry> peerEntries; for (const auto& p : peerSet) { if (!p->isActive()) { continue; } p->chokingRequired(true); if (p->peerInterested()) { peerEntries.push_back(PeerEntry(p)); continue; } p->optUnchoking(false); } unchoke(peerEntries); if (++round_ == 3) { round_ = 0; } } void swap(BtSeederStateChoke::PeerEntry& a, BtSeederStateChoke::PeerEntry& b) { a.swap(b); } } // namespace aria2
5,219
C++
.cc
155
30.245161
79
0.703615
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
837
BtChokeMessage.cc
aria2_aria2/src/BtChokeMessage.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "BtChokeMessage.h" #include "Peer.h" #include "BtMessageDispatcher.h" #include "BtRequestFactory.h" #include "SocketBuffer.h" namespace aria2 { const char BtChokeMessage::NAME[] = "choke"; BtChokeMessage::BtChokeMessage() : ZeroBtMessage{ID, NAME} {} std::unique_ptr<BtChokeMessage> BtChokeMessage::create(const unsigned char* data, size_t dataLength) { return ZeroBtMessage::create<BtChokeMessage>(data, dataLength); } void BtChokeMessage::doReceivedAction() { if (isMetadataGetMode()) { return; } getPeer()->peerChoking(true); getBtMessageDispatcher()->doChokedAction(); getBtRequestFactory()->doChokedAction(); } } // namespace aria2
2,264
C++
.cc
57
37.789474
79
0.765561
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
838
RequestSlot.cc
aria2_aria2/src/RequestSlot.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "RequestSlot.h" namespace aria2 { bool RequestSlot::isTimeout(const std::chrono::seconds& t) const { return dispatchedTime_.difference(global::wallclock()) >= t; } } // namespace aria2
1,795
C++
.cc
41
41.902439
79
0.760708
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
839
SimpleRandomizer.cc
aria2_aria2/src/SimpleRandomizer.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "SimpleRandomizer.h" #include <sys/types.h> #include <unistd.h> #include <cstdlib> #include <cassert> #include <cstring> #include <iostream> #ifdef __APPLE__ # include <Security/SecRandom.h> #endif // __APPLE__ #ifdef HAVE_LIBGNUTLS # include <gnutls/crypto.h> #endif // HAVE_LIBGNUTLS #ifdef HAVE_OPENSSL # include <openssl/rand.h> #endif // HAVE_OPENSSL #include "a2time.h" #include "a2functional.h" #include "LogFactory.h" #include "fmt.h" namespace aria2 { std::unique_ptr<SimpleRandomizer> SimpleRandomizer::randomizer_; const std::unique_ptr<SimpleRandomizer>& SimpleRandomizer::getInstance() { if (!randomizer_) { randomizer_.reset(new SimpleRandomizer()); } return randomizer_; } namespace { std::random_device rd; } // namespace #ifdef __MINGW32__ SimpleRandomizer::SimpleRandomizer() { BOOL r = ::CryptAcquireContext(&provider_, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); assert(r); } #else // !__MINGW32__ SimpleRandomizer::SimpleRandomizer() : gen_(rd()) {} #endif // !__MINGW32__ SimpleRandomizer::~SimpleRandomizer() { #ifdef __MINGW32__ CryptReleaseContext(provider_, 0); #endif } long int SimpleRandomizer::getRandomNumber(long int to) { assert(to > 0); return std::uniform_int_distribution<long int>(0, to - 1)(*this); } void SimpleRandomizer::getRandomBytes(unsigned char* buf, size_t len) { #ifdef __MINGW32__ BOOL r = CryptGenRandom(provider_, len, reinterpret_cast<BYTE*>(buf)); if (!r) { assert(r); abort(); } #elif defined(__APPLE__) auto rv = SecRandomCopyBytes(kSecRandomDefault, len, buf); assert(errSecSuccess == rv); #elif defined(HAVE_LIBGNUTLS) auto rv = gnutls_rnd(GNUTLS_RND_RANDOM, buf, len); if (rv != 0) { assert(0 == rv); abort(); } #elif defined(HAVE_OPENSSL) auto rv = RAND_bytes(buf, len); if (rv != 1) { assert(1 == rv); abort(); } #else constexpr static size_t blocklen = 256; auto iter = len / blocklen; auto p = buf; for (size_t i = 0; i < iter; ++i) { auto rv = getentropy(p, blocklen); if (rv != 0) { std::cerr << "getentropy: " << strerror(errno) << std::endl; assert(0); abort(); } p += blocklen; } auto rem = len - iter * blocklen; if (rem == 0) { return; } auto rv = getentropy(p, rem); if (rv != 0) { std::cerr << "getentropy: " << strerror(errno) << std::endl; assert(0); abort(); } #endif // !__MINGW32__ && !__APPLE__ && !HAVE_OPENSSL && !HAVE_LIBGNUTLS } } // namespace aria2
4,143
C++
.cc
136
27.845588
79
0.700175
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
859
SpeedCalc.cc
aria2_aria2/src/SpeedCalc.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "SpeedCalc.h" #include <algorithm> #include <functional> #include "wallclock.h" namespace aria2 { namespace { constexpr auto WINDOW_TIME = 10_s; } // namespace SpeedCalc::SpeedCalc() : accumulatedLength_(0), bytesWindow_(0), maxSpeed_(0) {} void SpeedCalc::reset() { timeSlots_.clear(); start_ = global::wallclock(); accumulatedLength_ = 0; bytesWindow_ = 0; maxSpeed_ = 0; } void SpeedCalc::removeStaleTimeSlot(const Timer& now) { while (!timeSlots_.empty()) { if (timeSlots_[0].first.difference(now) <= WINDOW_TIME) { break; } bytesWindow_ -= timeSlots_[0].second; timeSlots_.pop_front(); } } int SpeedCalc::calculateSpeed() { const auto& now = global::wallclock(); removeStaleTimeSlot(now); if (timeSlots_.empty()) { return 0; } auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>( timeSlots_[0].first.difference(now)) .count(); if (elapsed <= 0) { elapsed = 1; } int speed = bytesWindow_ * 1000 / elapsed; maxSpeed_ = std::max(speed, maxSpeed_); return speed; } int SpeedCalc::calculateNewestSpeed(int seconds) { const auto& now = global::wallclock(); removeStaleTimeSlot(now); int64_t bytesCount(0); auto it = timeSlots_.rbegin(); while (it != timeSlots_.rend()) { if (it->first.difference(now) > seconds * 1_s) { break; } bytesCount += (*it++).second; } if (it == timeSlots_.rbegin()) { return 0; } auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>( (*--it).first.difference(now)) .count(); if (elapsed <= 0) { elapsed = 1; } return bytesCount * (1000. / elapsed); } void SpeedCalc::update(size_t bytes) { const auto& now = global::wallclock(); removeStaleTimeSlot(now); if (timeSlots_.empty() || std::chrono::duration_cast<std::chrono::seconds>( timeSlots_.back().first.difference(now)) >= 1_s) { timeSlots_.push_back(std::make_pair(now, bytes)); } else { timeSlots_.back().second += bytes; } bytesWindow_ += bytes; accumulatedLength_ += bytes; } int SpeedCalc::calculateAvgSpeed() const { auto milliElapsed = std::chrono::duration_cast<std::chrono::milliseconds>( start_.difference(global::wallclock())) .count(); // if milliElapsed is too small, the average speed is rubbish, better // return 0 if (milliElapsed > 4) { int speed = accumulatedLength_ * 1000 / milliElapsed; return speed; } else { return 0; } } } // namespace aria2
4,211
C++
.cc
132
28.166667
80
0.684379
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
933
LibsslARC4Encryptor.cc
aria2_aria2/src/LibsslARC4Encryptor.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2010 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "LibsslARC4Encryptor.h" #if OPENSSL_VERSION_NUMBER >= 0x30000000L # include <cassert> # include <openssl/core_names.h> # include "DlAbortEx.h" #endif // OPENSSL_VERSION_NUMBER >= 0x30000000L namespace aria2 { #if OPENSSL_VERSION_NUMBER >= 0x30000000L ARC4Encryptor::ARC4Encryptor() : ctx_{nullptr} {} ARC4Encryptor::~ARC4Encryptor() { if (ctx_) { EVP_CIPHER_CTX_free(ctx_); } } #else // !(OPENSSL_VERSION_NUMBER >= 0x30000000L) ARC4Encryptor::ARC4Encryptor() {} ARC4Encryptor::~ARC4Encryptor() = default; #endif // !(OPENSSL_VERSION_NUMBER >= 0x30000000L) void ARC4Encryptor::init(const unsigned char* key, size_t keyLength) { #if OPENSSL_VERSION_NUMBER >= 0x30000000L if (ctx_) { EVP_CIPHER_CTX_free(ctx_); } ctx_ = EVP_CIPHER_CTX_new(); OSSL_PARAM params[] = { OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &keyLength), OSSL_PARAM_construct_end(), }; if (EVP_EncryptInit_ex2(ctx_, EVP_rc4(), nullptr, nullptr, params) != 1) { throw DL_ABORT_EX("Failed to initialize RC4 cipher"); } if (EVP_EncryptInit_ex2(ctx_, nullptr, key, nullptr, nullptr) != 1) { throw DL_ABORT_EX("Failed to set key to RC4 cipher"); } #else // !(OPENSSL_VERSION_NUMBER >= 0x30000000L) RC4_set_key(&key_, keyLength, key); #endif // !(OPENSSL_VERSION_NUMBER >= 0x30000000L) } void ARC4Encryptor::encrypt(size_t len, unsigned char* out, const unsigned char* in) { #if OPENSSL_VERSION_NUMBER >= 0x30000000L int outlen; if (EVP_EncryptUpdate(ctx_, out, &outlen, in, len) != 1) { throw DL_ABORT_EX("Failed to encrypt data with RC4 cipher"); } assert(static_cast<size_t>(outlen) == len); #else // !(OPENSSL_VERSION_NUMBER >= 0x30000000L) RC4(&key_, len, in, out); #endif // !(OPENSSL_VERSION_NUMBER >= 0x30000000L) } } // namespace aria2
3,435
C++
.cc
88
36.431818
79
0.723807
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
981
RandomStreamPieceSelector.cc
aria2_aria2/src/RandomStreamPieceSelector.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "RandomStreamPieceSelector.h" #include "BitfieldMan.h" #include "SimpleRandomizer.h" namespace aria2 { RandomStreamPieceSelector::RandomStreamPieceSelector(BitfieldMan* bitfieldMan) : bitfieldMan_(bitfieldMan) { } RandomStreamPieceSelector::~RandomStreamPieceSelector() = default; bool RandomStreamPieceSelector::select(size_t& index, size_t minSplitSize, const unsigned char* ignoreBitfield, size_t length) { size_t start = SimpleRandomizer::getInstance()->getRandomNumber( bitfieldMan_->countBlock()); auto rv = bitfieldMan_->getInorderMissingUnusedIndex( index, start, bitfieldMan_->countBlock(), minSplitSize, ignoreBitfield, length); if (rv) { return true; } rv = bitfieldMan_->getInorderMissingUnusedIndex(index, 0, start, minSplitSize, ignoreBitfield, length); if (rv) { return true; } // Fall back to inorder search because randomized search may fail // because of |minSplitSize| constraint. return bitfieldMan_->getInorderMissingUnusedIndex(index, minSplitSize, ignoreBitfield, length); } void RandomStreamPieceSelector::onBitfieldInit() {} } // namespace aria2
2,913
C++
.cc
67
38.477612
80
0.721733
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
993
BtNotInterestedMessage.cc
aria2_aria2/src/BtNotInterestedMessage.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "BtNotInterestedMessage.h" #include "Peer.h" #include "PeerStorage.h" #include "SocketBuffer.h" namespace aria2 { const char BtNotInterestedMessage::NAME[] = "not interested"; BtNotInterestedMessage::BtNotInterestedMessage() : ZeroBtMessage(ID, NAME), peerStorage_(nullptr) { } BtNotInterestedMessage::~BtNotInterestedMessage() = default; std::unique_ptr<BtNotInterestedMessage> BtNotInterestedMessage::create(const unsigned char* data, size_t dataLength) { return ZeroBtMessage::create<BtNotInterestedMessage>(data, dataLength); } void BtNotInterestedMessage::doReceivedAction() { if (isMetadataGetMode()) { return; } getPeer()->peerInterested(false); if (!getPeer()->amChoking()) { peerStorage_->executeChoke(); } } void BtNotInterestedMessage::setPeerStorage(PeerStorage* peerStorage) { peerStorage_ = peerStorage; } } // namespace aria2
2,480
C++
.cc
65
36.153846
79
0.770253
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
994
TimeA2.cc
aria2_aria2/src/TimeA2.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "TimeA2.h" #include <cstring> #include "util.h" #include "array_fun.h" namespace aria2 { Time::Time() : tp_(Clock::now()), good_(true) {} Time::Time(time_t t) : tp_(Clock::from_time_t(t)), good_(true) {} void Time::reset() { tp_ = Clock::now(); good_ = true; } Time::Clock::duration Time::difference() const { return Clock::now() - tp_; } Time::Clock::duration Time::difference(const Time& time) const { return time.tp_ - tp_; } void Time::setTimeFromEpoch(time_t t) { tp_ = Clock::from_time_t(t); good_ = true; } std::string Time::toHTTPDate() const { char buf[32]; time_t t = getTimeFromEpoch(); struct tm* tms = gmtime(&t); // returned struct is statically allocated. size_t r = strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", tms); return std::string(&buf[0], &buf[r]); } Time Time::parse(const std::string& datetime, const std::string& format) { struct tm tm; memset(&tm, 0, sizeof(tm)); char* r = strptime(datetime.c_str(), format.c_str(), &tm); if (r != datetime.c_str() + datetime.size()) { return Time::null(); } time_t thetime = timegm(&tm); if (thetime == -1) { if (tm.tm_year >= 2038 - 1900) { thetime = INT32_MAX; } } return Time(thetime); } Time Time::parseRFC1123(const std::string& datetime) { return parse(datetime, "%a, %d %b %Y %H:%M:%S GMT"); } Time Time::parseRFC1123Alt(const std::string& datetime) { return parse(datetime, "%a, %d %b %Y %H:%M:%S +0000"); } Time Time::parseRFC850(const std::string& datetime) { return parse(datetime, "%a, %d-%b-%y %H:%M:%S GMT"); } Time Time::parseRFC850Ext(const std::string& datetime) { return parse(datetime, "%a, %d-%b-%Y %H:%M:%S GMT"); } Time Time::parseAsctime(const std::string& datetime) { return parse(datetime, "%a %b %d %H:%M:%S %Y"); } Time Time::parseHTTPDate(const std::string& datetime) { Time (*funcs[])(const std::string&) = { &parseRFC1123, &parseRFC1123Alt, &parseRFC850, &parseAsctime, &parseRFC850Ext, }; for (auto func : funcs) { Time t = func(datetime); if (t.good()) { return t; } } return Time::null(); } } // namespace aria2
3,747
C++
.cc
115
30.226087
79
0.691946
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,006
SftpDownloadCommand.cc
aria2_aria2/src/SftpDownloadCommand.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "SftpDownloadCommand.h" #include "Request.h" #include "SocketCore.h" #include "Segment.h" #include "DownloadEngine.h" #include "RequestGroup.h" #include "Option.h" #include "FileEntry.h" #include "SocketRecvBuffer.h" #include "AuthConfig.h" #include "SftpFinishDownloadCommand.h" namespace aria2 { SftpDownloadCommand::SftpDownloadCommand( cuid_t cuid, const std::shared_ptr<Request>& req, const std::shared_ptr<FileEntry>& fileEntry, RequestGroup* requestGroup, DownloadEngine* e, const std::shared_ptr<SocketCore>& socket, std::unique_ptr<AuthConfig> authConfig) : DownloadCommand(cuid, req, fileEntry, requestGroup, e, socket, std::make_shared<SocketRecvBuffer>(socket)), authConfig_(std::move(authConfig)) { setWriteCheckSocket(getSocket()); } SftpDownloadCommand::~SftpDownloadCommand() = default; bool SftpDownloadCommand::prepareForNextSegment() { if (getOption()->getAsBool(PREF_FTP_REUSE_CONNECTION) && getFileEntry()->gtoloff(getSegments().front()->getPositionToWrite()) == getFileEntry()->getLength()) { auto c = make_unique<SftpFinishDownloadCommand>( getCuid(), getRequest(), getFileEntry(), getRequestGroup(), getDownloadEngine(), getSocket()); c->setStatus(Command::STATUS_ONESHOT_REALTIME); getDownloadEngine()->setNoWait(true); getDownloadEngine()->addCommand(std::move(c)); if (getRequestGroup()->downloadFinished()) { // To run checksum checking, we had to call following function here. DownloadCommand::prepareForNextSegment(); } return true; } auto rv = DownloadCommand::prepareForNextSegment(); if (rv) { return true; } // sftp may not get incoming data. Enable write check to make this // command invoke. setWriteCheckSocket(getSocket()); return false; } int64_t SftpDownloadCommand::getRequestEndOffset() const { return getFileEntry()->getLength(); } bool SftpDownloadCommand::shouldEnableWriteCheck() { return getSocket()->wantWrite() || !getSocket()->wantRead(); } } // namespace aria2
3,677
C++
.cc
93
36.494624
79
0.745312
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,021
BtInterestedMessage.cc
aria2_aria2/src/BtInterestedMessage.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "BtInterestedMessage.h" #include "Peer.h" #include "PeerStorage.h" #include "SocketBuffer.h" namespace aria2 { const char BtInterestedMessage::NAME[] = "interested"; BtInterestedMessage::BtInterestedMessage() : ZeroBtMessage(ID, NAME), peerStorage_(nullptr) { } BtInterestedMessage::~BtInterestedMessage() = default; std::unique_ptr<BtInterestedMessage> BtInterestedMessage::create(const unsigned char* data, size_t dataLength) { return ZeroBtMessage::create<BtInterestedMessage>(data, dataLength); } void BtInterestedMessage::doReceivedAction() { if (isMetadataGetMode()) { return; } auto& peer = getPeer(); peer->peerInterested(true); if (peer->amChoking()) { peerStorage_->executeChoke(); } } void BtInterestedMessage::setPeerStorage(PeerStorage* peerStorage) { peerStorage_ = peerStorage; } } // namespace aria2
2,460
C++
.cc
66
35.212121
79
0.766261
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,022
SHA1IOFile.cc
aria2_aria2/src/SHA1IOFile.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "SHA1IOFile.h" #include <cassert> namespace aria2 { SHA1IOFile::SHA1IOFile() : sha1_(MessageDigest::sha1()) {} std::string SHA1IOFile::digest() { return sha1_->digest(); } size_t SHA1IOFile::onRead(void* ptr, size_t count) { assert(0); return 0; } size_t SHA1IOFile::onWrite(const void* ptr, size_t count) { sha1_->update(ptr, count); return count; } char* SHA1IOFile::onGets(char* s, int size) { assert(0); return nullptr; } int SHA1IOFile::onVprintf(const char* format, va_list va) { assert(0); return -1; } int SHA1IOFile::onFlush() { return 0; } int SHA1IOFile::onClose() { return 0; } bool SHA1IOFile::onSupportsColor() { return false; } bool SHA1IOFile::isError() const { return false; } bool SHA1IOFile::isEOF() const { return false; } bool SHA1IOFile::isOpen() const { return true; } } // namespace aria2
2,450
C++
.cc
66
35.166667
79
0.746199
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,035
BtCheckIntegrityEntry.cc
aria2_aria2/src/BtCheckIntegrityEntry.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "BtCheckIntegrityEntry.h" #include "BtFileAllocationEntry.h" #include "RequestGroup.h" #include "PieceStorage.h" #include "DownloadEngine.h" #include "DiskAdaptor.h" #include "prefs.h" #include "Option.h" #include "util.h" #include "SingletonHolder.h" #include "Notifier.h" namespace aria2 { BtCheckIntegrityEntry::BtCheckIntegrityEntry(RequestGroup* requestGroup) : PieceHashCheckIntegrityEntry(requestGroup, nullptr) { } BtCheckIntegrityEntry::~BtCheckIntegrityEntry() = default; void BtCheckIntegrityEntry::onDownloadIncomplete( std::vector<std::unique_ptr<Command>>& commands, DownloadEngine* e) { auto& ps = getRequestGroup()->getPieceStorage(); ps->onDownloadIncomplete(); if (getRequestGroup()->getOption()->getAsBool(PREF_HASH_CHECK_ONLY)) { return; } const auto& diskAdaptor = ps->getDiskAdaptor(); if (diskAdaptor->isReadOnlyEnabled()) { // Now reopen DiskAdaptor with read only disabled. diskAdaptor->closeFile(); diskAdaptor->disableReadOnly(); diskAdaptor->openFile(); } proceedFileAllocation( commands, make_unique<BtFileAllocationEntry>(getRequestGroup()), e); } void BtCheckIntegrityEntry::onDownloadFinished( std::vector<std::unique_ptr<Command>>& commands, DownloadEngine* e) { auto group = getRequestGroup(); const auto& option = group->getOption(); if (option->getAsBool(PREF_BT_ENABLE_HOOK_AFTER_HASH_CHECK)) { util::executeHookByOptName(group, option.get(), PREF_ON_BT_DOWNLOAD_COMPLETE); SingletonHolder<Notifier>::instance()->notifyDownloadEvent( EVENT_ON_BT_DOWNLOAD_COMPLETE, group); } // TODO Currently,when all the checksums // are valid, then aria2 goes to seeding mode. Sometimes it is better // to exit rather than doing seeding. So, it would be good to toggle this // behavior. if (!option->getAsBool(PREF_HASH_CHECK_ONLY) && option->getAsBool(PREF_BT_HASH_CHECK_SEED)) { proceedFileAllocation( commands, make_unique<BtFileAllocationEntry>(getRequestGroup()), e); } } } // namespace aria2
3,671
C++
.cc
91
37.406593
79
0.75042
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,037
BtUnchokeMessage.cc
aria2_aria2/src/BtUnchokeMessage.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "BtUnchokeMessage.h" #include "Peer.h" #include "SocketBuffer.h" namespace aria2 { const char BtUnchokeMessage::NAME[] = "unchoke"; BtUnchokeMessage::BtUnchokeMessage() : ZeroBtMessage(ID, NAME) {} std::unique_ptr<BtUnchokeMessage> BtUnchokeMessage::create(const unsigned char* data, size_t dataLength) { return ZeroBtMessage::create<BtUnchokeMessage>(data, dataLength); } void BtUnchokeMessage::doReceivedAction() { if (isMetadataGetMode()) { return; } getPeer()->peerChoking(false); } } // namespace aria2
2,131
C++
.cc
53
38.283019
79
0.764479
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,054
HaveEraseCommand.cc
aria2_aria2/src/HaveEraseCommand.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "HaveEraseCommand.h" #include "DownloadEngine.h" #include "RequestGroupMan.h" #include "PieceStorage.h" #include "RequestGroup.h" #include "wallclock.h" namespace aria2 { HaveEraseCommand::HaveEraseCommand(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval) : TimeBasedCommand(cuid, e, std::move(interval), true) { } HaveEraseCommand::~HaveEraseCommand() = default; void HaveEraseCommand::preProcess() { if (getDownloadEngine()->getRequestGroupMan()->downloadFinished() || getDownloadEngine()->isHaltRequested()) { enableExit(); } } void HaveEraseCommand::process() { // we are making a copy of current wallclock. auto expiry = global::wallclock(); expiry.sub(5_s); const auto& groups = getDownloadEngine()->getRequestGroupMan()->getRequestGroups(); for (auto& group : groups) { const auto& ps = group->getPieceStorage(); if (!ps) { continue; } ps->removeAdvertisedPiece(expiry); } } } // namespace aria2
2,622
C++
.cc
70
34.571429
79
0.738601
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,061
StreamFileAllocationEntry.cc
aria2_aria2/src/StreamFileAllocationEntry.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "StreamFileAllocationEntry.h" #include <algorithm> #include "DownloadEngine.h" #include "Option.h" #include "prefs.h" #include "RequestGroup.h" #include "DownloadContext.h" #include "Command.h" #include "PeerStat.h" #include "FileEntry.h" #include "PieceStorage.h" #include "DiskAdaptor.h" #include "LogFactory.h" namespace aria2 { StreamFileAllocationEntry::StreamFileAllocationEntry( RequestGroup* requestGroup, std::unique_ptr<Command> nextCommand) : FileAllocationEntry(requestGroup, std::move(nextCommand)) { } StreamFileAllocationEntry::~StreamFileAllocationEntry() = default; void StreamFileAllocationEntry::prepareForNextAction( std::vector<std::unique_ptr<Command>>& commands, DownloadEngine* e) { auto rg = getRequestGroup(); auto& dctx = rg->getDownloadContext(); auto& ps = rg->getPieceStorage(); auto diskAdaptor = ps->getDiskAdaptor(); auto& option = rg->getOption(); // For DownloadContext::resetDownloadStartTime(), see also // RequestGroup::createInitialCommand() dctx->resetDownloadStartTime(); if (option->getAsBool(PREF_ENABLE_MMAP) && option->get(PREF_FILE_ALLOCATION) != V_NONE && diskAdaptor->size() <= option->getAsLLInt(PREF_MAX_MMAP_LIMIT)) { diskAdaptor->enableMmap(); } if (getNextCommand()) { // Reset download start time of PeerStat because it is started // before file allocation begins. const auto& fileEntries = dctx->getFileEntries(); for (auto& f : fileEntries) { const auto& reqs = f->getInFlightRequests(); for (auto& req : reqs) { const auto& peerStat = req->getPeerStat(); if (peerStat) { peerStat->downloadStart(); } } } // give _nextCommand a chance to execute in the next execution loop. getNextCommand()->setStatus(Command::STATUS_ONESHOT_REALTIME); e->setNoWait(true); commands.push_back(popNextCommand()); // try remaining uris rg->createNextCommandWithAdj(commands, e, -1); } else { rg->createNextCommandWithAdj(commands, e, 0); } if (option->getAsInt(PREF_AUTO_SAVE_INTERVAL) != 0 && !rg->allDownloadFinished()) { try { rg->saveControlFile(); } catch (RecoverableException& e) { A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } } } } // namespace aria2
3,902
C++
.cc
104
34.269231
79
0.72948
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,067
SocketRecvBuffer.cc
aria2_aria2/src/SocketRecvBuffer.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2011 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "SocketRecvBuffer.h" #include <cstring> #include <cassert> #include "SocketCore.h" #include "LogFactory.h" namespace aria2 { SocketRecvBuffer::SocketRecvBuffer(std::shared_ptr<SocketCore> socket) : socket_(std::move(socket)), pos_(buf_.data()), last_(pos_) { } SocketRecvBuffer::~SocketRecvBuffer() = default; ssize_t SocketRecvBuffer::recv() { size_t n = std::end(buf_) - last_; if (n == 0) { A2_LOG_DEBUG("Buffer full"); return 0; } socket_->readData(last_, n); last_ += n; return n; } void SocketRecvBuffer::drain(size_t n) { assert(pos_ + n <= last_); pos_ += n; if (pos_ == last_) { truncateBuffer(); } } void SocketRecvBuffer::truncateBuffer() { pos_ = last_ = buf_.data(); } } // namespace aria2
2,353
C++
.cc
66
33.5
79
0.731343
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,075
BtHandshakeMessage.cc
aria2_aria2/src/BtHandshakeMessage.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "BtHandshakeMessage.h" #include <cstring> #include "util.h" #include "a2functional.h" namespace aria2 { const unsigned char BtHandshakeMessage::BT_PSTR[] = "BitTorrent protocol"; const char BtHandshakeMessage::NAME[] = "handshake"; BtHandshakeMessage::BtHandshakeMessage() : SimpleBtMessage(ID, NAME) { init(); } BtHandshakeMessage::BtHandshakeMessage(const unsigned char* infoHash, const unsigned char* peerId) : SimpleBtMessage(ID, NAME) { init(); std::copy_n(infoHash, infoHash_.size(), std::begin(infoHash_)); std::copy_n(peerId, peerId_.size(), std::begin(peerId_)); } BtHandshakeMessage::~BtHandshakeMessage() = default; void BtHandshakeMessage::init() { pstrlen_ = 19; std::copy_n(BT_PSTR, pstr_.size(), std::begin(pstr_)); std::fill(std::begin(reserved_), std::end(reserved_), 0); // fast extension reserved_[7] |= 0x04u; // extended messaging reserved_[5] |= 0x10u; } std::unique_ptr<BtHandshakeMessage> BtHandshakeMessage::create(const unsigned char* data, size_t dataLength) { auto msg = make_unique<BtHandshakeMessage>(); msg->pstrlen_ = data[0]; std::copy_n(&data[1], msg->pstr_.size(), std::begin(msg->pstr_)); std::copy_n(&data[20], msg->reserved_.size(), std::begin(msg->reserved_)); std::copy_n(&data[28], msg->infoHash_.size(), std::begin(msg->infoHash_)); std::copy_n(&data[48], msg->peerId_.size(), std::begin(msg->peerId_)); return msg; } std::vector<unsigned char> BtHandshakeMessage::createMessage() { auto msg = std::vector<unsigned char>(MESSAGE_LENGTH); auto dst = msg.data(); *dst++ = pstrlen_; dst = std::copy(std::begin(pstr_), std::end(pstr_), dst); dst = std::copy(std::begin(reserved_), std::end(reserved_), dst); dst = std::copy(std::begin(infoHash_), std::end(infoHash_), dst); std::copy(std::begin(peerId_), std::end(peerId_), dst); return msg; } std::string BtHandshakeMessage::toString() const { return fmt("%s peerId=%s, reserved=%s", NAME, util::percentEncode(peerId_.data(), peerId_.size()).c_str(), util::toHex(reserved_.data(), reserved_.size()).c_str()); } bool BtHandshakeMessage::isFastExtensionSupported() const { return reserved_[7] & 0x04u; } bool BtHandshakeMessage::isExtendedMessagingEnabled() const { return reserved_[5] & 0x10u; } bool BtHandshakeMessage::isDHTEnabled() const { return reserved_[7] & 0x01u; } void BtHandshakeMessage::setInfoHash(const unsigned char* infoHash) { std::copy_n(infoHash, infoHash_.size(), std::begin(infoHash_)); } void BtHandshakeMessage::setPeerId(const unsigned char* peerId) { std::copy_n(peerId, peerId_.size(), std::begin(peerId_)); } } // namespace aria2
4,298
C++
.cc
107
37.504673
80
0.719626
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,092
IndexBtMessage.cc
aria2_aria2/src/IndexBtMessage.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2009 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "IndexBtMessage.h" #include "util.h" #include "a2functional.h" #include "bittorrent_helper.h" namespace aria2 { std::vector<unsigned char> IndexBtMessage::createMessage() { /** * len --- 5, 4bytes * id --- ?, 1byte * piece index --- index, 4bytes * total: 9bytes */ auto msg = std::vector<unsigned char>(MESSAGE_LENGTH); bittorrent::createPeerMessageString(msg.data(), MESSAGE_LENGTH, 5, getId()); bittorrent::setIntParam(&msg[5], index_); return msg; } std::string IndexBtMessage::toString() const { return fmt("%s index=%lu", getName(), static_cast<unsigned long>(index_)); } } // namespace aria2
2,235
C++
.cc
57
37.122807
79
0.74379
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,113
SftpFinishDownloadCommand.cc
aria2_aria2/src/SftpFinishDownloadCommand.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "SftpFinishDownloadCommand.h" #include "Request.h" #include "DownloadEngine.h" #include "prefs.h" #include "Option.h" #include "message.h" #include "fmt.h" #include "DlAbortEx.h" #include "SocketCore.h" #include "RequestGroup.h" #include "Logger.h" #include "LogFactory.h" #include "wallclock.h" #include "AuthConfigFactory.h" #include "AuthConfig.h" namespace aria2 { SftpFinishDownloadCommand::SftpFinishDownloadCommand( cuid_t cuid, const std::shared_ptr<Request>& req, const std::shared_ptr<FileEntry>& fileEntry, RequestGroup* requestGroup, DownloadEngine* e, const std::shared_ptr<SocketCore>& socket) : AbstractCommand(cuid, req, fileEntry, requestGroup, e, socket) { disableReadCheckSocket(); setWriteCheckSocket(getSocket()); } SftpFinishDownloadCommand::~SftpFinishDownloadCommand() = default; // overrides AbstractCommand::execute(). // AbstractCommand::_segments is empty. bool SftpFinishDownloadCommand::execute() { if (getRequestGroup()->isHaltRequested()) { return true; } try { if (readEventEnabled() || writeEventEnabled() || hupEventEnabled()) { getCheckPoint() = global::wallclock(); if (!getSocket()->sshSFTPClose()) { setWriteCheckSocketIf(getSocket(), getSocket()->wantWrite()); setReadCheckSocketIf(getSocket(), getSocket()->wantRead()); addCommandSelf(); return false; } auto authConfig = getDownloadEngine()->getAuthConfigFactory()->createAuthConfig( getRequest(), getRequestGroup()->getOption().get()); getDownloadEngine()->poolSocket(getRequest(), authConfig->getUser(), createProxyRequest(), getSocket(), ""); } else if (getCheckPoint().difference(global::wallclock()) >= getTimeout()) { A2_LOG_INFO(fmt("CUID#%" PRId64 " - Timeout before receiving transfer complete.", getCuid())); } else { addCommandSelf(); return false; } } catch (RecoverableException& e) { A2_LOG_INFO_EX(fmt("CUID#%" PRId64 " - Exception was thrown, but download was" " finished, so we can ignore the exception.", getCuid()), e); } if (getRequestGroup()->downloadFinished()) { return true; } else { return prepareForRetry(0); } } // This function never be called. bool SftpFinishDownloadCommand::executeInternal() { return true; } } // namespace aria2
4,122
C++
.cc
109
33.192661
79
0.700475
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,116
TimerA2.cc
aria2_aria2/src/TimerA2.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "TimerA2.h" namespace aria2 { // Add this offset to Timer::Clock::now() so that we can treat 0 value // as special case, and normal timeout always applies. constexpr auto OFFSET = 24_h; namespace { Timer::Clock::time_point getNow() { return Timer::Clock::now() + OFFSET; } } // namespace Timer::Timer() : tp_(getNow()) { reset(); } Timer::Timer(const Clock::time_point& tp) : tp_(tp) {} void Timer::reset() { tp_ = getNow(); } Timer::Clock::duration Timer::difference() const { auto now = getNow(); if (now < tp_) { return Timer::Clock::duration(0_s); } return now - tp_; } Timer::Clock::duration Timer::difference(const Timer& timer) const { if (timer.tp_ < tp_) { return Timer::Clock::duration(0_s); } return timer.tp_ - tp_; } bool Timer::isZero() const { return tp_.time_since_epoch() == Clock::duration::zero(); } } // namespace aria2
2,482
C++
.cc
65
36.138462
79
0.728785
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,118
BtFileAllocationEntry.cc
aria2_aria2/src/BtFileAllocationEntry.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "BtFileAllocationEntry.h" #include <algorithm> #include "BtSetup.h" #include "RequestGroup.h" #include "Command.h" #include "DownloadEngine.h" #include "DownloadContext.h" #include "FileEntry.h" #include "PieceStorage.h" #include "DiskAdaptor.h" #include "Option.h" #include "prefs.h" #include "LogFactory.h" namespace aria2 { BtFileAllocationEntry::BtFileAllocationEntry(RequestGroup* requestGroup) : FileAllocationEntry(requestGroup, nullptr) { } BtFileAllocationEntry::~BtFileAllocationEntry() = default; void BtFileAllocationEntry::prepareForNextAction( std::vector<std::unique_ptr<Command>>& commands, DownloadEngine* e) { auto rg = getRequestGroup(); auto& dctx = rg->getDownloadContext(); auto& ps = rg->getPieceStorage(); auto diskAdaptor = ps->getDiskAdaptor(); auto& option = rg->getOption(); BtSetup().setup(commands, rg, e, option.get()); if (option->getAsBool(PREF_ENABLE_MMAP) && option->get(PREF_FILE_ALLOCATION) != V_NONE && diskAdaptor->size() <= option->getAsLLInt(PREF_MAX_MMAP_LIMIT)) { diskAdaptor->enableMmap(); } if (!rg->downloadFinished()) { // For DownloadContext::resetDownloadStartTime(), see also // RequestGroup::createInitialCommand() dctx->resetDownloadStartTime(); const auto& fileEntries = dctx->getFileEntries(); if (isUriSuppliedForRequsetFileEntry(std::begin(fileEntries), std::end(fileEntries))) { rg->createNextCommandWithAdj(commands, e, 0); } if (option->getAsInt(PREF_AUTO_SAVE_INTERVAL) != 0) { try { rg->saveControlFile(); } catch (RecoverableException& e) { A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } } } else { #ifdef __MINGW32__ if (!diskAdaptor->isReadOnlyEnabled()) { // On Windows, if aria2 opens files with GENERIC_WRITE access // right, some programs cannot open them aria2 is seeding. To // avoid this situation, re-open the files with read-only // enabled. A2_LOG_INFO("Closing files and re-open them with read-only mode" " enabled."); diskAdaptor->closeFile(); diskAdaptor->enableReadOnly(); diskAdaptor->openFile(); } #endif // __MINGW32__ rg->enableSeedOnly(); } } } // namespace aria2
3,902
C++
.cc
103
34.116505
79
0.716623
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,122
SftpNegotiationCommand.cc
aria2_aria2/src/SftpNegotiationCommand.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "SftpNegotiationCommand.h" #include <cassert> #include <utility> #include "Request.h" #include "DownloadEngine.h" #include "RequestGroup.h" #include "PieceStorage.h" #include "FileEntry.h" #include "message.h" #include "util.h" #include "Option.h" #include "Logger.h" #include "LogFactory.h" #include "Segment.h" #include "DownloadContext.h" #include "DefaultBtProgressInfoFile.h" #include "RequestGroupMan.h" #include "SocketCore.h" #include "fmt.h" #include "DiskAdaptor.h" #include "SegmentMan.h" #include "AuthConfigFactory.h" #include "AuthConfig.h" #include "a2functional.h" #include "URISelector.h" #include "CheckIntegrityEntry.h" #include "NullProgressInfoFile.h" #include "ChecksumCheckIntegrityEntry.h" #include "SftpDownloadCommand.h" namespace aria2 { SftpNegotiationCommand::SftpNegotiationCommand( cuid_t cuid, const std::shared_ptr<Request>& req, const std::shared_ptr<FileEntry>& fileEntry, RequestGroup* requestGroup, DownloadEngine* e, const std::shared_ptr<SocketCore>& socket, Seq seq) : AbstractCommand(cuid, req, fileEntry, requestGroup, e, socket), sequence_(seq), authConfig_(e->getAuthConfigFactory()->createAuthConfig( req, requestGroup->getOption().get())) { path_ = getPath(); setWriteCheckSocket(getSocket()); const std::string& checksum = getOption()->get(PREF_SSH_HOST_KEY_MD); if (!checksum.empty()) { auto p = util::divide(std::begin(checksum), std::end(checksum), '='); hashType_.assign(p.first.first, p.first.second); util::lowercase(hashType_); digest_ = util::fromHex(p.second.first, p.second.second); } } SftpNegotiationCommand::~SftpNegotiationCommand() = default; bool SftpNegotiationCommand::executeInternal() { disableWriteCheckSocket(); for (;;) { switch (sequence_) { case SEQ_HANDSHAKE: setReadCheckSocket(getSocket()); if (!getSocket()->sshHandshake(hashType_, digest_)) { goto again; } A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - SSH handshake success", getCuid())); sequence_ = SEQ_AUTH_PASSWORD; break; case SEQ_AUTH_PASSWORD: if (!getSocket()->sshAuthPassword(authConfig_->getUser(), authConfig_->getPassword())) { goto again; } A2_LOG_DEBUG( fmt("CUID#%" PRId64 " - SSH authentication success", getCuid())); sequence_ = SEQ_SFTP_OPEN; break; case SEQ_SFTP_OPEN: if (!getSocket()->sshSFTPOpen(path_)) { goto again; } A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - SFTP file %s opened", getCuid(), path_.c_str())); sequence_ = SEQ_SFTP_STAT; break; case SEQ_SFTP_STAT: { int64_t totalLength; time_t mtime; if (!getSocket()->sshSFTPStat(totalLength, mtime, path_)) { goto again; } Time t(mtime); A2_LOG_INFO( fmt("CUID#%" PRId64 " - SFTP File %s, size=%" PRId64 ", mtime=%s", getCuid(), path_.c_str(), totalLength, t.toHTTPDate().c_str())); if (!getPieceStorage()) { getRequestGroup()->updateLastModifiedTime(Time(mtime)); onFileSizeDetermined(totalLength); } else { getRequestGroup()->validateTotalLength(getFileEntry()->getLength(), totalLength); sequence_ = SEQ_SFTP_SEEK; } break; } case SEQ_SFTP_SEEK: { sequence_ = SEQ_NEGOTIATION_COMPLETED; if (getSegments().empty()) { break; } auto& segment = getSegments().front(); A2_LOG_INFO(fmt("CUID#%" PRId64 " - SFTP seek to %" PRId64, getCuid(), segment->getPositionToWrite())); getSocket()->sshSFTPSeek(segment->getPositionToWrite()); break; } case SEQ_FILE_PREPARATION: sequence_ = SEQ_SFTP_SEEK; disableReadCheckSocket(); disableWriteCheckSocket(); return false; case SEQ_NEGOTIATION_COMPLETED: { auto command = make_unique<SftpDownloadCommand>( getCuid(), getRequest(), getFileEntry(), getRequestGroup(), getDownloadEngine(), getSocket(), std::move(authConfig_)); command->setStartupIdleTime( std::chrono::seconds(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME))); command->setLowestDownloadSpeedLimit( getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT)); command->setStatus(Command::STATUS_ONESHOT_REALTIME); getDownloadEngine()->setNoWait(true); if (getFileEntry()->isUniqueProtocol()) { getFileEntry()->removeURIWhoseHostnameIs(getRequest()->getHost()); } getRequestGroup()->getURISelector()->tuneDownloadCommand( getFileEntry()->getRemainingUris(), command.get()); getDownloadEngine()->addCommand(std::move(command)); return true; } case SEQ_DOWNLOAD_ALREADY_COMPLETED: case SEQ_HEAD_OK: case SEQ_EXIT: return true; }; } again: addCommandSelf(); if (getSocket()->wantWrite()) { setWriteCheckSocket(getSocket()); } return false; } void SftpNegotiationCommand::onFileSizeDetermined(int64_t totalLength) { getFileEntry()->setLength(totalLength); if (getFileEntry()->getPath().empty()) { auto suffixPath = util::createSafePath( util::percentDecode(std::begin(getRequest()->getFile()), std::end(getRequest()->getFile()))); getFileEntry()->setPath( util::applyDir(getOption()->get(PREF_DIR), suffixPath)); getFileEntry()->setSuffixPath(suffixPath); } getRequestGroup()->preDownloadProcessing(); if (totalLength == 0) { sequence_ = SEQ_NEGOTIATION_COMPLETED; if (getOption()->getAsBool(PREF_DRY_RUN)) { getRequestGroup()->initPieceStorage(); onDryRunFileFound(); return; } if (getDownloadContext()->knowsTotalLength() && getRequestGroup()->downloadFinishedByFileLength()) { // TODO Known issue: if .aria2 file exists, it will not be // deleted on successful verification, because .aria2 file is // not loaded. See also // HttpResponseCommand::handleOtherEncoding() getRequestGroup()->initPieceStorage(); if (getDownloadContext()->isChecksumVerificationNeeded()) { A2_LOG_DEBUG("Zero length file exists. Verify checksum."); auto entry = make_unique<ChecksumCheckIntegrityEntry>(getRequestGroup()); entry->initValidator(); getPieceStorage()->getDiskAdaptor()->openExistingFile(); getDownloadEngine()->getCheckIntegrityMan()->pushEntry( std::move(entry)); sequence_ = SEQ_EXIT; } else { getPieceStorage()->markAllPiecesDone(); getDownloadContext()->setChecksumVerified(true); sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED; A2_LOG_NOTICE(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED, GroupId::toHex(getRequestGroup()->getGID()).c_str(), getRequestGroup()->getFirstFilePath().c_str())); } poolConnection(); return; } getRequestGroup()->adjustFilename(std::make_shared<NullProgressInfoFile>()); getRequestGroup()->initPieceStorage(); getPieceStorage()->getDiskAdaptor()->initAndOpenFile(); if (getDownloadContext()->knowsTotalLength()) { A2_LOG_DEBUG("File length becomes zero and it means download completed."); // TODO Known issue: if .aria2 file exists, it will not be // deleted on successful verification, because .aria2 file is // not loaded. See also // HttpResponseCommand::handleOtherEncoding() if (getDownloadContext()->isChecksumVerificationNeeded()) { A2_LOG_DEBUG("Verify checksum for zero-length file"); auto entry = make_unique<ChecksumCheckIntegrityEntry>(getRequestGroup()); entry->initValidator(); getDownloadEngine()->getCheckIntegrityMan()->pushEntry( std::move(entry)); sequence_ = SEQ_EXIT; } else { sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED; getPieceStorage()->markAllPiecesDone(); } poolConnection(); return; } // We have to make sure that command that has Request object must // have segment after PieceStorage is initialized. See // AbstractCommand::execute() getSegmentMan()->getSegmentWithIndex(getCuid(), 0); return; } else { auto progressInfoFile = std::make_shared<DefaultBtProgressInfoFile>( getDownloadContext(), nullptr, getOption().get()); getRequestGroup()->adjustFilename(progressInfoFile); getRequestGroup()->initPieceStorage(); if (getOption()->getAsBool(PREF_DRY_RUN)) { onDryRunFileFound(); return; } auto checkIntegrityEntry = getRequestGroup()->createCheckIntegrityEntry(); if (!checkIntegrityEntry) { sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED; poolConnection(); return; } // We have to make sure that command that has Request object must // have segment after PieceStorage is initialized. See // AbstractCommand::execute() getSegmentMan()->getSegmentWithIndex(getCuid(), 0); checkIntegrityEntry->pushNextCommand(std::unique_ptr<Command>(this)); prepareForNextAction(std::move(checkIntegrityEntry)); disableReadCheckSocket(); sequence_ = SEQ_FILE_PREPARATION; } } void SftpNegotiationCommand::poolConnection() const { if (getOption()->getAsBool(PREF_FTP_REUSE_CONNECTION)) { // TODO we don't need options. Probably, we need to pool socket // using scheme, port and auth info as key getDownloadEngine()->poolSocket(getRequest(), authConfig_->getUser(), createProxyRequest(), getSocket(), ""); } } void SftpNegotiationCommand::onDryRunFileFound() { getPieceStorage()->markAllPiecesDone(); getDownloadContext()->setChecksumVerified(true); poolConnection(); sequence_ = SEQ_HEAD_OK; } std::string SftpNegotiationCommand::getPath() const { auto& req = getRequest(); auto path = req->getDir() + req->getFile(); return util::percentDecode(std::begin(path), std::end(path)); } } // namespace aria2
11,756
C++
.cc
308
32.344156
80
0.677905
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,131
SSHSession.cc
aria2_aria2/src/SSHSession.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "SSHSession.h" #include <cassert> #include "MessageDigest.h" namespace aria2 { SSHSession::SSHSession() : ssh2_(nullptr), sftp_(nullptr), sftph_(nullptr), fd_(-1) { } SSHSession::~SSHSession() { closeConnection(); } int SSHSession::closeConnection() { if (sftph_) { // TODO this could return LIBSSH2_ERROR_EAGAIN libssh2_sftp_close(sftph_); sftph_ = nullptr; } if (sftp_) { // TODO this could return LIBSSH2_ERROR_EAGAIN libssh2_sftp_shutdown(sftp_); sftp_ = nullptr; } if (ssh2_) { // TODO this could return LIBSSH2_ERROR_EAGAIN libssh2_session_disconnect(ssh2_, "bye"); libssh2_session_free(ssh2_); ssh2_ = nullptr; } return SSH_ERR_OK; } int SSHSession::gracefulShutdown() { if (sftph_) { auto rv = libssh2_sftp_close(sftph_); if (rv == LIBSSH2_ERROR_EAGAIN) { return SSH_ERR_WOULDBLOCK; } if (rv != 0) { return SSH_ERR_ERROR; } sftph_ = nullptr; } if (sftp_) { auto rv = libssh2_sftp_shutdown(sftp_); if (rv == LIBSSH2_ERROR_EAGAIN) { return SSH_ERR_WOULDBLOCK; } if (rv != 0) { return SSH_ERR_ERROR; } sftp_ = nullptr; } if (ssh2_) { auto rv = libssh2_session_disconnect(ssh2_, "bye"); if (rv == LIBSSH2_ERROR_EAGAIN) { return SSH_ERR_WOULDBLOCK; } if (rv != 0) { return SSH_ERR_ERROR; } libssh2_session_free(ssh2_); ssh2_ = nullptr; } return SSH_ERR_OK; } int SSHSession::sftpClose() { if (!sftph_) { return SSH_ERR_OK; } auto rv = libssh2_sftp_close(sftph_); if (rv == LIBSSH2_ERROR_EAGAIN) { return SSH_ERR_WOULDBLOCK; } if (rv != 0) { return SSH_ERR_ERROR; } sftph_ = nullptr; return SSH_ERR_OK; } int SSHSession::init(sock_t sockfd) { ssh2_ = libssh2_session_init(); if (!ssh2_) { return SSH_ERR_ERROR; } libssh2_session_set_blocking(ssh2_, 0); fd_ = sockfd; return SSH_ERR_OK; } int SSHSession::checkDirection() { auto dir = libssh2_session_block_directions(ssh2_); if (dir & LIBSSH2_SESSION_BLOCK_OUTBOUND) { return SSH_WANT_WRITE; } return SSH_WANT_READ; } ssize_t SSHSession::writeData(const void* data, size_t len) { // not implemented yet assert(0); } ssize_t SSHSession::readData(void* data, size_t len) { auto nread = libssh2_sftp_read(sftph_, static_cast<char*>(data), len); if (nread == LIBSSH2_ERROR_EAGAIN) { return SSH_ERR_WOULDBLOCK; } if (nread < 0) { return SSH_ERR_ERROR; } return nread; } int SSHSession::handshake() { auto rv = libssh2_session_handshake(ssh2_, fd_); if (rv == LIBSSH2_ERROR_EAGAIN) { return SSH_ERR_WOULDBLOCK; } if (rv != 0) { return SSH_ERR_ERROR; } return SSH_ERR_OK; } std::string SSHSession::hostkeyMessageDigest(const std::string& hashType) { int h; if (hashType == "sha-1") { h = LIBSSH2_HOSTKEY_HASH_SHA1; } else if (hashType == "md5") { h = LIBSSH2_HOSTKEY_HASH_MD5; } else { return ""; } auto fingerprint = libssh2_hostkey_hash(ssh2_, h); if (!fingerprint) { return ""; } return std::string(fingerprint, MessageDigest::getDigestLength(hashType)); } int SSHSession::authPassword(const std::string& user, const std::string& password) { auto rv = libssh2_userauth_password(ssh2_, user.c_str(), password.c_str()); if (rv == LIBSSH2_ERROR_EAGAIN) { return SSH_ERR_WOULDBLOCK; } if (rv != 0) { return SSH_ERR_ERROR; } return SSH_ERR_OK; } int SSHSession::sftpOpen(const std::string& path) { if (!sftp_) { sftp_ = libssh2_sftp_init(ssh2_); if (!sftp_) { if (libssh2_session_last_errno(ssh2_) == LIBSSH2_ERROR_EAGAIN) { return SSH_ERR_WOULDBLOCK; } return SSH_ERR_ERROR; } } if (!sftph_) { sftph_ = libssh2_sftp_open(sftp_, path.c_str(), LIBSSH2_FXF_READ, 0); if (!sftph_) { if (libssh2_session_last_errno(ssh2_) == LIBSSH2_ERROR_EAGAIN) { return SSH_ERR_WOULDBLOCK; } return SSH_ERR_ERROR; } } return SSH_ERR_OK; } int SSHSession::sftpStat(int64_t& totalLength, time_t& mtime) { LIBSSH2_SFTP_ATTRIBUTES attrs; auto rv = libssh2_sftp_fstat_ex(sftph_, &attrs, 0); if (rv == LIBSSH2_ERROR_EAGAIN) { return SSH_ERR_WOULDBLOCK; } if (rv != 0) { return SSH_ERR_ERROR; } totalLength = attrs.filesize; mtime = attrs.mtime; return SSH_ERR_OK; } void SSHSession::sftpSeek(int64_t pos) { libssh2_sftp_seek64(sftph_, pos); } std::string SSHSession::getLastErrorString() { if (!ssh2_) { return "SSH session has not been initialized yet"; } char* errmsg; libssh2_session_last_error(ssh2_, &errmsg, nullptr, 0); return errmsg; } } // namespace aria2
6,309
C++
.cc
235
23.502128
79
0.676194
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,167
BtKeepAliveMessage.cc
aria2_aria2/src/BtKeepAliveMessage.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "BtKeepAliveMessage.h" #include <cstring> namespace aria2 { const char BtKeepAliveMessage::NAME[] = "keep alive"; std::vector<unsigned char> BtKeepAliveMessage::createMessage() { /** * len --- 0, 4bytes * total: 4bytes */ return std::vector<unsigned char>(MESSAGE_LENGTH); } } // namespace aria2
1,918
C++
.cc
47
38.787234
79
0.754687
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,181
EvictSocketPoolCommand.cc
aria2_aria2/src/EvictSocketPoolCommand.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "EvictSocketPoolCommand.h" #include "RequestGroupMan.h" #include "DownloadEngine.h" namespace aria2 { EvictSocketPoolCommand::EvictSocketPoolCommand(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval) : TimeBasedCommand(cuid, e, std::move(interval), true) { } EvictSocketPoolCommand::~EvictSocketPoolCommand() = default; void EvictSocketPoolCommand::preProcess() { if (getDownloadEngine()->getRequestGroupMan()->downloadFinished() || getDownloadEngine()->isHaltRequested()) { enableExit(); } } void EvictSocketPoolCommand::process() { getDownloadEngine()->evictSocketPool(); } } // namespace aria2
2,287
C++
.cc
56
37.982143
79
0.750562
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,182
AsyncNameResolver.cc
aria2_aria2/src/AsyncNameResolver.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "AsyncNameResolver.h" #include <cstring> #include "A2STR.h" #include "LogFactory.h" #include "SocketCore.h" #include "util.h" #include "EventPoll.h" namespace aria2 { void callback(void* arg, int status, int timeouts, ares_addrinfo* result) { AsyncNameResolver* resolverPtr = reinterpret_cast<AsyncNameResolver*>(arg); if (status != ARES_SUCCESS) { resolverPtr->error_ = ares_strerror(status); resolverPtr->status_ = AsyncNameResolver::STATUS_ERROR; return; } for (auto ap = result->nodes; ap; ap = ap->ai_next) { char addrstring[NI_MAXHOST]; auto rv = getnameinfo(ap->ai_addr, ap->ai_addrlen, addrstring, sizeof(addrstring), nullptr, 0, NI_NUMERICHOST); if (rv == 0) { resolverPtr->resolvedAddresses_.push_back(addrstring); } } ares_freeaddrinfo(result); if (resolverPtr->resolvedAddresses_.empty()) { resolverPtr->error_ = "no address returned or address conversion failed"; resolverPtr->status_ = AsyncNameResolver::STATUS_ERROR; } else { resolverPtr->status_ = AsyncNameResolver::STATUS_SUCCESS; } } namespace { void sock_state_cb(void* arg, ares_socket_t fd, int read, int write) { auto resolver = static_cast<AsyncNameResolver*>(arg); resolver->handle_sock_state(fd, read, write); } } // namespace void AsyncNameResolver::handle_sock_state(ares_socket_t fd, int read, int write) { int events = 0; if (read) { events |= EventPoll::EVENT_READ; } if (write) { events |= EventPoll::EVENT_WRITE; } auto it = std::find_if( std::begin(socks_), std::end(socks_), [fd](const AsyncNameResolverSocketEntry& ent) { return ent.fd == fd; }); if (it == std::end(socks_)) { if (!events) { return; } socks_.emplace_back(AsyncNameResolverSocketEntry{fd, events}); return; } if (!events) { socks_.erase(it); return; } (*it).events = events; } AsyncNameResolver::AsyncNameResolver(int family, const std::string& servers) : status_(STATUS_READY), family_(family) { ares_options opts{}; opts.sock_state_cb = sock_state_cb; opts.sock_state_cb_data = this; // TODO evaluate return value ares_init_options(&channel_, &opts, ARES_OPT_SOCK_STATE_CB); if (!servers.empty()) { if (ares_set_servers_csv(channel_, servers.c_str()) != ARES_SUCCESS) { A2_LOG_DEBUG("ares_set_servers_csv failed"); } } } AsyncNameResolver::~AsyncNameResolver() { ares_destroy(channel_); } void AsyncNameResolver::resolve(const std::string& name) { hostname_ = name; status_ = STATUS_QUERYING; ares_addrinfo_hints hints{}; hints.ai_family = family_; ares_getaddrinfo(channel_, name.c_str(), nullptr, &hints, callback, this); } ares_socket_t AsyncNameResolver::getFds(fd_set* rfdsPtr, fd_set* wfdsPtr) const { ares_socket_t nfds = 0; for (const auto& ent : socks_) { if (ent.events & EventPoll::EVENT_READ) { FD_SET(ent.fd, rfdsPtr); nfds = std::max(nfds, ent.fd + 1); } if (ent.events & EventPoll::EVENT_WRITE) { FD_SET(ent.fd, wfdsPtr); nfds = std::max(nfds, ent.fd + 1); } } return nfds; } void AsyncNameResolver::process(fd_set* rfdsPtr, fd_set* wfdsPtr) { for (const auto& ent : socks_) { ares_socket_t readfd = ARES_SOCKET_BAD; ares_socket_t writefd = ARES_SOCKET_BAD; if (FD_ISSET(ent.fd, rfdsPtr) && (ent.events & EventPoll::EVENT_READ)) { readfd = ent.fd; } if (FD_ISSET(ent.fd, wfdsPtr) && (ent.events & EventPoll::EVENT_WRITE)) { writefd = ent.fd; } if (readfd != ARES_SOCKET_BAD || writefd != ARES_SOCKET_BAD) { process(readfd, writefd); } } } #ifdef HAVE_LIBCARES const std::vector<AsyncNameResolverSocketEntry>& AsyncNameResolver::getsock() const { return socks_; } void AsyncNameResolver::process(ares_socket_t readfd, ares_socket_t writefd) { ares_process_fd(channel_, readfd, writefd); } #endif // HAVE_LIBCARES bool AsyncNameResolver::operator==(const AsyncNameResolver& resolver) const { return this == &resolver; } } // namespace aria2
5,667
C++
.cc
169
30.260355
80
0.704375
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,196
DHTGetPeersMessage.cc
aria2_aria2/src/DHTGetPeersMessage.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "DHTGetPeersMessage.h" #include <cstring> #include <array> #include "DHTNode.h" #include "DHTRoutingTable.h" #include "DHTMessageFactory.h" #include "DHTMessageDispatcher.h" #include "DHTMessageCallback.h" #include "DHTPeerAnnounceStorage.h" #include "Peer.h" #include "DHTTokenTracker.h" #include "DHTGetPeersReplyMessage.h" #include "util.h" #include "BtRegistry.h" #include "DownloadContext.h" #include "Option.h" #include "SocketCore.h" namespace aria2 { const std::string DHTGetPeersMessage::GET_PEERS("get_peers"); const std::string DHTGetPeersMessage::INFO_HASH("info_hash"); DHTGetPeersMessage::DHTGetPeersMessage( const std::shared_ptr<DHTNode>& localNode, const std::shared_ptr<DHTNode>& remoteNode, const unsigned char* infoHash, const std::string& transactionID) : DHTQueryMessage{localNode, remoteNode, transactionID}, peerAnnounceStorage_{nullptr}, tokenTracker_{nullptr}, btRegistry_{nullptr}, family_{AF_INET} { memcpy(infoHash_, infoHash, DHT_ID_LENGTH); } void DHTGetPeersMessage::addLocalPeer(std::vector<std::shared_ptr<Peer>>& peers) { if (!btRegistry_) { return; } auto& dctx = btRegistry_->getDownloadContext( std::string(infoHash_, infoHash_ + DHT_ID_LENGTH)); if (!dctx) { return; } auto group = dctx->getOwnerRequestGroup(); auto& option = group->getOption(); auto& externalIP = option->get(PREF_BT_EXTERNAL_IP); if (externalIP.empty()) { return; } std::array<uint8_t, sizeof(struct in6_addr)> dst; if (inetPton(family_, externalIP.c_str(), dst.data()) == -1) { return; } auto tcpPort = btRegistry_->getTcpPort(); if (std::find_if(std::begin(peers), std::end(peers), [&externalIP, tcpPort](const std::shared_ptr<Peer>& peer) { return peer->getIPAddress() == externalIP && peer->getPort() == tcpPort; }) != std::end(peers)) { return; } peers.push_back(std::make_shared<Peer>(externalIP, tcpPort)); } void DHTGetPeersMessage::doReceivedAction() { std::string token = tokenTracker_->generateToken( infoHash_, getRemoteNode()->getIPAddress(), getRemoteNode()->getPort()); std::vector<std::shared_ptr<Peer>> peers; peerAnnounceStorage_->getPeers(peers, infoHash_); // Check to see localhost has the contents which has same infohash addLocalPeer(peers); std::vector<std::shared_ptr<DHTNode>> nodes; getRoutingTable()->getClosestKNodes(nodes, infoHash_); getMessageDispatcher()->addMessageToQueue( getMessageFactory()->createGetPeersReplyMessage( getRemoteNode(), std::move(nodes), std::move(peers), token, getTransactionID())); } std::unique_ptr<Dict> DHTGetPeersMessage::getArgument() { auto aDict = Dict::g(); aDict->put(DHTMessage::ID, String::g(getLocalNode()->getID(), DHT_ID_LENGTH)); aDict->put(INFO_HASH, String::g(infoHash_, DHT_ID_LENGTH)); return aDict; } const std::string& DHTGetPeersMessage::getMessageType() const { return GET_PEERS; } void DHTGetPeersMessage::setPeerAnnounceStorage(DHTPeerAnnounceStorage* storage) { peerAnnounceStorage_ = storage; } void DHTGetPeersMessage::setTokenTracker(DHTTokenTracker* tokenTracker) { tokenTracker_ = tokenTracker; } void DHTGetPeersMessage::setBtRegistry(BtRegistry* btRegistry) { btRegistry_ = btRegistry; } void DHTGetPeersMessage::setFamily(int family) { family_ = family; } std::string DHTGetPeersMessage::toStringOptional() const { return "info_hash=" + util::toHex(infoHash_, INFO_HASH_LENGTH); } } // namespace aria2
5,187
C++
.cc
140
33.828571
80
0.733174
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
1,233
gettext.h
aria2_aria2/lib/gettext.h
/* Convenience header for conditional use of GNU <libintl.h>. Copyright (C) 1995-1998, 2000-2002 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _LIBGETTEXT_H #define _LIBGETTEXT_H 1 /* NLS can be disabled through the configure --disable-nls option. */ #if ENABLE_NLS /* Get declarations of GNU message catalog functions. */ # include <libintl.h> #else /* Solaris /usr/include/locale.h includes /usr/include/libintl.h, which chokes if dcgettext is defined as a macro. So include it now, to make later inclusions of <locale.h> a NOP. We don't include <libintl.h> as well because people using "gettext.h" will not include <libintl.h>, and also including <libintl.h> would fail on SunOS 4, whereas <locale.h> is OK. */ #if defined(__sun) # include <locale.h> #endif /* Disabled NLS. The casts to 'const char *' serve the purpose of producing warnings for invalid uses of the value returned from these functions. On pre-ANSI systems without 'const', the config.h file is supposed to contain "#define const". */ # define gettext(Msgid) ((const char *) (Msgid)) # define dgettext(Domainname, Msgid) ((const char *) (Msgid)) # define dcgettext(Domainname, Msgid, Category) ((const char *) (Msgid)) # define ngettext(Msgid1, Msgid2, N) \ ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) # define dngettext(Domainname, Msgid1, Msgid2, N) \ ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) # define dcngettext(Domainname, Msgid1, Msgid2, N, Category) \ ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) # define textdomain(Domainname) ((const char *) (Domainname)) # define bindtextdomain(Domainname, Dirname) ((const char *) (Dirname)) # define bind_textdomain_codeset(Domainname, Codeset) ((const char *) (Codeset)) #endif /* A pseudo function call that serves as a marker for the automated extraction of messages, but does not call gettext(). The run-time translation is done at a different place in the code. The argument, String, should be a literal string. Concatenated strings and other string expressions won't work. The macro's expansion is not parenthesized, so that it is suitable as initializer for static 'char[]' or 'const char[]' variables. */ #define gettext_noop(String) String #endif /* _LIBGETTEXT_H */
3,049
C++
.h
57
50.596491
80
0.729195
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
true
false
false
1,261
getaddrinfo.h
aria2_aria2/src/getaddrinfo.h
/* * Copyright (c) 2001, 02 Motoyuki Kasahara * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _D_GETADDRINFO_H #define _D_GETADDRINFO_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef __MINGW32__ # undef SIZE_MAX #endif // __MINGW32__ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #ifdef __MINGW32__ # ifndef _WIN32_WINNT # define _WIN32_WINNT 0x501 # endif // _WIN32_WINNT # include <winsock2.h> # undef ERROR # include <ws2tcpip.h> #endif // __MINGW32__ #ifdef HAVE_SYS_SOCKET_H # include <sys/socket.h> #endif // HAVE_SYS_SOCKET_H #ifdef HAVE_NETDB_H # include <netdb.h> #endif // HAVE_NETDB_H #include <sys/types.h> /********************************************************************/ /* * Undefine all the macros. * <netdb.h> might defines some of them. */ #ifdef EAI_ADDRFAMILY # undef EAI_ADDRFAMILY #endif #ifdef EAI_AGAIN # undef EAI_AGAIN #endif #ifdef EAI_BADFLAGS # undef EAI_BADFLAGS #endif #ifdef EAI_FAIL # undef EAI_FAIL #endif #ifdef EAI_FAMILY # undef EAI_FAMILY #endif #ifdef EAI_MEMORY # undef EAI_MEMORY #endif #ifdef EAI_NONAME # undef EAI_NONAME #endif #ifdef EAI_OVERFLOW # undef EAI_OVERFLOW #endif #ifdef EAI_SERVICE # undef EAI_SERVICE #endif #ifdef EAI_SOCKTYPE # undef EAI_SOCKTYPE #endif #ifdef EAI_SYSTEM # undef EAI_SYSTEM #endif #ifdef AI_PASSIVE # undef AI_PASSIVE #endif #ifdef AI_CANONNAME # undef AI_CANONNAME #endif #ifdef AI_NUMERICHOST # undef AI_NUMERICHOST #endif #ifdef AI_NUMERICSERV # undef AI_NUMERICSERV #endif #ifdef AI_V4MAPPED # undef AI_V4MAPPED #endif #ifdef AI_ALL # undef AI_ALL #endif #ifdef AI_ADDRCONFIG # undef AI_ADDRCONFIG #endif #ifdef AI_DEFAULT # undef AI_DEFAULT #endif #ifdef NI_NOFQDN # undef NI_NOFQDN #endif #ifdef NI_NUMERICHOST # undef NI_NUMERICHOST #endif #ifdef NI_NAMEREQD # undef NI_NAMEREQD #endif #ifdef NI_NUMERICSERV # undef NI_NUMERICSERV #endif #ifdef NI_NUMERICSCOPE # undef NI_NUMERICSCOPE #endif #ifdef NI_DGRAM # undef NI_DGRAM #endif #ifdef NI_MAXHOST # undef NI_MAXHOST #endif #ifdef NI_MAXSERV # undef NI_MAXSERV #endif /* * Fake struct and function names. * <netdb.h> might declares all or some of them. */ #if defined(HAVE_GETADDRINFO) || defined(HAVE_GETNAMEINFO) # define addrinfo my_addrinfo # define gai_strerror my_gai_strerror # define freeaddrinfo my_freeaddrinfo # define getaddrinfo my_getaddrinfo # define getnameinfo my_getnameinfo #endif /* <from linux's netdb.h> */ /* Possible values for `ai_flags' field in `addrinfo' structure. */ #define AI_PASSIVE 0x0001 /* Socket address is intended for `bind'. */ #define AI_CANONNAME 0x0002 /* Request for canonical name. */ #define AI_NUMERICHOST 0x0004 /* Don't use name resolution. */ #define AI_V4MAPPED 0x0008 /* IPv4 mapped addresses are acceptable. */ #define AI_ALL 0x0010 /* Return IPv4 mapped and IPv6 addresses. */ #define AI_ADDRCONFIG \ 0x0020 /* Use configuration of this host to choose \ returned address type.. */ #ifdef __USE_GNU # define AI_IDN \ 0x0040 /* IDN encode input (assuming it is encoded \ in the current locale's character set) \ before looking it up. */ # define AI_CANONIDN 0x0080 /* Translate canonical name from IDN format. */ # define AI_IDN_ALLOW_UNASSIGNED \ 0x0100 /* Don't reject unassigned Unicode \ code points. */ # define AI_IDN_USE_STD3_ASCII_RULES \ 0x0200 /* Validate strings according to \ STD3 rules. */ #endif #define AI_NUMERICSERV 0x0400 /* Don't use name resolution. */ /* Error values for `getaddrinfo' function. */ #define EAI_BADFLAGS -1 /* Invalid value for `ai_flags' field. */ #define EAI_NONAME -2 /* NAME or SERVICE is unknown. */ #define EAI_AGAIN -3 /* Temporary failure in name resolution. */ #define EAI_FAIL -4 /* Non-recoverable failure in name res. */ #define EAI_NODATA -5 /* No address associated with NAME. */ #define EAI_FAMILY -6 /* `ai_family' not supported. */ #define EAI_SOCKTYPE -7 /* `ai_socktype' not supported. */ #define EAI_SERVICE -8 /* SERVICE not supported for `ai_socktype'. */ #define EAI_ADDRFAMILY -9 /* Address family for NAME not supported. */ #define EAI_MEMORY -10 /* Memory allocation failure. */ #define EAI_SYSTEM -11 /* System error returned in `errno'. */ #define EAI_OVERFLOW -12 /* Argument buffer overflow. */ #ifdef __USE_GNU # define EAI_INPROGRESS -100 /* Processing request in progress. */ # define EAI_CANCELED -101 /* Request canceled. */ # define EAI_NOTCANCELED -102 /* Request not canceled. */ # define EAI_ALLDONE -103 /* All requests done. */ # define EAI_INTR -104 /* Interrupted by a signal. */ # define EAI_IDN_ENCODE -105 /* IDN encoding failed. */ #endif #define NI_MAXHOST 1025 #define NI_MAXSERV 32 #define NI_NUMERICHOST 1 /* Don't try to look up hostname. */ #define NI_NUMERICSERV 2 /* Don't convert port number to name. */ #define NI_NOFQDN 4 /* Only return nodename portion. */ #define NI_NAMEREQD 8 /* Don't return numeric addresses. */ #define NI_DGRAM 16 /* Look up UDP service rather than TCP. */ #ifdef __USE_GNU # define NI_IDN 32 /* Convert name from IDN format. */ # define NI_IDN_ALLOW_UNASSIGNED \ 64 /* Don't reject unassigned Unicode \ code points. */ # define NI_IDN_USE_STD3_ASCII_RULES \ 128 /* Validate strings according to \ STD3 rules. */ #endif /* </from linux's netdb.h> */ #define AI_DEFAULT (AI_V4MAPPED | AI_ADDRCONFIG) /* * Address families and Protocol families. */ #ifndef AF_UNSPEC # define AF_UNSPEC AF_INET #endif #ifndef PF_UNSPEC # define PF_UNSPEC PF_INET #endif /* Nexenta OS(GNU/Solaris OS) defines `struct addrinfo' in netdb.h */ #if !defined(__MINGW32__) && !defined(__sun) /* * struct addrinfo. */ struct addrinfo { int ai_flags; int ai_family; int ai_socktype; int ai_protocol; socklen_t ai_addrlen; char* ai_canonname; struct sockaddr* ai_addr; struct addrinfo* ai_next; }; #endif // !__MINGW32__ && !__sun /* * Functions. */ #ifdef __STDC__ const char* gai_strerror(int); void freeaddrinfo(struct addrinfo*); int getaddrinfo(const char*, const char*, const struct addrinfo*, struct addrinfo**); int getnameinfo(const struct sockaddr*, socklen_t, char*, socklen_t, char*, socklen_t, int); #else const char* gai_strerror(); void freeaddrinfo(); int getaddrinfo(); int getnameinfo(); #endif #ifdef __cplusplus }; #endif /* __cplusplus */ #endif /* not _D_GETADDRINFO_H */
8,569
C++
.h
258
31.217054
80
0.666828
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,276
timespec.h
aria2_aria2/src/timespec.h
/* * aria2 - The high speed download utility * * Copyright (C) 2010 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_TIMESPEC_H #define D_TIMESPEC_H #include "common.h" #include <time.h> struct timespec { time_t tv_sec; long tv_nsec; }; #endif // D_TIMESPEC_H
1,736
C++
.h
42
39.404762
79
0.760947
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,307
a2netcompat.h
aria2_aria2/src/a2netcompat.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_A2NETCOMPAT_H #define D_A2NETCOMPAT_H #include "a2io.h" #ifdef __MINGW32__ # ifdef HAVE_WS2TCPIP_H # include <ws2tcpip.h> # endif // HAVE_WS2TCPIP_H #endif // __MINGW32__ #ifdef __MINGW32__ # define a2_sockopt_t char* # ifndef HAVE_GETADDRINFO # define HAVE_GETADDRINFO # endif // !HAVE_GETADDRINFO # undef HAVE_GAI_STRERROR # undef gai_strerror #else # define a2_sockopt_t void* #endif // __MINGW32__ #ifdef HAVE_NETDB_H # include <netdb.h> #endif // HAVE_NETDB_H #ifdef HAVE_SYS_SOCKET_H # include <sys/socket.h> #endif // HAVE_SYS_SOCKET_H #ifdef HAVE_NETINET_IN_H # include <netinet/in.h> #endif // HAVE_NETINET_IN_H #ifdef HAVE_NETINET_TCP_H # include <netinet/tcp.h> #endif // HAVE_NETINET_TCP_H #ifdef HAVE_ARPA_INET_H # include <arpa/inet.h> #endif // HAVE_ARPA_INET_H #ifdef HAVE_NETINET_IN_H # include <netinet/in.h> #endif // HAVE_NETINET_IN_H #ifdef HAVE_SYS_UIO_H # include <sys/uio.h> #endif // HAVE_SYS_UIO_H #ifndef HAVE_GETADDRINFO # include "getaddrinfo.h" # define HAVE_GAI_STRERROR #endif // HAVE_GETADDRINFO #ifndef HAVE_GAI_STRERROR # include "gai_strerror.h" #endif // HAVE_GAI_STRERROR #include <string> #ifdef HAVE_WINSOCK2_H # define sock_t SOCKET #else # define sock_t int #endif #ifndef AI_ADDRCONFIG # define AI_ADDRCONFIG 0 #endif // !AI_ADDRCONFIG #define DEFAULT_AI_FLAGS AI_ADDRCONFIG #ifdef __MINGW32__ # ifndef SHUT_WR # define SHUT_WR SD_SEND # endif // !SHUT_WR #endif // __MINGW32__ union sockaddr_union { sockaddr sa; sockaddr_storage storage; sockaddr_in6 in6; sockaddr_in in; }; struct SockAddr { sockaddr_union su; socklen_t suLength; }; // Human readable address, family and port. In other words, addr is // text name, usually obtained from getnameinfo(3). The family field // is the protocol family if it is known when generating this object. // If it is unknown, this is AF_UNSPEC. struct Endpoint { std::string addr; int family; uint16_t port; }; #define A2_DEFAULT_IOV_MAX 128 #if defined(IOV_MAX) && IOV_MAX < A2_DEFAULT_IOV_MAX # define A2_IOV_MAX IOV_MAX #else # define A2_IOV_MAX A2_DEFAULT_IOV_MAX #endif #ifdef __MINGW32__ typedef WSABUF a2iovec; # define A2IOVEC_BASE buf # define A2IOVEC_LEN len #else // !__MINGW32__ typedef struct iovec a2iovec; # define A2IOVEC_BASE iov_base # define A2IOVEC_LEN iov_len #endif // !__MINGW32__ #endif // D_A2NETCOMPAT_H
4,004
C++
.h
130
29.238462
79
0.743117
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,316
Platform.h
aria2_aria2/src/Platform.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_PLATFORM_H #define D_PLATFORM_H #include "common.h" #ifdef HAVE_OPENSSL # include <openssl/opensslv.h> # if OPENSSL_VERSION_NUMBER >= 0x30000000L # include <openssl/provider.h> # endif // OPENSSL_VERSION_NUMBER >= 0x30000000L #endif // HAVE_OPENSSL namespace aria2 { class Platform { private: static bool initialized_; #ifdef HAVE_OPENSSL # if OPENSSL_VERSION_NUMBER >= 0x30000000L static OSSL_PROVIDER* legacy_provider_; static OSSL_PROVIDER* default_provider_; # endif // OPENSSL_VERSION_NUMBER >= 0x30000000L #endif // HAVE_OPENSSL public: Platform(); ~Platform(); static bool setUp(); static bool tearDown(); static bool isInitialized(); }; } // namespace aria2 #endif // D_PLATFORM_H
2,335
C++
.h
62
35.709677
79
0.75586
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,323
localtime_r.h
aria2_aria2/src/localtime_r.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2007 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef _D_LOCALTIME_R_H #define _D_LOCALTIME_R_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include <time.h> #undef localtime_r struct tm* localtime_r(const time_t* clock, struct tm* result); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* not _D_LOCALTIME_R_H */
1,891
C++
.h
46
39.282609
79
0.75136
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,354
gai_strerror.h
aria2_aria2/src/gai_strerror.h
/* * Copyright (c) 2001, 02 Motoyuki Kasahara * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _D_GAI_STRERROR_H #define _D_GAI_STRERROR_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef __MINGW32__ # undef SIZE_MAX #endif // __MINGW32__ #ifndef EAI_SYSTEM # define EAI_SYSTEM -11 /* System error returned in `errno'. */ #endif #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H /* * Fake struct and function names. * <netdb.h> might declares all or some of them. */ #if defined(HAVE_GAI_STRERROR) # define gai_strerror my_gai_strerror #endif /* * Functions. */ #ifdef __STDC__ const char* gai_strerror(int); #else const char* gai_strerror(); #endif #ifdef __cplusplus }; #endif /* __cplusplus */ #endif /* not _D_GAI_STRERROR_H */
2,233
C++
.h
60
35.55
77
0.754621
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
1,420
a2io.h
aria2_aria2/src/a2io.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_A2IO_H #define D_A2IO_H #include "common.h" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <cerrno> #ifdef HAVE_POLL_H # include <poll.h> #endif // HAVE_POLL_H #ifdef HAVE_IO_H # include <io.h> #endif // HAVE_IO_H #ifdef HAVE_WINIOCTL_H # include <winioctl.h> #endif // HAVE_WINIOCTL_H #ifdef HAVE_SHARE_H # include <share.h> #endif // HAVE_SHARE_H // in some platforms following definitions are missing: #ifndef EINPROGRESS # define EINPROGRESS (WSAEINPROGRESS) #endif // EINPROGRESS #ifndef O_NONBLOCK # define O_NONBLOCK (O_NDELAY) #endif // O_NONBLOCK #ifndef O_BINARY # define O_BINARY (0) #endif // O_BINARY // st_mode flags #ifndef S_IRUSR # define S_IRUSR 0000400 /* read permission, owner */ #endif /* S_IRUSR */ #ifndef S_IWUSR # define S_IWUSR 0000200 /* write permission, owner */ #endif /* S_IWUSR */ #ifndef S_IXUSR # define S_IXUSR 0000100 /* execute/search permission, owner */ #endif /* S_IXUSR */ #ifndef S_IRWXU # define S_IRWXU (S_IRUSR | S_IWUSR | S_IXUSR) #endif /* S_IRWXU */ #ifndef S_IRGRP # define S_IRGRP 0000040 /* read permission, group */ #endif /* S_IRGRP */ #ifndef S_IWGRP # define S_IWGRP 0000020 /* write permission, group */ #endif /* S_IWGRP */ #ifndef S_IXGRP # define S_IXGRP 0000010 /* execute/search permission, group */ #endif /* S_IXGRP */ #ifndef S_IRWXG # define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP) #endif /* S_IRWXG */ #ifndef S_IROTH # define S_IROTH 0000004 /* read permission, other */ #endif /* S_IROTH */ #ifndef S_IWOTH # define S_IWOTH 0000002 /* write permission, other */ #endif /* S_IWOTH */ #ifndef S_IXOTH # define S_IXOTH 0000001 /* execute/search permission, other */ #endif /* S_IXOTH */ #ifndef S_IRWXO # define S_IRWXO (S_IROTH | S_IWOTH | S_IXOTH) #endif /* S_IRWXO */ // Use 'nul' instead of /dev/null in win32. #ifdef HAVE_WINSOCK2_H # define DEV_NULL "nul" #else # define DEV_NULL "/dev/null" #endif // HAVE_WINSOCK2_H // Use 'con' instead of '/dev/stdin' and '/dev/stdout' in win32. #ifdef HAVE_WINSOCK2_H # define DEV_STDIN "con" # define DEV_STDOUT "con" #else # define DEV_STDIN "/dev/stdin" # define DEV_STDOUT "/dev/stdout" #endif // HAVE_WINSOCK2_H #ifdef __MINGW32__ # define a2lseek(fd, offset, origin) _lseeki64(fd, offset, origin) # define a2fseek(fd, offset, origin) _fseeki64(fd, offset, origin) # define a2fstat(fd, buf) _fstati64(fd, buf) # define a2ftell(fd) _ftelli64(fd) # define a2wstat(path, buf) _wstati64(path, buf) # ifdef stat # undef stat # endif // stat # define a2_struct_stat struct _stati64 # define a2stat(path, buf) _wstati64(path, buf) # define a2tell(handle) _telli64(handle) # define a2mkdir(path, openMode) _wmkdir(path) # define a2utimbuf _utimbuf # define a2utime(path, times) _wutime(path, times) # define a2unlink(path) _wunlink(path) # define a2rmdir(path) _wrmdir(path) // For Windows, we share files for reading and writing. # define a2open(path, flags, mode) _wsopen(path, flags, _SH_DENYNO, mode) # define a2fopen(path, mode) _wfsopen(path, mode, _SH_DENYNO) // # define a2ftruncate(fd, length): We don't use ftruncate in Mingw build # define a2_off_t off_t #elif defined(__ANDROID__) || defined(ANDROID) # define a2lseek(fd, offset, origin) lseek64(fd, offset, origin) // # define a2fseek(fp, offset, origin): No fseek64 and not used in aria2 # define a2fstat(fd, buf) fstat64(fd, buf) // # define a2ftell(fd): No ftell64 and not used in aria2 # define a2_struct_stat struct stat64 # define a2stat(path, buf) stat64(path, buf) # define a2mkdir(path, openMode) mkdir(path, openMode) # define a2utimbuf utimbuf # define a2utime(path, times) ::utime(path, times) # define a2unlink(path) unlink(path) # define a2rmdir(path) rmdir(path) # define a2open(path, flags, mode) open(path, flags, mode) # define a2fopen(path, mode) fopen(path, mode) // Android NDK R8e does not provide ftruncate64 prototype, so let's // define it here. # ifdef __cplusplus extern "C" { # endif extern int ftruncate64(int fd, off64_t length); # ifdef __cplusplus } # endif # define a2ftruncate(fd, length) ftruncate64(fd, length) // Use off64_t directly since android does not offer transparent // switching between off_t and off64_t. # define a2_off_t off64_t #else // !__MINGW32__ && !(defined(__ANDROID__) || defined(ANDROID)) # define a2lseek(fd, offset, origin) lseek(fd, offset, origin) # define a2fseek(fp, offset, origin) fseek(fp, offset, origin) # define a2fstat(fp, buf) fstat(fp, buf) # define a2ftell(fp) ftell(fp) # define a2_struct_stat struct stat # define a2stat(path, buf) stat(path, buf) # define a2mkdir(path, openMode) mkdir(path, openMode) # define a2utimbuf utimbuf # define a2utime(path, times) ::utime(path, times) # define a2unlink(path) unlink(path) # define a2rmdir(path) rmdir(path) # define a2open(path, flags, mode) open(path, flags, mode) # define a2fopen(path, mode) fopen(path, mode) # define a2ftruncate(fd, length) ftruncate(fd, length) # define a2_off_t off_t #endif #define OPEN_MODE S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH #define DIR_OPEN_MODE S_IRWXU | S_IRWXG | S_IRWXO #ifdef __MINGW32__ # define A2_BAD_FD INVALID_HANDLE_VALUE #else // !__MINGW32__ # define A2_BAD_FD -1 #endif // !__MINGW32__ #endif // D_A2IO_H
7,143
C++
.h
189
36.57672
79
0.699741
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,435
message.h
aria2_aria2/src/message.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_MESSAGE_H #define D_MESSAGE_H #include "common.h" // clang-format off #define MSG_SEGMENT_DOWNLOAD_COMPLETED \ "CUID#%" PRId64 " - The download for one segment completed successfully." #define MSG_NO_SEGMENT_AVAILABLE "CUID#%" PRId64 " - No segment available." #define MSG_CONNECTING_TO_SERVER "CUID#%" PRId64 " - Connecting to %s:%d" #define MSG_REDIRECT "CUID#%" PRId64 " - Redirecting to %s" #define MSG_SENDING_REQUEST "CUID#%" PRId64 " - Requesting:\n%s" #define MSG_RECEIVE_RESPONSE "CUID#%" PRId64 " - Response received:\n%s" #define MSG_DOWNLOAD_ABORTED "CUID#%" PRId64 " - Download aborted. URI=%s" #define MSG_RESTARTING_DOWNLOAD "CUID#%" PRId64 " - Restarting the download. URI=%s" #define MSG_TORRENT_DOWNLOAD_ABORTED "CUID#%" PRId64 " - Download aborted." #define MSG_MAX_TRY \ "CUID#%" PRId64 " - %d times attempted, but no success. Download aborted." #define MSG_SEND_PEER_MESSAGE "CUID#%" PRId64 " - To: %s:%d %s" #define MSG_RECEIVE_PEER_MESSAGE "CUID#%" PRId64 " - From: %s:%d %s" #define MSG_GOT_NEW_PIECE "CUID#%" PRId64 " - we got new piece. index=%lu" #define MSG_GOT_WRONG_PIECE "CUID#%" PRId64 " - we got wrong piece. index=%lu" #define MSG_DOWNLOAD_NOT_COMPLETE "CUID#%" PRId64 " - Download not complete: %s" #define MSG_DOWNLOAD_ALREADY_COMPLETED _("GID#%s - Download has already completed: %s") #define MSG_RESOLVING_HOSTNAME "CUID#%" PRId64 " - Resolving hostname %s" #define MSG_NAME_RESOLUTION_COMPLETE \ "CUID#%" PRId64 " - Name resolution complete: %s -> %s" #define MSG_NAME_RESOLUTION_FAILED \ "CUID#%" PRId64 " - Name resolution for %s failed:%s" #define MSG_DNS_CACHE_HIT "CUID#%" PRId64 " - DNS cache hit: %s -> %s" #define MSG_CONNECTING_TO_PEER "CUID#%" PRId64 " - Connecting to the peer %s" #define MSG_PIECE_RECEIVED \ "CUID#%" PRId64 " - Piece received. index=%lu, begin=%d, length=%d, offset=%" PRId64 "," \ " blockIndex=%lu" #define MSG_PIECE_BITFIELD "CUID#%" PRId64 " - Piece bitfield %s" #define MSG_REJECT_PIECE_CHOKED \ "CUID#%" PRId64 " - Reject piece message in queue because the peer has been" \ " choked. index=%lu, begin=%d, length=%d" #define MSG_REJECT_PIECE_CANCEL \ "CUID#%" PRId64 " - Reject piece message in queue because cancel message received." \ " index=%lu, begin=%d, length=%d" #define MSG_FILE_VALIDATION_FAILURE \ "CUID#%" PRId64 " - Exception caught while validating file integrity." #define MSG_PEER_INTERESTED "CUID#%" PRId64 " - Interested in the peer" #define MSG_PEER_NOT_INTERESTED "CUID#%" PRId64 " - Not interested in the peer" #define MSG_DELETING_REQUEST_SLOT "CUID#%" PRId64 " - Deleting request slot" \ " index=%lu, begin=%d, blockIndex=%lu" #define MSG_DELETING_REQUEST_SLOT_CHOKED "CUID#%" PRId64 " - Deleting request slot" \ " index=%lu, begin=%d, blockIndex=%lu because localhost got choked." #define MSG_DELETING_REQUEST_SLOT_TIMEOUT "CUID#%" PRId64 " - Deleting request slot" \ " index=%lu, begin=%d, blockIndex=%lu because of time out" #define MSG_DELETING_REQUEST_SLOT_ACQUIRED "CUID#%" PRId64 " - Deleting request slot" \ " index=%lu, begin=%d, blockIndex=%lu because the block has been acquired." #define MSG_FAST_EXTENSION_ENABLED "CUID#%" PRId64 " - Fast extension enabled." #define MSG_EXTENDED_MESSAGING_ENABLED "CUID#%" PRId64 " - Extended Messaging enabled." #define MSG_FILE_ALLOCATION_FAILURE \ "CUID#%" PRId64 " - Exception caught while allocating file space." #define MSG_CONTENT_DISPOSITION_DETECTED \ "CUID#%" PRId64 " - Content-Disposition detected. Use %s as filename" #define MSG_PEER_BANNED "CUID#%" PRId64 " - Peer %s:%d banned." #define MSG_LISTENING_PORT \ "CUID#%" PRId64 " - Using port %d for accepting new connections" #define MSG_BIND_FAILURE "CUID#%" PRId64 " - An error occurred while binding port=%d" #define MSG_INCOMING_PEER_CONNECTION \ "CUID#%" PRId64 " - Incoming connection, adding new command CUID#%" PRId64 "" #define MSG_ACCEPT_FAILURE "CUID#%" PRId64 " - Error in accepting connection" #define MSG_TRACKER_RESPONSE_PROCESSING_FAILED \ "CUID#%" PRId64 " - Error occurred while processing tracker response." #define MSG_DHT_ENABLED_PEER "CUID#%" PRId64 " - The peer is DHT-enabled." #define MSG_CONNECT_FAILED_AND_RETRY \ "CUID#%" PRId64 " - Could not to connect to %s:%u. Trying another address" #define MSG_UNRECOGNIZED_URI _("Unrecognized URI or unsupported protocol: %s") #define MSG_TRACKER_WARNING_MESSAGE _("Tracker returned warning message: %s") #define MSG_SEGMENT_FILE_EXISTS _("The segment file %s exists.") #define MSG_SEGMENT_FILE_DOES_NOT_EXIST _("The segment file %s does not exist.") #define MSG_SAVING_SEGMENT_FILE _("Saving the segment file %s") #define MSG_SAVED_SEGMENT_FILE _("The segment file was saved successfully.") #define MSG_LOADING_SEGMENT_FILE _("Loading the segment file %s.") #define MSG_LOADED_SEGMENT_FILE _("The segment file was loaded successfully.") #define MSG_NO_URL_TO_DOWNLOAD _("No URI to download. Download aborted.") #define MSG_FILE_ALREADY_EXISTS _("File %s exists, but a control file(*.aria2) does not exist. Download was canceled in order to prevent your file from being truncated to 0. If you are sure to download the file all over again, then delete it or add --allow-overwrite=true option and restart aria2.") #define MSG_ALLOCATING_FILE _("Allocating file %s, %s bytes") #define MSG_FILE_NOT_FOUND _("File not found") #define MSG_NOT_DIRECTORY _("Not a directory") #define MSG_INSUFFICIENT_CHECKSUM _("Insufficient checksums. checksumLength=%d, numChecksum=%d") #define MSG_WRITING_FILE _("Writing file %s") #define MSG_NO_PEER_LIST_RECEIVED _("No peer list received.") #define MSG_ADDING_PEER _("Adding peer %s:%d") #define MSG_DELETING_USED_PIECE _("Deleting used piece index=%d, fillRate(%%)=%d<=%d") #define MSG_SELECTIVE_DOWNLOAD_COMPLETED _("Download of selected files was complete.") #define MSG_DOWNLOAD_COMPLETED _("The download was complete.") #define MSG_REMOVED_HAVE_ENTRY _("Removed %lu have entries.") #define MSG_VALIDATING_FILE _("Validating file %s") #define MSG_ALLOCATION_COMPLETED "%ld seconds to allocate %" PRId64 " byte(s)" #define MSG_FILE_ALLOCATION_DISPATCH \ "Dispatching FileAllocationCommand for CUID#%" PRId64 "." #define MSG_METALINK_QUEUEING _("Metalink: Queueing %s for download.") #define MSG_FILE_DOWNLOAD_COMPLETED _("Download complete: %s") #define MSG_SEEDING_END _("Seeding is over.") #define MSG_NO_CHUNK_CHECKSUM _("No chunk to verify.") #define MSG_GOOD_CHUNK_CHECKSUM _("Good chunk checksum. hash=%s") #define MSG_LOADING_COOKIE_FAILED _("Failed to load cookies from %s") #define MSG_INCORRECT_NETRC_PERMISSION _(".netrc file %s does not have correct permissions. It should be 600. netrc support disabled.") #define MSG_LOGGING_STARTED _("Logging started.") #define MSG_URI_REQUIRED _("Specify at least one URL.") #define MSG_DAEMON_FAILED _("daemon failed.") #define MSG_VERIFICATION_SUCCESSFUL _("Verification finished successfully. file=%s") #define MSG_VERIFICATION_FAILED _("Checksum error detected. file=%s") #define MSG_INCOMPLETE_RANGE _("Incomplete range specified. %s") #define MSG_STRING_INTEGER_CONVERSION_FAILURE _("Failed to convert string into value: %s") #define MSG_RESOURCE_NOT_FOUND _("Resource not found") #define MSG_FILE_RENAMED _("File already exists. Renamed to %s.") #define MSG_CANNOT_PARSE_METALINK _("Cannot parse metalink XML file. XML may be malformed.") #define MSG_TOO_SMALL_PAYLOAD_SIZE _("Too small payload size for %s, size=%lu.") #define MSG_REMOVED_DEFUNCT_CONTROL_FILE _("Removed the defunct control file %s because the download file %s doesn't exist.") #define MSG_SHARE_RATIO_REPORT _("Your share ratio was %.1f, uploaded/downloaded=%sB/%sB") #define MSG_MISSING_BT_INFO _("Missing %s in torrent metainfo.") #define MSG_NEGATIVE_LENGTH_BT_INFO _("%s does not allow negative integer %" PRId64 "") #define MSG_NULL_TRACKER_RESPONSE _("Tracker returned null data.") #define MSG_WINSOCK_INIT_FAILD _("Windows socket library initialization failed") #define MSG_TIME_HAS_PASSED _("%ld second(s) has passed. Stopping application.") #define MSG_SIGNATURE_SAVED _("Saved signature as %s. Please note that aria2" \ " doesn't verify signatures.") #define MSG_SIGNATURE_NOT_SAVED _("Saving signature as %s failed. Maybe file" \ " already exists.") #define MSG_OPENING_READABLE_SERVER_STAT_FILE_FAILED \ _("Failed to open ServerStat file %s for read.") #define MSG_SERVER_STAT_LOADED _("ServerStat file %s loaded successfully.") #define MSG_READING_SERVER_STAT_FILE_FAILED _("Failed to read ServerStat from" \ " %s.") #define MSG_OPENING_WRITABLE_SERVER_STAT_FILE_FAILED \ _("Failed to open ServerStat file %s for write.") #define MSG_SERVER_STAT_SAVED _("ServerStat file %s saved successfully.") #define MSG_WRITING_SERVER_STAT_FILE_FAILED _("Failed to write ServerStat to" \ " %s.") #define MSG_ESTABLISHING_CONNECTION_FAILED \ _("Failed to establish connection, cause: %s") #define MSG_NETWORK_PROBLEM _("Network problem has occurred. cause:%s") #define MSG_LOADING_SYSTEM_TRUSTED_CA_CERTS_FAILED \ _("Failed to load trusted CA certificates from system. Cause: %s") #define MSG_LOADING_TRUSTED_CA_CERT_FAILED \ _("Failed to load trusted CA certificates from %s. Cause: %s") #define MSG_CERT_VERIFICATION_FAILED \ _("Certificate verification failed. Cause: %s See --ca-certificate and" \ " --check-certificate option.") #define MSG_NO_CERT_FOUND _("No certificate found.") #define MSG_HOSTNAME_NOT_MATCH _("Hostname not match.") #define MSG_NO_FILES_TO_DOWNLOAD _("No files to download.") #define MSG_WARN_NO_CA_CERT \ _("You may encounter the certificate verification error with HTTPS server." \ " See --ca-certificate and --check-certificate option.") #define MSG_WARN_UNKNOWN_TLS_CONNECTION \ _("aria2c had to connect to the other side using an unknown TLS protocol. " \ "The integrity and confidentiality of the connection might be " \ "compromised.\nPeer: %s") #define MSG_WARN_OLD_TLS_CONNECTION \ _("aria2c had to connect to the other side using an old and vulnerable TLS" \ " protocol. The integrity and confidentiality of the connection might be" \ " compromised.\nProtocol: %s, Peer: %s") #define MSG_SHOW_FILES _("Printing the contents of file '%s'...") #define MSG_NOT_TORRENT_METALINK _("This file is neither Torrent nor Metalink" \ " file. Skipping.") #define MSG_GID_NOT_PROVIDED "GID is not provided." #define MSG_CANNOT_PARSE_XML_RPC_REQUEST "Failed to parse xml-rpc request." #define MSG_GOOD_BYE_SEEDER "Client is in seed state: Good Bye Seeder;)" #define MSG_NOT_FILE _("Is '%s' a file?") #define MSG_INTERFACE_NOT_FOUND _("Failed to find given interface %s," \ " cause: %s") #define MSG_METADATA_SAVED _("Saved metadata as %s.") #define MSG_METADATA_NOT_SAVED _("Saving metadata as %s failed. Maybe file" \ " already exists.") #define MSG_DIR_TRAVERSAL_DETECTED _("Detected directory traversal directive in %s") #define MSG_HASH_CHECK_NOT_DONE \ "File has already been downloaded but hash check has not been done yet." #define MSG_REMOVING_UNSELECTED_FILE _("GID#%s - Removing unselected file.") #define MSG_FILE_REMOVED _("File %s removed.") #define MSG_FILE_COULD_NOT_REMOVED _("File %s could not be removed.") #define EX_TIME_OUT _("Timeout.") #define EX_INVALID_CHUNK_SIZE _("Invalid chunk size.") #define EX_TOO_LARGE_CHUNK _("Too large chunk. size=%d") #define EX_INVALID_HEADER _("Invalid header.") #define EX_INVALID_RESPONSE _("Invalid response.") #define EX_NO_HEADER _("No header found.") #define EX_NO_STATUS_HEADER _("No status header.") #define EX_PROXY_CONNECTION_FAILED _("Proxy connection failed.") #define EX_CONNECTION_FAILED _("Connection failed.") #define EX_FILENAME_MISMATCH _("The requested filename and the previously registered one are not same. Expected:%s Actual:%s") #define EX_BAD_STATUS _("The response status is not successful. status=%d") #define EX_TOO_LARGE_FILE "Too large file size. size=%" PRId64 "" #define EX_TRANSFER_ENCODING_NOT_SUPPORTED _("Transfer encoding %s is not supported.") #define EX_SSL_INIT_FAILURE _("SSL initialization failed: %s") #define EX_SSL_IO_ERROR _("SSL I/O error") #define EX_SSL_PROTOCOL_ERROR _("SSL protocol error") #define EX_SSL_UNKNOWN_ERROR _("SSL unknown error %d") #define EX_SSL_CONNECT_ERROR _("SSL initialization failed: OpenSSL connect error %d") #define EX_SIZE_MISMATCH "Size mismatch Expected:%" PRId64 " Actual:%" PRId64 "" #define EX_AUTH_FAILED _("Authorization failed.") #define EX_GOT_EOF _("Got EOF from the server.") #define EX_EOF_FROM_PEER _("Got EOF from peer.") #define EX_MALFORMED_META_INFO _("Malformed meta info.") #define EX_FILE_OPEN _("Failed to open the file %s, cause: %s") #define EX_FILE_WRITE _("Failed to write into the file %s, cause: %s") #define EX_FILE_READ _("Failed to read from the file %s, cause: %s") #define EX_DATA_READ _("Failed to read data from disk.") #define EX_FILE_SHA1SUM _("Failed to calculate SHA1 digest of or a part of the file %s, cause: %s") #define EX_FILE_SEEK _("Failed to seek the file %s, cause: %s") #define EX_FILE_OFFSET_OUT_OF_RANGE "The offset is out of range, offset=%" PRId64 "" #define EX_NOT_DIRECTORY _("%s is not a directory.") #define EX_MAKE_DIR _("Failed to make the directory %s, cause: %s") #define EX_SEGMENT_FILE_WRITE "Failed to write into the segment file %s" #define EX_SEGMENT_FILE_READ "Failed to read from the segment file %s" #define EX_SOCKET_OPEN _("Failed to open a socket, cause: %s") #define EX_SOCKET_SET_OPT _("Failed to set a socket option, cause: %s") #define EX_SOCKET_BLOCKING _("Failed to set a socket as blocking, cause: %s") #define EX_SOCKET_NONBLOCKING _("Failed to set a socket as non-blocking, cause: %s") #define EX_SOCKET_BIND _("Failed to bind a socket, cause: %s") #define EX_SOCKET_LISTEN _("Failed to listen to a socket, cause: %s") #define EX_SOCKET_ACCEPT _("Failed to accept a peer connection, cause: %s") #define EX_SOCKET_GET_NAME _("Failed to get the name of socket, cause: %s") #define EX_SOCKET_GET_PEER _("Failed to get the name of connected peer, cause: %s") #define EX_RESOLVE_HOSTNAME _("Failed to resolve the hostname %s, cause: %s") #define EX_SOCKET_CONNECT _("Failed to connect to the host %s, cause: %s") #define EX_SOCKET_CHECK_WRITABLE _("Failed to check whether the socket is writable, cause: %s") #define EX_SOCKET_CHECK_READABLE _("Failed to check whether the socket is readable, cause: %s") #define EX_SOCKET_SEND _("Failed to send data, cause: %s") #define EX_SOCKET_RECV _("Failed to receive data, cause: %s") #define EX_SOCKET_PEEK _("Failed to peek data, cause: %s") #define EX_SOCKET_UNKNOWN_ERROR _("Unknown socket error %d (0x%x)") #define EX_FILE_ALREADY_EXISTS _("File %s exists, but %s does not exist.") #define EX_INVALID_PAYLOAD_SIZE \ _("Invalid payload size for %s, size=%lu. It should be %lu.") #define EX_INVALID_BT_MESSAGE_ID _("Invalid ID=%d for %s. It should be %d.") #define EX_INVALID_CHUNK_CHECKSUM "Chunk checksum validation failed. checksumIndex=%lu, offset=%" PRId64 ", expectedHash=%s, actualHash=%s" #define EX_DOWNLOAD_ABORTED _("Download aborted.") #define EX_DUPLICATE_FILE_DOWNLOAD _("File %s is being downloaded by other command.") #define EX_INSUFFICIENT_CHECKSUM _("Insufficient checksums.") #define EX_TRACKER_FAILURE _("Tracker returned failure reason: %s") #define EX_FLOODING_DETECTED _("Flooding detected.") #define EX_DROP_INACTIVE_CONNECTION \ _("Drop connection because no request/piece messages were exchanged in a" \ " certain period(%ld seconds).") #define EX_INFOHASH_MISMATCH_IN_SEGFILE _("The infoHash in torrent file doesn't match to one in .aria2 file.") #define EX_NO_SUCH_FILE_ENTRY _("No such file entry %s") #define EX_TOO_SLOW_DOWNLOAD_SPEED _("Too slow Downloading speed: %d <= %d(B/s), host:%s") #define EX_NO_HTTP_REQUEST_ENTRY_FOUND _("No HttpRequestEntry found.") #define EX_LOCATION_HEADER_REQUIRED _("Got %d status, but no location header provided.") #define EX_INVALID_RANGE_HEADER "Invalid range header. Request: %" PRId64 "-%" PRId64 "/%" PRId64 ", Response: %" PRId64 "-%" PRId64 "/%" PRId64 "" #define EX_NO_RESULT_WITH_YOUR_PREFS _("No file matched with your preference.") #define EX_EXCEPTION_CAUGHT _("Exception caught") #define EX_TOO_LONG_PAYLOAD _("Max payload length exceeded or invalid. length = %u") #define EX_FILE_LENGTH_MISMATCH_BETWEEN_LOCAL_AND_REMOTE _("Invalid file length. Cannot continue download %s: local %s, remote %s") // clang-format on #endif // D_MESSAGE_H
18,949
C++
.h
285
64.105263
299
0.699812
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,441
libgen.h
aria2_aria2/src/libgen.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef _D_LIBGEN_H #define _D_LIBGEN_H 1 #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef __MINGW32__ char* basename(char* path); char* dirname(char* path); #else char* basename(const char* path); char* dirname(const char* path); #endif // __MINGW32__ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* not _D_LIBGEN_H */
1,948
C++
.h
50
37.16
79
0.747485
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
1,451
asctime_r.h
aria2_aria2/src/asctime_r.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2008 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef _D_ASCTIME_R_H #define _D_ASCTIME_R_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include <time.h> #undef asctime_r char* asctime_r(const struct tm*, char*); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* not _D_ASCTIME_R_H */
1,861
C++
.h
46
38.630435
79
0.749447
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,469
usage_text.h
aria2_aria2/src/usage_text.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ // clang-format off #define TEXT_DIR \ _(" -d, --dir=DIR The directory to store the downloaded file.") #define TEXT_OUT \ _(" -o, --out=FILE The file name of the downloaded file. It is\n" \ " always relative to the directory given in -d\n" \ " option. When the -Z option is used, this option\n" \ " will be ignored.") #define TEXT_LOG \ _(" -l, --log=LOG The file name of the log file. If '-' is\n" \ " specified, log is written to stdout.") #define TEXT_DAEMON \ _(" -D, --daemon[=true|false] Run as daemon. The current working directory will\n" \ " be changed to \"/\" and standard input, standard\n" \ " output and standard error will be redirected to\n" \ " \"/dev/null\".") #define TEXT_SPLIT \ _(" -s, --split=N Download a file using N connections. If more\n" \ " than N URIs are given, first N URIs are used and\n" \ " remaining URLs are used for backup. If less than\n" \ " N URIs are given, those URLs are used more than\n" \ " once so that N connections total are made\n" \ " simultaneously. The number of connections to the\n" \ " same host is restricted by the \n" \ " --max-connection-per-server option. See also the\n" \ " --min-split-size option.") #define TEXT_RETRY_WAIT \ _(" --retry-wait=SEC Set the seconds to wait between retries. \n" \ " With SEC > 0, aria2 will retry download when the\n" \ " HTTP server returns 503 response.") #define TEXT_TIMEOUT \ _(" -t, --timeout=SEC Set timeout in seconds.") #define TEXT_MAX_TRIES \ _(" -m, --max-tries=N Set number of tries. 0 means unlimited.") #define TEXT_HTTP_PROXY \ _(" --http-proxy=PROXY Use a proxy server for HTTP. To override a\n"\ " previously defined proxy, use \"\".\n" \ " See also the --all-proxy option.\n" \ " This affects all http downloads.") #define TEXT_HTTPS_PROXY \ _(" --https-proxy=PROXY Use a proxy server for HTTPS. To override a \n" \ " previously defined proxy, use \"\".\n" \ " See also the --all-proxy option.\n" \ " This affects all https downloads.") #define TEXT_FTP_PROXY \ _(" --ftp-proxy=PROXY Use a proxy server for FTP. To override a \n" \ " previously defined proxy, use \"\".\n" \ " See also the --all-proxy option.\n" \ " This affects all ftp downloads.") #define TEXT_ALL_PROXY \ _(" --all-proxy=PROXY Use a proxy server for all protocols. To override\n" \ " a previously defined proxy, use \"\".\n" \ " You also can override this setting and specify a\n" \ " proxy server for a particular protocol using the\n" \ " --http-proxy, --https-proxy and --ftp-proxy\n" \ " options.\n" \ " This affects all downloads.") #define TEXT_HTTP_USER \ _(" --http-user=USER Set HTTP user. This affects all URLs.") #define TEXT_HTTP_PASSWD \ _(" --http-passwd=PASSWD Set HTTP password. This affects all URLs.") #define TEXT_PROXY_METHOD \ _(" --proxy-method=METHOD Set the method to use in proxy request.") #define TEXT_REFERER \ _(" --referer=REFERER Set an http referrer (Referer). This affects\n" \ " all http/https downloads. If \"*\" is given,\n" \ " the download URI is also used as the referrer.\n" \ " This may be useful when used together with\n" \ " the -P option.") #define TEXT_FTP_USER \ _(" --ftp-user=USER Set FTP user. This affects all URLs.") #define TEXT_FTP_PASSWD \ _(" --ftp-passwd=PASSWD Set FTP password. This affects all URLs.") #define TEXT_FTP_TYPE \ _(" --ftp-type=TYPE Set FTP transfer type.") #define TEXT_FTP_PASV \ _(" -p, --ftp-pasv[=true|false] Use the passive mode in FTP. If false is given,\n" \ " the active mode will be used.") #define TEXT_LOWEST_SPEED_LIMIT \ _(" --lowest-speed-limit=SPEED Close connection if download speed is lower than\n" \ " or equal to this value(bytes per sec).\n" \ " 0 means aria2 does not have a lowest speed limit.\n" \ " You can append K or M(1K = 1024, 1M = 1024K).\n" \ " This option does not affect BitTorrent downloads.") #define TEXT_MAX_OVERALL_DOWNLOAD_LIMIT \ _(" --max-overall-download-limit=SPEED Set max overall download speed in bytes/sec.\n" \ " 0 means unrestricted.\n" \ " You can append K or M(1K = 1024, 1M = 1024K).\n" \ " To limit the download speed per download, use\n" \ " --max-download-limit option.") #define TEXT_MAX_DOWNLOAD_LIMIT \ _(" --max-download-limit=SPEED Set max download speed per each download in\n" \ " bytes/sec. 0 means unrestricted.\n" \ " You can append K or M(1K = 1024, 1M = 1024K).\n" \ " To limit the overall download speed, use\n" \ " --max-overall-download-limit option.") #define TEXT_FILE_ALLOCATION \ _(" --file-allocation=METHOD Specify file allocation method.\n" \ " 'none' doesn't pre-allocate file space. 'prealloc'\n" \ " pre-allocates file space before download begins.\n" \ " This may take some time depending on the size of\n" \ " the file.\n" \ " If you are using newer file systems such as ext4\n" \ " (with extents support), btrfs, xfs or NTFS\n" \ " (MinGW build only), 'falloc' is your best\n" \ " choice. It allocates large(few GiB) files\n" \ " almost instantly. Don't use 'falloc' with legacy\n" \ " file systems such as ext3 and FAT32 because it\n" \ " takes almost the same time as 'prealloc' and it\n" \ " blocks aria2 entirely until allocation finishes.\n" \ " 'falloc' may not be available if your system\n" \ " doesn't have posix_fallocate() function.\n" \ " 'trunc' uses ftruncate() system call or\n" \ " platform-specific counterpart to truncate a file\n" \ " to a specified length.") #define TEXT_NO_FILE_ALLOCATION_LIMIT \ _(" --no-file-allocation-limit=SIZE No file allocation is made for files whose\n" \ " size is smaller than SIZE.\n" \ " You can append K or M(1K = 1024, 1M = 1024K).") #define TEXT_ENABLE_DIRECT_IO \ _(" --enable-direct-io[=true|false] Enable directI/O, which lowers cpu usage while\n" \ " allocating files.\n" \ " Turn off if you encounter any error") #define TEXT_ALLOW_OVERWRITE \ _(" --allow-overwrite[=true|false] Restart download from scratch if the\n" \ " corresponding control file doesn't exist. See\n" \ " also --auto-file-renaming option.") #define TEXT_ALLOW_PIECE_LENGTH_CHANGE \ _(" --allow-piece-length-change[=true|false] If false is given, aria2 aborts\n" \ " download when a piece length is different from\n" \ " one in a control file. If true is given, you can\n" \ " proceed but some download progress will be lost.") #define TEXT_FORCE_SEQUENTIAL \ _(" -Z, --force-sequential[=true|false] Fetch URIs in the command-line sequentially\n" \ " and download each URI in a separate session, like\n" \ " the usual command-line download utilities.") #define TEXT_AUTO_FILE_RENAMING \ _(" --auto-file-renaming[=true|false] Rename file name if the same file already\n" \ " exists. This option works only in http(s)/ftp\n" \ " download.\n" \ " The new file name has a dot and a number(1..9999)\n" \ " appended after the name, but before the file\n" \ " extension, if any.") #define TEXT_PARAMETERIZED_URI \ _(" -P, --parameterized-uri[=true|false] Enable parameterized URI support.\n" \ " You can specify set of parts:\n" \ " http://{sv1,sv2,sv3}/foo.iso\n" \ " Also you can specify numeric sequences with step\n" \ " counter:\n" \ " http://host/image[000-100:2].img\n" \ " A step counter can be omitted.\n" \ " If all URIs do not point to the same file, such\n" \ " as the second example above, -Z option is\n" \ " required.") #define TEXT_ENABLE_HTTP_KEEP_ALIVE \ _(" --enable-http-keep-alive[=true|false] Enable HTTP/1.1 persistent connection.") #define TEXT_ENABLE_HTTP_PIPELINING \ _(" --enable-http-pipelining[=true|false] Enable HTTP/1.1 pipelining.") #define TEXT_CHECK_INTEGRITY \ _(" -V, --check-integrity[=true|false] Check file integrity by validating piece\n" \ " hashes or a hash of entire file. This option has\n" \ " effect only in BitTorrent, Metalink downloads\n" \ " with checksums or HTTP(S)/FTP downloads with\n" \ " --checksum option. If piece hashes are provided,\n" \ " this option can detect damaged portions of a file\n" \ " and re-download them. If a hash of entire file is\n" \ " provided, hash check is only done when file has\n" \ " been already download. This is determined by file\n" \ " length. If hash check fails, file is\n" \ " re-downloaded from scratch. If both piece hashes\n" \ " and a hash of entire file are provided, only\n" \ " piece hashes are used.") #define TEXT_BT_HASH_CHECK_SEED \ _(" --bt-hash-check-seed[=true|false] If true is given, after hash check using\n" \ " --check-integrity option and file is complete,\n" \ " continue to seed file. If you want to check file\n" \ " and download it only when it is damaged or\n" \ " incomplete, set this option to false.\n" \ " This option has effect only on BitTorrent\n" \ " download.") #define TEXT_REALTIME_CHUNK_CHECKSUM \ _(" --realtime-chunk-checksum[=true|false] Validate chunk of data by calculating\n" \ " checksum while downloading a file if chunk\n" \ " checksums are provided.") #define TEXT_CONTINUE \ _(" -c, --continue[=true|false] Continue downloading a partially downloaded\n" \ " file. Use this option to resume a download\n" \ " started by a web browser or another program\n" \ " which downloads files sequentially from the\n" \ " beginning. Currently this option is only\n" \ " applicable to http(s)/ftp downloads.") #define TEXT_USER_AGENT \ _(" -U, --user-agent=USER_AGENT Set user agent for http(s) downloads.") #define TEXT_NO_NETRC \ _(" -n, --no-netrc[=true|false] Disables netrc support.") #define TEXT_NETRC_PATH \ _(" --netrc-path=FILE Specify the path to the netrc file.") #define TEXT_INPUT_FILE \ _(" -i, --input-file=FILE Downloads URIs found in FILE. You can specify\n" \ " multiple URIs for a single entity: separate\n" \ " URIs on a single line using the TAB character.\n" \ " Reads input from stdin when '-' is specified.\n" \ " Additionally, options can be specified after each\n" \ " line of URI. This optional line must start with\n" \ " one or more white spaces and have one option per\n" \ " single line. See INPUT FILE section of man page\n" \ " for details. See also --deferred-input option.") #define TEXT_MAX_CONCURRENT_DOWNLOADS \ _(" -j, --max-concurrent-downloads=N Set maximum number of parallel downloads for\n" \ " every static (HTTP/FTP) URL, torrent and metalink.\n" \ " See also --split and --optimize-concurrent-downloads options.") #define TEXT_OPTIMIZE_CONCURRENT_DOWNLOADS\ _(" --optimize-concurrent-downloads[=true|false|A:B] Optimizes the number of\n" \ " concurrent downloads according to the bandwidth\n" \ " available. aria2 uses the download speed observed\n" \ " in the previous downloads to adapt the number of\n" \ " downloads launched in parallel according to the\n" \ " rule N = A + B Log10(speed in Mbps). The\n" \ " coefficients A and B can be customized in the\n" \ " option arguments with A and B separated by a\n" \ " colon. The default values (A=5,B=25) lead to\n" \ " using typically 5 parallel downloads on 1Mbps\n" \ " networks and above 50 on 100Mbps networks. The\n" \ " number of parallel downloads remains constrained\n" \ " under the maximum defined by the\n" \ " max-concurrent-downloads parameter.") #define TEXT_LOAD_COOKIES \ _(" --load-cookies=FILE Load Cookies from FILE using the Firefox3 format\n" \ " and Mozilla/Firefox(1.x/2.x)/Netscape format.") #define TEXT_SAVE_COOKIES \ _(" --save-cookies=FILE Save Cookies to FILE in Mozilla/Firefox(1.x/2.x)/\n" \ " Netscape format. If FILE already exists, it is\n" \ " overwritten. Session Cookies are also saved and\n" \ " their expiry values are treated as 0.") #define TEXT_SHOW_FILES \ _(" -S, --show-files[=true|false] Print file listing of .torrent, .meta4 and\n" \ " .metalink file and exit. More detailed\n" \ " information will be listed in case of torrent\n" \ " file.") #define TEXT_SELECT_FILE \ _(" --select-file=INDEX... Set file to download by specifying its index.\n" \ " You can find the file index using the\n" \ " --show-files option. Multiple indexes can be\n" \ " specified by using ',', for example: \"3,6\".\n" \ " You can also use '-' to specify a range: \"1-5\".\n" \ " ',' and '-' can be used together.\n" \ " When used with the -M option, index may vary\n" \ " depending on the query(see --metalink-* options).") #define TEXT_TORRENT_FILE \ _(" -T, --torrent-file=TORRENT_FILE The path to the .torrent file.") #define TEXT_FOLLOW_TORRENT \ _(" --follow-torrent=true|false|mem If true or mem is specified, when a file\n" \ " whose suffix is .torrent or content type is\n" \ " application/x-bittorrent is downloaded, aria2\n" \ " parses it as a torrent file and downloads files\n" \ " mentioned in it.\n" \ " If mem is specified, a torrent file is not\n" \ " written to the disk, but is just kept in memory.\n" \ " If false is specified, the .torrent file is\n" \ " downloaded to the disk, but is not parsed as a\n" \ " torrent and its contents are not downloaded.") #define TEXT_LISTEN_PORT \ _(" --listen-port=PORT... Set TCP port number for BitTorrent downloads.\n" \ " Multiple ports can be specified by using ',',\n" \ " for example: \"6881,6885\". You can also use '-'\n" \ " to specify a range: \"6881-6999\". ',' and '-' can\n" \ " be used together.") #define TEXT_MAX_OVERALL_UPLOAD_LIMIT \ _(" --max-overall-upload-limit=SPEED Set max overall upload speed in bytes/sec.\n" \ " 0 means unrestricted.\n" \ " You can append K or M(1K = 1024, 1M = 1024K).\n" \ " To limit the upload speed per torrent, use\n" \ " --max-upload-limit option.") #define TEXT_MAX_UPLOAD_LIMIT \ _(" -u, --max-upload-limit=SPEED Set max upload speed per each torrent in\n" \ " bytes/sec. 0 means unrestricted.\n" \ " You can append K or M(1K = 1024, 1M = 1024K).\n" \ " To limit the overall upload speed, use\n" \ " --max-overall-upload-limit option.") #define TEXT_SEED_TIME \ _(" --seed-time=MINUTES Specify seeding time in (fractional) minutes.\n" \ " Also see the --seed-ratio option.") #define TEXT_SEED_RATIO \ _(" --seed-ratio=RATIO Specify share ratio. Seed completed torrents\n" \ " until share ratio reaches RATIO.\n" \ " You are strongly encouraged to specify equals or\n" \ " more than 1.0 here. Specify 0.0 if you intend to\n" \ " do seeding regardless of share ratio.\n" \ " If --seed-time option is specified along with\n" \ " this option, seeding ends when at least one of\n" \ " the conditions is satisfied.") #define TEXT_PEER_ID_PREFIX \ _(" --peer-id-prefix=PEER_ID_PREFIX Specify the prefix of peer ID. The peer ID in\n" \ " BitTorrent is 20 byte length. If more than 20\n" \ " bytes are specified, only first 20 bytes are\n" \ " used. If less than 20 bytes are specified, random\n" \ " byte data are added to make its length 20 bytes.") #define TEXT_PEER_AGENT \ _(" --peer-agent=PEER_AGENT Set client reported during Extended torrent handshakes") #define TEXT_ENABLE_PEER_EXCHANGE \ _(" --enable-peer-exchange[=true|false] Enable Peer Exchange extension.") #define TEXT_ENABLE_DHT \ _(" --enable-dht[=true|false] Enable IPv4 DHT functionality. It also enables\n" \ " UDP tracker support. If a private flag is set\n" \ " in a torrent, aria2 doesn't use DHT for that\n" \ " download even if ``true`` is given.") #define TEXT_DHT_LISTEN_PORT \ _(" --dht-listen-port=PORT... Set UDP listening port used by DHT(IPv4, IPv6)\n" \ " and UDP tracker. Multiple ports can be specified\n" \ " by using ',', for example: \"6881,6885\". You can\n" \ " also use '-' to specify a range: \"6881-6999\".\n" \ " ',' and '-' can be used together.") #define TEXT_DHT_ENTRY_POINT \ _(" --dht-entry-point=HOST:PORT Set host and port as an entry point to IPv4 DHT\n" \ " network.") #define TEXT_DHT_FILE_PATH \ _(" --dht-file-path=PATH Change the IPv4 DHT routing table file to PATH.") #define TEXT_BT_MIN_CRYPTO_LEVEL \ _(" --bt-min-crypto-level=plain|arc4 Set minimum level of encryption method.\n" \ " If several encryption methods are provided by a\n" \ " peer, aria2 chooses the lowest one which satisfies\n" \ " the given level.") #define TEXT_BT_REQUIRE_CRYPTO \ _(" --bt-require-crypto[=true|false] If true is given, aria2 doesn't accept and\n" \ " establish connection with legacy BitTorrent\n" \ " handshake. Thus aria2 always uses Obfuscation\n" \ " handshake.") #define TEXT_BT_REQUEST_PEER_SPEED_LIMIT \ _(" --bt-request-peer-speed-limit=SPEED If the whole download speed of every\n" \ " torrent is lower than SPEED, aria2 temporarily\n" \ " increases the number of peers to try for more\n" \ " download speed. Configuring this option with your\n" \ " preferred download speed can increase your\n" \ " download speed in some cases.\n" \ " You can append K or M(1K = 1024, 1M = 1024K).") #define TEXT_BT_MAX_OPEN_FILES \ _(" --bt-max-open-files=NUM Specify maximum number of files to open in\n" \ " multi-file BitTorrent/Metalink downloads\n" \ " globally.") #define TEXT_BT_SEED_UNVERIFIED \ _(" --bt-seed-unverified[=true|false] Seed previously downloaded files without\n" \ " verifying piece hashes.") #define TEXT_BT_MAX_PEERS \ _(" --bt-max-peers=NUM Specify the maximum number of peers per torrent.\n" \ " 0 means unlimited.\n" \ " See also --bt-request-peer-speed-limit option.") #define TEXT_METALINK_FILE \ _(" -M, --metalink-file=METALINK_FILE The file path to the .meta4 and .metalink\n" \ " file. Reads input from stdin when '-' is\n" \ " specified.") #define TEXT_METALINK_SERVERS \ _(" -C, --metalink-servers=NUM_SERVERS The number of servers to connect to\n" \ " simultaneously. Some Metalinks regulate the\n" \ " number of servers to connect. aria2 strictly\n" \ " respects them. This means that if Metalink defines\n" \ " the maxconnections attribute lower than\n" \ " NUM_SERVERS, then aria2 uses the value of\n" \ " maxconnections attribute instead of NUM_SERVERS.\n" \ " See also -s and -j options.") #define TEXT_METALINK_VERSION \ _(" --metalink-version=VERSION The version of the file to download.") #define TEXT_METALINK_LANGUAGE \ _(" --metalink-language=LANGUAGE The language of the file to download.") #define TEXT_METALINK_OS \ _(" --metalink-os=OS The operating system of the file to download.") #define TEXT_METALINK_LOCATION \ _(" --metalink-location=LOCATION[,...] The location of the preferred server.\n" \ " A comma-delimited list of locations is\n" \ " acceptable.") #define TEXT_METALINK_PREFERRED_PROTOCOL \ _(" --metalink-preferred-protocol=PROTO Specify preferred protocol. Specify 'none'\n" \ " if you don't have any preferred protocol.") #define TEXT_FOLLOW_METALINK \ _(" --follow-metalink=true|false|mem If true or mem is specified, when a file\n" \ " whose suffix is .meta4 or .metalink, or content\n" \ " type of application/metalink4+xml or\n" \ " application/metalink+xml is downloaded, aria2\n" \ " parses it as a metalink file and downloads files\n" \ " mentioned in it.\n" \ " If mem is specified, a metalink file is not\n" \ " written to the disk, but is just kept in memory.\n" \ " If false is specified, the .metalink file is\n" \ " downloaded to the disk, but is not parsed as a\n" \ " metalink file and its contents are not\n" \ " downloaded.") #define TEXT_METALINK_ENABLE_UNIQUE_PROTOCOL \ _(" --metalink-enable-unique-protocol[=true|false] If true is given and several\n" \ " protocols are available for a mirror in a metalink\n" \ " file, aria2 uses one of them.\n" \ " Use --metalink-preferred-protocol option to\n" \ " specify the preference of protocol.") #define TEXT_VERSION \ _(" -v, --version Print the version number and exit.") #define TEXT_HELP \ _(" -h, --help[=TAG|KEYWORD] Print usage and exit.\n" \ " The help messages are classified with tags. A tag\n" \ " starts with \"#\". For example, type \"--help=#http\"\n" \ " to get the usage for the options tagged with\n" \ " \"#http\". If non-tag word is given, print the usage\n" \ " for the options whose name includes that word.") #define TEXT_NO_CONF \ _(" --no-conf[=true|false] Disable loading aria2.conf file.") #define TEXT_CONF_PATH \ _(" --conf-path=PATH Change the configuration file path to PATH.") #define TEXT_STOP \ _(" --stop=SEC Stop application after SEC seconds has passed.\n" \ " If 0 is given, this feature is disabled.") #define TEXT_HEADER \ _(" --header=HEADER Append HEADER to HTTP request header. You can use\n" \ " this option repeatedly to specify more than one\n" \ " header:\n" \ " aria2c --header=\"X-A: b78\" --header=\"X-B: 9J1\"\n" \ " http://host/file") #define TEXT_QUIET \ _(" -q, --quiet[=true|false] Make aria2 quiet(no console output).") #define TEXT_ASYNC_DNS \ _(" --async-dns[=true|false] Enable asynchronous DNS.") #define TEXT_FTP_REUSE_CONNECTION \ _(" --ftp-reuse-connection[=true|false] Reuse connection in FTP.") #define TEXT_SUMMARY_INTERVAL \ _(" --summary-interval=SEC Set interval to output download progress summary.\n" \ " Setting 0 suppresses the output.") #define TEXT_LOG_LEVEL \ _(" --log-level=LEVEL Set log level to output to file specified using\n" \ " --log option.") #define TEXT_REMOTE_TIME \ _(" -R, --remote-time[=true|false] Retrieve timestamp of the remote file from the\n" \ " remote HTTP/FTP server and if it is available,\n" \ " apply it to the local file.") #define TEXT_CONNECT_TIMEOUT \ _(" --connect-timeout=SEC Set the connect timeout in seconds to establish\n" \ " connection to HTTP/FTP/proxy server. After the\n" \ " connection is established, this option makes no\n" \ " effect and --timeout option is used instead.") #define TEXT_MAX_FILE_NOT_FOUND \ _(" --max-file-not-found=NUM If aria2 receives `file not found' status from the\n" \ " remote HTTP/FTP servers NUM times without getting\n" \ " a single byte, then force the download to fail.\n" \ " Specify 0 to disable this option.\n" \ " This options is effective only when using\n" \ " HTTP/FTP servers. The number of retry attempt is\n" \ " counted toward --max-tries, so it should be\n" \ " configured too.") #define TEXT_URI_SELECTOR \ _(" --uri-selector=SELECTOR Specify URI selection algorithm.\n" \ " If 'inorder' is given, URI is tried in the order\n" \ " appeared in the URI list.\n" \ " If 'feedback' is given, aria2 uses download speed\n" \ " observed in the previous downloads and choose\n" \ " fastest server in the URI list. This also\n" \ " effectively skips dead mirrors. The observed\n" \ " download speed is a part of performance profile\n" \ " of servers mentioned in --server-stat-of and\n" \ " --server-stat-if options.\n" \ " If 'adaptive' is given, selects one of the best\n" \ " mirrors for the first and reserved connections.\n" \ " For supplementary ones, it returns mirrors which\n" \ " has not been tested yet, and if each of them has\n" \ " already been tested, returns mirrors which has to\n" \ " be tested again. Otherwise, it doesn't select\n" \ " anymore mirrors. Like 'feedback', it uses a\n" \ " performance profile of servers.") #define TEXT_SERVER_STAT_OF \ _(" --server-stat-of=FILE Specify the filename to which performance profile\n" \ " of the servers is saved. You can load saved data\n" \ " using --server-stat-if option.") #define TEXT_SERVER_STAT_IF \ _(" --server-stat-if=FILE Specify the filename to load performance profile\n" \ " of the servers. The loaded data will be used in\n" \ " some URI selector such as 'feedback'.\n" \ " See also --uri-selector option") #define TEXT_SERVER_STAT_TIMEOUT \ _(" --server-stat-timeout=SEC Specifies timeout in seconds to invalidate\n" \ " performance profile of the servers since the last\n" \ " contact to them.") #define TEXT_AUTO_SAVE_INTERVAL \ _(" --auto-save-interval=SEC Save a control file(*.aria2) every SEC seconds.\n" \ " If 0 is given, a control file is not saved during\n" \ " download. aria2 saves a control file when it stops\n" \ " regardless of the value.") #define TEXT_CERTIFICATE \ _(" --certificate=FILE Use the client certificate in FILE.\n" \ " The certificate must be in PEM format.\n" \ " You may use --private-key option to specify the\n" \ " private key.") #define TEXT_PRIVATE_KEY \ _(" --private-key=FILE Use the private key in FILE.\n" \ " The private key must be decrypted and in PEM\n" \ " format. See also --certificate option.") #define TEXT_CA_CERTIFICATE \ _(" --ca-certificate=FILE Use the certificate authorities in FILE to verify\n" \ " the peers. The certificate file must be in PEM\n" \ " format and can contain multiple CA certificates.\n" \ " Use --check-certificate option to enable\n" \ " verification.") #define TEXT_CHECK_CERTIFICATE \ _(" --check-certificate[=true|false] Verify the peer using certificates specified\n" \ " in --ca-certificate option.") #define TEXT_NO_PROXY \ _(" --no-proxy=DOMAINS Specify comma separated hostnames, domains or\n" \ " network address with or without CIDR block where\n" \ " proxy should not be used.") #define TEXT_USE_HEAD \ _(" --use-head[=true|false] Use HEAD method for the first request to the HTTP\n" \ " server.") #define TEXT_NO_WANT_DIGEST_HEADER \ _(" --no-want-digest-header[=true|false] Whether to disable Want-Digest header \n" \ " when doing requests.") #define TEXT_CONTENT_DISPOSITION_DEFAULT_UTF8 \ _(" --content-disposition-default-utf8[=true|false] Handle quoted string in\n" \ " Content-Disposition header as UTF-8 instead of\n" \ " ISO-8859-1, for example, the filename parameter,\n" \ " but not the extended version filename*.") #define TEXT_EVENT_POLL \ _(" --event-poll=POLL Specify the method for polling events.") #define TEXT_BT_EXTERNAL_IP \ _(" --bt-external-ip=IPADDRESS Specify the external IP address to use in\n" \ " BitTorrent download and DHT. It may be sent to\n" \ " BitTorrent tracker. For DHT, this option should\n" \ " be set to report that local node is downloading\n" \ " a particular torrent. This is critical to use\n" \ " DHT in a private network. Although this function\n" \ " is named 'external', it can accept any kind of IP\n" \ " addresses.") #define TEXT_HTTP_AUTH_CHALLENGE \ _(" --http-auth-challenge[=true|false] Send HTTP authorization header only when it\n" \ " is requested by the server. If false is set, then\n" \ " authorization header is always sent to the server.\n" \ " There is an exception: if username and password\n" \ " are embedded in URI, authorization header is\n" \ " always sent to the server regardless of this\n" \ " option.") #define TEXT_INDEX_OUT \ _(" -O, --index-out=INDEX=PATH Set file path for file with index=INDEX. You can\n" \ " find the file index using the --show-files option.\n" \ " PATH is a relative path to the path specified in\n" \ " --dir option. You can use this option multiple\n" \ " times.") #define TEXT_DRY_RUN \ _(" --dry-run[=true|false] If true is given, aria2 just checks whether the\n" \ " remote file is available and doesn't download\n" \ " data. This option has effect on HTTP/FTP download.\n" \ " BitTorrent downloads are canceled if true is\n" \ " specified.") #define TEXT_BT_TRACKER_INTERVAL \ _(" --bt-tracker-interval=SEC Set the interval in seconds between tracker\n" \ " requests. This completely overrides interval value\n" \ " and aria2 just uses this value and ignores the\n" \ " min interval and interval value in the response of\n" \ " tracker. If 0 is set, aria2 determines interval\n" \ " based on the response of tracker and the download\n" \ " progress.") #define TEXT_ON_DOWNLOAD_COMPLETE \ _(" --on-download-complete=COMMAND Set the command to be executed after download\n" \ " completed.\n" \ " See --on-download-start option for the\n" \ " requirement of COMMAND.\n" \ " See also --on-download-stop option.") #define TEXT_ON_DOWNLOAD_START \ _(" --on-download-start=COMMAND Set the command to be executed after download\n" \ " got started. aria2 passes 3 arguments to COMMAND:\n" \ " GID, the number of files and file path. See Event\n" \ " Hook in man page for more details.") #define TEXT_ON_DOWNLOAD_PAUSE \ _(" --on-download-pause=COMMAND Set the command to be executed after download\n" \ " was paused.\n"\ " See --on-download-start option for the\n" \ " requirement of COMMAND.") #define TEXT_ON_DOWNLOAD_ERROR \ _(" --on-download-error=COMMAND Set the command to be executed after download\n" \ " aborted due to error.\n" \ " See --on-download-start option for the\n" \ " requirement of COMMAND.\n" \ " See also --on-download-stop option.") #define TEXT_ON_DOWNLOAD_STOP \ _(" --on-download-stop=COMMAND Set the command to be executed after download\n" \ " stopped. You can override the command to be\n" \ " executed for particular download result using\n" \ " --on-download-complete and --on-download-error. If\n" \ " they are specified, command specified in this\n" \ " option is not executed.\n" \ " See --on-download-start option for the\n" \ " requirement of COMMAND.") #define TEXT_BT_STOP_TIMEOUT \ _(" --bt-stop-timeout=SEC Stop BitTorrent download if download speed is 0 in\n" \ " consecutive SEC seconds. If 0 is given, this\n" \ " feature is disabled.") #define TEXT_BT_PRIORITIZE_PIECE \ _(" --bt-prioritize-piece=head[=SIZE],tail[=SIZE] Try to download first and last\n" \ " pieces of each file first. This is useful for\n" \ " previewing files. The argument can contain 2\n" \ " keywords:head and tail. To include both keywords,\n" \ " they must be separated by comma. These keywords\n" \ " can take one parameter, SIZE. For example, if\n" \ " head=SIZE is specified, pieces in the range of\n" \ " first SIZE bytes of each file get higher priority.\n" \ " tail=SIZE means the range of last SIZE bytes of\n" \ " each file. SIZE can include K or M(1K = 1024, 1M =\n" \ " 1024K). If SIZE is omitted, SIZE=1M is used.") #define TEXT_INTERFACE \ _(" --interface=INTERFACE Bind sockets to given interface. You can specify\n" \ " interface name, IP address and hostname.") #define TEXT_MULTIPLE_INTERFACE \ _(" --multiple-interface=INTERFACES Comma separated list of interfaces to bind\n" \ " sockets to. Requests will be split among the\n" \ " interfaces to achieve link aggregation. You can\n" \ " specify interface name, IP address and hostname.\n" \ " If --interface is used, this option will be\n" \ " ignored.") #define TEXT_DISABLE_IPV6 \ _(" --disable-ipv6[=true|false] Disable IPv6.") #define TEXT_BT_SAVE_METADATA \ _(" --bt-save-metadata[=true|false] Save metadata as .torrent file. This option has\n" \ " effect only when BitTorrent Magnet URI is used.\n" \ " The filename is hex encoded info hash with suffix\n" \ " .torrent. The directory to be saved is the same\n" \ " directory where download file is saved. If the\n" \ " same file already exists, metadata is not saved.\n" \ " See also --bt-metadata-only option.") #define TEXT_HTTP_NO_CACHE \ _(" --http-no-cache[=true|false] Send Cache-Control: no-cache and Pragma: no-cache\n" \ " header to avoid cached content. If false is\n" \ " given, these headers are not sent and you can add\n" \ " Cache-Control header with a directive you like\n" \ " using --header option.") #define TEXT_BT_METADATA_ONLY \ _(" --bt-metadata-only[=true|false] Download metadata only. The file(s) described\n" \ " in metadata will not be downloaded. This option\n" \ " has effect only when BitTorrent Magnet URI is\n" \ " used. See also --bt-save-metadata option.") #define TEXT_HUMAN_READABLE \ _(" --human-readable[=true|false] Print sizes and speed in human readable format\n" \ " (e.g., 1.2Ki, 3.4Mi) in the console readout.") #define TEXT_BT_ENABLE_LPD \ _(" --bt-enable-lpd[=true|false] Enable Local Peer Discovery.") #define TEXT_BT_LPD_INTERFACE \ _(" --bt-lpd-interface=INTERFACE Use given interface for Local Peer Discovery. If\n" \ " this option is not specified, the default\n" \ " interface is chosen. You can specify interface\n" \ " name and IP address.") #define TEXT_REUSE_URI \ _(" --reuse-uri[=true|false] Reuse already used URIs if no unused URIs are\n" \ " left.") #define TEXT_ALL_PROXY_USER \ _(" --all-proxy-user=USER Set user for --all-proxy.") #define TEXT_ALL_PROXY_PASSWD \ _(" --all-proxy-passwd=PASSWD Set password for --all-proxy.") #define TEXT_HTTP_PROXY_USER \ _(" --http-proxy-user=USER Set user for --http-proxy.") #define TEXT_HTTP_PROXY_PASSWD \ _(" --http-proxy-passwd=PASSWD Set password for --http-proxy.") #define TEXT_HTTPS_PROXY_USER \ _(" --https-proxy-user=USER Set user for --https-proxy.") #define TEXT_HTTPS_PROXY_PASSWD \ _(" --https-proxy-passwd=PASSWD Set password for --https-proxy.") #define TEXT_FTP_PROXY_USER \ _(" --ftp-proxy-user=USER Set user for --ftp-proxy.") #define TEXT_FTP_PROXY_PASSWD \ _(" --ftp-proxy-passwd=PASSWD Set password for --ftp-proxy.") #define TEXT_REMOVE_CONTROL_FILE \ _(" --remove-control-file[=true|false] Remove control file before download. Using\n" \ " with --allow-overwrite=true, download always\n" \ " starts from scratch. This will be useful for\n" \ " users behind proxy server which disables resume.") #define TEXT_ALWAYS_RESUME \ _(" --always-resume[=true|false] Always resume download. If true is given, aria2\n" \ " always tries to resume download and if resume is\n" \ " not possible, aborts download. If false is given,\n" \ " when all given URIs do not support resume or\n" \ " aria2 encounters N URIs which does not support\n" \ " resume (N is the value specified using\n" \ " --max-resume-failure-tries option), aria2\n" \ " downloads file from scratch.\n" \ " See --max-resume-failure-tries option.") #define TEXT_MAX_RESUME_FAILURE_TRIES \ _(" --max-resume-failure-tries=N When used with --always-resume=false, aria2\n" \ " downloads file from scratch when aria2 detects N\n" \ " number of URIs that does not support resume. If N\n" \ " is 0, aria2 downloads file from scratch when all\n" \ " given URIs do not support resume.\n" \ " See --always-resume option.") #define TEXT_BT_TRACKER_TIMEOUT \ _(" --bt-tracker-timeout=SEC Set timeout in seconds.") #define TEXT_BT_TRACKER_CONNECT_TIMEOUT \ _(" --bt-tracker-connect-timeout=SEC Set the connect timeout in seconds to\n" \ " establish connection to tracker. After the\n" \ " connection is established, this option makes no\n" \ " effect and --bt-tracker-timeout option is used\n" \ " instead.") #define TEXT_DHT_MESSAGE_TIMEOUT \ _(" --dht-message-timeout=SEC Set timeout in seconds.") #define TEXT_HTTP_ACCEPT_GZIP \ _(" --http-accept-gzip[=true|false] Send 'Accept-Encoding: deflate, gzip' request\n" \ " header and inflate response if remote server\n" \ " responds with 'Content-Encoding: gzip' or\n" \ " 'Content-Encoding: deflate'.") #define TEXT_SAVE_SESSION \ _(" --save-session=FILE Save error/unfinished downloads to FILE on exit.\n" \ " You can pass this output file to aria2c with -i\n" \ " option on restart. Please note that downloads\n" \ " added by aria2.addTorrent and aria2.addMetalink\n" \ " RPC method and whose metadata could not be saved\n" \ " as a file will not be saved. Downloads removed\n" \ " using aria2.remove and aria2.forceRemove will not\n" \ " be saved.") #define TEXT_MAX_CONNECTION_PER_SERVER \ _(" -x, --max-connection-per-server=NUM The maximum number of connections to one\n" \ " server for each download.") #define TEXT_MIN_SPLIT_SIZE \ _(" -k, --min-split-size=SIZE aria2 does not split less than 2*SIZE byte range.\n" \ " For example, let's consider downloading 20MiB\n" \ " file. If SIZE is 10M, aria2 can split file into 2\n" \ " range [0-10MiB) and [10MiB-20MiB) and download it\n" \ " using 2 sources(if --split >= 2, of course).\n" \ " If SIZE is 15M, since 2*15M > 20MiB, aria2 does\n" \ " not split file and download it using 1 source.\n" \ " You can append K or M(1K = 1024, 1M = 1024K).") #define TEXT_CONDITIONAL_GET \ _(" --conditional-get[=true|false] Download file only when the local file is older\n" \ " than remote file. Currently, this function has\n" \ " many limitations. See man page for details.") #define TEXT_ON_BT_DOWNLOAD_COMPLETE \ _(" --on-bt-download-complete=COMMAND For BitTorrent, a command specified in\n" \ " --on-download-complete is called after download\n" \ " completed and seeding is over. On the other hand,\n" \ " this option sets the command to be executed after\n" \ " download completed but before seeding.\n" \ " See --on-download-start option for the\n" \ " requirement of COMMAND.") #define TEXT_ENABLE_ASYNC_DNS6 \ _(" --enable-async-dns6[=true|false] Enable IPv6 name resolution in asynchronous\n" \ " DNS resolver. This option will be ignored when\n" \ " --async-dns=false.") #define TEXT_ENABLE_DHT6 \ _(" --enable-dht6[=true|false] Enable IPv6 DHT functionality.\n" \ " Use --dht-listen-port option to specify port\n" \ " number to listen on. See also --dht-listen-addr6\n" \ " option.") #define TEXT_DHT_LISTEN_ADDR6 \ _(" --dht-listen-addr6=ADDR Specify address to bind socket for IPv6 DHT. \n" \ " It should be a global unicast IPv6 address of the\n" \ " host.") #define TEXT_DHT_ENTRY_POINT6 \ _(" --dht-entry-point6=HOST:PORT Set host and port as an entry point to IPv6 DHT\n" \ " network.") #define TEXT_DHT_FILE_PATH6 \ _(" --dht-file-path6=PATH Change the IPv6 DHT routing table file to PATH.") #define TEXT_BT_TRACKER \ _(" --bt-tracker=URI[,...] Comma separated list of additional BitTorrent\n" \ " tracker's announce URI. These URIs are not\n" \ " affected by --bt-exclude-tracker option because\n" \ " they are added after URIs in --bt-exclude-tracker\n" \ " option are removed.") #define TEXT_BT_EXCLUDE_TRACKER \ _(" --bt-exclude-tracker=URI[,...] Comma separated list of BitTorrent tracker's\n" \ " announce URI to remove. You can use special value\n" \ " '*' which matches all URIs, thus removes all\n" \ " announce URIs. When specifying '*' in shell\n" \ " command-line, don't forget to escape or quote it.\n" \ " See also --bt-tracker option.") #define TEXT_MAX_DOWNLOAD_RESULT \ _(" --max-download-result=NUM Set maximum number of download result kept in\n" \ " memory. The download results are completed/error/\n" \ " removed downloads. The download results are stored\n" \ " in FIFO queue and it can store at most NUM\n" \ " download results. When queue is full and new\n" \ " download result is created, oldest download result\n" \ " is removed from the front of the queue and new one\n" \ " is pushed to the back. Setting big number in this\n" \ " option may result high memory consumption after\n" \ " thousands of downloads. Specifying 0 means no\n" \ " download result is kept. Note that unfinished\n" \ " downloads are kept in memory regardless of this\n" \ " option value. See\n" \ " --keep-unfinished-download-result option.") #define TEXT_ASYNC_DNS_SERVER \ _(" --async-dns-server=IPADDRESS[,...] Comma separated list of DNS server address\n" \ " used in asynchronous DNS resolver. Usually\n" \ " asynchronous DNS resolver reads DNS server\n" \ " addresses from /etc/resolv.conf. When this option\n" \ " is used, it uses DNS servers specified in this\n" \ " option instead of ones in /etc/resolv.conf. You\n" \ " can specify both IPv4 and IPv6 address. This\n" \ " option is useful when the system does not have\n" \ " /etc/resolv.conf and user does not have the\n" \ " permission to create it.") #define TEXT_ENABLE_RPC \ _(" --enable-rpc[=true|false] Enable JSON-RPC/XML-RPC server.\n" \ " It is strongly recommended to set secret\n" \ " authorization token using --rpc-secret option.\n" \ " See also --rpc-listen-port option.") #define TEXT_RPC_MAX_REQUEST_SIZE \ _(" --rpc-max-request-size=SIZE Set max size of JSON-RPC/XML-RPC request. If aria2\n" \ " detects the request is more than SIZE bytes, it\n" \ " drops connection.") #define TEXT_RPC_USER \ _(" --rpc-user=USER Set JSON-RPC/XML-RPC user. This option will be\n" \ " deprecated in the future release. Migrate to\n" \ " --rpc-secret option as soon as possible.") #define TEXT_RPC_PASSWD \ _(" --rpc-passwd=PASSWD Set JSON-RPC/XML-RPC password. This option will\n" \ " be deprecated in the future release. Migrate to\n" \ " --rpc-secret option as soon as possible.") #define TEXT_RPC_LISTEN_ALL \ _(" --rpc-listen-all[=true|false] Listen incoming JSON-RPC/XML-RPC requests on all\n" \ " network interfaces. If false is given, listen only\n" \ " on local loopback interface.") #define TEXT_RPC_LISTEN_PORT \ _(" --rpc-listen-port=PORT Specify a port number for JSON-RPC/XML-RPC server\n" \ " to listen to.") #define TEXT_SHOW_CONSOLE_READOUT \ _(" --show-console-readout[=true|false] Show console readout.") #define TEXT_METALINK_BASE_URI \ _(" --metalink-base-uri=URI Specify base URI to resolve relative URI in\n" \ " metalink:url and metalink:metaurl element in a\n" \ " metalink file stored in local disk. If URI points\n" \ " to a directory, URI must end with '/'.") #define TEXT_STREAM_PIECE_SELECTOR \ _(" --stream-piece-selector=SELECTOR Specify piece selection algorithm\n" \ " used in HTTP/FTP download. Piece means fixed\n" \ " length segment which is downloaded in parallel\n" \ " in segmented download. If 'default' is given,\n" \ " aria2 selects piece so that it reduces the\n" \ " number of establishing connection. This is\n" \ " reasonable default behaviour because\n" \ " establishing connection is an expensive\n" \ " operation.\n" \ " If 'inorder' is given, aria2 selects piece which\n" \ " has minimum index. Index=0 means first of the\n" \ " file. This will be useful to view movie while\n" \ " downloading it. --enable-http-pipelining option\n" \ " may be useful to reduce reconnection overhead.\n" \ " Please note that aria2 honors\n" \ " --min-split-size option, so it will be necessary\n" \ " to specify a reasonable value to\n" \ " --min-split-size option.\n" \ " If 'random' is given, aria2 selects piece\n" \ " randomly. Like 'inorder', --min-split-size\n" \ " option is honored.\n" \ " If 'geom' is given, at the beginning aria2\n" \ " selects piece which has minimum index like\n" \ " 'inorder', but it exponentially increasingly\n" \ " keeps space from previously selected piece. This\n" \ " will reduce the number of establishing connection\n" \ " and at the same time it will download the\n" \ " beginning part of the file first. This will be\n" \ " useful to view movie while downloading it.") #define TEXT_TRUNCATE_CONSOLE_READOUT \ _(" --truncate-console-readout[=true|false] Truncate console readout to fit in\n"\ " a single line.") #define TEXT_PAUSE \ _(" --pause[=true|false] Pause download after added. This option is\n" \ " effective only when --enable-rpc=true is given.") #define TEXT_RPC_ALLOW_ORIGIN_ALL \ _(" --rpc-allow-origin-all[=true|false] Add Access-Control-Allow-Origin header\n" \ " field with value '*' to the RPC response.") #define TEXT_DOWNLOAD_RESULT \ _(" --download-result=OPT This option changes the way \"Download Results\"\n" \ " is formatted. If OPT is 'default', print GID,\n" \ " status, average download speed and path/URI. If\n" \ " multiple files are involved, path/URI of first\n" \ " requested file is printed and remaining ones are\n" \ " omitted.\n" \ " If OPT is 'full', print GID, status, average\n" \ " download speed, percentage of progress and\n" \ " path/URI. The percentage of progress and\n" \ " path/URI are printed for each requested file in\n" \ " each row.\n" \ " If OPT is 'hide', \"Download Results\" is hidden.") #define TEXT_HASH_CHECK_ONLY \ _(" --hash-check-only[=true|false] If true is given, after hash check using\n" \ " --check-integrity option, abort download whether\n" \ " or not download is complete.") #define TEXT_CHECKSUM \ _(" --checksum=TYPE=DIGEST Set checksum. TYPE is hash type. The supported\n" \ " hash type is listed in \"Hash Algorithms\" in\n" \ " \"aria2c -v\". DIGEST is hex digest.\n" \ " For example, setting sha-1 digest looks like\n" \ " this:\n" \ " sha-1=0192ba11326fe2298c8cb4de616f4d4140213838\n" \ " This option applies only to HTTP(S)/FTP\n" \ " downloads.") #define TEXT_PIECE_LENGTH \ _(" --piece-length=LENGTH Set a piece length for HTTP/FTP downloads. This\n" \ " is the boundary when aria2 splits a file. All\n" \ " splits occur at multiple of this length. This\n" \ " option will be ignored in BitTorrent downloads.\n" \ " It will be also ignored if Metalink file\n" \ " contains piece hashes.") #define TEXT_STOP_WITH_PROCESS \ _(" --stop-with-process=PID Stop application when process PID is not running.\n" \ " This is useful if aria2 process is forked from a\n" \ " parent process. The parent process can fork aria2\n" \ " with its own pid and when parent process exits\n" \ " for some reason, aria2 can detect it and shutdown\n" \ " itself.") #define TEXT_DEFERRED_INPUT \ _(" --deferred-input[=true|false] If true is given, aria2 does not read all URIs\n" \ " and options from file specified by -i option at\n" \ " startup, but it reads one by one when it needs\n" \ " later. This may reduce memory usage if input\n" \ " file contains a lot of URIs to download.\n" \ " If false is given, aria2 reads all URIs and\n" \ " options at startup.") #define TEXT_BT_REMOVE_UNSELECTED_FILE \ _(" --bt-remove-unselected-file[=true|false] Removes the unselected files when\n" \ " download is completed in BitTorrent. To\n" \ " select files, use --select-file option. If\n" \ " it is not used, all files are assumed to be\n" \ " selected. Please use this option with care\n" \ " because it will actually remove files from\n" \ " your disk.") #define TEXT_ENABLE_MMAP \ _(" --enable-mmap[=true|false] Map files into memory.") #define TEXT_RPC_CERTIFICATE \ _(" --rpc-certificate=FILE Use the certificate in FILE for RPC server.\n" \ " The certificate must be in PEM format.\n" \ " Use --rpc-private-key option to specify the\n" \ " private key. Use --rpc-secure option to enable\n" \ " encryption.") #define TEXT_RPC_PRIVATE_KEY \ _(" --rpc-private-key=FILE Use the private key in FILE for RPC server.\n" \ " The private key must be decrypted and in PEM\n" \ " format. Use --rpc-secure option to enable\n" \ " encryption. See also --rpc-certificate option.") #define TEXT_RPC_SECURE \ _(" --rpc-secure[=true|false] RPC transport will be encrypted by SSL/TLS.\n" \ " The RPC clients must use https scheme to access\n" \ " the server. For WebSocket client, use wss\n" \ " scheme. Use --rpc-certificate and\n" \ " --rpc-private-key options to specify the\n" \ " server certificate and private key.") #define TEXT_RPC_SAVE_UPLOAD_METADATA \ _(" --rpc-save-upload-metadata[=true|false] Save the uploaded torrent or\n" \ " metalink metadata in the directory specified\n" \ " by --dir option. The filename consists of\n" \ " SHA-1 hash hex string of metadata plus\n" \ " extension. For torrent, the extension is\n" \ " '.torrent'. For metalink, it is '.meta4'.\n" \ " If false is given to this option, the\n" \ " downloads added by aria2.addTorrent or\n" \ " aria2.addMetalink will not be saved by\n" \ " --save-session option.") #define TEXT_FORCE_SAVE \ _(" --force-save[=true|false] Save download with --save-session option even\n" \ " if the download is completed or removed. This\n" \ " option also saves control file in that\n" \ " situations. This may be useful to save\n" \ " BitTorrent seeding which is recognized as\n" \ " completed state.") #define TEXT_SAVE_NOT_FOUND \ _(" --save-not-found[=true|false] Save download with --save-session option even\n" \ " if the file was not found on the server. This\n" \ " option also saves control file in that\n" \ " situations.") #define TEXT_DISK_CACHE \ _(" --disk-cache=SIZE Enable disk cache. If SIZE is 0, the disk cache\n" \ " is disabled. This feature caches the downloaded\n" \ " data in memory, which grows to at most SIZE\n" \ " bytes. The cache storage is created for aria2\n" \ " instance and shared by all downloads. The one\n" \ " advantage of the disk cache is reduce the disk\n" \ " I/O because the data are written in larger unit\n" \ " and it is reordered by the offset of the file.\n" \ " If hash checking is involved and the data are\n" \ " cached in memory, we don't need to read them\n" \ " from the disk.\n" \ " SIZE can include K or M(1K = 1024, 1M = 1024K).") #define TEXT_GID \ _(" --gid=GID Set GID manually. aria2 identifies each\n" \ " download by the ID called GID. The GID must be\n" \ " hex string of 16 characters, thus [0-9a-fA-F]\n" \ " are allowed and leading zeros must not be\n" \ " stripped. The GID all 0 is reserved and must\n" \ " not be used. The GID must be unique, otherwise\n" \ " error is reported and the download is not added.\n" \ " This option is useful when restoring the\n" \ " sessions saved using --save-session option. If\n" \ " this option is not used, new GID is generated\n" \ " by aria2.") #define TEXT_CONSOLE_LOG_LEVEL \ _(" --console-log-level=LEVEL Set log level to output to console.") #define TEXT_SAVE_SESSION_INTERVAL \ _(" --save-session-interval=SEC Save error/unfinished downloads to a file\n" \ " specified by --save-session option every SEC\n" \ " seconds. If 0 is given, file will be saved only\n" \ " when aria2 exits.") #define TEXT_ENABLE_COLOR \ _(" --enable-color[=true|false] Enable color output for a terminal.") #define TEXT_RPC_SECRET \ _(" --rpc-secret=TOKEN Set RPC secret authorization token.") #define TEXT_DSCP \ _(" --dscp=DSCP Set DSCP value in outgoing IP packets of\n" \ " BitTorrent traffic for QoS. This parameter sets\n" \ " only DSCP bits in TOS field of IP packets,\n" \ " not the whole field. If you take values\n" \ " from /usr/include/netinet/ip.h divide them by 4\n" \ " (otherwise values would be incorrect, e.g. your\n" \ " CS1 class would turn into CS4). If you take\n" \ " commonly used values from RFC, network vendors'\n" \ " documentation, Wikipedia or any other source,\n" \ " use them as they are.") #define TEXT_RLIMIT_NOFILE \ _(" --rlimit-nofile=NUM Set the soft limit of open file descriptors.\n" \ " This open will only have effect when:\n" \ " a) The system supports it (posix)\n" \ " b) The limit does not exceed the hard limit.\n" \ " c) The specified limit is larger than the\n" \ " current soft limit.\n" \ " This is equivalent to setting nofile via ulimit,\n" \ " except that it will never decrease the limit.") #define TEXT_PAUSE_METADATA \ _(" --pause-metadata[=true|false]\n" \ " Pause downloads created as a result of metadata\n" \ " download. There are 3 types of metadata\n" \ " downloads in aria2: (1) downloading .torrent\n" \ " file. (2) downloading torrent metadata using\n" \ " magnet link. (3) downloading metalink file.\n" \ " These metadata downloads will generate downloads\n" \ " using their metadata. This option pauses these\n" \ " subsequent downloads. This option is effective\n" \ " only when --enable-rpc=true is given.") #define TEXT_BT_DETACH_SEED_ONLY \ _(" --bt-detach-seed-only[=true|false]\n" \ " Exclude seed only downloads when counting\n" \ " concurrent active downloads (See -j option).\n" \ " This means that if -j3 is given and this option\n" \ " is turned on and 3 downloads are active and one\n" \ " of those enters seed mode, then it is excluded\n" \ " from active download count (thus it becomes 2),\n" \ " and the next download waiting in queue gets\n" \ " started. But be aware that seeding item is still\n" \ " recognized as active download in RPC method.") #define TEXT_MIN_TLS_VERSION \ _(" --min-tls-version=VERSION Specify minimum SSL/TLS version to enable.") #define TEXT_BT_FORCE_ENCRYPTION \ _(" --bt-force-encryption[=true|false]\n" \ " Requires BitTorrent message payload encryption\n" \ " with arc4. This is a shorthand of\n" \ " --bt-require-crypto --bt-min-crypto-level=arc4.\n" \ " If true is given, deny legacy BitTorrent\n" \ " handshake and only use Obfuscation handshake and\n" \ " always encrypt message payload.") #define TEXT_SSH_HOST_KEY_MD \ _(" --ssh-host-key-md=TYPE=DIGEST\n" \ " Set checksum for SSH host public key. TYPE is\n" \ " hash type. The supported hash type is sha-1 or\n" \ " md5. DIGEST is hex digest. For example:\n" \ " sha-1=b030503d4de4539dc7885e6f0f5e256704edf4c3\n" \ " This option can be used to validate server's\n" \ " public key when SFTP is used. If this option is\n" \ " not set, which is default, no validation takes\n" \ " place.") #define TEXT_SOCKET_RECV_BUFFER_SIZE \ _(" --socket-recv-buffer-size=SIZE\n" \ " Set the maximum socket receive buffer in bytes.\n" \ " Specifying 0 will disable this option. This value\n" \ " will be set to socket file descriptor using\n" \ " SO_RCVBUF socket option with setsockopt() call.") #define TEXT_BT_ENABLE_HOOK_AFTER_HASH_CHECK \ _(" --bt-enable-hook-after-hash-check[=true|false] Allow hook command invocation\n" \ " after hash check (see -V option) in BitTorrent\n" \ " download. By default, when hash check succeeds,\n" \ " the command given by --on-bt-download-complete\n" \ " is executed. To disable this action, give false\n" \ " to this option.") #define TEXT_MAX_MMAP_LIMIT \ _(" --max-mmap-limit=SIZE Set the maximum file size to enable mmap (see\n" \ " --enable-mmap option). The file size is\n" \ " determined by the sum of all files contained in\n" \ " one download. For example, if a download\n" \ " contains 5 files, then file size is the total\n" \ " size of those files. If file size is strictly\n" \ " greater than the size specified in this option,\n" \ " mmap will be disabled.") #define TEXT_STDERR \ _(" --stderr[=true|false] Redirect all console output that would be\n" \ " otherwise printed in stdout to stderr.") #define TEXT_KEEP_UNFINISHED_DOWNLOAD_RESULT \ _(" --keep-unfinished-download-result[=true|false]\n" \ " Keep unfinished download results even if doing\n" \ " so exceeds --max-download-result. This is useful\n" \ " if all unfinished downloads must be saved in\n" \ " session file (see --save-session option). Please\n" \ " keep in mind that there is no upper bound to the\n" \ " number of unfinished download result to keep. If\n" \ " that is undesirable, turn this option off.") #define TEXT_BT_LOAD_SAVED_METADATA \ _(" --bt-load-saved-metadata[=true|false]\n" \ " Before getting torrent metadata from DHT when\n" \ " downloading with magnet link, first try to read\n" \ " file saved by --bt-save-metadata option. If it is\n" \ " successful, then skip downloading metadata from\n" \ " DHT.") // clang-format on
87,393
C++
.h
1,129
73.566873
98
0.45073
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,474
a2time.h
aria2_aria2/src/a2time.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_A2TIME_H #define D_A2TIME_H #include <time.h> #include <sys/time.h> #include <chrono> #ifndef HAVE_LOCALTIME_R # include "localtime_r.h" #endif // HAVE_LOCALTIME_R #ifndef HAVE_GETTIMEOFDAY # include "gettimeofday.h" #endif // HAVE_GETTIMEOFDAY #ifndef HAVE_STRPTIME # include "strptime.h" #endif // HAVE_STRPTIME #ifndef HAVE_TIMEGM # include "timegm.h" #endif // HAVE_TIMEGM #ifndef HAVE_ASCTIME_R # include "asctime_r.h" #endif // HAVE_ASCTIME_R #ifdef __MINGW32__ # define suseconds_t uint64_t #endif #ifndef HAVE_A2_STRUCT_TIMESPEC # include "timespec.h" #endif // !HAVE_A2_STRUCT_TIMESPEC // Rounding error in millis constexpr auto A2_DELTA_MILLIS = std::chrono::milliseconds(10); #endif // D_A2TIME_H
2,332
C++
.h
63
35.349206
79
0.758636
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,483
timegm.h
aria2_aria2/src/timegm.h
/* * aria2 - The high speed download utility * * Copyright (C) 2012 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_TIMEGM_H #define D_TIMEGM_H #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include <time.h> #ifndef HAVE_TIMEGM time_t timegm(struct tm* tm); #endif // HAVE_TIMEGM #ifdef __cplusplus } #endif /* __cplusplus */ #endif // D_TIMEGM_H
1,902
C++
.h
49
37.020408
79
0.755014
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,490
DHTConstants.h
aria2_aria2/src/DHTConstants.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_DHT_CONSTANTS_H #define D_DHT_CONSTANTS_H #include "common.h" #include "TimerA2.h" #include "a2functional.h" namespace aria2 { // Increment this if major improvements or bug fixes are made in DHT // code. This is 2 bytes unsigned integer. constexpr uint16_t DHT_VERSION = 3U; constexpr size_t DHT_ID_LENGTH = 20; constexpr size_t DHT_TRANSACTION_ID_LENGTH = 4; // See --dht-message-timeout option. constexpr auto DHT_MESSAGE_TIMEOUT = 10_s; constexpr auto DHT_NODE_CONTACT_INTERVAL = 15_min; constexpr auto DHT_BUCKET_REFRESH_INTERVAL = 15_min; constexpr auto DHT_BUCKET_REFRESH_CHECK_INTERVAL = 5_min; constexpr auto DHT_PEER_ANNOUNCE_PURGE_INTERVAL = 30_min; constexpr auto DHT_PEER_ANNOUNCE_INTERVAL = 15_min; constexpr auto DHT_PEER_ANNOUNCE_CHECK_INTERVAL = 5_min; constexpr auto DHT_TOKEN_UPDATE_INTERVAL = 10_min; } // namespace aria2 #endif // D_DHT_CONSTANTS_H
2,491
C++
.h
56
42.660714
79
0.768595
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,530
SHA1IOFile.h
aria2_aria2/src/SHA1IOFile.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_SHA1_IO_FILE_H #define D_SHA1_IO_FILE_H #include "IOFile.h" #include "MessageDigest.h" #include <memory> namespace aria2 { // Class to calculate SHA1 hash value for data written into this // object. No file I/O is done in this class. class SHA1IOFile : public IOFile { public: SHA1IOFile(); std::string digest(); protected: // Not implemented virtual size_t onRead(void* ptr, size_t count) CXX11_OVERRIDE; virtual size_t onWrite(const void* ptr, size_t count) CXX11_OVERRIDE; // Not implemented virtual char* onGets(char* s, int size) CXX11_OVERRIDE; virtual int onVprintf(const char* format, va_list va) CXX11_OVERRIDE; virtual int onFlush() CXX11_OVERRIDE; virtual int onClose() CXX11_OVERRIDE; virtual bool onSupportsColor() CXX11_OVERRIDE; virtual bool isError() const CXX11_OVERRIDE; virtual bool isEOF() const CXX11_OVERRIDE; virtual bool isOpen() const CXX11_OVERRIDE; private: std::unique_ptr<MessageDigest> sha1_; }; } // namespace aria2 #endif // D_SHA1_IO_FILE_H
2,619
C++
.h
64
38.84375
79
0.758932
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,538
BtConstants.h
aria2_aria2/src/BtConstants.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_BT_CONSTANTS_H #define D_BT_CONSTANTS_H #include "common.h" #include "a2functional.h" namespace aria2 { constexpr size_t INFO_HASH_LENGTH = 20; constexpr size_t PIECE_HASH_LENGTH = 20; constexpr size_t PEER_ID_LENGTH = 20; constexpr size_t MAX_BLOCK_LENGTH = 64_k; constexpr size_t DEFAULT_MAX_OUTSTANDING_REQUEST = 6; // Upper Bound of the number of outstanding request constexpr size_t UB_MAX_OUTSTANDING_REQUEST = 256; constexpr size_t METADATA_PIECE_SIZE = 16_k; constexpr const char LPD_MULTICAST_ADDR[] = "239.192.152.143"; constexpr uint16_t LPD_MULTICAST_PORT = 6771; constexpr size_t COMPACT_LEN_IPV4 = 6; constexpr size_t COMPACT_LEN_IPV6 = 18; } // namespace aria2 #endif // D_BT_CONSTANTS_H
2,324
C++
.h
53
41.981132
79
0.764628
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,548
strptime.h
aria2_aria2/src/strptime.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2007 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef _D_STRPTIME_H #define _D_STRPTIME_H #include <time.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ char* strptime(const char* buf, const char* format, struct tm* timeptr); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* not _D_STRPTIME_H */
1,871
C++
.h
45
39.755556
79
0.751099
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
1,555
uri_split.h
aria2_aria2/src/uri_split.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2012 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_URI_SPLIT_H #define D_URI_SPLIT_H #ifdef __cplusplus extern "C" { #endif #include <sys/types.h> #include <stdint.h> typedef enum { USR_SCHEME, USR_HOST, USR_PORT, USR_PATH, USR_QUERY, USR_FRAGMENT, USR_USERINFO, USR_USER, USR_PASSWD, USR_BASENAME, USR_MAX } uri_split_field; typedef enum { USF_IPV6ADDR = 1 } uri_split_flag; /* The structure is based on http-parser by Joyent, Inc and other Node contributors. https://github.com/joyent/http-parser */ typedef struct { uint16_t field_set; uint16_t port; struct { uint16_t off; uint16_t len; } fields[USR_MAX]; uint8_t flags; } uri_split_result; /* Splits URI |uri| and stores the results in the |res|. To check * particular URI component is available, evaluate |res->field_set| * with 1 shifted by the field defined in uri_split_field. If the * |res| is NULL, processing is done but the result will not stored. * If the host component of the |uri| is IPv6 numeric address, then * USF_IPV6ADDR & res->flags will be nonzero. * * This function returns 0 if it succeeds, or -1. */ int uri_split(uri_split_result* res, const char* uri); #ifdef __cplusplus } #endif #endif /* D_URI_SPLIT_H */
2,803
C++
.h
80
32.8875
79
0.742352
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
1,576
libssl_compat.h
aria2_aria2/src/libssl_compat.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2016 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef LIBSSL_COMPAT_H #define LIBSSL_COMPAT_H #include <openssl/opensslv.h> #if defined(LIBRESSL_VERSION_NUMBER) # define LIBRESSL_IN_USE 1 #else // !defined(LIBRESSL_VERSION_NUMBER) # define LIBRESSL_IN_USE 0 #endif // !defined(LIBRESSL_VERSION_NUMBER) #define OPENSSL_101_API \ ((!LIBRESSL_IN_USE && OPENSSL_VERSION_NUMBER >= 0x1010000fL) || \ (LIBRESSL_IN_USE && LIBRESSL_VERSION_NUMBER >= 0x20700000L)) #endif // LIBSSL_COMPAT_H
2,110
C++
.h
46
44
80
0.73301
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,587
SSHSession.h
aria2_aria2/src/SSHSession.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef SSH_SESSION_H #define SSH_SESSION_H #include "common.h" #include "a2netcompat.h" #include <string> #include <libssh2.h> #include <libssh2_sftp.h> namespace aria2 { enum SSHDirection { SSH_WANT_READ = 1, SSH_WANT_WRITE }; enum SSHErrorCode { SSH_ERR_OK = 0, SSH_ERR_ERROR = -1, SSH_ERR_WOULDBLOCK = -2 }; class SSHSession { public: SSHSession(); // MUST deallocate all resources ~SSHSession(); SSHSession(const SSHSession&) = delete; SSHSession& operator=(const SSHSession&) = delete; // Initializes SSH session. The |sockfd| is the underlying // transport socket. This function returns SSH_ERR_OK if it // succeeds, or SSH_ERR_ERROR. int init(sock_t sockfd); // Closes the SSH session. Don't close underlying transport // socket. This function returns SSH_ERR_OK if it succeeds, or // SSH_ERR_ERROR. int closeConnection(); int gracefulShutdown(); // Returns SSH_WANT_READ if SSH session needs more data from remote // endpoint to proceed, or SSH_WANT_WRITE if SSH session needs to // write more data to proceed. If SSH session needs neither read nor // write data at the moment, SSH_WANT_READ must be returned. int checkDirection(); // Sends |data| with length |len|. This function returns the number // of bytes sent if it succeeds, or SSH_ERR_WOULDBLOCK if the // underlying transport blocks, or SSH_ERR_ERROR. ssize_t writeData(const void* data, size_t len); // Receives data into |data| with length |len|. This function // returns the number of bytes received if it succeeds, or // SSH_ERR_WOULDBLOCK if the underlying transport blocks, or // SSH_ERR_ERROR. ssize_t readData(void* data, size_t len); // Performs handshake. This function returns SSH_ERR_OK // if it succeeds, or SSH_ERR_WOULDBLOCK if the underlying transport // blocks, or SSH_ERR_ERROR. int handshake(); // Returns message digest of host's public key. |hashType| must be // either "sha-1" or "md5". std::string hostkeyMessageDigest(const std::string& hashType); // Performs authentication using username and password. This // function returns SSH_ERR_OK if it succeeds, or SSH_ERR_WOULDBLOCK // if the underlying transport blocks, or SSH_ERR_ERROR. int authPassword(const std::string& user, const std::string& password); // Starts SFTP session and opens remote file |path|. This function // returns SSH_ERR_OK if it succeeds, or SSH_ERR_WOULDBLOCK if the // underlying transport blocks, or SSH_ERR_ERROR. int sftpOpen(const std::string& path); // Closes remote file opened by sftpOpen(). This function returns // SSH_ERR_OK if it succeeds, or SSH_ERR_WOULDBLOCK if the // underlying transport blocks, or SSH_ERR_ERROR. int sftpClose(); // Gets total length and modified time of opened file by sftpOpen(). // On success, total length and modified time are assigned to // |totalLength| and |mtime|. This function returns SSH_ERR_OK if // it succeeds, or SSH_ERR_WOULDBLOCK if the underlying transport // blocks, or SSH_ERR_ERROR. int sftpStat(int64_t& totalLength, time_t& mtime); // Moves file position to |pos|. void sftpSeek(int64_t pos); // Returns last error string std::string getLastErrorString(); private: LIBSSH2_SESSION* ssh2_; LIBSSH2_SFTP* sftp_; LIBSSH2_SFTP_HANDLE* sftph_; sock_t fd_; }; } // namespace aria2 #endif // SSH_SESSION_H
4,979
C++
.h
115
40.695652
79
0.742302
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,601
TimeA2.h
aria2_aria2/src/TimeA2.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_TIME_H #define D_TIME_H #include "common.h" #include <stdint.h> #include <string> #include "a2time.h" namespace aria2 { class Time { public: using Clock = std::chrono::system_clock; // The time value is initialized so that it represents the time at which // this object was created. Time(); Time(const Time& time) = default; Time(Time&& time) = default; Time(time_t sec); Time& operator=(const Time& time) = default; Time& operator=(Time&& time) = default; bool operator<(const Time& time) const { return tp_ < time.tp_; } bool operator>(const Time& time) const { return time < *this; } bool operator<=(const Time& time) const { return !(time < *this); } bool operator>=(const Time& time) const { return !(*this < time); } // Makes this object's time value up to date. void reset(); Clock::duration difference() const; Clock::duration difference(const Time& now) const; const Clock::time_point& getTime() const { return tp_; } void setTimeFromEpoch(time_t sec); time_t getTimeFromEpoch() const { return Clock::to_time_t(tp_); } template <typename duration> void advance(const duration& t) { tp_ += t; } bool good() const { return good_; } bool bad() const { return !good_; } static Time null() { return Time(0, false); } std::string toHTTPDate() const; // Currently timezone is assumed as GMT. static Time parse(const std::string& datetime, const std::string& format); // Currently timezone is assumed to GMT. static Time parseRFC1123(const std::string& datetime); // Like parseRFC1123, but only accepts trailing "+0000" instead of // last 3 letters "GMT". static Time parseRFC1123Alt(const std::string& datetime); // Currently timezone is assumed to GMT. static Time parseRFC850(const std::string& datetime); // Currently timezone is assumed to GMT. Basically the format is // RFC850, but year part is 4digit, eg 2008 This format appears in // original Netscape's PERSISTENT CLIENT STATE HTTP COOKIES // Specification. http://curl.haxx.se/rfc/cookie_spec.html static Time parseRFC850Ext(const std::string& datetime); // Currently timezone is assumed to GMT. // ANSI C's asctime() format static Time parseAsctime(const std::string& datetime); // Try parseRFC1123, parseRFC850, parseAsctime, parseRFC850Ext in // that order and returns the first "good" Time object returned by // these functions. static Time parseHTTPDate(const std::string& datetime); private: Time(time_t t, bool good) : tp_(Clock::from_time_t(t)), good_(good) {} Clock::time_point tp_; bool good_; }; } // namespace aria2 #endif // D_TIME_H
4,243
C++
.h
96
41.5625
79
0.732702
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,629
SocketRecvBuffer.h
aria2_aria2/src/SocketRecvBuffer.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2011 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_SOCKET_RECV_BUFFER_H #define D_SOCKET_RECV_BUFFER_H #include "common.h" #include <memory> #include <array> #include "a2functional.h" namespace aria2 { class SocketCore; class SocketRecvBuffer { public: SocketRecvBuffer(std::shared_ptr<SocketCore> socket); ~SocketRecvBuffer(); // Reads data from socket as much as capacity allows. Returns the // number of bytes read. ssize_t recv(); // Truncates the contents of buffer to 0. void truncateBuffer(); // Drains first n bytes of data from buffer. It is an programmer's // responsibility to ensure that n is smaller or equal to the // buffered data. void drain(size_t n); const std::shared_ptr<SocketCore>& getSocket() const { return socket_; } const unsigned char* getBuffer() const { return pos_; } size_t getBufferLength() const { return last_ - pos_; } bool bufferEmpty() const { return pos_ == last_; } private: std::array<unsigned char, 16_k> buf_; std::shared_ptr<SocketCore> socket_; unsigned char* pos_; unsigned char* last_; }; } // namespace aria2 #endif // D_SOCKET_RECV_BUFFER_H
2,696
C++
.h
67
38.014925
79
0.747706
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,634
common.h
aria2_aria2/src/common.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_COMMON_H #define D_COMMON_H #ifdef HAVE_CONFIG_H # include "config.h" #endif #ifdef __MINGW32__ # ifdef malloc # undef malloc # endif # ifdef realloc # undef realloc # endif #endif // __MINGW32__ #ifdef __MINGW32__ # define WIN32_LEAN_AND_MEAN # ifndef WINVER # define WINVER 0x501 # endif // !WINVER # ifndef _WIN32_WINNT # define _WIN32_WINNT 0x501 # endif // _WIN32_WINNT # ifdef HAVE_WINSOCK2_H # ifndef FD_SETSIZE # define FD_SETSIZE 32768 # endif // !FD_SETSIZE # include <winsock2.h> # undef ERROR # endif // HAVE_WINSOCK2_H # include <windows.h> #endif // __MINGW32__ #ifdef ENABLE_NLS // If we put #include <gettext.h> outside of #ifdef ENABLE_NLS and // --disable-nls is used, gettext(msgid) is defined as ((const char *) // (Msgid)). System header includes libintl.h regardless of // --disable-nls. For example, #include <string> will include // libintl.h through include chain. Since libintl.h refers gettext and // it is defined as non-function form, this causes compile error. User // reported gcc-4.2.2 has this problem. But gcc-4.4.5 does not suffer // from this problem. # include <gettext.h> # define _(String) gettext(String) #else // ENABLE_NLS # define _(String) String #endif // use C99 limit macros #define __STDC_LIMIT_MACROS // included here for compatibility issues with old compiler/libraries. #ifdef HAVE_STDINT_H # include <stdint.h> #endif // HAVE_STDINT_H // For PRId64 #define __STDC_FORMAT_MACROS #ifdef HAVE_INTTYPES_H # include <inttypes.h> #endif // HAVE_INTTYPES_H #ifdef HAVE_SYS_TYPES_H # include <sys/types.h> #endif #endif // D_COMMON_H
3,240
C++
.h
93
33.419355
79
0.739726
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,649
GenericParser.h
aria2_aria2/src/GenericParser.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2012 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_GENERIC_PARSER_H #define D_GENERIC_PARSER_H #include <array> #include "common.h" #include "a2io.h" #include "util.h" namespace aria2 { template <typename Parser, typename ParserStateMachine, bool allowEmptyName = false> class GenericParser { public: GenericParser() : parser_{&psm_} { psm_.setAllowEmptyMemberName(allowEmptyName); } ~GenericParser() = default; typedef typename ParserStateMachine::ResultType ResultType; typedef ParserStateMachine ParserStateMachineType; // Parses |size| bytes of data |data| and returns the number of // bytes processed. On error, one of the negative error codes is // returned. ssize_t parseUpdate(const char* data, size_t size) { return parser_.parseUpdate(data, size); } // Parses |size| bytes of data |data| and returns result. On error, // null value is returned. On success, the |error| will be the // number of bytes processed (>= 0). On error, it will be one of the // negative error code. This function also resets underlying parser // facility and make it ready to reuse. ResultType parseFinal(const char* data, size_t size, ssize_t& error) { ResultType res; error = parser_.parseFinal(data, size); if (error < 0) { res = ParserStateMachine::noResult(); } else { res = psm_.getResult(); } parser_.reset(); return res; } private: ParserStateMachine psm_; Parser parser_; }; template <typename Parser> typename Parser::ResultType parseFile(Parser& parser, const std::string& filename) { int fd; // TODO Overrode a2open(const char*,..) and a2open(const std::wstring&,..) while ((fd = a2open(utf8ToWChar(filename).c_str(), O_BINARY | O_RDONLY, OPEN_MODE)) == -1 && errno == EINTR) ; if (fd == -1) { return Parser::ParserStateMachineType::noResult(); } auto fdclose = defer(fd, close); std::array<char, 4_k> buf; ssize_t nread; ssize_t nproc; while ((nread = read(fd, buf.data(), buf.size())) > 0) { nproc = parser.parseUpdate(buf.data(), nread); if (nproc < 0) { break; } } return parser.parseFinal(0, 0, nproc); } } // namespace aria2 #endif // D_GENERIC_PARSER_H
3,848
C++
.h
108
32.157407
79
0.708501
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,672
SocketCore.h
aria2_aria2/src/SocketCore.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_SOCKET_CORE_H #define D_SOCKET_CORE_H #include "common.h" #include <string> #include <cstdlib> #include <utility> #include <vector> #include <memory> #include "a2netcompat.h" #include "a2io.h" #include "a2netcompat.h" #include "a2time.h" namespace aria2 { #ifdef ENABLE_SSL class TLSContext; class TLSSession; #endif // ENABLE_SSL #ifdef HAVE_LIBSSH2 class SSHSession; #endif // HAVE_LIBSSH2 class SocketCore { friend bool operator==(const SocketCore& s1, const SocketCore& s2); friend bool operator!=(const SocketCore& s1, const SocketCore& s2); friend bool operator<(const SocketCore& s1, const SocketCore& s2); private: // socket type defined in <sys/socket.h> int sockType_; // socket endpoint descriptor sock_t sockfd_; static int protocolFamily_; static int ipDscp_; static std::vector<SockAddr> bindAddrs_; static std::vector<std::vector<SockAddr>> bindAddrsList_; static std::vector<std::vector<SockAddr>>::iterator bindAddrsListIt_; static int socketRecvBufferSize_; bool blocking_; int secure_; bool wantRead_; bool wantWrite_; #if ENABLE_SSL // TLS context for client side static std::shared_ptr<TLSContext> clTlsContext_; // TLS context for server side static std::shared_ptr<TLSContext> svTlsContext_; std::shared_ptr<TLSSession> tlsSession_; /** * Makes this socket secure. The connection must be established * before calling this method. * * If you are going to verify peer's certificate, hostname must be supplied. */ bool tlsHandshake(TLSContext* tlsctx, const std::string& hostname); #endif // ENABLE_SSL #ifdef HAVE_LIBSSH2 std::unique_ptr<SSHSession> sshSession_; void sshCheckDirection(); #endif // HAVE_LIBSSH2 void init(); void bind(const struct sockaddr* addr, socklen_t addrlen); void setSockOpt(int level, int optname, void* optval, socklen_t optlen); public: SocketCore(int sockType = SOCK_STREAM); // Formally, private constructor, but made public to use with // std::make_shared. SocketCore(sock_t sockfd, int sockType); ~SocketCore(); sock_t getSockfd() const { return sockfd_; } bool isOpen() const { return sockfd_ != (sock_t)-1; } void setMulticastInterface(const std::string& localAddr); void setMulticastTtl(unsigned char ttl); void setMulticastLoop(unsigned char loop); void joinMulticastGroup(const std::string& multicastAddr, uint16_t multicastPort, const std::string& localAddr); // Enables TCP_NODELAY socket option if f == true. void setTcpNodelay(bool f); // Set DSCP byte void applyIpDscp(); static void setIpDscp(int ipDscp) { // Here we prepare DSCP value for IPTOS option, which sets whole DS field ipDscp_ = ipDscp << 2; } void create(int family, int protocol = 0); void bindWithFamily(uint16_t port, int family, int flags = AI_PASSIVE); /** * Creates a socket and bind it with locahost's address and port. * flags is set to struct addrinfo's ai_flags. * @param port port to listen. If 0 is specified, os automatically * choose available port. */ void bind(uint16_t port, int flags = AI_PASSIVE); void bind(const char* addrp, uint16_t port, int family, int flags = AI_PASSIVE); /** * Listens form connection on it. * Call bind(uint16_t) before calling this function. */ void beginListen(); /** * Returns host address, family and port of this socket. */ Endpoint getAddrInfo() const; /** * Stores address of this socket to sockaddr. len must be * initialized to the size of sockaddr. On success, address data is * stored in sockaddr and actual size of address structure is stored * in len. */ void getAddrInfo(sockaddr_union& sockaddr, socklen_t& len) const; /** * Returns address family of this socket. * The socket must be connected or bounded to address. */ int getAddressFamily() const; /** * Returns peer's address, family and port. */ Endpoint getPeerInfo() const; /** * Accepts incoming connection on this socket. * You must call beginListen() before calling this method. * @return accepted socket. */ std::shared_ptr<SocketCore> acceptConnection() const; /** * Connects to the server named host and the destination port is port. * This method makes socket non-blocking mode. * To make the socket blocking mode again, call setBlockingMode() after * the connection is established. * @param host hostname or ip address to connect to * @param port service port number to connect to * @param tcpNodelay true to disable Nagle algorithm */ void establishConnection(const std::string& host, uint16_t port, bool tcpNodelay = true); void setNonBlockingMode(); /** * Makes this socket blocking mode. */ void setBlockingMode(); /** * Closes the connection of this socket. */ void closeConnection(); /** * Checks whether this socket is available for writing. * @param timeout the amount of time elapsed before the checking are timed * out. * @return true if the socket is available for writing, * otherwise returns false. */ bool isWritable(time_t timeout); /** * Checks whether this socket is available for reading. * @param timeout the amount of time elapsed before the checking are timed * out. * @return true if the socket is available for reading, * otherwise returns false. */ bool isReadable(time_t timeout); /** * Writes data into this socket. data is a pointer pointing the first * byte of the data and len is the length of data. * If the underlying socket is in blocking mode, this method may block until * all data is sent. * If the underlying socket is in non-blocking mode, this method may return * even if all data is sent. The size of written data is returned. If * underlying socket gets EAGAIN, wantRead_ or wantWrite_ is set accordingly. * This method sets wantRead_ and wantWrite_ to false before do anything else. * @param data data to write * @param len length of data */ ssize_t writeData(const void* data, size_t len); ssize_t writeData(const std::string& msg) { return writeData(msg.c_str(), msg.size()); } ssize_t writeData(const void* data, size_t len, const std::string& host, uint16_t port); ssize_t writeVector(a2iovec* iov, size_t iovcnt); /** * Reads up to len bytes from this socket. * data is a pointer pointing the first * byte of the data, which must be allocated before this method is called. * len is the size of the allocated memory. When this method returns * successfully, len is replaced by the size of the read data. * If the underlying socket is in blocking mode, this method may block until * at least 1byte is received. * If the underlying socket is in non-blocking mode, this method may return * even if no single byte is received. If the underlying socket gets EAGAIN, * wantRead_ or wantWrite_ is set accordingly. * This method sets wantRead_ and wantWrite_ to false before do anything else. * @param data holder to store data. * @param len the maximum size data can store. This method assigns * the number of bytes read to len. */ void readData(void* data, size_t& len); // sender.addr will be numerihost assigned. ssize_t readDataFrom(void* data, size_t len, Endpoint& sender); #ifdef ENABLE_SSL // Performs TLS server side handshake. If handshake is completed, // returns true. If handshake has not been done yet, returns false. bool tlsAccept(); // Performs TLS client side handshake. If handshake is completed, // returns true. If handshake has not been done yet, returns false. // // If you are going to verify peer's certificate, hostname must be // supplied. bool tlsConnect(const std::string& hostname); #endif // ENABLE_SSL #ifdef HAVE_LIBSSH2 // Performs SSH handshake bool sshHandshake(const std::string& hashType, const std::string& digest); // Performs SSH authentication using username and password. bool sshAuthPassword(const std::string& user, const std::string& password); // Starts sftp session and open remote file |path|. bool sshSFTPOpen(const std::string& path); // Closes sftp remote file gracefully bool sshSFTPClose(); // Gets total length and modified time for remote file currently // opened. |path| is used for logging. bool sshSFTPStat(int64_t& totalLength, time_t& mtime, const std::string& path); // Seeks file position to |pos|. void sshSFTPSeek(int64_t pos); bool sshGracefulShutdown(); #endif // HAVE_LIBSSH2 bool operator==(const SocketCore& s) { return sockfd_ == s.sockfd_; } bool operator!=(const SocketCore& s) { return !(*this == s); } bool operator<(const SocketCore& s) { return sockfd_ < s.sockfd_; } std::string getSocketError() const; /** * Returns true if the underlying socket gets EAGAIN in the previous * readData() or writeData() and the socket needs more incoming data to * continue the operation. */ bool wantRead() const; /** * Returns true if the underlying socket gets EAGAIN in the previous * readData() or writeData() and the socket needs to write more data. */ bool wantWrite() const; // Returns buffered data which are already received. This data was // already read from socket, and ready to read without reading // socket. size_t getRecvBufferedLength() const; #ifdef ENABLE_SSL static void setClientTLSContext(const std::shared_ptr<TLSContext>& tlsContext); static void setServerTLSContext(const std::shared_ptr<TLSContext>& tlsContext); #endif // ENABLE_SSL static void setProtocolFamily(int protocolFamily) { protocolFamily_ = protocolFamily; } static void setSocketRecvBufferSize(int size); static int getSocketRecvBufferSize(); // Bind socket to interface. interface may be specified as a // hostname, IP address or interface name like eth0. If the given // interface is not found or binding socket is failed, exception // will be thrown. Set protocolFamily_ before calling this function // if you limit protocol family. // // We cannot use interface as an argument because it is a reserved // keyword in MSVC. static void bindAddress(const std::string& iface); static void bindAllAddress(const std::string& ifaces); // Collects IP addresses of given interface iface and stores in // ifAddres. iface may be specified as a hostname, IP address or // interface name like eth0. You can limit the family of IP // addresses to collect using family argument. aiFlags is passed to // getaddrinfo() as hints.ai_flags. No throw. static std::vector<SockAddr> getInterfaceAddress(const std::string& iface, int family = AF_UNSPEC, int aiFlags = 0); }; // Set default ai_flags. hints.ai_flags is initialized with this // value. void setDefaultAIFlags(int flags); // Wrapper function for getaddrinfo(). The value // flags|DEFAULT_AI_FLAGS is used as ai_flags. You can override // DEFAULT_AI_FLAGS value by calling setDefaultAIFlags() with new // flags. int callGetaddrinfo(struct addrinfo** resPtr, const char* host, const char* service, int family, int sockType, int flags, int protocol); // Provides functionality of inet_ntop using getnameinfo. The return // value is the exact value of getnameinfo returns. You can get error // message using gai_strerror(3). int inetNtop(int af, const void* src, char* dst, socklen_t size); // Provides functionality of inet_pton using getBinAddr. If af is // AF_INET, dst is assumed to be the pointer to struct in_addr. If af // is AF_INET6, dst is assumed to be the pointer to struct in6_addr. // // This function returns 0 if it succeeds, or -1. int inetPton(int af, const char* src, void* dst); namespace net { // Stores binary representation of IP address ip which is represented // in text. ip must be numeric IPv4 or IPv6 address. dest must be // allocated by caller before the call. For IPv4 address, dest must be // at least 4. For IPv6 address, dest must be at least 16. Returns the // number of bytes written in dest, that is 4 for IPv4 and 16 for // IPv6. Return 0 if error occurred. size_t getBinAddr(void* dest, const std::string& ip); // Verifies hostname against presented identifiers in the certificate. // The implementation is based on the procedure described in RFC 6125. bool verifyHostname(const std::string& hostname, const std::vector<std::string>& dnsNames, const std::vector<std::string>& ipAddrs, const std::string& commonName); // Checks public IP address are configured for each family: IPv4 and // IPv6. The result can be obtained using getIpv4AddrConfigured() and // getIpv6AddrConfigured() respectively. void checkAddrconfig(); bool getIPv4AddrConfigured(); bool getIPv6AddrConfigured(); } // namespace net } // namespace aria2 #endif // D_SOCKET_CORE_H
14,733
C++
.h
354
37.847458
80
0.725963
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,674
DHKeyExchange.h
aria2_aria2/src/DHKeyExchange.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_DH_KEY_EXCHANGE_H #define D_DH_KEY_EXCHANGE_H #include "common.h" #ifdef USE_INTERNAL_BIGNUM # include "InternalDHKeyExchange.h" #elif HAVE_LIBGMP # include "LibgmpDHKeyExchange.h" #elif HAVE_LIBGCRYPT # include "LibgcryptDHKeyExchange.h" #elif HAVE_OPENSSL # include "LibsslDHKeyExchange.h" #endif // HAVE_OPENSSL #endif // D_DH_KEY_EXCHANGE_H
1,957
C++
.h
47
39.93617
79
0.765723
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
1,679
LibsslARC4Encryptor.h
aria2_aria2/src/LibsslARC4Encryptor.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_LIBSSL_ARC4_ENCRYPTOR_H #define D_LIBSSL_ARC4_ENCRYPTOR_H #include "common.h" #include <cstdlib> #include <openssl/opensslv.h> #if OPENSSL_VERSION_NUMBER >= 0x30000000L # include <openssl/evp.h> #else // !(OPENSSL_VERSION_NUMBER >= 0x30000000L) # include <openssl/rc4.h> #endif // !(OPENSSL_VERSION_NUMBER >= 0x30000000L) namespace aria2 { class ARC4Encryptor { private: #if OPENSSL_VERSION_NUMBER >= 0x30000000L EVP_CIPHER_CTX* ctx_; #else // !(OPENSSL_VERSION_NUMBER >= 0x30000000L) RC4_KEY key_; #endif // !(OPENSSL_VERSION_NUMBER >= 0x30000000L) public: ARC4Encryptor(); ~ARC4Encryptor(); void init(const unsigned char* key, size_t keyLength); // Encrypts data in in buffer to out buffer. in and out can be the // same buffer. void encrypt(size_t len, unsigned char* out, const unsigned char* in); }; } // namespace aria2 #endif // D_LIBSSL_ARC4_ENCRYPTOR_H
2,498
C++
.h
62
38.354839
79
0.75299
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,680
gettimeofday.h
aria2_aria2/src/gettimeofday.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2007 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef _D_GETTIMEOFDAY_H #define _D_GETTIMEOFDAY_H 1 #ifdef __MINGW32__ # undef SIZE_MAX #endif // __MINGW32__ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <sys/time.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifndef HAVE_GETTIMEOFDAY int __cdecl gettimeofday(struct timeval* __restrict__ tp, void* __restrict__ tzp __attribute__((unused))); #endif // HAVE_GETTIMEOFDAY #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* not _D_GETTIMEOFDAY_H */
2,132
C++
.h
54
37.259259
79
0.738395
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,711
SftpNegotiationCommand.h
aria2_aria2/src/SftpNegotiationCommand.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_SFTP_NEGOTIATION_COMMAND_H #define D_SFTP_NEGOTIATION_COMMAND_H #include "AbstractCommand.h" namespace aria2 { class SocketCore; class AuthConfig; class SftpNegotiationCommand : public AbstractCommand { public: enum Seq { SEQ_HANDSHAKE, SEQ_AUTH_PASSWORD, SEQ_SFTP_OPEN, SEQ_SFTP_STAT, SEQ_SFTP_SEEK, SEQ_NEGOTIATION_COMPLETED, SEQ_DOWNLOAD_ALREADY_COMPLETED, SEQ_HEAD_OK, SEQ_FILE_PREPARATION, SEQ_EXIT, }; private: void onFileSizeDetermined(int64_t totalLength); void poolConnection() const; void onDryRunFileFound(); std::string getPath() const; std::shared_ptr<SocketCore> socket_; Seq sequence_; std::unique_ptr<AuthConfig> authConfig_; // remote file path std::string path_; // expected host's public key message digest: hash type and digest // (raw binary value). std::string hashType_; std::string digest_; protected: virtual bool executeInternal() CXX11_OVERRIDE; public: SftpNegotiationCommand(cuid_t cuid, const std::shared_ptr<Request>& req, const std::shared_ptr<FileEntry>& fileEntry, RequestGroup* requestGroup, DownloadEngine* e, const std::shared_ptr<SocketCore>& s, Seq seq = SEQ_HANDSHAKE); virtual ~SftpNegotiationCommand(); }; } // namespace aria2 #endif // D_SFTP_NEGOTIATION_COMMAND_H
3,000
C++
.h
80
33.7875
79
0.73299
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,714
AsyncNameResolver.h
aria2_aria2/src/AsyncNameResolver.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_ASYNC_NAME_RESOLVER_H #define D_ASYNC_NAME_RESOLVER_H #include "common.h" #include <string> #include <vector> #include <ares.h> #include "a2netcompat.h" namespace aria2 { struct AsyncNameResolverSocketEntry { ares_socket_t fd; int events; }; class AsyncNameResolver { friend void callback(void* arg, int status, int timeouts, ares_addrinfo* result); public: enum STATUS { STATUS_READY, STATUS_QUERYING, STATUS_SUCCESS, STATUS_ERROR, }; private: std::vector<AsyncNameResolverSocketEntry> socks_; STATUS status_; int family_; ares_channel channel_; std::vector<std::string> resolvedAddresses_; std::string error_; std::string hostname_; public: AsyncNameResolver(int family, const std::string& servers); ~AsyncNameResolver(); void resolve(const std::string& name); const std::vector<std::string>& getResolvedAddresses() const { return resolvedAddresses_; } const std::string& getError() const { return error_; } STATUS getStatus() const { return status_; } ares_socket_t getFds(fd_set* rfdsPtr, fd_set* wfdsPtr) const; void process(fd_set* rfdsPtr, fd_set* wfdsPtr); int getFamily() const { return family_; } #ifdef HAVE_LIBCARES const std::vector<AsyncNameResolverSocketEntry>& getsock() const; void process(ares_socket_t readfd, ares_socket_t writefd); #endif // HAVE_LIBCARES bool operator==(const AsyncNameResolver& resolver) const; void setAddr(const std::string& addrString); const std::string& getHostname() const { return hostname_; } void handle_sock_state(ares_socket_t sock, int read, int write); }; } // namespace aria2 #endif // D_ASYNC_NAME_RESOLVER_H
3,299
C++
.h
88
34.670455
79
0.747722
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,752
TimerA2.h
aria2_aria2/src/TimerA2.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_TIMER_A2_H #define D_TIMER_A2_H #include "common.h" #include <chrono> #include "a2time.h" #include "a2functional.h" namespace aria2 { class Timer { public: using Clock = std::chrono::steady_clock; // The time value is initialized so that it represents the time at which // this object was created. Timer(); Timer(const Timer& time) = default; Timer(Timer&& time) = default; template <typename duration> constexpr explicit Timer(const duration& t) : tp_(t) { } explicit Timer(const Clock::time_point& tp); Timer& operator=(Timer&& timer) = default; Timer& operator=(const Timer& timer) = default; bool operator<(const Timer& timer) const { return tp_ < timer.tp_; } bool operator>(const Timer& timer) const { return timer < *this; } bool operator<=(const Timer& timer) const { return !(timer < *this); } bool operator>=(const Timer& timer) const { return !(*this < timer); } void reset(); template <typename duration> void reset(const duration& t) { tp_ = Clock::time_point(t); } Clock::duration difference() const; Clock::duration difference(const Timer& timer) const; // Returns true if this object's time value is zero. bool isZero() const; template <typename duration> void advance(const duration& t) { tp_ += t; } template <typename duration> void sub(const duration& t) { tp_ -= t; } const Clock::time_point& getTime() const { return tp_; } static Timer zero() { return Timer(0_s); } private: Clock::time_point tp_; }; } // namespace aria2 #endif // D_TIMER_A2_H
3,160
C++
.h
78
38.012821
79
0.730065
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,777
ARC4Encryptor.h
aria2_aria2/src/ARC4Encryptor.h
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #ifndef D_ARC4_ENCRYPTOR_H #define D_ARC4_ENCRYPTOR_H #include "common.h" #ifdef USE_INTERNAL_ARC4 # include "InternalARC4Encryptor.h" #elif HAVE_LIBNETTLE # include "LibnettleARC4Encryptor.h" #elif HAVE_LIBGCRYPT # include "LibgcryptARC4Encryptor.h" #elif HAVE_OPENSSL # include "LibsslARC4Encryptor.h" #endif #endif // D_ARC4_ENCRYPTOR_H
1,943
C++
.h
47
39.617021
79
0.768093
aria2/aria2
35,165
3,564
1,088
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false