From deb73c56694a1d6eaf6fa27a4569aed4be941367 Mon Sep 17 00:00:00 2001 From: Tindy X <49061470+tindy2013@users.noreply.github.com> Date: Mon, 3 Jul 2023 13:52:52 +0800 Subject: [PATCH] Enhancements Fix support for generating Loon configs. Refactor libraries. --- cmake/FindQuickJS.cmake | 2 +- scripts/Dockerfile | 3 +- scripts/build.alpine.release.sh | 3 +- scripts/build.macos.release.sh | 3 +- scripts/build.windows.release.sh | 3 +- scripts/config.termux.sh | 3 +- src/generator/config/nodemanip.cpp | 2 +- src/generator/config/ruleconvert.cpp | 26 +- src/generator/config/subexport.cpp | 327 ++++++++++----------- src/generator/template/templates.cpp | 6 +- src/handler/interfaces.cpp | 48 +-- src/handler/settings.cpp | 286 +++++++++--------- src/handler/upload.cpp | 32 +- src/handler/webget.cpp | 4 +- src/lib/wrapper.cpp | 2 +- src/main.cpp | 10 +- src/parser/subparser.cpp | 16 +- src/utils/file.cpp | 4 +- src/utils/ini_reader/ini_reader.h | 422 +++++++++++++-------------- src/utils/network.cpp | 2 +- src/utils/rapidjson_extra.h | 4 +- src/utils/string.cpp | 6 +- src/utils/string.h | 1 + src/utils/system.cpp | 8 +- 24 files changed, 605 insertions(+), 618 deletions(-) diff --git a/cmake/FindQuickJS.cmake b/cmake/FindQuickJS.cmake index 3880c93..22a1c42 100644 --- a/cmake/FindQuickJS.cmake +++ b/cmake/FindQuickJS.cmake @@ -1,6 +1,6 @@ find_path(QUICKJS_INCLUDE_DIRS quickjs/quickjs.h) -find_library(QUICKJS_LIBRARY quickjs) +find_library(QUICKJS_LIBRARY quickjs/libquickjs.a) set(QUICKJS_LIBRARIES "${QUICKJS_LIBRARY}") diff --git a/scripts/Dockerfile b/scripts/Dockerfile index 66e54ce..fc1b9ba 100644 --- a/scripts/Dockerfile +++ b/scripts/Dockerfile @@ -12,7 +12,8 @@ RUN apk add --no-cache --virtual .build-tools git g++ build-base linux-headers c git submodule update --init && \ cmake -DCMAKE_BUILD_TYPE=Release . && \ make quickjs -j $THREADS && \ - install -m644 quickjs/libquickjs.a /usr/lib && \ + install -d /usr/lib/quickjs/ && \ + install -m644 quickjs/libquickjs.a /usr/lib/quickjs/ && \ install -d /usr/include/quickjs/ && \ install -m644 quickjs/quickjs.h quickjs/quickjs-libc.h /usr/include/quickjs/ && \ install -m644 quickjspp.hpp /usr/include && \ diff --git a/scripts/build.alpine.release.sh b/scripts/build.alpine.release.sh index ebeec70..21cb50c 100644 --- a/scripts/build.alpine.release.sh +++ b/scripts/build.alpine.release.sh @@ -20,7 +20,8 @@ git clone https://github.com/ftk/quickjspp --depth=1 cd quickjspp cmake -DCMAKE_BUILD_TYPE=Release . make quickjs -j2 -install -m644 quickjs/libquickjs.a /usr/lib/ +install -d /usr/lib/quickjs/ +install -m644 quickjs/libquickjs.a /usr/lib/quickjs/ install -d /usr/include/quickjs/ install -m644 quickjs/quickjs.h quickjs/quickjs-libc.h /usr/include/quickjs/ install -m644 quickjspp.hpp /usr/include/ diff --git a/scripts/build.macos.release.sh b/scripts/build.macos.release.sh index 3e9c1a0..f774ea3 100644 --- a/scripts/build.macos.release.sh +++ b/scripts/build.macos.release.sh @@ -21,7 +21,8 @@ git clone https://github.com/ftk/quickjspp --depth=1 cd quickjspp cmake -DCMAKE_BUILD_TYPE=Release . make quickjs -j8 -install -m644 quickjs/libquickjs.a /usr/local/lib/ +install -d /usr/local/lib/quickjs/ +install -m644 quickjs/libquickjs.a /usr/local/lib/quickjs/ install -d /usr/local/include/quickjs/ install -m644 quickjs/quickjs.h quickjs/quickjs-libc.h /usr/local/include/quickjs/ install -m644 quickjspp.hpp /usr/local/include/ diff --git a/scripts/build.windows.release.sh b/scripts/build.windows.release.sh index 8becc96..ad4dd27 100644 --- a/scripts/build.windows.release.sh +++ b/scripts/build.windows.release.sh @@ -18,7 +18,8 @@ cd quickjspp patch quickjs/quickjs-libc.c -i ../scripts/patches/0001-quickjs-libc-add-realpath-for-Windows.patch cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release . make quickjs -j4 -install -m644 quickjs/libquickjs.a "$MINGW_PREFIX/lib/" +install -d "$MINGW_PREFIX/lib/quickjs/" +install -m644 quickjs/libquickjs.a "$MINGW_PREFIX/lib/quickjs/" install -d "$MINGW_PREFIX/include/quickjs" install -m644 quickjs/quickjs.h quickjs/quickjs-libc.h "$MINGW_PREFIX/include/quickjs/" install -m644 quickjspp.hpp "$MINGW_PREFIX/include/" diff --git a/scripts/config.termux.sh b/scripts/config.termux.sh index ba15153..7f991be 100644 --- a/scripts/config.termux.sh +++ b/scripts/config.termux.sh @@ -20,7 +20,8 @@ git clone https://github.com/ftk/quickjspp --depth=1 cd quickjspp cmake -DCMAKE_BUILD_TYPE=Release . make quickjs -j3 -install -m644 quickjs/libquickjs.a $PREFIX/lib/ +install -d $PREFIX/lib/quickjs/ +install -m644 quickjs/libquickjs.a $PREFIX/lib/quickjs/ install -d $PREFIX/include/quickjs/ install -m644 quickjs/quickjs.h quickjs/quickjs-libc.h $PREFIX/include/quickjs/ install -m644 quickjspp.hpp $PREFIX/include/ diff --git a/src/generator/config/nodemanip.cpp b/src/generator/config/nodemanip.cpp index 6d6d425..f7174ea 100644 --- a/src/generator/config/nodemanip.cpp +++ b/src/generator/config/nodemanip.cpp @@ -68,7 +68,7 @@ int addNodes(std::string link, std::vector &allNodes, int groupID, parse_ switch(args.size()) { case 0: - link = parse(std::string(), string_array()); + link = parse("", string_array()); break; case 1: link = parse(args[0], string_array()); diff --git a/src/generator/config/ruleconvert.cpp b/src/generator/config/ruleconvert.cpp index 64a53d7..92fb40a 100644 --- a/src/generator/config/ruleconvert.cpp +++ b/src/generator/config/ruleconvert.cpp @@ -245,28 +245,28 @@ void rulesetToSurge(INIReader &base_rule, std::vector &ruleset_c switch(surge_ver) //other version: -3 for Surfboard, -4 for Loon { case 0: - base_rule.SetCurrentSection("RoutingRule"); //Mellow + base_rule.set_current_section("RoutingRule"); //Mellow break; case -1: - base_rule.SetCurrentSection("filter_local"); //Quantumult X + base_rule.set_current_section("filter_local"); //Quantumult X break; case -2: - base_rule.SetCurrentSection("TCP"); //Quantumult + base_rule.set_current_section("TCP"); //Quantumult break; default: - base_rule.SetCurrentSection("Rule"); + base_rule.set_current_section("Rule"); } if(overwrite_original_rules) { - base_rule.EraseSection(); + base_rule.erase_section(); switch(surge_ver) { case -1: - base_rule.EraseSection("filter_remote"); + base_rule.erase_section("filter_remote"); break; case -4: - base_rule.EraseSection("Remote Rule"); + base_rule.erase_section("Remote Rule"); break; } } @@ -308,7 +308,7 @@ void rulesetToSurge(INIReader &base_rule, std::vector &ruleset_c if(surge_ver == -1 && x.rule_type == RULESET_QUANX && isLink(rule_path)) { strLine = rule_path + ", tag=" + rule_group + ", force-policy=" + rule_group + ", enabled=true"; - base_rule.Set("filter_remote", "{NONAME}", strLine); + base_rule.set("filter_remote", "{NONAME}", strLine); continue; } if(fileExist(rule_path)) @@ -325,13 +325,13 @@ void rulesetToSurge(INIReader &base_rule, std::vector &ruleset_c { strLine = remote_path_prefix + "/getruleset?type=2&url=" + urlSafeBase64Encode(rule_path_typed) + "&group=" + urlSafeBase64Encode(rule_group); strLine += ", tag=" + rule_group + ", enabled=true"; - base_rule.Set("filter_remote", "{NONAME}", strLine); + base_rule.set("filter_remote", "{NONAME}", strLine); continue; } else if(surge_ver == -4 && remote_path_prefix.size()) { strLine = remote_path_prefix + "/getruleset?type=1&url=" + urlSafeBase64Encode(rule_path_typed) + "," + rule_group; - base_rule.Set("Remote Rule", "{NONAME}", strLine); + base_rule.set("Remote Rule", "{NONAME}", strLine); continue; } } @@ -359,13 +359,13 @@ void rulesetToSurge(INIReader &base_rule, std::vector &ruleset_c { strLine = remote_path_prefix + "/getruleset?type=2&url=" + urlSafeBase64Encode(rule_path_typed) + "&group=" + urlSafeBase64Encode(rule_group); strLine += ", tag=" + rule_group + ", enabled=true"; - base_rule.Set("filter_remote", "{NONAME}", strLine); + base_rule.set("filter_remote", "{NONAME}", strLine); continue; } else if(surge_ver == -4) { strLine = rule_path + "," + rule_group; - base_rule.Set("Remote Rule", "{NONAME}", strLine); + base_rule.set("Remote Rule", "{NONAME}", strLine); continue; } } @@ -450,6 +450,6 @@ void rulesetToSurge(INIReader &base_rule, std::vector &ruleset_c for(std::string &x : allRules) { - base_rule.Set("{NONAME}", x); + base_rule.set("{NONAME}", x); } } diff --git a/src/generator/config/subexport.cpp b/src/generator/config/subexport.cpp index 3e3c46b..6dcb9fc 100644 --- a/src/generator/config/subexport.cpp +++ b/src/generator/config/subexport.cpp @@ -159,7 +159,7 @@ void processRemark(std::string &oldremark, std::string &newremark, string_array { if(proc_comma) { - if(oldremark.find(',') != oldremark.npos) + if(oldremark.find(',') != std::string::npos) { oldremark.insert(0, "\""); oldremark.append("\""); @@ -213,9 +213,9 @@ void groupGenerate(const std::string &rule, std::vector &nodelist, string void proxyToClash(std::vector &nodes, YAML::Node &yamlnode, const ProxyGroupConfigs &extra_proxy_group, bool clashR, extra_settings &ext) { - YAML::Node proxies, singleproxy, singlegroup, original_groups; + YAML::Node proxies, original_groups; std::vector nodelist; - string_array remarks_list, filtered_nodelist; + string_array remarks_list; /// proxies style bool block = false, compact = false; switch(hash_(ext.clash_proxies_style)) @@ -233,7 +233,7 @@ void proxyToClash(std::vector &nodes, YAML::Node &yamlnode, const ProxyGr for(Proxy &x : nodes) { - singleproxy.reset(); + YAML::Node singleproxy; std::string type = getProxyTypeName(x.Type); std::string remark, pluginopts = replaceAllDistinct(x.PluginOption, ";", "&"); @@ -424,6 +424,8 @@ void proxyToClash(std::vector &nodes, YAML::Node &yamlnode, const ProxyGr } break; case ProxyType::Snell: + if (x.SnellVersion >= 4) + continue; singleproxy["type"] = "snell"; singleproxy["psk"] = x.Password; if(x.SnellVersion != 0) @@ -471,8 +473,8 @@ void proxyToClash(std::vector &nodes, YAML::Node &yamlnode, const ProxyGr for(const ProxyGroupConfig &x : extra_proxy_group) { - singlegroup.reset(); - eraseElements(filtered_nodelist); + YAML::Node singlegroup; + string_array filtered_nodelist; singlegroup["name"] = x.Name; singlegroup["type"] = x.TypeStr(); @@ -517,11 +519,11 @@ void proxyToClash(std::vector &nodes, YAML::Node &yamlnode, const ProxyGr //singlegroup.SetStyle(YAML::EmitterStyle::Flow); bool replace_flag = false; - for(unsigned int i = 0; i < original_groups.size(); i++) + for(auto && original_group : original_groups) { - if(original_groups[i]["name"].as() == x.Name) + if(original_group["name"].as() == x.Name) { - original_groups[i] = singlegroup; + original_group.reset(singlegroup); replace_flag = true; break; } @@ -547,7 +549,7 @@ std::string proxyToClash(std::vector &nodes, const std::string &base_conf catch (std::exception &e) { writeLog(0, std::string("Clash base loader failed with error: ") + e.what(), LOG_LEVEL_ERROR); - return std::string(); + return ""; } proxyToClash(nodes, yamlnode, extra_proxy_group, clashR, ext); @@ -589,33 +591,30 @@ std::string proxyToClash(std::vector &nodes, const std::string &base_conf std::string proxyToSurge(std::vector &nodes, const std::string &base_conf, std::vector &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, int surge_ver, extra_settings &ext) { INIReader ini; - std::string proxy; std::string output_nodelist; - tribool udp, tfo, scv, tls13; std::vector nodelist; unsigned short local_port = 1080; - - string_array remarks_list, filtered_nodelist, args; + string_array remarks_list; ini.store_any_line = true; // filter out sections that requires direct-save - ini.AddDirectSaveSection("General"); - ini.AddDirectSaveSection("Replica"); - ini.AddDirectSaveSection("Rule"); - ini.AddDirectSaveSection("MITM"); - ini.AddDirectSaveSection("Script"); - ini.AddDirectSaveSection("Host"); - ini.AddDirectSaveSection("URL Rewrite"); - ini.AddDirectSaveSection("Header Rewrite"); - if(ini.Parse(base_conf) != 0 && !ext.nodelist) + ini.add_direct_save_section("General"); + ini.add_direct_save_section("Replica"); + ini.add_direct_save_section("Rule"); + ini.add_direct_save_section("MITM"); + ini.add_direct_save_section("Script"); + ini.add_direct_save_section("Host"); + ini.add_direct_save_section("URL Rewrite"); + ini.add_direct_save_section("Header Rewrite"); + if(ini.parse(base_conf) != 0 && !ext.nodelist) { - writeLog(0, "Surge base loader failed with error: " + ini.GetLastError(), LOG_LEVEL_ERROR); - return std::string(); + writeLog(0, "Surge base loader failed with error: " + ini.get_last_error(), LOG_LEVEL_ERROR); + return ""; } - ini.SetCurrentSection("Proxy"); - ini.EraseSection(); - ini.Set("{NONAME}", "DIRECT = direct"); + ini.set_current_section("Proxy"); + ini.erase_section(); + ini.set("{NONAME}", "DIRECT = direct"); for(Proxy &x : nodes) { @@ -632,16 +631,14 @@ std::string proxyToSurge(std::vector &nodes, const std::string &base_conf std::string port = std::to_string(x.Port); bool &tlssecure = x.TLSSecure; - udp = ext.udp; - tfo = ext.tfo; - scv = ext.skip_cert_verify; - tls13 = ext.tls13; + tribool udp = ext.udp, tfo = ext.tfo, scv = ext.skip_cert_verify, tls13 = ext.tls13; udp.define(x.UDP); tfo.define(x.TCPFastOpen); scv.define(x.AllowInsecure); tls13.define(x.TLS13); - proxy.clear(); + std::string proxy; + string_array args; switch(x.Type) { @@ -772,7 +769,7 @@ std::string proxyToSurge(std::vector &nodes, const std::string &base_conf output_nodelist += remark + " = " + proxy + "\n"; else { - ini.Set("{NONAME}", remark + " = " + proxy); + ini.set("{NONAME}", remark + " = " + proxy); nodelist.emplace_back(x); } remarks_list.emplace_back(std::move(remark)); @@ -781,12 +778,12 @@ std::string proxyToSurge(std::vector &nodes, const std::string &base_conf if(ext.nodelist) return output_nodelist; - ini.SetCurrentSection("Proxy Group"); - ini.EraseSection(); + ini.set_current_section("Proxy Group"); + ini.erase_section(); for(const ProxyGroupConfig &x : extra_proxy_group) { - eraseElements(filtered_nodelist); - proxy.clear(); + string_array filtered_nodelist; + std::string group; switch(x.Type) { @@ -799,9 +796,9 @@ std::string proxyToSurge(std::vector &nodes, const std::string &base_conf continue; break; case ProxyGroupType::SSID: - proxy = x.TypeStr() + ",default=" + x.Proxies[0] + ","; - proxy += join(x.Proxies.begin() + 1, x.Proxies.end(), ","); - ini.Set("{NONAME}", x.Name + " = " + proxy); //insert order + group = x.TypeStr() + ",default=" + x.Proxies[0] + ","; + group += join(x.Proxies.begin() + 1, x.Proxies.end(), ","); + ini.set("{NONAME}", x.Name + " = " + group); //insert order continue; default: continue; @@ -815,54 +812,50 @@ std::string proxyToSurge(std::vector &nodes, const std::string &base_conf if(filtered_nodelist.size() == 1) { - proxy = toLower(filtered_nodelist[0]); - switch(hash_(proxy)) + group = toLower(filtered_nodelist[0]); + switch(hash_(group)) { case "direct"_hash: case "reject"_hash: case "reject-tinygif"_hash: - ini.Set("Proxy", "{NONAME}", x.Name + " = " + proxy); + ini.set("Proxy", "{NONAME}", x.Name + " = " + group); continue; } } - proxy = x.TypeStr() + ","; - proxy += join(filtered_nodelist, ","); + group = x.TypeStr() + ","; + group += join(filtered_nodelist, ","); if(x.Type == ProxyGroupType::URLTest || x.Type == ProxyGroupType::Fallback || x.Type == ProxyGroupType::LoadBalance) { - proxy += ",url=" + x.Url + ",interval=" + std::to_string(x.Interval); + group += ",url=" + x.Url + ",interval=" + std::to_string(x.Interval); if(x.Tolerance > 0) - proxy += ",tolerance=" + std::to_string(x.Tolerance); + group += ",tolerance=" + std::to_string(x.Tolerance); if(x.Timeout > 0) - proxy += ",timeout=" + std::to_string(x.Timeout); + group += ",timeout=" + std::to_string(x.Timeout); if(!x.Persistent.is_undef()) - proxy += ",persistent=" + x.Persistent.get_str(); + group += ",persistent=" + x.Persistent.get_str(); if(!x.EvaluateBeforeUse.is_undef()) - proxy += ",evaluate-before-use=" + x.EvaluateBeforeUse.get_str(); + group += ",evaluate-before-use=" + x.EvaluateBeforeUse.get_str(); } - ini.Set("{NONAME}", x.Name + " = " + proxy); //insert order + ini.set("{NONAME}", x.Name + " = " + group); //insert order } if(ext.enable_rule_generator) rulesetToSurge(ini, ruleset_content_array, surge_ver, ext.overwrite_original_rules, ext.managed_config_prefix); - return ini.ToString(); + return ini.to_string(); } std::string proxyToSingle(std::vector &nodes, int types, extra_settings &ext) { /// types: SS=1 SSR=2 VMess=4 Trojan=8 - std::string remark, hostname, port, password, method; - std::string plugin, pluginopts; - std::string protocol, protoparam, obfs, obfsparam; - std::string id, aid, transproto, faketype, host, path, quicsecure, quicsecret; std::string proxyStr, allLinks; bool ss = GETBIT(types, 1), ssr = GETBIT(types, 2), vmess = GETBIT(types, 3), trojan = GETBIT(types, 4); for(Proxy &x : nodes) { - remark = x.Remark; + std::string remark = x.Remark; std::string &hostname = x.Hostname, &password = x.Password, &method = x.EncryptMethod, &plugin = x.Plugin, &pluginopts = x.PluginOption, &protocol = x.Protocol, &protoparam = x.ProtocolParam, &obfs = x.OBFS, &obfsparam = x.OBFSParam, &id = x.UserId, &transproto = x.TransferProtocol, &host = x.Host, &path = x.Path, &faketype = x.FakeType; bool &tlssecure = x.TLSSecure; std::string port = std::to_string(x.Port); @@ -938,12 +931,9 @@ std::string proxyToSingle(std::vector &nodes, int types, extra_settings & std::string proxyToSSSub(std::string base_conf, std::vector &nodes, extra_settings &ext) { rapidjson::Document json, base; - std::string remark, hostname, password, method; - std::string plugin, pluginopts; - std::string protocol, obfs; std::string output_content; - rapidjson::Document::AllocatorType &alloc = json.GetAllocator(); + auto &alloc = json.GetAllocator(); json.SetObject(); json.AddMember("remarks", "", alloc); json.AddMember("server", "", alloc); @@ -971,8 +961,8 @@ std::string proxyToSSSub(std::string base_conf, std::vector &nodes, extra output_content = "["; for(Proxy &x : nodes) { - remark = x.Remark; - hostname = x.Hostname; + std::string &remark = x.Remark; + std::string &hostname = x.Hostname; std::string &password = x.Password; std::string &method = x.EncryptMethod; std::string &plugin = x.Plugin; @@ -1012,10 +1002,10 @@ std::string proxyToQuan(std::vector &nodes, const std::string &base_conf, { INIReader ini; ini.store_any_line = true; - if(!ext.nodelist && ini.Parse(base_conf) != 0) + if(!ext.nodelist && ini.parse(base_conf) != 0) { - writeLog(0, "Quantumult base loader failed with error: " + ini.GetLastError(), LOG_LEVEL_ERROR); - return std::string(); + writeLog(0, "Quantumult base loader failed with error: " + ini.get_last_error(), LOG_LEVEL_ERROR); + return ""; } proxyToQuan(nodes, ini, ruleset_content_array, extra_proxy_group, ext); @@ -1024,23 +1014,22 @@ std::string proxyToQuan(std::vector &nodes, const std::string &base_conf, { string_array allnodes; std::string allLinks; - ini.GetAll("SERVER", "{NONAME}", allnodes); + ini.get_all("SERVER", "{NONAME}", allnodes); if(!allnodes.empty()) allLinks = join(allnodes, "\n"); return base64Encode(allLinks); } - return ini.ToString(); + return ini.to_string(); } void proxyToQuan(std::vector &nodes, INIReader &ini, std::vector &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { - std::string type, proxyStr; - tribool scv; + std::string proxyStr; std::vector nodelist; string_array remarks_list; - ini.SetCurrentSection("SERVER"); - ini.EraseSection(); + ini.set_current_section("SERVER"); + ini.erase_section(); for(Proxy &x : nodes) { std::string remark = x.Remark; @@ -1056,6 +1045,7 @@ void proxyToQuan(std::vector &nodes, INIReader &ini, std::vector &nodes, INIReader &ini, std::vector &nodes, INIReader &ini, std::vector &nodes, INIReader &ini, std::vector &nodes, INIReader &ini, std::vector &nodes, const std::string &base_conf, std::vector &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { INIReader ini; ini.store_any_line = true; - ini.AddDirectSaveSection("general"); - ini.AddDirectSaveSection("dns"); - ini.AddDirectSaveSection("rewrite_remote"); - ini.AddDirectSaveSection("rewrite_local"); - ini.AddDirectSaveSection("task_local"); - ini.AddDirectSaveSection("mitm"); - ini.AddDirectSaveSection("server_remote"); - if(!ext.nodelist && ini.Parse(base_conf) != 0) + ini.add_direct_save_section("general"); + ini.add_direct_save_section("dns"); + ini.add_direct_save_section("rewrite_remote"); + ini.add_direct_save_section("rewrite_local"); + ini.add_direct_save_section("task_local"); + ini.add_direct_save_section("mitm"); + ini.add_direct_save_section("server_remote"); + if(!ext.nodelist && ini.parse(base_conf) != 0) { - writeLog(0, "QuantumultX base loader failed with error: " + ini.GetLastError(), LOG_LEVEL_ERROR); - return std::string(); + writeLog(0, "QuantumultX base loader failed with error: " + ini.get_last_error(), LOG_LEVEL_ERROR); + return ""; } proxyToQuanX(nodes, ini, ruleset_content_array, extra_proxy_group, ext); @@ -1259,28 +1249,25 @@ std::string proxyToQuanX(std::vector &nodes, const std::string &base_conf { string_array allnodes; std::string allLinks; - ini.GetAll("server_local", "{NONAME}", allnodes); + ini.get_all("server_local", "{NONAME}", allnodes); if(!allnodes.empty()) allLinks = join(allnodes, "\n"); return allLinks; } - return ini.ToString(); + return ini.to_string(); } void proxyToQuanX(std::vector &nodes, INIReader &ini, std::vector &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { std::string type; - std::string remark, hostname, port, method; - std::string password, plugin, pluginopts; - std::string id, transproto, host, path; - std::string protocol, protoparam, obfs, obfsparam; + std::string remark; std::string proxyStr; tribool udp, tfo, scv, tls13; std::vector nodelist; string_array remarks_list; - ini.SetCurrentSection("server_local"); - ini.EraseSection(); + ini.set_current_section("server_local"); + ini.erase_section(); for(Proxy &x : nodes) { if(ext.append_proxy_type) @@ -1338,7 +1325,7 @@ void proxyToQuanX(std::vector &nodes, INIReader &ini, std::vector &nodes, INIReader &ini, std::vector &nodes, INIReader &ini, std::vector &nodes, INIReader &ini, std::vector &nodes, INIReader &ini, std::vector &nodes, std::string &group, std::strin { rapidjson::StringBuffer sb; rapidjson::Writer writer(sb); - size_t index = 0; + int index = 0; if(group.empty()) group = "SSD"; @@ -1603,29 +1590,29 @@ std::string proxyToMellow(std::vector &nodes, const std::string &base_con { INIReader ini; ini.store_any_line = true; - if(ini.Parse(base_conf) != 0) + if(ini.parse(base_conf) != 0) { - writeLog(0, "Mellow base loader failed with error: " + ini.GetLastError(), LOG_LEVEL_ERROR); - return std::string(); + writeLog(0, "Mellow base loader failed with error: " + ini.get_last_error(), LOG_LEVEL_ERROR); + return ""; } proxyToMellow(nodes, ini, ruleset_content_array, extra_proxy_group, ext); - return ini.ToString(); + return ini.to_string(); } void proxyToMellow(std::vector &nodes, INIReader &ini, std::vector &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { std::string proxy; - std::string type, remark, hostname, port, username, password, method; + std::string remark, username, password, method; std::string plugin, pluginopts; std::string id, aid, transproto, faketype, host, path, quicsecure, quicsecret, tlssecure; std::string url; tribool tfo, scv; std::vector nodelist; - string_array vArray, remarks_list, filtered_nodelist; + string_array vArray, remarks_list; - ini.SetCurrentSection("Endpoint"); + ini.set_current_section("Endpoint"); for(Proxy &x : nodes) { @@ -1637,8 +1624,7 @@ void proxyToMellow(std::vector &nodes, INIReader &ini, std::vector &nodes, INIReader &ini, std::vector &nodes, INIReader &ini, std::vector &nodes, INIReader &ini, std::vector &nodes, const std::string &base_conf, std::vector &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { rapidjson::Document json; INIReader ini; - std::string proxy; std::string output_nodelist; - tribool scv; std::vector nodelist; - string_array vArray, remarks_list, filtered_nodelist; + string_array remarks_list; ini.store_any_line = true; - if(ini.Parse(base_conf) != INIREADER_EXCEPTION_NONE && !ext.nodelist) + if(ini.parse(base_conf) != INIREADER_EXCEPTION_NONE && !ext.nodelist) { - writeLog(0, "Loon base loader failed with error: " + ini.GetLastError(), LOG_LEVEL_ERROR); - return std::string(); + writeLog(0, "Loon base loader failed with error: " + ini.get_last_error(), LOG_LEVEL_ERROR); + return ""; } - - ini.SetCurrentSection("Proxy"); - ini.EraseSection(); + ini.set_current_section("Proxy"); + ini.erase_section(); for(Proxy &x : nodes) { @@ -1795,7 +1777,7 @@ std::string proxyToLoon(std::vector &nodes, const std::string &base_conf, tribool scv = ext.skip_cert_verify; scv.define(x.AllowInsecure); - proxy.clear(); + std::string proxy; switch(x.Type) { @@ -1813,59 +1795,58 @@ std::string proxyToLoon(std::vector &nodes, const std::string &base_conf, if(method == "auto") method = "chacha20-ietf-poly1305"; - proxy = "vmess," + hostname + "," + port + "," + method + ",\"" + id + "\",over-tls:" + (tlssecure ? "true" : "false"); + proxy = "vmess," + hostname + "," + port + "," + method + ",\"" + id + "\",over-tls=" + (tlssecure ? "true" : "false"); if(tlssecure) - proxy += ",tls-name:" + host; + proxy += ",tls-name=" + host; switch(hash_(transproto)) { case "tcp"_hash: - proxy += ",transport:tcp"; + proxy += ",transport=tcp"; break; case "ws"_hash: - proxy += ",transport:ws,path:" + path + ",host:" + host; + proxy += ",transport=ws,path=" + path + ",host=" + host; break; default: continue; } if(!scv.is_undef()) - proxy += ",skip-cert-verify:" + std::string(scv.get() ? "1" : "0"); + proxy += ",skip-cert-verify=" + std::string(scv.get() ? "true" : "false"); break; case ProxyType::ShadowsocksR: - proxy = "ShadowsocksR," + hostname + "," + port + "," + method + ",\"" + password + "\"," + protocol + ",{" + protoparam + "}," + obfs + ",{" + obfsparam + "}"; + proxy = "ShadowsocksR," + hostname + "," + port + "," + method + ",\"" + password + "\",protocol=" + protocol + ",protocol-param=" + protoparam + ",obfs=" + obfs + ",obfs-param=" + obfsparam; break; - /* - case ProxyType::SOCKS5: - proxy = "socks5, " + hostname + ", " + port + ", " + username + ", " + password; - if(ext.skip_cert_verify) - proxy += ", skip-cert-verify:1"; - break; - */ case ProxyType::HTTP: - proxy = "http," + hostname + "," + port + "," + username + "," + password; + proxy = "http," + hostname + "," + port + "," + username + ",\"" + password + "\""; + break; + case ProxyType::HTTPS: + proxy = "https," + hostname + "," + port + "," + username + ",\"" + password + "\""; + if(!host.empty()) + proxy += ",tls-name=" + host; + if(!scv.is_undef()) + proxy += ",skip-cert-verify=" + std::string(scv.get() ? "true" : "false"); break; case ProxyType::Trojan: - proxy = "trojan," + hostname + "," + port + "," + password; + proxy = "trojan," + hostname + "," + port + ",\"" + password + "\""; if(!host.empty()) - proxy += ",tls-name:" + host; + proxy += ",tls-name=" + host; if(!scv.is_undef()) - proxy += ",skip-cert-verify:" + std::string(scv.get() ? "1" : "0"); + proxy += ",skip-cert-verify=" + std::string(scv.get() ? "true" : "false"); break; default: continue; } - /* if(ext.tfo) - proxy += ", tfo=true"; + proxy += ",fast-open=true"; if(ext.udp) - proxy += ", udp-relay=true"; - */ + proxy += ",udp=true"; + if(ext.nodelist) output_nodelist += remark + " = " + proxy + "\n"; else { - ini.Set("{NONAME}", remark + " = " + proxy); + ini.set("{NONAME}", remark + " = " + proxy); nodelist.emplace_back(x); remarks_list.emplace_back(std::move(remark)); } @@ -1874,25 +1855,26 @@ std::string proxyToLoon(std::vector &nodes, const std::string &base_conf, if(ext.nodelist) return output_nodelist; - ini.SetCurrentSection("Proxy Group"); - ini.EraseSection(); + ini.set_current_section("Proxy Group"); + ini.erase_section(); for(const ProxyGroupConfig &x : extra_proxy_group) { - eraseElements(filtered_nodelist); - proxy.clear(); + string_array filtered_nodelist; + std::string group, group_extra; switch(x.Type) { case ProxyGroupType::Select: + case ProxyGroupType::LoadBalance: case ProxyGroupType::URLTest: case ProxyGroupType::Fallback: break; case ProxyGroupType::SSID: if(x.Proxies.size() < 2) continue; - proxy = x.TypeStr() + ",default=" + x.Proxies[0] + ","; - proxy += join(x.Proxies.begin() + 1, x.Proxies.end(), ","); - ini.Set("{NONAME}", x.Name + " = " + proxy); //insert order + group = x.TypeStr() + ",default=" + x.Proxies[0] + ","; + group += join(x.Proxies.begin() + 1, x.Proxies.end(), ","); + ini.set("{NONAME}", x.Name + " = " + group); //insert order continue; default: continue; @@ -1904,20 +1886,23 @@ std::string proxyToLoon(std::vector &nodes, const std::string &base_conf, if(filtered_nodelist.empty()) filtered_nodelist.emplace_back("DIRECT"); - proxy = x.TypeStr() + ","; + group = x.TypeStr() + ","; /* for(std::string &y : filtered_nodelist) - proxy += "," + y; + group += "," + y; */ - proxy += join(filtered_nodelist, ","); - if(x.Type == ProxyGroupType::URLTest || x.Type == ProxyGroupType::Fallback) - proxy += ",url=" + x.Url + ",interval=" + std::to_string(x.Interval); + group += join(filtered_nodelist, ","); + if(x.Type != ProxyGroupType::Select) { + group += ",url=" + x.Url + ",interval=" + std::to_string(x.Interval); + if (x.Type == ProxyGroupType::LoadBalance) + group += ",strategy=" + std::string(x.Strategy == BalanceStrategy::RoundRobin ? "round-robin" : "pcc"); + } - ini.Set("{NONAME}", x.Name + " = " + proxy); //insert order + ini.set("{NONAME}", x.Name + " = " + group); //insert order } if(ext.enable_rule_generator) rulesetToSurge(ini, ruleset_content_array, -4, ext.overwrite_original_rules, ext.managed_config_prefix); - return ini.ToString(); + return ini.to_string(); } diff --git a/src/generator/template/templates.cpp b/src/generator/template/templates.cpp index 9a3469a..d3f4758 100644 --- a/src/generator/template/templates.cpp +++ b/src/generator/template/templates.cpp @@ -151,7 +151,7 @@ int render_template(const std::string &content, const template_args &vars, std:: { std::string key = args.at(0)->get(), value = args.at(1)->get(); parse_json_pointer(data, key, value); - return std::string(); + return ""; }); env.add_callback("split", 3, [&data](inja::Arguments &args) { @@ -159,7 +159,7 @@ int render_template(const std::string &content, const template_args &vars, std:: string_array vArray = split(content, delim); for(size_t index = 0; index < vArray.size(); index++) parse_json_pointer(data, dest + "." + std::to_string(index), vArray[index]); - return std::string(); + return ""; }); env.add_callback("append", 2, [&data](inja::Arguments &args) { @@ -175,7 +175,7 @@ int render_template(const std::string &content, const template_args &vars, std:: } output_content.append(value); data[nlohmann::json::json_pointer(pointer)] = output_content; - return std::string(); + return ""; }); env.add_callback("getLink", 1, [](inja::Arguments &args) { diff --git a/src/handler/interfaces.cpp b/src/handler/interfaces.cpp index 8da0557..2625387 100644 --- a/src/handler/interfaces.cpp +++ b/src/handler/interfaces.cpp @@ -958,15 +958,15 @@ std::string surgeConfToClash(RESPONSE_CALLBACK_ARGS) base_content = fetchFile(url, proxy, global.cacheConfig); - if(ini.Parse(base_content) != INIREADER_EXCEPTION_NONE) + if(ini.parse(base_content) != INIREADER_EXCEPTION_NONE) { - std::string errmsg = "Parsing Surge config failed! Reason: " + ini.GetLastError(); + std::string errmsg = "Parsing Surge config failed! Reason: " + ini.get_last_error(); //std::cerr<::from_ini(tempArray, "@"); safe_set_renames(configs); @@ -900,20 +900,20 @@ void readConf() } } - if(ini.SectionExist("userinfo")) + if(ini.section_exist("userinfo")) { - ini.EnterSection("userinfo"); - if(ini.ItemPrefixExist("stream_rule")) + ini.enter_section("userinfo"); + if(ini.item_prefix_exist("stream_rule")) { - ini.GetAll("stream_rule", tempArray); + ini.get_all("stream_rule", tempArray); importItems(tempArray, false); auto configs = INIBinding::from::from_ini(tempArray, "|"); safe_set_streams(configs); eraseElements(tempArray); } - if(ini.ItemPrefixExist("time_rule")) + if(ini.item_prefix_exist("time_rule")) { - ini.GetAll("time_rule", tempArray); + ini.get_all("time_rule", tempArray); importItems(tempArray, false); auto configs = INIBinding::from::from_ini(tempArray, "|"); safe_set_times(configs); @@ -921,45 +921,45 @@ void readConf() } } - ini.EnterSection("managed_config"); - ini.GetBoolIfExist("write_managed_config", global.writeManagedConfig); - ini.GetIfExist("managed_config_prefix", global.managedConfigPrefix); - ini.GetIntIfExist("config_update_interval", global.updateInterval); - ini.GetBoolIfExist("config_update_strict", global.updateStrict); - ini.GetIfExist("quanx_device_id", global.quanXDevID); + ini.enter_section("managed_config"); + ini.get_bool_if_exist("write_managed_config", global.writeManagedConfig); + ini.get_if_exist("managed_config_prefix", global.managedConfigPrefix); + ini.get_int_if_exist("config_update_interval", global.updateInterval); + ini.get_bool_if_exist("config_update_strict", global.updateStrict); + ini.get_if_exist("quanx_device_id", global.quanXDevID); - ini.EnterSection("emojis"); - ini.GetBoolIfExist("add_emoji", global.addEmoji); - ini.GetBoolIfExist("remove_old_emoji", global.removeEmoji); - if(ini.ItemPrefixExist("rule")) + ini.enter_section("emojis"); + ini.get_bool_if_exist("add_emoji", global.addEmoji); + ini.get_bool_if_exist("remove_old_emoji", global.removeEmoji); + if(ini.item_prefix_exist("rule")) { - ini.GetAll("rule", tempArray); + ini.get_all("rule", tempArray); importItems(tempArray, false); auto configs = INIBinding::from::from_ini(tempArray, ","); safe_set_emojis(configs); eraseElements(tempArray); } - if(ini.SectionExist("rulesets")) - ini.EnterSection("rulesets"); + if(ini.section_exist("rulesets")) + ini.enter_section("rulesets"); else - ini.EnterSection("ruleset"); - global.enableRuleGen = ini.GetBool("enabled"); + ini.enter_section("ruleset"); + global.enableRuleGen = ini.get_bool("enabled"); if(global.enableRuleGen) { - ini.GetBoolIfExist("overwrite_original_rules", global.overwriteOriginalRules); - ini.GetBoolIfExist("update_ruleset_on_request", global.updateRulesetOnRequest); - if(ini.ItemPrefixExist("ruleset")) + ini.get_bool_if_exist("overwrite_original_rules", global.overwriteOriginalRules); + ini.get_bool_if_exist("update_ruleset_on_request", global.updateRulesetOnRequest); + if(ini.item_prefix_exist("ruleset")) { string_array vArray; - ini.GetAll("ruleset", vArray); + ini.get_all("ruleset", vArray); importItems(vArray, false); global.customRulesets = INIBinding::from::from_ini(vArray); } - else if(ini.ItemPrefixExist("surge_ruleset")) + else if(ini.item_prefix_exist("surge_ruleset")) { string_array vArray; - ini.GetAll("surge_ruleset", vArray); + ini.get_all("surge_ruleset", vArray); importItems(vArray, false); global.customRulesets = INIBinding::from::from_ini(vArray); } @@ -970,22 +970,22 @@ void readConf() global.updateRulesetOnRequest = false; } - if(ini.SectionExist("proxy_groups")) - ini.EnterSection("proxy_groups"); + if(ini.section_exist("proxy_groups")) + ini.enter_section("proxy_groups"); else - ini.EnterSection("clash_proxy_group"); - if(ini.ItemPrefixExist("custom_proxy_group")) + ini.enter_section("clash_proxy_group"); + if(ini.item_prefix_exist("custom_proxy_group")) { string_array vArray; - ini.GetAll("custom_proxy_group", vArray); + ini.get_all("custom_proxy_group", vArray); importItems(vArray, false); global.customProxyGroups = INIBinding::from::from_ini(vArray); } - ini.EnterSection("template"); - ini.GetIfExist("template_path", global.templatePath); + ini.enter_section("template"); + ini.get_if_exist("template_path", global.templatePath); string_multimap tempmap; - ini.GetItems(tempmap); + ini.get_items(tempmap); eraseElements(global.templateVars); for(auto &x : tempmap) { @@ -995,36 +995,36 @@ void readConf() } global.templateVars["managed_config_prefix"] = global.managedConfigPrefix; - if(ini.SectionExist("aliases")) + if(ini.section_exist("aliases")) { - ini.EnterSection("aliases"); - ini.GetItems(tempmap); + ini.enter_section("aliases"); + ini.get_items(tempmap); webServer.reset_redirect(); for(auto &x : tempmap) webServer.append_redirect(x.first, x.second); } - if(ini.SectionExist("tasks")) + if(ini.section_exist("tasks")) { string_array vArray; - ini.EnterSection("tasks"); - ini.GetAll("task", vArray); + ini.enter_section("tasks"); + ini.get_all("task", vArray); importItems(vArray, false); global.enableCron = !vArray.empty(); global.cronTasks = INIBinding::from::from_ini(vArray); refresh_schedule(); } - ini.EnterSection("server"); - ini.GetIfExist("listen", global.listenAddress); - ini.GetIntIfExist("port", global.listenPort); - webServer.serve_file_root = ini.Get("serve_file_root"); + ini.enter_section("server"); + ini.get_if_exist("listen", global.listenAddress); + ini.get_int_if_exist("port", global.listenPort); + webServer.serve_file_root = ini.get("serve_file_root"); webServer.serve_file = !webServer.serve_file_root.empty(); - ini.EnterSection("advanced"); + ini.enter_section("advanced"); std::string log_level; - ini.GetIfExist("log_level", log_level); - ini.GetBoolIfExist("print_debug_info", global.printDbgInfo); + ini.get_if_exist("log_level", log_level); + ini.get_bool_if_exist("print_debug_info", global.printDbgInfo); if(global.printDbgInfo) global.logLevel = LOG_LEVEL_VERBOSE; else @@ -1050,19 +1050,19 @@ void readConf() global.logLevel = LOG_LEVEL_INFO; } } - ini.GetIntIfExist("max_pending_connections", global.maxPendingConns); - ini.GetIntIfExist("max_concurrent_threads", global.maxConcurThreads); - ini.GetNumberIfExist("max_allowed_rulesets", global.maxAllowedRulesets); - ini.GetNumberIfExist("max_allowed_rules", global.maxAllowedRules); - ini.GetNumberIfExist("max_allowed_download_size", global.maxAllowedDownloadSize); - if(ini.ItemExist("enable_cache")) + ini.get_int_if_exist("max_pending_connections", global.maxPendingConns); + ini.get_int_if_exist("max_concurrent_threads", global.maxConcurThreads); + ini.get_number_if_exist("max_allowed_rulesets", global.maxAllowedRulesets); + ini.get_number_if_exist("max_allowed_rules", global.maxAllowedRules); + ini.get_number_if_exist("max_allowed_download_size", global.maxAllowedDownloadSize); + if(ini.item_exist("enable_cache")) { - if(ini.GetBool("enable_cache")) + if(ini.get_bool("enable_cache")) { - ini.GetIntIfExist("cache_subscription", global.cacheSubscription); - ini.GetIntIfExist("cache_config", global.cacheConfig); - ini.GetIntIfExist("cache_ruleset", global.cacheRuleset); - ini.GetBoolIfExist("serve_cache_on_fetch_fail", global.serveCacheOnFetchFail); + ini.get_int_if_exist("cache_subscription", global.cacheSubscription); + ini.get_int_if_exist("cache_config", global.cacheConfig); + ini.get_int_if_exist("cache_ruleset", global.cacheRuleset); + ini.get_bool_if_exist("serve_cache_on_fetch_fail", global.serveCacheOnFetchFail); } else { @@ -1070,9 +1070,9 @@ void readConf() global.serveCacheOnFetchFail = false; } } - ini.GetBoolIfExist("script_clean_context", global.scriptCleanContext); - ini.GetBoolIfExist("async_fetch_ruleset", global.asyncFetchRuleset); - ini.GetBoolIfExist("skip_failed_links", global.skipFailedLinks); + ini.get_bool_if_exist("script_clean_context", global.scriptCleanContext); + ini.get_bool_if_exist("async_fetch_ruleset", global.asyncFetchRuleset); + ini.get_bool_if_exist("skip_failed_links", global.skipFailedLinks); writeLog(0, "Load preference settings in INI format completed.", LOG_LEVEL_INFO); } @@ -1227,27 +1227,27 @@ int loadExternalConfig(std::string &path, ExternalConfig &ext) INIReader ini; ini.store_isolated_line = true; - ini.SetIsolatedItemsSection("custom"); - if(ini.Parse(base_content) != INIREADER_EXCEPTION_NONE) + ini.set_isolated_items_section("custom"); + if(ini.parse(base_content) != INIREADER_EXCEPTION_NONE) { - //std::cerr<<"Load external configuration failed. Reason: "<::from_ini(vArray); } - std::string ruleset_name = ini.ItemPrefixExist("ruleset") ? "ruleset" : "surge_ruleset"; - if(ini.ItemPrefixExist(ruleset_name)) + std::string ruleset_name = ini.item_prefix_exist("ruleset") ? "ruleset" : "surge_ruleset"; + if(ini.item_prefix_exist(ruleset_name)) { string_array vArray; - ini.GetAll(ruleset_name, vArray); + ini.get_all(ruleset_name, vArray); importItems(vArray, global.APIMode); if(global.maxAllowedRulesets && vArray.size() > global.maxAllowedRulesets) { @@ -1257,44 +1257,44 @@ int loadExternalConfig(std::string &path, ExternalConfig &ext) ext.surge_ruleset = INIBinding::from::from_ini(vArray); } - ini.GetIfExist("clash_rule_base", ext.clash_rule_base); - ini.GetIfExist("surge_rule_base", ext.surge_rule_base); - ini.GetIfExist("surfboard_rule_base", ext.surfboard_rule_base); - ini.GetIfExist("mellow_rule_base", ext.mellow_rule_base); - ini.GetIfExist("quan_rule_base", ext.quan_rule_base); - ini.GetIfExist("quanx_rule_base", ext.quanx_rule_base); - ini.GetIfExist("loon_rule_base", ext.loon_rule_base); - ini.GetIfExist("sssub_rule_base", ext.sssub_rule_base); + ini.get_if_exist("clash_rule_base", ext.clash_rule_base); + ini.get_if_exist("surge_rule_base", ext.surge_rule_base); + ini.get_if_exist("surfboard_rule_base", ext.surfboard_rule_base); + ini.get_if_exist("mellow_rule_base", ext.mellow_rule_base); + ini.get_if_exist("quan_rule_base", ext.quan_rule_base); + ini.get_if_exist("quanx_rule_base", ext.quanx_rule_base); + ini.get_if_exist("loon_rule_base", ext.loon_rule_base); + ini.get_if_exist("sssub_rule_base", ext.sssub_rule_base); - ini.GetBoolIfExist("overwrite_original_rules", ext.overwrite_original_rules); - ini.GetBoolIfExist("enable_rule_generator", ext.enable_rule_generator); + ini.get_bool_if_exist("overwrite_original_rules", ext.overwrite_original_rules); + ini.get_bool_if_exist("enable_rule_generator", ext.enable_rule_generator); - if(ini.ItemPrefixExist("rename")) + if(ini.item_prefix_exist("rename")) { string_array vArray; - ini.GetAll("rename", vArray); + ini.get_all("rename", vArray); importItems(vArray, global.APIMode); ext.rename = INIBinding::from::from_ini(vArray, "@"); } - ext.add_emoji = ini.Get("add_emoji"); - ext.remove_old_emoji = ini.Get("remove_old_emoji"); - if(ini.ItemPrefixExist("emoji")) + ext.add_emoji = ini.get("add_emoji"); + ext.remove_old_emoji = ini.get("remove_old_emoji"); + if(ini.item_prefix_exist("emoji")) { string_array vArray; - ini.GetAll("emoji", vArray); + ini.get_all("emoji", vArray); importItems(vArray, global.APIMode); ext.emoji = INIBinding::from::from_ini(vArray, ","); } - if(ini.ItemPrefixExist("include_remarks")) - ini.GetAll("include_remarks", ext.include); - if(ini.ItemPrefixExist("exclude_remarks")) - ini.GetAll("exclude_remarks", ext.exclude); + if(ini.item_prefix_exist("include_remarks")) + ini.get_all("include_remarks", ext.include); + if(ini.item_prefix_exist("exclude_remarks")) + ini.get_all("exclude_remarks", ext.exclude); - if(ini.SectionExist("template") && ext.tpl_args != nullptr) + if(ini.section_exist("template") && ext.tpl_args != nullptr) { - ini.EnterSection("template"); + ini.enter_section("template"); string_multimap tempmap; - ini.GetItems(tempmap); + ini.get_items(tempmap); for(auto &x : tempmap) ext.tpl_args->local_vars[x.first] = x.second; } diff --git a/src/handler/upload.cpp b/src/handler/upload.cpp index 39f1101..1d689f6 100644 --- a/src/handler/upload.cpp +++ b/src/handler/upload.cpp @@ -41,15 +41,15 @@ int uploadGist(std::string name, std::string path, std::string content, bool wri return -1; } - ini.ParseFile("gistconf.ini"); - if(ini.EnterSection("common") != 0) + ini.parse_file("gistconf.ini"); + if(ini.enter_section("common") != 0) { //std::cerr<<"gistconf.ini has incorrect format. Skipping...\n"; writeLog(0, "gistconf.ini has incorrect format. Skipping...", LOG_LEVEL_ERROR); return -1; } - token = ini.Get("token"); + token = ini.get("token"); if(!token.size()) { //std::cerr<<"No token is provided. Skipping...\n"; @@ -57,12 +57,12 @@ int uploadGist(std::string name, std::string path, std::string content, bool wri return -1; } - id = ini.Get("id"); - username = ini.Get("username"); + id = ini.get("id"); + username = ini.get("username"); if(!path.size()) { - if(ini.ItemExist("path")) - path = ini.Get(name, "path"); + if(ini.item_exist("path")) + path = ini.get(name, "path"); else path = name; } @@ -102,16 +102,16 @@ int uploadGist(std::string name, std::string path, std::string content, bool wri //std::cerr<<"Writing to Gist success!\nGenerator: "< std::string { - if(global.accessToken.size()) + if(!global.accessToken.empty()) { std::string token = getUrlArg(request.argument, "token"); if(token != global.accessToken) @@ -206,7 +206,7 @@ int main(int argc, char *argv[]) webServer.append_response("GET", "/readconf", "text/plain", [](RESPONSE_CALLBACK_ARGS) -> std::string { - if(global.accessToken.size()) + if(!global.accessToken.empty()) { std::string token = getUrlArg(request.argument, "token"); if(token != global.accessToken) @@ -223,7 +223,7 @@ int main(int argc, char *argv[]) webServer.append_response("POST", "/updateconf", "text/plain", [](RESPONSE_CALLBACK_ARGS) -> std::string { - if(global.accessToken.size()) + if(!global.accessToken.empty()) { std::string token = getUrlArg(request.argument, "token"); if(token != global.accessToken) diff --git a/src/parser/subparser.cpp b/src/parser/subparser.cpp index 4a2cf4b..6a51eaf 100644 --- a/src/parser/subparser.cpp +++ b/src/parser/subparser.cpp @@ -1293,17 +1293,17 @@ bool explodeSurge(std::string surge, std::vector &nodes) ini.store_isolated_line = true; ini.keep_empty_section = false; ini.allow_dup_section_titles = true; - ini.SetIsolatedItemsSection("Proxy"); - ini.IncludeSection("Proxy"); - ini.AddDirectSaveSection("Proxy"); + ini.set_isolated_items_section("Proxy"); + ini.include_section("Proxy"); + ini.add_direct_save_section("Proxy"); if(surge.find("[Proxy]") != surge.npos) - surge = regReplace(surge, "^[\\S\\s]*?\\[", "[", false); - ini.Parse(surge); + surge = regReplace(surge, R"(^[\S\s]*?\[)", "[", false); + ini.parse(surge); - if(!ini.SectionExist("Proxy")) + if(!ini.section_exist("Proxy")) return false; - ini.EnterSection("Proxy"); - ini.GetItems(proxies); + ini.enter_section("Proxy"); + ini.get_items(proxies); const std::string proxystr = "(.*?)\\s*=\\s*(.*)"; diff --git a/src/utils/file.cpp b/src/utils/file.cpp index f6d059a..3d1928a 100644 --- a/src/utils/file.cpp +++ b/src/utils/file.cpp @@ -2,7 +2,7 @@ #include #include -#include "string.h" +#include "utils/string.h" bool isInScope(const std::string &path) { @@ -22,7 +22,7 @@ std::string fileGet(const std::string &path, bool scope_limit) std::string content; if(scope_limit && !isInScope(path)) - return std::string(); + return ""; std::FILE *fp = std::fopen(path.c_str(), "rb"); if(fp) diff --git a/src/utils/ini_reader/ini_reader.h b/src/utils/ini_reader/ini_reader.h index eca6cc8..bb76a15 100644 --- a/src/utils/ini_reader/ini_reader.h +++ b/src/utils/ini_reader/ini_reader.h @@ -51,17 +51,17 @@ private: int last_error = INIREADER_EXCEPTION_NONE; unsigned int last_error_index = 0; - inline int __priv_save_error_and_return(int x) + inline int save_error_and_return(int x) { last_error = x; return last_error; } - inline bool __priv_chk_ignore(const std::string §ion) + inline bool chk_ignore(const std::string §ion) { bool excluded = false, included = false; excluded = std::find(exclude_sections.begin(), exclude_sections.end(), section) != exclude_sections.end(); - if(include_sections.size()) + if(!include_sections.empty()) included = std::find(include_sections.begin(), include_sections.end(), section) != include_sections.end(); else included = true; @@ -69,12 +69,12 @@ private: return excluded || !included; } - inline bool __priv_chk_direct_save(const std::string §ion) + inline bool chk_direct_save(const std::string §ion) { return std::find(direct_save_sections.cbegin(), direct_save_sections.cend(), section) != direct_save_sections.cend(); } - inline std::string __priv_get_err_str(int error) + inline std::string get_err_str(int error) { switch(error) { @@ -87,30 +87,30 @@ private: case INIREADER_EXCEPTION_OUTOFBOUND: return "Item exists outside of any section"; case INIREADER_EXCEPTION_NOTPARSED: - return "Parse error"; + return "parse error"; default: return "Undefined"; } } - template inline void eraseElements(std::vector &target) + template inline void erase_elements(std::vector &target) { target.clear(); target.shrink_to_fit(); } - template inline void eraseElements(T &target) + template inline void erase_elements(T &target) { T().swap(target); } public: /** - * @brief Set this flag to true to do a UTF8-To-GBK conversion before parsing data. Only useful in Windows. + * @brief set this flag to true to do a UTF8-To-GBK conversion before parsing data. Only useful in Windows. */ bool do_utf8_to_gbk = false; /** - * @brief Set this flag to true so any line within the section will be stored even it doesn't follow the "name=value" format. + * @brief set this flag to true so any line within the section will be stored even it doesn't follow the "name=value" format. * These lines will store as the name "{NONAME}". */ bool store_any_line = false; @@ -139,12 +139,12 @@ public: } /** - * @brief Parse a file during initialization. + * @brief parse a file during initialization. */ explicit INIReader(const std::string &filePath) { parsed = false; - ParseFile(filePath); + parse_file(filePath); } ~INIReader() = default; @@ -171,18 +171,18 @@ public: INIReader(const INIReader &src) = default; - std::string GetLastError() + std::string get_last_error() { if(parsed) - return __priv_get_err_str(last_error); + return get_err_str(last_error); else - return "line " + std::to_string(last_error_index) + ": " + __priv_get_err_str(last_error); + return "line " + std::to_string(last_error_index) + ": " + get_err_str(last_error); } /** * @brief Exclude a section with the given name. */ - void ExcludeSection(const std::string §ion) + void exclude_section(const std::string §ion) { exclude_sections.emplace_back(section); } @@ -190,7 +190,7 @@ public: /** * @brief Include a section with the given name. */ - void IncludeSection(const std::string §ion) + void include_section(const std::string §ion) { include_sections.emplace_back(section); } @@ -198,28 +198,28 @@ public: /** * @brief Add a section to the direct-save sections list. */ - void AddDirectSaveSection(const std::string §ion) + void add_direct_save_section(const std::string §ion) { direct_save_sections.emplace_back(section); } /** - * @brief Set isolated items to given section. + * @brief set isolated items to given section. */ - void SetIsolatedItemsSection(const std::string §ion) + void set_isolated_items_section(const std::string §ion) { isolated_items_section = section; } /** - * @brief Parse INI content into mapped data structure. + * @brief parse INI content into mapped data structure. * If exclude sections are set, these sections will not be stored. * If include sections are set, only these sections will be stored. */ - int Parse(std::string content) //parse content into mapped data + int parse(std::string content) //parse content into mapped data { - if(!content.size()) //empty content - return __priv_save_error_and_return(INIREADER_EXCEPTION_EMPTY); + if(content.empty()) //empty content + return save_error_and_return(INIREADER_EXCEPTION_EMPTY); //remove UTF-8 BOM if(content.compare(0, 3, "\xEF\xBB\xBF") == 0) @@ -232,16 +232,16 @@ public: std::stringstream strStrm; char delimiter = getLineBreak(content); - EraseAll(); //first erase all data + erase_all(); //first erase all data if(do_utf8_to_gbk && isStrUTF8(content)) content = utf8ToACP(content); //do conversion if flag is set - if(store_isolated_line && isolated_items_section.size()) + if(store_isolated_line && !isolated_items_section.empty()) { curSection = isolated_items_section; //items before any section define will be store in this section //check this section first - inExcludedSection = __priv_chk_ignore(curSection); //check if this section is excluded - inDirectSaveSection = __priv_chk_direct_save(curSection); //check if this section requires direct-save + inExcludedSection = chk_ignore(curSection); //check if this section is excluded + inDirectSaveSection = chk_direct_save(curSection); //check if this section requires direct-save inIsolatedSection = true; } strStrm<= 2 && strLine[0] == '/' && strLine[1] == '/')) && !inDirectSaveSection) //empty lines and comments are ignored continue; processEscapeChar(strLine); if(strLine[0] == '[' && strLine[lineSize - 1] == ']') //is a section title { thisSection = strLine.substr(1, lineSize - 2); //save section title - inExcludedSection = __priv_chk_ignore(thisSection); //check if this section is excluded - inDirectSaveSection = __priv_chk_direct_save(thisSection); //check if this section requires direct-save + inExcludedSection = chk_ignore(thisSection); //check if this section is excluded + inDirectSaveSection = chk_direct_save(thisSection); //check if this section requires direct-save - if(curSection.size() && (keep_empty_section || itemGroup.size())) //just finished reading a section + if(!curSection.empty() && (keep_empty_section || !itemGroup.empty())) //just finished reading a section { if(ini_content.find(curSection) != ini_content.end()) //a section with the same name has been inserted { - if(allow_dup_section_titles || !ini_content.at(curSection).size()) + if(allow_dup_section_titles || ini_content.at(curSection).empty()) { auto iter = ini_content.at(curSection); //get the existing section iter.merge(itemGroup); //move new items to this section } - else if(ini_content.at(curSection).size()) - return __priv_save_error_and_return(INIREADER_EXCEPTION_DUPLICATE); //not allowed, stop + else if(!ini_content.at(curSection).empty()) + return save_error_and_return(INIREADER_EXCEPTION_DUPLICATE); //not allowed, stop } else if(!inIsolatedSection || isolated_items_section != thisSection) { - if(itemGroup.size()) + if(!itemGroup.empty()) read_sections.push_back(curSection); //add to read sections list if(std::find(section_order.cbegin(), section_order.cend(), curSection) == section_order.cend()) section_order.emplace_back(curSection); //add to section order if not added before @@ -282,33 +282,33 @@ public: } } inIsolatedSection = false; - eraseElements(itemGroup); //reset section storage + erase_elements(itemGroup); //reset section storage curSection = thisSection; //start a new section } - else if(((store_any_line && pos_equal == strLine.npos) || inDirectSaveSection) && !inExcludedSection && curSection.size()) //store a line without name + else if(((store_any_line && pos_equal == std::string::npos) || inDirectSaveSection) && !inExcludedSection && !curSection.empty()) //store a line without name { itemGroup.emplace("{NONAME}", strLine); } - else if(pos_equal != strLine.npos) //is an item + else if(pos_equal != std::string::npos) //is an item { if(inExcludedSection) //this section is excluded continue; - if(!curSection.size()) //not in any section - return __priv_save_error_and_return(INIREADER_EXCEPTION_OUTOFBOUND); + if(curSection.empty()) //not in any section + return save_error_and_return(INIREADER_EXCEPTION_OUTOFBOUND); string_size pos_value = strLine.find_first_not_of(' ', pos_equal + 1); itemName = trim(strLine.substr(0, pos_equal)); - if(pos_value != strLine.npos) //not a key with empty value + if(pos_value != std::string::npos) //not a key with empty value { itemVal = strLine.substr(pos_value); itemGroup.emplace(std::move(itemName), std::move(itemVal)); //insert to current section } else - itemGroup.emplace(std::move(itemName), std::string()); + itemGroup.emplace(std::move(itemName), ""); } - if(include_sections.size() && include_sections == read_sections) //all included sections has been read + if(!include_sections.empty() && include_sections == read_sections) //all included sections has been read break; //exit now } - if(curSection.size() && (keep_empty_section || itemGroup.size())) //final section + if(!curSection.empty() && (keep_empty_section || !itemGroup.empty())) //final section { if(ini_content.find(curSection) != ini_content.end()) //a section with the same name has been inserted { @@ -317,12 +317,12 @@ public: auto &iter = ini_content.at(curSection); //get the existing section iter.merge(itemGroup); //move new items to this section } - else if(ini_content.at(curSection).size()) - return __priv_save_error_and_return(INIREADER_EXCEPTION_DUPLICATE); //not allowed, stop + else if(!ini_content.at(curSection).empty()) + return save_error_and_return(INIREADER_EXCEPTION_DUPLICATE); //not allowed, stop } else if(!inIsolatedSection || isolated_items_section != thisSection) { - if(itemGroup.size()) + if(!itemGroup.empty()) read_sections.emplace_back(curSection); //add to read sections list if(std::find(section_order.cbegin(), section_order.cend(), curSection) == section_order.cend()) section_order.emplace_back(curSection); //add to section order if not added before @@ -330,23 +330,23 @@ public: } } parsed = true; - return __priv_save_error_and_return(INIREADER_EXCEPTION_NONE); //all done + return save_error_and_return(INIREADER_EXCEPTION_NONE); //all done } /** - * @brief Parse an INI file into mapped data structure. + * @brief parse an INI file into mapped data structure. */ - int ParseFile(const std::string &filePath) + int parse_file(const std::string &filePath) { if(!fileExist(filePath)) - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); - return Parse(fileGet(filePath)); + return save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); + return parse(fileGet(filePath)); } /** * @brief Check whether a section exist. */ - bool SectionExist(const std::string §ion) + bool section_exist(const std::string §ion) { return ini_content.find(section) != ini_content.end(); } @@ -354,7 +354,7 @@ public: /** * @brief Count of sections in the whole INI. */ - unsigned int SectionCount() + unsigned int section_count() { return ini_content.size(); } @@ -362,7 +362,7 @@ public: /** * @brief Return all section names inside INI. */ - string_array GetSections() + string_array get_section_names() { return section_order; } @@ -370,19 +370,19 @@ public: /** * @brief Enter a section with the given name. Section name and data will be cached to speed up the following reading process. */ - int EnterSection(const std::string §ion) + int enter_section(const std::string §ion) { - if(!SectionExist(section)) - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); + if(!section_exist(section)) + return save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); current_section = cached_section = section; cached_section_content = ini_content.find(section); - return __priv_save_error_and_return(INIREADER_EXCEPTION_NONE); + return save_error_and_return(INIREADER_EXCEPTION_NONE); } /** - * @brief Set current section. + * @brief set current section. */ - void SetCurrentSection(const std::string §ion) + void set_current_section(const std::string §ion) { current_section = section; } @@ -390,9 +390,9 @@ public: /** * @brief Check whether an item exist in the given section. Return false if the section does not exist. */ - bool ItemExist(const std::string §ion, const std::string &itemName) + bool item_exist(const std::string §ion, const std::string &itemName) { - if(!SectionExist(section)) + if(!section_exist(section)) return false; if(section != cached_section) @@ -407,17 +407,17 @@ public: /** * @brief Check whether an item exist in current section. Return false if the section does not exist. */ - bool ItemExist(const std::string &itemName) + bool item_exist(const std::string &itemName) { - return current_section.size() ? ItemExist(current_section, itemName) : false; + return !current_section.empty() && item_exist(current_section, itemName); } /** * @brief Check whether an item with the given name prefix exist in the given section. Return false if the section does not exist. */ - bool ItemPrefixExist(const std::string §ion, const std::string &itemName) + bool item_prefix_exists(const std::string §ion, const std::string &itemName) { - if(!SectionExist(section)) + if(!section_exist(section)) return false; if(section != cached_section) @@ -426,49 +426,47 @@ public: cached_section_content = ini_content.find(section); } - for(auto &x : cached_section_content->second) - { - if(x.first.find(itemName) == 0) - return true; - } + auto &items = cached_section_content->second; - return false; + return std::any_of(items.cbegin(), items.cend(), [&](auto &x) { + return x.first.find(itemName) == 0; + }); } /** * @brief Check whether an item with the given name prefix exist in current section. Return false if the section does not exist. */ - bool ItemPrefixExist(const std::string &itemName) + bool item_prefix_exist(const std::string &itemName) { - return current_section.size() ? ItemPrefixExist(current_section, itemName) : false; + return !current_section.empty() && item_prefix_exists(current_section, itemName); } /** * @brief Count of items in the given section. Return 0 if the section does not exist. */ - unsigned int ItemCount(const std::string §ion) + unsigned int item_count(const std::string §ion) { - if(!parsed || !SectionExist(section)) - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTPARSED); + if(!parsed || !section_exist(section)) + return save_error_and_return(INIREADER_EXCEPTION_NOTPARSED); return ini_content.at(section).size(); } /** - * @brief Erase all data from the data structure and reset parser status. + * @brief erase all data from the data structure and reset parser status. */ - void EraseAll() + void erase_all() { - eraseElements(ini_content); - eraseElements(section_order); + erase_elements(ini_content); + erase_elements(section_order); cached_section.clear(); cached_section_content = ini_content.end(); parsed = false; } - ini_data_struct::iterator GetItemsRef(const std::string §ion) + ini_data_struct::iterator get_items_ref(const std::string §ion) { - if(!parsed || !SectionExist(section)) + if(!parsed || !section_exist(section)) return ini_content.end(); if(cached_section != section) @@ -482,35 +480,35 @@ public: /** * @brief Retrieve all items in the given section. */ - int GetItems(const std::string §ion, string_multimap &data) + int get_items(const std::string §ion, string_multimap &data) { - auto section_ref = GetItemsRef(section); + auto section_ref = get_items_ref(section); if(section_ref == ini_content.end()) - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); + return save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); data = section_ref->second; - return __priv_save_error_and_return(INIREADER_EXCEPTION_NONE); + return save_error_and_return(INIREADER_EXCEPTION_NONE); } /** * @brief Retrieve all items in current section. */ - int GetItems(string_multimap &data) + int get_items(string_multimap &data) { - return current_section.size() ? GetItems(current_section, data) : -1; + return !current_section.empty() ? get_items(current_section, data) : -1; } /** * @brief Retrieve item(s) with the same name prefix in the given section. */ - int GetAll(const std::string §ion, const std::string &itemName, string_array &results) //retrieve item(s) with the same itemName prefix + int get_all(const std::string §ion, const std::string &itemName, string_array &results) //retrieve item(s) with the same itemName prefix { if(!parsed) - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTPARSED); + return save_error_and_return(INIREADER_EXCEPTION_NOTPARSED); - auto section_ref = GetItemsRef(section); + auto section_ref = get_items_ref(section); if(section_ref == ini_content.end()) - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); + return save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); for(auto &x : section_ref->second) { @@ -518,24 +516,24 @@ public: results.emplace_back(x.second); } - return __priv_save_error_and_return(INIREADER_EXCEPTION_NONE); + return save_error_and_return(INIREADER_EXCEPTION_NONE); } /** * @brief Retrieve item(s) with the same name prefix in current section. */ - int GetAll(const std::string &itemName, string_array &results) + int get_all(const std::string &itemName, string_array &results) { - return current_section.size() ? GetAll(current_section, itemName, results) : -1; + return !current_section.empty() ? get_all(current_section, itemName, results) : -1; } /** * @brief Retrieve one item with the exact same name in the given section. */ - std::string Get(const std::string §ion, const std::string &itemName) //retrieve one item with the exact same itemName + std::string get(const std::string §ion, const std::string &itemName) //retrieve one item with the exact same itemName { - if(!parsed || !SectionExist(section)) - return std::string(); + if(!parsed || !section_exist(section)) + return ""; if(cached_section != section) { @@ -548,68 +546,68 @@ public: if(iter != cache.end()) return iter->second; - return std::string(); + return ""; } /** * @brief Retrieve one item with the exact same name in current section. */ - std::string Get(const std::string &itemName) + std::string get(const std::string &itemName) { - return current_section.size() ? Get(current_section, itemName) : std::string(); + return !current_section.empty() ? get(current_section, itemName) : ""; } /** * @brief Retrieve one item with the exact same name in the given section, if exist. */ - int GetIfExist(const std::string §ion, const std::string &itemName, std::string &target) //retrieve one item with the exact same itemName + int get_if_exist(const std::string §ion, const std::string &itemName, std::string &target) //retrieve one item with the exact same itemName { if(!parsed) - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTPARSED); + return save_error_and_return(INIREADER_EXCEPTION_NOTPARSED); - if(ItemExist(section, itemName)) + if(item_exist(section, itemName)) { - target = Get(section, itemName); - return __priv_save_error_and_return(INIREADER_EXCEPTION_NONE); + target = get(section, itemName); + return save_error_and_return(INIREADER_EXCEPTION_NONE); } - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); + return save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); } /** * @brief Retrieve one item with the exact same name in current section, if exist. */ - int GetIfExist(const std::string &itemName, std::string &target) + int get_if_exist(const std::string &itemName, std::string &target) { - return current_section.size() ? GetIfExist(current_section, itemName, target) : INIREADER_EXCEPTION_NOTEXIST; + return !current_section.empty() ? get_if_exist(current_section, itemName, target) : INIREADER_EXCEPTION_NOTEXIST; } /** * @brief Retrieve one boolean item value with the exact same name in the given section. */ - bool GetBool(const std::string §ion, const std::string &itemName) + bool get_bool(const std::string §ion, const std::string &itemName) { - return Get(section, itemName) == "true"; + return get(section, itemName) == "true"; } /** * @brief Retrieve one boolean item value with the exact same name in current section. */ - bool GetBool(const std::string &itemName) + bool get_bool(const std::string &itemName) { - return current_section.size() ? Get(current_section, itemName) == "true" : false; + return !current_section.empty() && get(current_section, itemName) == "true"; } /** * @brief Retrieve one boolean item value with the exact same name in the given section. */ - int GetBoolIfExist(const std::string §ion, const std::string &itemName, bool &target) + int get_bool_if_exist(const std::string §ion, const std::string &itemName, bool &target) { std::string result; - int retval = GetIfExist(section, itemName, result); - if(retval != INIREADER_EXCEPTION_NONE) - return retval; - if(result.size()) + int retVal = get_if_exist(section, itemName, result); + if(retVal != INIREADER_EXCEPTION_NONE) + return retVal; + if(!result.empty()) target = result == "true"; return INIREADER_EXCEPTION_NONE; } @@ -617,21 +615,21 @@ public: /** * @brief Retrieve one boolean item value with the exact same name in current section. */ - int GetBoolIfExist(const std::string &itemName, bool &target) + int get_bool_if_exist(const std::string &itemName, bool &target) { - return current_section.size() ? GetBoolIfExist(current_section, itemName, target) : INIREADER_EXCEPTION_NOTEXIST; + return !current_section.empty() ? get_bool_if_exist(current_section, itemName, target) : INIREADER_EXCEPTION_NOTEXIST; } /** * @brief Retrieve one number item value with the exact same name in the given section. */ - template int GetNumberIfExist(const std::string §ion, const std::string &itemName, T &target) + template int get_number_if_exist(const std::string §ion, const std::string &itemName, T &target) { std::string result; - int retval = GetIfExist(section, itemName, result); - if(retval != INIREADER_EXCEPTION_NONE) - return retval; - if(result.size()) + int retVal = get_if_exist(section, itemName, result); + if(retVal != INIREADER_EXCEPTION_NONE) + return retVal; + if(!result.empty()) target = to_number(result, target); return INIREADER_EXCEPTION_NONE; } @@ -639,73 +637,72 @@ public: /** * @brief Retrieve one number item value with the exact same name in current section. */ - template int GetNumberIfExist(const std::string &itemName, T &target) + template int get_number_if_exist(const std::string &itemName, T &target) { - return current_section.size() ? GetNumberIfExist(current_section, itemName, target) : INIREADER_EXCEPTION_NOTEXIST; + return !current_section.empty() ? get_number_if_exist(current_section, itemName, target) : INIREADER_EXCEPTION_NOTEXIST; } /** * @brief Retrieve one integer item value with the exact same name in the given section. */ - int GetIntIfExist(const std::string §ion, const std::string &itemName, int &target) + int get_int_if_exist(const std::string §ion, const std::string &itemName, int &target) { - return GetNumberIfExist(section, itemName, target); + return get_number_if_exist(section, itemName, target); } /** * @brief Retrieve one integer item value with the exact same name in current section. */ - int GetIntIfExist(const std::string &itemName, int &target) + int get_int_if_exist(const std::string &itemName, int &target) { - return GetNumberIfExist(itemName, target); + return get_number_if_exist(itemName, target); } /** * @brief Retrieve one integer item value with the exact same name in the given section. */ - int GetInt(const std::string §ion, const std::string &itemName) + int get_int(const std::string §ion, const std::string &itemName) { - return to_int(Get(section, itemName), 0); + return to_int(get(section, itemName), 0); } /** * @brief Retrieve one integer item value with the exact same name in current section. */ - int GetInt(const std::string &itemName) + int get_int(const std::string &itemName) { - return GetInt(current_section, itemName); + return get_int(current_section, itemName); } /** * @brief Retrieve the first item found in the given section. */ - std::string GetFirst(const std::string §ion, const std::string &itemName) //return the first item value found in section + std::string get_first(const std::string §ion, const std::string &itemName) //return the first item value found in section { if(!parsed) - return std::string(); + return ""; string_array result; - if(GetAll(section, itemName, result) != -1) + if(get_all(section, itemName, result) != -1) return result[0]; else - return std::string(); + return ""; } /** * @brief Retrieve the first item found in current section. */ - std::string GetFirst(const std::string &itemName) + std::string get_first(const std::string &itemName) { - return current_section.size() ? GetFirst(current_section, itemName) : std::string(); + return !current_section.empty() ? get_first(current_section, itemName) : ""; } /** * @brief Retrieve a string style array with specific separator and write into integer array. */ - template void GetIntArray(const std::string §ion, const std::string &itemName, const std::string &separator, T &Array) + template void get_int_array(const std::string §ion, const std::string &itemName, const std::string &separator, T& Array) { - string_array vArray; - unsigned int index, UBound = sizeof(Array) / sizeof(Array[0]); - vArray = split(Get(section, itemName), separator); + unsigned int index, UBound = sizeof(Array[0]) / sizeof(Array); + string_array vArray = split(get(section, itemName), separator); for(index = 0; index < vArray.size() && index < UBound; index++) Array[index] = stoi(vArray[index]); for(; index < UBound; index++) @@ -715,24 +712,24 @@ public: /** * @brief Retrieve a string style array with specific separator and write into integer array. */ - template void GetIntArray(const std::string &itemName, const std::string &separator, T &Array) + template void get_int_array(const std::string &itemName, const std::string &separator, T& Array) { - if(current_section.size()) - GetIntArray(current_section, itemName, separator, Array); + if(!current_section.empty()) + get_int_array(current_section, itemName, separator, Array); } /** * @brief Add a std::string value with given values. */ - int Set(const std::string §ion, std::string itemName, std::string itemVal) + int set(const std::string §ion, std::string itemName, std::string itemVal) { - if(!section.size()) - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); + if(section.empty()) + return save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); if(!parsed) parsed = true; - if(SectionExist(section)) + if(section_exist(section)) { string_multimap &mapTemp = ini_content.at(section); mapTemp.insert(std::pair(std::move(itemName), std::move(itemVal))); @@ -745,110 +742,109 @@ public: section_order.emplace_back(section); } - return __priv_save_error_and_return(INIREADER_EXCEPTION_NONE); + return save_error_and_return(INIREADER_EXCEPTION_NONE); } /** * @brief Add a string value with given values. */ - int Set(std::string itemName, std::string itemVal) + int set(std::string itemName, std::string itemVal) { - if(!current_section.size()) - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); - return Set(current_section, std::move(itemName), std::move(itemVal)); + if(current_section.empty()) + return save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); + return set(current_section, std::move(itemName), std::move(itemVal)); } /** * @brief Add a boolean value with given values. */ - int SetBool(const std::string §ion, std::string itemName, bool itemVal) + int set_bool(const std::string §ion, std::string itemName, bool itemVal) { - return Set(section, std::move(itemName), itemVal ? "true" : "false"); + return set(section, std::move(itemName), itemVal ? "true" : "false"); } /** * @brief Add a boolean value with given values. */ - int SetBool(std::string itemName, bool itemVal) + int set_bool(std::string itemName, bool itemVal) { - return SetBool(current_section, std::move(itemName), itemVal); + return set_bool(current_section, std::move(itemName), itemVal); } /** * @brief Add a double value with given values. */ - int SetDouble(const std::string §ion, std::string itemName, double itemVal) + int set_double(const std::string §ion, std::string itemName, double itemVal) { - return Set(section, std::move(itemName), std::to_string(itemVal)); + return set(section, std::move(itemName), std::to_string(itemVal)); } /** * @brief Add a double value with given values. */ - int SetDouble(std::string itemName, double itemVal) + int set_double(std::string itemName, double itemVal) { - return SetDouble(current_section, std::move(itemName), itemVal); + return set_double(current_section, std::move(itemName), itemVal); } /** * @brief Add a long value with given values. */ - int SetLong(const std::string §ion, std::string itemName, long itemVal) + int set_long(const std::string §ion, std::string itemName, long itemVal) { - return Set(section, std::move(itemName), std::to_string(itemVal)); + return set(section, std::move(itemName), std::to_string(itemVal)); } /** * @brief Add a long value with given values. */ - int SetLong(std::string itemName, long itemVal) + int set_long(std::string itemName, long itemVal) { - return SetLong(current_section, std::move(itemName), itemVal); + return set_long(current_section, std::move(itemName), itemVal); } /** * @brief Add an array with the given separator. */ - template int SetArray(const std::string §ion, std::string itemName, const std::string &separator, T &Array) + template int set_array(const std::string §ion, std::string itemName, const std::string &separator, T &Array) { std::string data; data = std::accumulate(std::begin(Array), std::end(Array), std::string(), [&](auto a, auto b) { return std::move(a) + std::to_string(b) + separator; }); data.erase(data.size() - 1); - return Set(section, std::move(itemName), data); + return set(section, std::move(itemName), data); } /** * @brief Add an array with the given separator. */ - template int SetArray(std::string itemName, const std::string &separator, T &Array) + template int set_array(std::string itemName, const std::string &separator, T &Array) { - return current_section.size() ? SetArray(current_section, std::move(itemName), separator, Array) : -1; + return !current_section.empty() ? set_array(current_section, std::move(itemName), separator, Array) : -1; } /** * @brief Rename an existing section. */ - int RenameSection(const std::string &oldName, std::string newName) + int rename_section(const std::string &oldName, const std::string& newName) { - if(!SectionExist(oldName) || SectionExist(newName)) - return __priv_save_error_and_return(INIREADER_EXCEPTION_DUPLICATE); + if(!section_exist(oldName) || section_exist(newName)) + return save_error_and_return(INIREADER_EXCEPTION_DUPLICATE); auto nodeHandler = ini_content.extract(oldName); - nodeHandler.key() = std::move(newName); + nodeHandler.key() = newName; ini_content.insert(std::move(nodeHandler)); std::replace(section_order.begin(), section_order.end(), oldName, newName); - return __priv_save_error_and_return(INIREADER_EXCEPTION_NONE); + return save_error_and_return(INIREADER_EXCEPTION_NONE); } /** - * @brief Erase all items with the given name. + * @brief erase all items with the given name. */ - int Erase(const std::string §ion, const std::string &itemName) + int erase(const std::string §ion, const std::string &itemName) { - int retVal; - if(!SectionExist(section)) - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); + if(!section_exist(section)) + return save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); - retVal = ini_content.at(section).erase(itemName); + auto retVal = ini_content.at(section).erase(itemName); if(retVal && cached_section == section) { cached_section_content = ini_content.find(section); @@ -857,47 +853,47 @@ public: } /** - * @brief Erase all items with the given name. + * @brief erase all items with the given name. */ - int Erase(const std::string &itemName) + int erase(const std::string &itemName) { - return current_section.size() ? Erase(current_section, itemName) : -1; + return !current_section.empty() ? erase(current_section, itemName) : -1; } /** - * @brief Erase the first item with the given name. + * @brief erase the first item with the given name. */ - int EraseFirst(const std::string §ion, const std::string &itemName) + int erase_first(const std::string §ion, const std::string &itemName) { string_multimap &mapTemp = ini_content.at(section); - string_multimap::iterator iter = mapTemp.find(itemName); + auto iter = mapTemp.find(itemName); if(iter != mapTemp.end()) { mapTemp.erase(iter); - return __priv_save_error_and_return(INIREADER_EXCEPTION_NONE); + return save_error_and_return(INIREADER_EXCEPTION_NONE); } else { - return __priv_save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); + return save_error_and_return(INIREADER_EXCEPTION_NOTEXIST); } } /** - * @brief Erase the first item with the given name. + * @brief erase the first item with the given name. */ - int EraseFirst(const std::string &itemName) + int erase_first(const std::string &itemName) { - return current_section.size() ? EraseFirst(current_section, itemName) : -1; + return !current_section.empty() ? erase_first(current_section, itemName) : -1; } /** - * @brief Erase all items in the given section. + * @brief erase all items in the given section. */ - void EraseSection(const std::string §ion) + void erase_section(const std::string §ion) { if(ini_content.find(section) == ini_content.end()) return; - eraseElements(ini_content.at(section)); + erase_elements(ini_content.at(section)); if(cached_section == section) { cached_section_content = ini_content.end(); @@ -906,18 +902,18 @@ public: } /** - * @brief Erase all items in current section. + * @brief erase all items in current section. */ - void EraseSection() + void erase_section() { - if(current_section.size()) - EraseSection(current_section); + if(!current_section.empty()) + erase_section(current_section); } /** * @brief Remove a section from INI. */ - void RemoveSection(const std::string §ion) + void remove_section(const std::string §ion) { if(ini_content.find(section) == ini_content.end()) return; @@ -933,21 +929,21 @@ public: /** * @brief Remove current section from INI. */ - void RemoveSection() + void remove_section() { - if(current_section.size()) - RemoveSection(current_section); + if(!current_section.empty()) + remove_section(current_section); } /** * @brief Export the whole INI data structure into a string. */ - std::string ToString() + std::string to_string() { std::string content, itemVal; if(!parsed) - return std::string(); + return ""; for(auto &x : section_order) { @@ -981,9 +977,9 @@ public: /** * @brief Export the whole INI data structure into a file. */ - int ToFile(const std::string &filePath) + int to_file(const std::string &filePath) { - return fileWrite(filePath, ToString(), true); + return fileWrite(filePath, to_string(), true); } }; diff --git a/src/utils/network.cpp b/src/utils/network.cpp index bd7d47a..da28454 100644 --- a/src/utils/network.cpp +++ b/src/utils/network.cpp @@ -18,7 +18,7 @@ std::string hostnameToIPAddr(const std::string &host) if(retVal != 0) { freeaddrinfo(retAddrInfo); - return std::string(); + return ""; } for(cur = retAddrInfo; cur != NULL; cur = cur->ai_next) diff --git a/src/utils/rapidjson_extra.h b/src/utils/rapidjson_extra.h index 3809040..591f350 100644 --- a/src/utils/rapidjson_extra.h +++ b/src/utils/rapidjson_extra.h @@ -21,7 +21,7 @@ template void exception_thrower(T e) inline void operator >> (const rapidjson::Value& value, std::string& i) { if(value.IsNull()) - i = std::string(); + i = ""; else if(value.IsString()) i = std::string(value.GetString()); else if(value.IsInt64()) @@ -31,7 +31,7 @@ inline void operator >> (const rapidjson::Value& value, std::string& i) else if(value.IsDouble()) i = std::to_string(value.GetDouble()); else - i = std::string(); + i = ""; } inline void operator >> (const rapidjson::Value& value, int& i) diff --git a/src/utils/string.cpp b/src/utils/string.cpp index b1d9bf2..0730f84 100644 --- a/src/utils/string.cpp +++ b/src/utils/string.cpp @@ -234,13 +234,13 @@ std::string trimWhitespace(const std::string &str, bool before, bool after) { epos = str.find_last_not_of(whitespaces); if(epos == std::string::npos) - return std::string(); + return ""; } if(before) { bpos = str.find_first_not_of(whitespaces); if(bpos == std::string::npos) - return std::string(); + return ""; } return str.substr(bpos, epos - bpos + 1); } @@ -295,7 +295,7 @@ std::string getUrlArg(const std::string &url, const std::string &request) break; pos--; } - return std::string(); + return ""; } std::string replaceAllDistinct(std::string str, const std::string &old_value, const std::string &new_value) diff --git a/src/utils/string.h b/src/utils/string.h index 05fa52a..7c16bec 100644 --- a/src/utils/string.h +++ b/src/utils/string.h @@ -7,6 +7,7 @@ #include #include +using string = std::string; using string_size = std::string::size_type; using string_array = std::vector; using string_map = std::map; diff --git a/src/utils/system.cpp b/src/utils/system.cpp index beaa15d..222b9af 100644 --- a/src/utils/system.cpp +++ b/src/utils/system.cpp @@ -50,7 +50,7 @@ std::string getSystemProxy() if(ret != ERROR_SUCCESS) { //std::cout << "open failed: " << ret << std::endl; - return std::string(); + return ""; } DWORD values_count, max_value_name_len, max_value_len; @@ -59,7 +59,7 @@ std::string getSystemProxy() if(ret != ERROR_SUCCESS) { //std::cout << "query failed" << std::endl; - return std::string(); + return ""; } std::vector, DWORD, std::shared_ptr>> values; @@ -103,7 +103,7 @@ std::string getSystemProxy() } */ //return 0; - return std::string(); + return ""; #else string_array proxy_env = {"all_proxy", "ALL_PROXY", "http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY"}; for(std::string &x : proxy_env) @@ -112,6 +112,6 @@ std::string getSystemProxy() if(proxy != NULL) return std::string(proxy); } - return std::string(); + return ""; #endif // _WIN32 }