id
int64
0
877k
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
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 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
10,405
power_of_a_number.cpp
OpenGenus_cosmos/code/divide_conquer/src/power_of_a_number/power_of_a_number.cpp
/* PROBLEM STATEMENT: Given 2 numbers x and y, you need to find x raise to y. */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define FIO ios::sync_with_stdio(0); ll power(ll a,ll b) { ll res=1; while(b!=0) { if(b%2!=0) { res=(res*a)%1000000007; b--; } else { a=(a*a)%1000000007; b/=2; } } return res; } int main() { FIO; ll number_a,number_b,answer; cin >> number_a >> number_b; answer = power(number_a,number_b); cout << answer; return 0; }
533
C++
.cpp
35
12.371429
55
0.607646
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,408
karatsubamultiply.cpp
OpenGenus_cosmos/code/divide_conquer/src/karatsuba_multiplication/karatsubamultiply.cpp
// Author: Tote93 #include <iostream> #include <string> #include <sstream> #include <cstdlib> /* Prototypes */ int getBiggerSize(const std::string &number1, const std::string &number2); void checkNumbers(int size, std::string &number1, std::string &number2); std::string KaratsubaMultiply(std::string &number1, std::string &number2, int limit); std::string AddNumbers(std::string &number1, std::string &number2); void removeNonSignificantZeros(std::string &c); void splitString(std::string original, std::string &sub1, std::string &sub2); int main() { std::string number1, number2; std::cout << "Insert the first number \n"; std::cin >> number1; std::cout << "Insert the second number \n"; std::cin >> number2; int size = getBiggerSize(number1, number2); checkNumbers(size, number1, number2); std::string result = KaratsubaMultiply(number1, number2, number1.length()); //Returns number to original without non-significant zeros removeNonSignificantZeros(number1); removeNonSignificantZeros(number2); std::cout << "Result " << number1 << " * " << number2 << " = " << result << "\n"; } int getBiggerSize(const std::string &number1, const std::string &number2) { int numb1Length = number1.length(); int numb2Length = number2.length(); return (numb1Length > numb2Length) ? numb1Length : numb2Length; } void checkNumbers(int size, std::string &number1, std::string &number2) { int newSize = 0, nZeros = 0; newSize = getBiggerSize(number1, number2); nZeros = newSize - number1.length(); number1.insert(number1.begin(), nZeros, '0'); nZeros = newSize - number2.length(); number2.insert(number2.begin(), nZeros, '0'); if (number1.length() % 2 != 0) number1.insert(number1.begin(), 1, '0'); if (number2.length() % 2 != 0) number2.insert(number2.begin(), 1, '0'); } std::string KaratsubaMultiply(std::string &number1, std::string &number2, int limit) { int n = number1.length(), s; std::string w, x, y, z; std::string final1, final2, final3; std::string total; if (n == 1) { int integer1, integer2, aux; integer1 = atoi (number1.c_str()); integer2 = atoi (number2.c_str()); aux = integer1 * integer2; //We can replace two next lines with -> total = to_string(aux) using c++11 std::ostringstream temp; temp << aux; total = temp.str(); removeNonSignificantZeros (total); return total; } else { s = n / 2; splitString (number1, w, x); splitString (number2, y, z); final1 = KaratsubaMultiply (w, y, n); final1.append(2 * s, '0'); std::string wz = KaratsubaMultiply (w, z, n); std::string xy = KaratsubaMultiply (x, y, n); final2 = AddNumbers (wz, xy); final2.append(s, '0'); final3 = KaratsubaMultiply (x, z, n); total = AddNumbers (final1, final2); return AddNumbers (total, final3); } } void removeNonSignificantZeros(std::string &c) { int acum = 0; for (int i = 0; i < c.length(); ++i) { if (c[i] != '0') break; else acum++; } if (c.length() != acum) c = c.substr(acum, c.length()); else c = c.substr(acum - 1, c.length()); } void splitString(std::string original, std::string &sub1, std::string &sub2) { int n, n1, n2; sub1 = sub2 = ""; n = original.length(); if (n % 2 == 0) { n1 = n / 2; n2 = n1; } else { n1 = (n + 1) / 2; n2 = n1 - 1; } sub1 = original.substr(0, n1); sub2 = original.substr(n1, n); if (sub1.length() % 2 != 0 && sub2.length() > 2) sub1.insert(sub1.begin(), 1, '0'); if (sub2.length() > 2 && sub2.length() % 2 != 0) sub2.insert(sub2.begin(), 1, '0'); } std::string AddNumbers(std::string &number1, std::string &number2) { int x, y, aux = 0, aux2 = 0; int digitos = getBiggerSize(number1, number2); std::string total, total2, cadena; int n1 = number1.length(); int n2 = number2.length(); if (n1 > n2) number2.insert(number2.begin(), n1 - n2, '0'); else number1.insert(number1.begin(), n2 - n1, '0'); for (int i = digitos - 1; i >= 0; i--) { x = number1[i] - '0'; y = number2[i] - '0'; aux = x + y + aux2; if (aux >= 10) { aux2 = 1; aux = aux % 10; } else aux2 = 0; total2 = '0' + aux; total.insert(0, total2); if (i == 0 && aux2 == 1) { total2 = "1"; total.insert(0, total2); removeNonSignificantZeros(total); return total; } } removeNonSignificantZeros(total); return total; }
5,039
C++
.cpp
154
25.538961
86
0.564219
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,409
main.cpp
OpenGenus_cosmos/code/divide_conquer/src/strassen_matrix_multiplication/main.cpp
//The following program contains the strassen algorithm along with the Currently Fastest Matrix Multiplication Algorithm for sparse matrices // Developed by Raphael Yuster and Uri Zwick // I have also included a time calculator in case anyone wanted to check time taken by each algorithms // Although mathematcially the fast multiplication algorithm should take less time, since it is of lesser order O(n^t) // however it has a large preceeding constant thus the effect of the algorthm can only be seen in larger matrices #include <algorithm> #include <chrono> #include <iostream> #include <random> #include <vector> std::vector<std::vector<int>> generator(int m, int n) { std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution<std::mt19937::result_type> dist6(0, 1); std::vector<std::vector<int>> ans; for (int i = 0; i < m; i++) { std::vector<int> row; for (int j = 0; j < n; j++) { if ((i + j) % 5 != 5) row.push_back(dist6(rng)); else row.push_back(0); } ans.push_back(row); } return ans; } int f(const std::vector<std::vector<int>>& a) { return a[0][0]; } std::vector<std::vector<int>> retriever(const std::vector<std::vector<int>>& matrix, int x, int y) { std::vector<std::vector<int>> ans; for (int i = 0; i < x; i++) { std::vector<int> row; for (int j = 0; j < y; j++) row.push_back(matrix[i][j]); ans.push_back(row); } return ans; } std::vector<std::vector<int>> converter(const std::vector<std::vector<int>>& matrix) { auto noOfRows = matrix.size(); auto noOfCols = matrix[0].size(); std::vector<std::vector<int>>::size_type t = 1; std::vector<std::vector<int>>::size_type p; if (x > y) p = noOfRows; else p = noOfCols; while (t < p) t *= 2; p = t; int flag = 0; std::vector<std::vector<int>> ans; for (vector<vector<int>>::size_type i = 0; i < p; i++) { if (i >= noOfRows) flag = 1; std::vector<int> row; for (std::vector<int>::size_type j = 0; j < p; j++) { if (flag == 1) row.push_back(0); else { if (j >= noOfCols) row.push_back(0); else row.push_back(matrix[i][j]); } } ans.push_back(row); } return ans; } void print(const std::vector<std::vector<int>>& grid) { for (std::vector<std::vector<int>>::size_type i = 0; i < grid.size(); i++) { for (std::vector<int>::size_type j = 0; j < grid[i].size(); j++) std::cout << grid[i][j] << ' '; std::cout << std::endl; } } std::vector<std::vector<int>> add(const std::vector<std::vector<int>>& a, const std::vector<std::vector<int>>& b) { std::vector<std::vector<int>> ans; for (std::vector<std::vector<int>>::size_type i = 0; i < a.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < a[i].size(); j++) { int temp = a[i][j] + b[i][j]; row.push_back(temp); } ans.push_back(row); } return ans; } std::vector<std::vector<int>> subtract(const std::vector<std::vector<int>>& a, const std::vector<std::vector<int>>& b) { std::vector<std::vector<int>> ans; for (std::vector<std::vector<int>>::size_type i = 0; i < a.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < a[i].size(); j++) { int temp = a[i][j] - b[i][j]; row.push_back(temp); } ans.push_back(row); } return ans; } std::vector<std::vector<int>> naive_multi(const std::vector<std::vector<int>>& a, const std::vector<std::vector<int>>& b) { int s = 0; std::vector<std::vector<int>> ans; for (std::vector<std::vector<int>>::size_type i = 0; i < a.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < b[i].size(); j++) { s = 0; for (std::vector<int>::size_type k = 0; k < a[i].size(); k++) s += a[i][k] * b[k][j]; row.push_back(s); } ans.push_back(row); } return ans; } std::vector<std::vector<int>> strassen(const std::vector<std::vector<int>>& m1, const std::vector<std::vector<int>>& m2) { std::vector<std::vector<int>>::size_type s1 = m1.size(); std::vector<std::vector<int>>::size_type s2 = m2.size(); if (s1 > 2 && s2 > 2) { std::vector<std::vector<int>> a, b, c, d, e, f, g, h, ans; for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size() / 2; i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < m1[i].size() / 2; j++) row.push_back(m1[i][j]); a.push_back(row); } for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size() / 2; i++) { vector<int> row; for (std::vector<int>::size_type j = m1[i].size() / 2; j < m1[i].size(); j++) row.push_back(m1[i][j]); b.push_back(row); } for (std::vector<std::vector<int>>::size_type i = m1.size() / 2; i < m1.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < m1[i].size() / 2; j++) row.push_back(m1[i][j]); c.push_back(row); } for (std::vector<std::vector<int>>::size_type i = m1.size() / 2; i < m1.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = m1[i].size() / 2; j < m1[i].size(); j++) row.push_back(m1[i][j]); d.push_back(row); } for (std::vector<std::vector<int>>::size_type i = 0; i < m2.size() / 2; i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < m2[i].size() / 2; j++) row.push_back(m2[i][j]); e.push_back(row); } for (std::vector<std::vector<int>>::size_type i = 0; i < m2.size() / 2; i++) { vector<int> row; for (std::vector<int>::size_type j = m2[i].size() / 2; j < m2[i].size(); j++) row.push_back(m2[i][j]); f.push_back(row); } for (std::vector<std::vector<int>>::size_type i = m2.size() / 2; i < m2.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < m2[i].size() / 2; j++) row.push_back(m2[i][j]); g.push_back(row); } for (std::vector<std::vector<int>>::size_type i = m2.size() / 2; i < m2.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = m2[i].size() / 2; j < m2[i].size(); j++) row.push_back(m2[i][j]); h.push_back(row); } std::vector<std::vector<int>> p1, p2, p3, p4, p5, p6, p7; p1 = strassen(a, subtract(f, h)); p2 = strassen(add(a, b), h); p3 = strassen(add(c, d), e); p4 = strassen(d, subtract(g, e)); p5 = strassen(add(a, d), add(e, h)); p6 = strassen(subtract(b, d), add(g, h)); p7 = strassen(subtract(a, c), add(e, f)); std::vector<std::vector<int>> c1, c2, c3, c4; c1 = subtract(add(add(p5, p4), p6), p2); c2 = add(p1, p2); c3 = add(p3, p4); c4 = subtract(add(p1, p5), add(p3, p7)); int flag1, flag2; for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size(); i++) { std::vector<int> row; if (i < m1.size() / 2) flag1 = 0; else flag1 = 1; for (std::vector<int>::size_type j = 0; j < m2[i].size(); j++) { if (j < m2[i].size() / 2) { if (flag1 == 0) row.push_back(c1[i][j]); else row.push_back(c3[i - m1.size() / 2][j]); } else { if (flag1 == 0) row.push_back(c2[i][j - m2[i].size() / 2]); else row.push_back(c4[i - m1.size() / 2][j - m2[i].size() / 2]); } } ans.push_back(row); } return ans; } else { std::vector<std::vector<int>> v; v = naive_multi(m1, m2); return v; } } std::vector<std::vector<int>> fast_multi(const std::vector<std::vector<int>>& m1, const std::vector<std::vector<int>>& m2) { std::vector<int> ranges, ranges_c, ind; std::vector<std::vector<int>> ans; for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size(); i++) { int a = 0; int b = 0; for (std::vector<std::vector<int>>::size_type j = 0; j < m1[i].size(); j++) { if (m1[j][i] != 0) a += 1; if (m2[i][j] != 0) b += 1; } ranges.push_back(a * b); ranges_c.push_back(a * b); } sort(ranges.begin(), ranges.end()); int comp, index; for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size(); i++) { int s = 0; for (std::vector<std::vector<int>>::size_type j = 0; j <= i; j++) s += ranges[j]; s += (m1.size() - i - 1) * m1.size() * m1.size(); if (i == 0) { comp = s; index = 1; } else if (s < comp) { comp = s; index = i + 1; } } for (int g = 0; g < index; g++) { for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size(); i++) if (ranges_c[i] == ranges[g]) { ind.push_back(i); break; } } for (std::vector<vector<int>>::size_type i = 0; i < m1.size(); i++) { int flag; int flag_search = 0; for (std::vector<int>::size_type j = 0; j < ind.size(); j++) if (i == ind[j]) { flag_search = 1; break; } std::vector<std::vector<int>> row, col; for (std::vector<int>::size_type j = 0; j < ind.size(); j++) { std::vector<int> temp1, temp2; temp1.push_back(m1[j][i]); temp2.push_back(m2[i][j]); col.push_back(temp1); row.push_back(temp2); } if (i == 0) { if (flag_search == 1) ans = naive_multi(col, row); else { std::vector<std::vector<int>> row_c, col_c; row_c = converter(row); col_c = converter(col); ans = retriever(strassen(col_c, row_c), m1.size(), m1.size()); } } else { std::vector<std::vector<int>> v1, v2; if (flag_search == 1) v1 = naive_multi(col, row); else { std::vector<std::vector<int>> row_c, col_c; row_c = converter(row); col_c = converter(col); v1 = retriever(strassen(col_c, row_c), m1.size(), m1.size()); } ans = add(v1, ans); } } return ans; } int main() { std::vector<vector<int>> matrix1, matrix2, v1, v2, v3; int i1, j1; int i2, j2; std::cout << "enter the dimensions of matrix1\n"; std::cin >> i1 >> j1; std::cout << '\n'; std::cout << "enter the dimensions of matrix2\n"; std::cin >> i2 >> j2; std::cout << '\n'; int x, y; for (x = 0; x < i1; x++) { std::vector<int> row; for (y = 0; y < j1; y++) { int temp; std::cout << "enter the " << x + 1 << " , " << y + 1 << " element for matrix1 - "; std::cin >> temp; row.push_back(temp); } matrix1.push_back(row); } for (x = 0; x < i2; x++) { std::vector<int> row; for (y = 0; y < j2; y++) { int temp; std::cout << "enter the " << x + 1 << " , " << y + 1 << " element for matrix2 - "; std::cin >> temp; row.push_back(temp); } matrix2.push_back(row); } //print(matrix1); std::vector<std::vector<int>> m1, m2, m3, m4; m1 = converter(matrix1); m2 = converter(matrix2); //print(m1); //cout << "a\n"; //print(m2); //cout <<"a\n"; /* * m3 = generator(1024, 1024); * m4 = generator(1024, 1024); */ auto start = std::chrono::high_resolution_clock::now(); v1 = retriever(naive_multi(m1, m2), i1, j2); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(start - stop); std::cout << "tiime taken by function" << duration.count() << endl; //print(v1); auto start2 = std::chrono::high_resolution_clock::now(); v2 = retriever(strassen(m1, m2), i1, j2); auto stop2 = std::chrono::high_resolution_clock::now(); auto duration2 = std::chrono::duration_cast<microseconds>(start2 - stop2); std::cout << "tiime taken by function" << duration2.count() << endl; /* * auto start_3 = std::chrono::high_resolution_clock::now(); * v3 = retriever(fast_multi(m1, m2), i_1, j_2); * auto stop_3 = std::chrono::high_resolution_clock::now(); * auto duration_3 = std::chrono::duration_cast<microseconds>(start_3 - stop_3); * * * cout << "tiime taken by function" << duration_3.count() << endl; */ //print(v2); print(v1); return 0; }
14,156
C++
.cpp
422
24.222749
140
0.46854
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,411
inversion_count.cpp
OpenGenus_cosmos/code/divide_conquer/src/inversion_count/inversion_count.cpp
// divide conquer | inversion count | C++ // Part of Cosmos by OpenGenus Foundation #include <iostream> using namespace std; int mergesort(int arr[], int l, int r); int merge(int arr[], int l, int m, int r); int main() { int n, a[100], i; cout << "Enter nuber of elements : "; cin >> n; cout << "Enter the elements : "; for (i = 0; i < n; i++) cin >> a[i]; cout << "Number of inversion = " << mergesort(a, 0, n - 1); return 0; } //merge int merge(int arr[], int l, int m, int r) { int i, j, k, c[100], count = 0; i = 0; j = l; k = m; while (j <= m - 1 && k <= r) { if (arr[j] <= arr[k]) c[i++] = arr[j++]; else { c[i++] = arr[k++]; count += m - j; } } while (j <= m - 1) c[i++] = arr[j++]; while (k <= r) c[i++] = arr[k++]; i = 0; while (l <= r) arr[l++] = c[i++]; return count; } //mergesort int mergesort(int arr[], int l, int r) { int x = 0, y = 0, z = 0; int m = (l + r) / 2; if (l < r) { x += mergesort(arr, l, m); y += mergesort(arr, m + 1, r); z += merge(arr, l, m + 1, r); } return x + y + z; }
1,245
C++
.cpp
56
16.946429
63
0.443308
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,412
test_search.cpp
OpenGenus_cosmos/code/search/test/test_search.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #define CATCH_CONFIG_MAIN #include "../../../test/c++/catch.hpp" #include <list> #include <vector> #include <iterator> #include <algorithm> #include "../src/binary_search/binary_search.cpp" #include "../src/exponential_search/exponential_search.cpp" #include "../src/fibonacci_search/fibonacci_search.cpp" #include "../src/interpolation_search/interpolation_search.cpp" #include "../src/jump_search/jump_search.cpp" #include "../src/linear_search/linear_search.cpp" #include "../src/ternary_search/ternary_search.cpp" // #define InputIterator #define RandomAccessIterator #define SearchFunc binarySearch #ifdef InputIteratorContainer #define Container list #endif #ifdef RandomAccessIterator #define Container vector #endif using std::list; using std::vector; TEST_CASE("search algorithm") { // common interface int *(*psf)(int *, int *, const int &); Container<int>::iterator (*vsf)(Container<int>::iterator, Container<int>::iterator, const int &); // substitute our search algorithm vsf = SearchFunc; psf = SearchFunc; auto testWithRandomValue = [&](size_t size) { using std::rand; using std::sort; // size == 0: avoid division by 0 int boundaryOfPossibleValue = static_cast<int>(size + (size == 0)); // initial containers int *podPtr = new int[size]; auto podPtrEnd = podPtr + size; Container<int> container(size); // initial random values for containers for (size_t i = 0; i < size; ++i) { int randomValue = rand() % boundaryOfPossibleValue; podPtr[i] = randomValue; container[i] = randomValue; } sort(podPtr, podPtrEnd); sort(container.begin(), container.end()); // based standard search // if found then compare to value, else compare to pointer is end // range of random values is [0:boundOfPossibleValue] // +/-30 is test out of boundary for (int i = -30; i < boundaryOfPossibleValue + 30; ++i) if (std::binary_search(podPtr, podPtrEnd, i)) { CHECK(*psf(podPtr, podPtrEnd, i) == i); CHECK(*vsf(container.begin(), container.end(), i) == i); } else { CHECK(psf(podPtr, podPtrEnd, i) == podPtrEnd); CHECK(vsf(container.begin(), container.end(), i) == container.end()); } delete[] podPtr; }; SECTION("empty") { testWithRandomValue(0); } SECTION("1 elem") { for (int i = 0; i < 1000; ++i) testWithRandomValue(1); } SECTION("2 elems") { for (int i = 0; i < 1000; ++i) testWithRandomValue(2); } SECTION("3 elems") { for (int i = 0; i < 1000; ++i) testWithRandomValue(3); } SECTION("random size") { for (int i = 0; i < 1000; ++i) testWithRandomValue(50 + std::rand() % 100); } SECTION("large size") { testWithRandomValue(1e6 + std::rand() % 10000); } }
4,265
C++
.cpp
104
24
100
0.441226
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,413
ternary_search.cpp
OpenGenus_cosmos/code/search/src/ternary_search/ternary_search.cpp
/* * Part of Cosmos by OpenGenus Foundation * * Ternary Search Uses Divide And Conquer Technique * * ternary search synopsis * * namespace ternary_search_impl * { * template<typename _RandomAccessIter, * typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type, * typename _Less> * _RandomAccessIter * ternarySearchImpl(_RandomAccessIter first, * _RandomAccessIter last, * const _RandomAccessIter &notFoundSentinel, * const _ValueType &find, * _Less less); * } // ternary_search_impl * * template<typename _RandomAccessIter, * typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type, * typename _Less> * _RandomAccessIter * ternarySearch(_RandomAccessIter begin, _RandomAccessIter end, const _ValueType &find, _Less less); * * template<typename _RandomAccessIter, * typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type> * _RandomAccessIter * ternarySearch(_RandomAccessIter begin, _RandomAccessIter end, const _ValueType &find); */ #include <functional> namespace ternary_search_impl { template<typename _RandomAccessIter, typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type, typename _Less> _RandomAccessIter ternarySearchImpl(_RandomAccessIter first, _RandomAccessIter last, const _RandomAccessIter &notFoundSentinel, const _ValueType &find, _Less less) { if (first <= last) { auto dist = std::distance(first, last); auto leftMid = first + dist / 3, rightMid = last - dist / 3; auto lessThanLeftMid = less(find, *leftMid), greaterThanLeftMid = less(*leftMid, find), lessThanRightMid = less(find, *rightMid), greaterThanRightMid = less(*rightMid, find); if (lessThanLeftMid == greaterThanLeftMid) return leftMid; if (lessThanRightMid == greaterThanRightMid) return rightMid; if (lessThanLeftMid) return ternarySearchImpl(first, leftMid - 1, notFoundSentinel, find, less); else if (greaterThanRightMid) return ternarySearchImpl(rightMid + 1, last, notFoundSentinel, find, less); else return ternarySearchImpl(leftMid + 1, rightMid - 1, notFoundSentinel, find, less); } return notFoundSentinel; } } // ternary_search_impl template<typename _RandomAccessIter, typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type, typename _Less> _RandomAccessIter ternarySearch(_RandomAccessIter begin, _RandomAccessIter end, const _ValueType &find, _Less less) { if (begin < end) { auto res = ternary_search_impl::ternarySearchImpl(begin, end - 1, end, find, less); return res == end ? end : res; } return end; } template<typename _RandomAccessIter, typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type> _RandomAccessIter ternarySearch(_RandomAccessIter begin, _RandomAccessIter end, const _ValueType &find) { return ternarySearch(begin, end, find, std::less<_ValueType>()); }
3,381
C++
.cpp
85
33.717647
101
0.665652
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,415
interpolation_search.cpp
OpenGenus_cosmos/code/search/src/interpolation_search/interpolation_search.cpp
/* * Part of Cosmos by OpenGenus Foundation * * interpolation search synopsis * * warning: in order to follow the convention of STL, the interface is [begin, end) !!! * * // [begin, end) * template<typename _Random_Access_Iter, * typename _Type = typename std::iterator_traits<_Random_Access_Iter>::value_type, * typename _Compare> * _Random_Access_Iter * interpolationSearch(_Random_Access_Iter begin, * _Random_Access_Iter end, * _Type const &find, * _Compare compare); * * // [begin, end) * template<typename _Random_Access_Iter, * typename _Type = typename std::iterator_traits<_Random_Access_Iter>::value_type> * _Random_Access_Iter * interpolationSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Type const &find); */ #include <functional> // [begin, end) template<typename _Random_Access_Iter, typename _Type = typename std::iterator_traits<_Random_Access_Iter>::value_type, typename _Compare> _Random_Access_Iter interpolationSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Type const &find, _Compare compare) { auto notFound = end; if (begin != end) { --end; // TODO: replace '<=' with '!=' or else to be more useful, // (e.g., allow input iterator can be passed) while (begin <= end) { // Now we will enquire the position keeping in mind the uniform distribution in mind auto pos = begin; if (compare(*begin, *end)) { auto len = std::distance(begin, end) * (find - *begin) / (*end - *begin); std::advance(pos, len); } if (pos < begin || pos > end) break; else if (compare(*pos, find)) begin = ++pos; else if (compare(find, *pos)) end = --pos; else return pos; } } return notFound; } // [begin, end) template<typename _Random_Access_Iter, typename _Type = typename std::iterator_traits<_Random_Access_Iter>::value_type> _Random_Access_Iter interpolationSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Type const &find) { return interpolationSearch(begin, end, find, std::less<_Type>()); }
2,412
C++
.cpp
69
28.275362
96
0.586473
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,416
sentinellinearsearch.cpp
OpenGenus_cosmos/code/search/src/linear_search/sentinellinearsearch.cpp
/* * Part of Cosmos by OpenGenus Foundation */ /* * Author: Visakh S * Github: visakhsuku * Input: The number of elements in an array, The element to be searched, An integer array. * Output: if found returns "found" else "not found", using the sentinel linear search algorithm. */ #include <iostream> #include <vector> using namespace std; void sentinelLinearSearch(std::vector<int> v, int n, int x) { int last, i = 0; last = v[n - 1]; v[n - 1] = x; while (v[i] != x) i++; if (i < n - 1 || last == x) cout << "found"; else cout << "not found"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, x, input; std::vector<int> v; cin >> n >> x; for (int i = 0; i < n; ++i) { cin >> input; v.push_back(input); } sentinelLinearSearch(v, n, x); return 0; }
878
C++
.cpp
38
19.236842
97
0.587112
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,417
linear_search.cpp
OpenGenus_cosmos/code/search/src/linear_search/linear_search.cpp
/* * Part of Cosmos by OpenGenus Foundation * * linear search synopsis * * warning: in order to follow the convention of STL, the interface is [begin, end) !!! * * namespace linear_search_impl * { * template<typename _Input_Iter, * typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type, typename _Compare> * _Input_Iter * linearSearchImpl(_Input_Iter begin, * _Input_Iter end, * _Tp const &find, * _Compare comp, * std::input_iterator_tag); * } // linear_search_impl * * template<typename _Input_Iter, * typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type, typename _Compare> * _Input_Iter * linearSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find, _Compare comp); * * template<typename _Input_Iter, * typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type> * _Input_Iter * linearSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find); */ #include <functional> namespace linear_search_impl { template<typename _Input_Iter, typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type, typename _Compare> _Input_Iter linearSearchImpl(_Input_Iter begin, _Input_Iter end, _Tp const &find, _Compare comp, std::input_iterator_tag) { _Input_Iter current = begin; while (current != end) { if (comp(*current, find)) break; ++current; } return current; } } // linear_search_impl template<typename _Input_Iter, typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type, typename _Compare> _Input_Iter linearSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find, _Compare comp) { auto category = typename std::iterator_traits<_Input_Iter>::iterator_category(); return linear_search_impl::linearSearchImpl(begin, end, find, comp, category); } template<typename _Input_Iter, typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type> _Input_Iter linearSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find) { return linearSearch(begin, end, find, std::equal_to<_Tp>()); }
2,258
C++
.cpp
67
29.746269
101
0.651716
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,419
exponential_search.cpp
OpenGenus_cosmos/code/search/src/exponential_search/exponential_search.cpp
/* * Part of Cosmos by OpenGenus Foundation * * jump search synopsis * * warning: in order to follow the convention of STL, the interface is [begin, end) !!! * * namespace exponenial_search_impl * { * template<typename _Random_Access_Iter, typename _Comp, * typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, * typename _Difference = typename std::iterator_traits<_Random_Access_Iter>::difference_type> * std::pair<_Random_Access_Iter, bool> * binarySearchImpl(_Random_Access_Iter first, * _Random_Access_Iter last, * _Tp const &find, * _Comp comp, * std::random_access_iterator_tag); * * template<typename _Random_Access_Iter, * typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, * typename _Compare> * _Random_Access_Iter * exponentialSearchImpl(_Random_Access_Iter begin, * _Random_Access_Iter end, * _Tp const &find, * _Compare comp, * std::random_access_iterator_tag); * } // exponenial_search_impl * * template<typename _Random_Access_Iter, * typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, * typename _Compare> * _Random_Access_Iter * exponentialSearch(_Random_Access_Iter begin, * _Random_Access_Iter end, * _Tp const &find, * _Compare comp); * * template<typename _Random_Access_Iter, * typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type> * _Random_Access_Iter * exponentialSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find); */ #include <functional> namespace exponenial_search_impl { template<typename _Random_Access_Iter, typename _Comp, typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, typename _Difference = typename std::iterator_traits<_Random_Access_Iter>::difference_type> std::pair<_Random_Access_Iter, bool> binarySearchImpl(_Random_Access_Iter first, _Random_Access_Iter last, _Tp const &find, _Comp comp, std::random_access_iterator_tag) { while (first <= last) { auto mid = first + (last - first) / 2; if (comp(*mid, find)) first = mid + 1; else if (comp(find, *mid)) last = mid - 1; else return std::make_pair(mid, true); } return std::make_pair(last, false); } template<typename _Random_Access_Iter, typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, typename _Compare> _Random_Access_Iter exponentialSearchImpl(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find, _Compare comp, std::random_access_iterator_tag) { if (begin != end) { if (!comp(*begin, find)) return (!comp(find, *begin)) ? begin : end; auto blockBegin = begin; auto offset = 1; while (blockBegin < end && comp(*blockBegin, find)) { std::advance(blockBegin, offset); offset *= 2; } auto blockEnd = blockBegin < end ? blockBegin : end; std::advance(blockBegin, -1 * (offset / 2)); auto res = binarySearchImpl(blockBegin, blockEnd, find, comp, std::random_access_iterator_tag()); if (res.second) return res.first; } return end; } } // exponenial_search_impl template<typename _Random_Access_Iter, typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, typename _Compare> _Random_Access_Iter exponentialSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find, _Compare comp) { auto category = typename std::iterator_traits<_Random_Access_Iter>::iterator_category(); return exponenial_search_impl::exponentialSearchImpl(begin, end, find, comp, category); } template<typename _Random_Access_Iter, typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type> _Random_Access_Iter exponentialSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find) { return exponentialSearch(begin, end, find, std::less<_Tp>()); }
4,677
C++
.cpp
122
31.5
103
0.595862
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,420
binarysearchrecursion.cpp
OpenGenus_cosmos/code/search/src/binary_search/binarysearchrecursion.cpp
#include <iostream> using namespace std; int BinarySearch(int arr[], int start, int end, int item){ if(start > end) return -1; int mid = start + (end-start)/2; if (arr[mid] == item) return mid; else if(arr[mid] < item) BinarySearch(arr, mid+1, end, item); else BinarySearch(arr, start, mid-1, item); } int main(){ int arr[5] = {2,4,5,6,8}; int n = 5; int item = 6; int index = BinarySearch(arr, 0, n-1, item); if(index>=0) cout << "Element Found at index - " << index; else cout << "Element Not Found!!"; return 0; }
621
C++
.cpp
24
20.541667
58
0.567063
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,421
binary_search.cpp
OpenGenus_cosmos/code/search/src/binary_search/binary_search.cpp
/* * Part of Cosmos by OpenGenus Foundation * * binary search synopsis * * warning: in order to follow the convention of STL, the interface is [begin, end) !!! * * namespace binary_search_impl * { * struct binary_search_tag {}; * struct recursive_binary_search_tag :public binary_search_tag {}; * struct iterative_binary_search_tag :public binary_search_tag {}; * * // [first, last] * template<typename _Random_Access_Iter, typename _Comp, * typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, * typename _Difference * = typename std::iterator_traits<_Random_Access_Iter>::difference_type> * std::pair<_Random_Access_Iter, bool> * binarySearchImpl(_Random_Access_Iter first, * _Random_Access_Iter last, * _Tp const &find, * _Comp comp, * std::random_access_iterator_tag, * recursive_binary_search_tag); * * // [first, last] * template<typename _Random_Access_Iter, typename _Comp, * typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, * typename _Difference * = typename std::iterator_traits<_Random_Access_Iter>::difference_type> * std::pair<_Random_Access_Iter, bool> * binarySearchImpl(_Random_Access_Iter first, * _Random_Access_Iter last, * _Tp const &find, * _Comp comp, * std::random_access_iterator_tag, * iterative_binary_search_tag); * } // binary_search_impl * * // [begin, end) * template<typename _Random_Access_Iter, * typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, * typename iterator_category * = typename std::iterator_traits<_Random_Access_Iter>::iterator_category, * typename _Comp> * _Random_Access_Iter * binarySearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find, _Comp comp); * * // [begin, end) * template<typename _Random_Access_Iter, * typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type> * _Random_Access_Iter * binarySearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find); */ #include <functional> namespace binary_search_impl { struct binary_search_tag {}; struct recursive_binary_search_tag : public binary_search_tag {}; struct iterative_binary_search_tag : public binary_search_tag {}; // [first, last] template<typename _Random_Access_Iter, typename _Comp, typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, typename _Difference = typename std::iterator_traits<_Random_Access_Iter>::difference_type> std::pair<_Random_Access_Iter, bool> binarySearchImpl(_Random_Access_Iter first, _Random_Access_Iter last, _Tp const &find, _Comp comp, std::random_access_iterator_tag, recursive_binary_search_tag) { // verifying the base condition in order to proceed with the binary search if (first <= last) { // calculating the middle most term _Random_Access_Iter mid = first + (last - first) / 2; // checking whether the term to be searched lies in the first half or second half of the series if (comp(*mid, find)) return binarySearchImpl(mid + 1, last, find, comp, std::random_access_iterator_tag(), recursive_binary_search_tag()); else if (comp(find, *mid)) return binarySearchImpl(first, mid - 1, find, comp, std::random_access_iterator_tag(), iterative_binary_search_tag()); else return std::make_pair(mid, true); } return std::make_pair(last, false); } // [first, last] template<typename _Random_Access_Iter, typename _Comp, typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, typename _Difference = typename std::iterator_traits<_Random_Access_Iter>::difference_type> std::pair<_Random_Access_Iter, bool> binarySearchImpl(_Random_Access_Iter first, _Random_Access_Iter last, _Tp const &find, _Comp comp, std::random_access_iterator_tag, iterative_binary_search_tag) { while (first <= last) { _Random_Access_Iter mid = first + (last - first) / 2; if (comp(*mid, find)) first = mid + 1; else if (comp(find, *mid)) last = mid - 1; else return std::make_pair(mid, true); } return std::make_pair(last, false); } } // binary_search_impl // [begin, end) template<typename _Random_Access_Iter, typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, typename _Comp> _Random_Access_Iter binarySearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find, _Comp comp) { if (begin >= end) return end; auto category = typename std::iterator_traits<_Random_Access_Iter>::iterator_category(); auto tag = binary_search_impl::recursive_binary_search_tag(); auto res = binary_search_impl::binarySearchImpl(begin, end - 1, find, comp, category, tag); if (res.second) return res.first; else return end; } // [begin, end) template<typename _Random_Access_Iter, typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type> _Random_Access_Iter binarySearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find) { return binarySearch(begin, end, find, std::less<_Tp>()); }
6,088
C++
.cpp
150
33.26
108
0.598853
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,422
binary_search_2.cpp
OpenGenus_cosmos/code/search/src/binary_search/binary_search_2.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <vector> #include <cstdlib> #include <iostream> #include <algorithm> /* Utility functions */ void fill(std::vector<int> &v) { for (auto& elem : v) elem = rand() % 100; } void printArr(std::vector<int> &v) { for (const auto& elem : v) std::cout << elem << " "; std::cout << "\n"; } /* Binary search with fewer comparisons */ int binarySearch(std::vector<int> &v, int key) { int l = 0, r = v.size(); while (r - l > 1) { int m = l + (r - l) / 2; if (v[m] > key) r = m; else l = m; } return (v[l] == key) ? l : -1; } /* Driver program */ int main() { int size; std::cout << "Enter the array size:"; std::cin >> size; std::vector<int> v(size); fill(v); std::cout << "Array (sorted) : "; sort(v.begin(), v.end()); printArr(v); int key; std::cout << "Search for (input search key) : "; std::cin >> key; std::cout << "Found " << key << " at index " << binarySearch(v, key) << "\n"; }
1,087
C++
.cpp
47
18.787234
81
0.526777
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,423
jump_search.cpp
OpenGenus_cosmos/code/search/src/jump_search/jump_search.cpp
/* * Part of Cosmos by OpenGenus Foundation * * jump search synopsis * * warning: in order to follow the convention of STL, the interface is [begin, end) !!! * * namespace jump_search_impl * { * template<typename _Random_Access_Iter, * typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, * typename _Compare> * _Random_Access_Iter * jumpSearchImpl(_Random_Access_Iter begin, * _Random_Access_Iter end, * _Tp const &find, * _Compare comp, * std::random_access_iterator_tag); * } // jump_search_impl * * template<typename _Random_Access_Iter, * typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, * typename _Compare> * _Random_Access_Iter * jumpSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find, _Compare comp); * * template<typename _Random_Access_Iter, * typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type> * _Random_Access_Iter * jumpSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find); */ #include <functional> #include <cmath> namespace jump_search_impl { template<typename _Random_Access_Iter, typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, typename _Compare> _Random_Access_Iter jumpSearchImpl(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find, _Compare comp, std::random_access_iterator_tag) { if (begin != end) { auto dist = std::distance(begin, end); auto sqrtDist = static_cast<size_t>(std::sqrt(dist)); auto curr = begin; // 1. Finding the block where element is while (curr < end && comp(*curr, find)) std::advance(curr, sqrtDist); if (curr != begin) std::advance(curr, -sqrtDist); // 2. Doing a linear search for find in block while (curr < end && sqrtDist-- > 0 && comp(*curr, find)) std::advance(curr, 1); // 3. If element is found if (!comp(*curr, find) && !comp(find, *curr)) return curr; } return end; } } // jump_search_impl template<typename _Random_Access_Iter, typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type, typename _Compare> _Random_Access_Iter jumpSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find, _Compare comp) { auto category = typename std::iterator_traits<_Random_Access_Iter>::iterator_category(); return jump_search_impl::jumpSearchImpl(begin, end, find, comp, category); } template<typename _Random_Access_Iter, typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type> _Random_Access_Iter jumpSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find) { return jumpSearch(begin, end, find, std::less<_Tp>()); }
3,026
C++
.cpp
81
32.654321
98
0.646458
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,424
test_huffman.cpp
OpenGenus_cosmos/code/compression/test/lossless_compression/huffman/test_huffman.cpp
#include "../../../src/lossless_compression/huffman/huffman.cpp" #include <iostream> #include <fstream> #include <iterator> using namespace std; // test only for Huffman::base_type is 64bit class HuffmanTest { public: HuffmanTest() { if (sizeof(Huffman::base_type) != 8) cout << "the test require that Huffman::base_type based on 64bit\n"; testCalculateFrequency(); testImportDictionary(); testExportDictionary(); testSeperateHeaderAndCode(); testSeperateCode(); testStringToBinary(); testBinaryToHex(); testHexToBinary(); } void testCalculateFrequency() { Huffman huf; assert(huf.frequency_.empty() == true); huf.frequency_.clear(); huf.calculateFrequency("a"); assert(huf.frequency_.size() == 1 && huf.frequency_.find('a') != huf.frequency_.end() && huf.frequency_.find('a')->second == 1); huf.frequency_.clear(); huf.calculateFrequency("aba"); assert(huf.frequency_.size() == 2 && huf.frequency_.find('a') != huf.frequency_.end() && huf.frequency_.find('a')->second == 2 && huf.frequency_.find('b') != huf.frequency_.end() && huf.frequency_.find('b')->second == 1 && huf.frequency_.find('c') == huf.frequency_.end()); } void testImportDictionary() { Huffman huf; std::string parameter{}; assert(huf.reverse_dictionary_.empty() == true); parameter.clear(); huf.reverse_dictionary_.clear(); parameter = ""; huf.importDictionary(parameter); assert(huf.reverse_dictionary_.empty() == true); parameter.clear(); huf.reverse_dictionary_.clear(); parameter.append("c"); parameter += huf.DELIMITER; parameter.append("123"); parameter += huf.DELIMITER; huf.importDictionary(parameter); assert(huf.reverse_dictionary_.size() == 1 && huf.reverse_dictionary_.find("123")->second == 'c'); } void testExportDictionary() { Huffman huf; std::string res{}; assert(huf.dictionary_.empty() == true); huf.dictionary_.insert(std::make_pair('c', "123")); assert(huf.dictionary_.size() == 1 && huf.dictionary_.find('c')->second == "123"); } void testSeperateHeaderAndCode() { Huffman huf; std::pair<std::string, std::string> res; res = huf.seperateHeaderAndCode(huf.addSeperateCode("")); assert(res.first == "" && res.second == ""); res = huf.seperateHeaderAndCode(huf.addSeperateCode("123")); assert(res.first == "123" && res.second == ""); res = huf.seperateHeaderAndCode(huf.addSeperateCode("123").append("456")); assert(res.first == "123" && res.second == "456"); } void testSeperateCode() { Huffman huf; std::string res; res = huf.removeSeperateCode(huf.addSeperateCode("")); assert(res == ""); res = huf.removeSeperateCode(huf.addSeperateCode(huf.addSeperateCode(""))); assert(res == huf.addSeperateCode("")); res = huf.removeSeperateCode(huf.addSeperateCode("123")); assert(res == "123"); res = huf.removeSeperateCode( \ huf.addSeperateCode(huf.removeSeperateCode(huf.addSeperateCode("456")))); assert(res == "456"); } void testStringToBinary() { Huffman huf; std::string res; huf.dictionary_.insert(std::make_pair('a', "0")); huf.dictionary_.insert(std::make_pair('b', "10")); huf.dictionary_.insert(std::make_pair('c', "11")); res = huf.stringToBinary(""); assert(res == ""); res = huf.stringToBinary("a"); assert(res == "0"); res = huf.stringToBinary("ab"); assert(res == "010"); res = huf.stringToBinary("abc"); assert(res == "01011"); res = huf.stringToBinary("abca"); assert(res == "010110"); res = huf.stringToBinary("cbabc"); assert(res == "111001011"); } void testBinaryToHex() { Huffman huf; std::string res, expect; std::string delim{}, bin{}; bin = ""; huf.binary_bit_ = bin.size(); res = huf.binaryToHex(bin); expect = ""; while (expect.size() % (int)(huf.GUARANTEE_BIT / sqrt(huf.HEX_BIT))) expect.push_back('0'); assert(res == ""); bin = "1011"; huf.binary_bit_ = bin.size(); res = huf.binaryToHex(bin); expect = "b000000000000000 "; assert(res == expect); bin = "10111110"; huf.binary_bit_ = bin.size(); res = huf.binaryToHex(bin); expect = "be00000000000000 "; assert(res == expect); bin = "101111101001"; huf.binary_bit_ = bin.size(); res = huf.binaryToHex(bin); expect = "be90000000000000 "; assert(res == expect); bin = "1011111010010111"; huf.binary_bit_ = bin.size(); res = huf.binaryToHex(bin); expect = "be97000000000000 "; assert(res == expect); bin = "10111110100101111010011100101000"; huf.binary_bit_ = bin.size(); res = huf.binaryToHex(bin); expect = "be97a72800000000 "; assert(res == expect); bin = ("10111110100101111010011100101000111"); huf.binary_bit_ = bin.size(); res = huf.binaryToHex(bin); expect = "be97a728e0000000 "; assert(res == expect); bin = ("1011111010010111101001110010100011100100111010001011111110110101" \ "1011111010010111101001110010100011100100111010001011111110110101"); huf.binary_bit_ = bin.size(); res = huf.binaryToHex(bin); expect = "be97a728e4e8bfb5 be97a728e4e8bfb5 "; assert(res == expect); } void testHexToBinary() { Huffman huf; std::string hex, res; std::string delim{}; hex = ""; huf.binary_bit_ = hex.size() * 4; while (hex.size() % huf.GUARANTEE_BIT) hex.push_back('0'); res = huf.hexToBinary(hex); assert(res == ""); hex = "b00000000000000 "; huf.binary_bit_ = hex.size() * 4; res = huf.hexToBinary(hex); assert(res == "0000101100000000000000000000000000000000000000000000000000000000"); hex = "be97a728e4e8bfb5 be97a728e4e8bfb5 "; huf.binary_bit_ = hex.size() * 4; res = huf.hexToBinary(hex); assert(res == ("1011111010010111101001110010100011" \ "1001001110100010111111101101011011" \ "1110100101111010011100101000111001" \ "0011101000101111111011010110111110")); } }; int main() { HuffmanTest test; Huffman huf; if (huf.decompression(huf.compression(huf.decompression(huf.compression("")))) != "") cout << "error empty\n"; Huffman huf2; if (huf2.decompression(huf2.compression(huf2.decompression(huf2.compression(" ")))) != " ") cout << "error separate\n"; Huffman huf6; if (huf6.decompression(huf6.compression(huf6.decompression( huf6.compression("COMPRESSION_TESTCOMPRESSION_TEST")))) != "COMPRESSION_TESTCOMPRESSION_TEST") cout << "error binary6\n"; Huffman huf7; if (huf7.decompression(huf7.compression(huf7.decompression(huf7.compression(" ")))) != " ") cout << "error delimiter\n"; // Huffman huf8; // fstream in, out; // in.open("input.png"); // out.open("output.png", ios::out | ios::trunc); // if (in.fail() || out.fail()) // cout << "error find file\n"; // else // huf8.decompression(huf8.compression(in), out); // in.close(); // out.close(); return 0; }
7,993
C++
.cpp
215
28.483721
103
0.574053
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,427
space001.cpp
OpenGenus_cosmos/guides/coding_style/c++/uncrustify_tests/input/space001.cpp
#include <iostream> #include<vector> using namespace std; void bar(int,int,int) { // less space if(true) { vector<int> vec{1,2,3}; int i=(1+2)*3; } } void foo( ) { // more space if (true) { vector<int> vec{1 , 2 , 3}; int i = (1 + 2) * 3; bar (1 , 2 , 3); } while (true) for (int i = 0; i < 10; ++i) do cout << 123; while (true); int i = 1 ; switch (i) { case 1 : cout << 1 ; break ; default : break ; } }
696
C++
.cpp
36
11.222222
43
0.343988
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,428
test_sample.cpp
OpenGenus_cosmos/test/c++/test_sample.cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" // this function should be stored in code folder bool isEqual(int a, int b) { return a == b; } TEST_CASE("just sample", "[sample]") { REQUIRE(isEqual(1, 0) == false); }
225
C++
.cpp
9
23
48
0.682243
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,429
validate_ip.cc
OpenGenus_cosmos/code/networking/src/validate_ip/validate_ip.cc
#include <arpa/inet.h> bool Config::validateIpAddress(const string &ipAddress) { struct sockaddr_in sa; int result = inet_pton(AF_INET, ipAddress.c_str(), &(sa.sin_addr)); return result != 0; } // add drive / test code
232
C++
.cc
8
26.375
71
0.695067
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,430
dfa.hh
OpenGenus_cosmos/code/theory_of_computation/src/deterministic_finite_automaton/dfa.hh
#ifndef DFA_H #define DFA_H #endif #define MAX_TRANSITION 50 #define MAX_STATES 100 using namespace std; typedef struct { int (*condition)(char); int stateId; } dfaTransition; typedef struct { int id; bool actionable; int noOfTransitions; std::string actionName; dfaTransition transitions[MAX_TRANSITIONS]; int defaultToStateId; } dfaState; typedef struct { int startStateId; int currentStateId; int noOfStates; dfaState* states[MAX_STATES]; } dfa; dfa* dfa_createDFA(); void dfa_reset(dfa* dfa); //makes the dfa ready for consumption. i.e. sets the current state to start state. void dfa_makeNextTransition(dfa* dfa, char c); void dfa_addState(dfa* pDFA, dfaState* newState); dfaState* dfa_createState(int hasAction, char* actionName); void dfa_addTransition(dfa* dfa, int fromStateID, int(*condition)(char), int toStateID);
845
C++
.h
33
24.030303
108
0.790323
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,431
lgraph_struct.h
OpenGenus_cosmos/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_struct.h
/* * Part of Cosmos by OpenGenus Foundation. * Author : ABDOUS Kamel * Here we have the definition of a graph using adjacency-list representation. * NB : LG stands for "list graph". */ #ifndef GRAPH_STRUCT_H #define GRAPH_STRUCT_H #include <stdlib.h> typedef size_t Node_ID; /* * One directed edge. */ typedef struct OneEdge { Node_ID nodeID; // ID of enter node. struct OneEdge* next; } OneEdge; /* * Directed edges of a node. */ typedef struct { int degree; // Number of edges. OneEdge* l_edgesHead; } N_Edges; /* * Node of a graph with adjacency-list representation. */ typedef struct { Node_ID ID; // ID of the node. N_Edges edges; } LG_Node; /* * A Graph struct using adjacency-list representation. * Let G = (S, A). */ typedef struct { size_t n; // |S| LG_Node* nodes; // This will be allocated dynamicaly } L_Graph; /* ---------------------------GETTERS-----------------------------------------*/ size_t gLG_NbNodes(L_Graph* graph); LG_Node* gLG_NodesArray(L_Graph* graph); LG_Node* gLG_Node(L_Graph* graph, size_t ID); Node_ID gNode_ID(LG_Node* node); N_Edges* gNode_EdgesList(LG_Node* node); int gNode_degree(LG_Node* node); OneEdge* gNode_EdgesHead(LG_Node* node); int gEdge_DestNode(OneEdge* edge); OneEdge* gEdgesList_Next(OneEdge* edge); void Node_incDegree(LG_Node* node); /* ----------------------------SETTERS----------------------------------------*/ void sLG_NbNodes(L_Graph* graph, size_t n); void sLG_NodesArray(L_Graph* graph, LG_Node* nodes); void sNode_ID(LG_Node* node, Node_ID ID); void sNode_degree(LG_Node* node, int degree); void sNode_EdgesHead(LG_Node* node, OneEdge* head); void sEdge_DestNode(OneEdge* edge, int nodeID); void sEdgesList_Next(OneEdge* edge, OneEdge* next); /* -------------------------ALLOCATION FUNCTIONS------------------------------*/ /* * Creates a new graph with adjacency-list representation. * * @n Number of nodes. * @graph The struct that will hold the graph. * * @return 0 on success. * -1 when malloc error. */ int createLGraph(size_t n, L_Graph* graph); /* * Frees the given graph. * * @graph The graph to free. */ void freeLGraph(L_Graph* graph); /* * Allocate a new edge. * * @node_ID The dest node. * @return A pointer to the new edge on success. * NULL on failure. */ OneEdge* createEdge(Node_ID node_ID); /* * Inits edges list of a node. * * @edgesList A pointer to the node. * @head_ID The ID of the node that's going to be the head of the list. * Give a negative value to avoid head. * @return 0 on success, -1 on failure. */ int initEdgesList(LG_Node* node, int head_ID); /* * Frees the edges list of the given node. * * @node A pointer to the node. */ void freeEdgesList(LG_Node* node); /* --------------------------ADDING EDGES-------------------------------------*/ /* * Add a new directed edge to the graph, connecting src to dest. * * @graph The graph. * @src_ID ID of the source node. * @dest_ID ID of the dest node. * * @return 0 on success, -1 on failure. */ int LGraph_addDEdge(L_Graph* graph, Node_ID src_ID, Node_ID dest_ID); /* * Connect srcNode to dest_ID by a directed edge. * * @srcNode The source node. * @dest_ID ID of the dest node. * * @return 0 on success, -1 on failure. */ int Node_addDEdge(LG_Node* srcNode, Node_ID dest_ID); /* * Add a new undirected edge to the graph, connecting id1 & id2. * * @graph The graph. * @id1 ID of a node. * @id2 ID of a node. * * @return 0 on success, -1 on failure. */ int LGraph_addUEdge(L_Graph* graph, Node_ID id1, Node_ID id2); /* * Add an undirected edge between node1 & node2. * * @node1 a node. * @node2 a node. * @return 0 on success, -1 on failure. */ int Node_addUEdge(LG_Node* node1, LG_Node* node2); #endif // GRAPH_STRUCT
3,801
C++
.h
150
23.553333
80
0.651754
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,432
lgraph_stack.h
OpenGenus_cosmos/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_stack.h
/* * Part of Cosmos by OpenGenus Foundation. * Author : ABDOUS Kamel * Stack for pushing nodes ids. */ #ifndef LGRAPH_STACK_H #define LGRAPH_STACK_H #include "lgraph_struct.h" /* * A common stack definition. */ typedef struct { size_t n; Node_ID* nodes; int head; } LG_Stack; /* * Creates a stack of size n. * @n The size of the stack. * @stack A pointer to a stack struct. * @return 0 on success, -1 on malloc failure. */ int createLG_Stack(size_t n, LG_Stack* stack); /* * Frees the stack. * @stack A pointer to a stack struct. */ void freeLG_Stack(LG_Stack* stack); /* * @stack A pointer to a stack struct. * @return 1 if the stack is full, 0 otherwise. */ int LG_StackFull(LG_Stack* stack); /* * @stack A pointer to a stack struct. * @return 1 if the stack is empty, 0 otherwise. */ int LG_StackEmpty(LG_Stack* stack); /* * Pushes node on top of the stack. * Doesn't push if the stack is full. * @stack A pointer to a stack struct. * @node id of the node to push. */ void LG_StackPush(LG_Stack* stack, Node_ID node); /* * Pops the top of the stack. * Doesn't pop if the stack is empty. * @stack A pointer to a stack struct. * @return The id of the node of the top of the stack. * If the stack is empty, returns 0, but this shouldn't be an indicator, * since a node of id 0 can be of the top of the stack. Use LG_StackEmpty for checking. */ Node_ID LG_StackPop(LG_Stack* stack); /* * Peeks the top of the stack whitout poping it. * @stack A pointer to a stack struct. * @return Same as LG_StackPop. */ Node_ID LG_StackPeek(LG_Stack* stack); #endif // LGRAPH_STACK
1,645
C++
.h
69
21.942029
95
0.696737
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,433
mgraph_struct.h
OpenGenus_cosmos/code/graph_algorithms/src/data_structures/adjacency_matrix_c/mgraph_struct.h
/* * Part of Cosmos by OpenGenus Foundation. * Author : ABDOUS Kamel * Here we have the definition of a graph using adjacency-matrix representation. * NB : MG stands for "matrix graph". */ #ifndef MGRAPH_STRUCT_H #define MGRAPH_STRUCT_H #include <stdlib.h> /* Change this to change weighting type, if there is one */ typedef int EdgeType; /* Don't change this, use Node_ID instead of int to refer to nodes */ typedef int Node_ID; /* * A Graph struct using adjacency-matrix representation. * Let G = (S, A). */ typedef struct { int n; /* |S| */ EdgeType** matrix; /* This will be allocated dynamicaly */ } M_Graph; /* * Creates a new graph with matrix-list representation. * * @n Number of nodes. * @graph The struct that will hold the graph. * * @return 0 on success. * -1 when malloc error. */ int createMGraph(size_t n, M_Graph* graph); /* * Frees the given graph. * * @graph The graph to free. */ void freeMGraph(M_Graph* graph); /* * Sets M[i][j] to val. */ void MG_set(M_Graph* graph, Node_ID i, Node_ID j, EdgeType val); /* * Returns M[i][j]; */ EdgeType MG_get(M_Graph* graph, Node_ID i, Node_ID j); /* * Returns graph->n; */ size_t MG_size(M_Graph* graph); #endif // MGRAPH_STRUCT
1,239
C++
.h
56
20.375
80
0.69257
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,434
luvector.hpp
OpenGenus_cosmos/code/computational_geometry/src/sphere_tetrahedron_intersection/luvector.hpp
/* * N dimensional loop unrolled vector class. * * https://github.com/RedBlight/LoopUnrolledVector * * Refactored a little bit for "cosmos" repository. * */ #ifndef LU_VECTOR_INCLUDED #define LU_VECTOR_INCLUDED #include <sstream> #include <string> #include <complex> #include <vector> #include <iostream> namespace LUV { // LuVector.hpp template<std::size_t N, class T> class LuVector; template<class T> using LuVector2 = LuVector<2, T>; template<class T> using LuVector3 = LuVector<3, T>; using LuVector2f = LuVector<2, float>; using LuVector2d = LuVector<2, double>; using LuVector2c = LuVector<2, std::complex<double>>; using LuVector3f = LuVector<3, float>; using LuVector3d = LuVector<3, double>; using LuVector3c = LuVector<3, std::complex<double>>; // Added for cosmos const double pi = 3.14159265358979323846; // LuVector_Op.hpp template<std::size_t N> struct LoopIndex { }; template<class T, class S> struct OpCopy { inline void operator ()(T& lhs, const S& rhs) { lhs = rhs; } }; ////////////////////////////////////////////////////////////// template<class T, class S> struct OpAdd { inline void operator ()(T& lhs, const S& rhs) { lhs += rhs; } }; template<class T, class S> struct OpSub { inline void operator ()(T& lhs, const S& rhs) { lhs -= rhs; } }; template<class T, class S> struct OpMul { inline void operator ()(T& lhs, const S& rhs) { lhs *= rhs; } }; template<class T, class S> struct OpDiv { inline void operator ()(T& lhs, const S& rhs) { lhs /= rhs; } }; ////////////////////////////////////////////////////////////// template<class T, class S> struct OpAbs { inline void operator ()(T& lhs, const S& rhs) { lhs = std::abs(rhs); } }; template<class T, class S> struct OpArg { inline void operator ()(T& lhs, const S& rhs) { lhs = std::arg(rhs); } }; template<std::size_t N, class T, class S> struct OpMin { inline void operator ()(LuVector<N, T>& result, const LuVector<N, T>& lhs, const LuVector<N, S>& rhs, const std::size_t& I) { result[I] = lhs[I] < rhs[I] ? lhs[I] : rhs[I]; } }; template<std::size_t N, class T, class S> struct OpMax { inline void operator ()(LuVector<N, T>& result, const LuVector<N, T>& lhs, const LuVector<N, S>& rhs, const std::size_t& I) { result[I] = lhs[I] > rhs[I] ? lhs[I] : rhs[I]; } }; template<std::size_t N, class T, class S> struct OpDot { inline void operator ()(T& result, const LuVector<N, T>& lhs, const LuVector<N, S>& rhs, const std::size_t& I) { result += lhs[I] * rhs[I]; } }; ////////////////////////////////////////////////////////////// template<class T> struct OpOstream { inline void operator ()(std::ostream& lhs, const T& rhs, const std::string& delimiter) { lhs << rhs << delimiter; } }; // LuVector_Unroll.hpp // VECTOR OP SCALAR template<std::size_t I, std::size_t N, class T, class S, template<class, class> class OP> inline void Unroll(LuVector<N, T>& lhs, const S& rhs, OP<T, S> operation, LoopIndex<I>) { Unroll(lhs, rhs, operation, LoopIndex<I-1>()); operation(lhs[I], rhs); } template<std::size_t N, class T, class S, template<class, class> class OP> inline void Unroll(LuVector<N, T>& lhs, const S& rhs, OP<T, S> operation, LoopIndex<0>) { operation(lhs[0], rhs); } // SCALAR OP VECTOR template<std::size_t I, std::size_t N, class T, class S, template<class, class> class OP> inline void Unroll(S& lhs, const LuVector<N, T>& rhs, OP<T, S> operation, LoopIndex<I>) { Unroll(lhs, rhs, operation, LoopIndex<I-1>()); operation(lhs, rhs[I]); } template<std::size_t N, class T, class S, template<class, class> class OP> inline void Unroll(S& lhs, const LuVector<N, T>& rhs, OP<T, S> operation, LoopIndex<0>) { operation(lhs, rhs[0]); } // VECTOR OP VECTOR template<std::size_t I, std::size_t N, class T, class S, template<class, class> class OP> inline void Unroll(LuVector<N, T>& lhs, const LuVector<N, S>& rhs, OP<T, S> operation, LoopIndex<I>) { Unroll(lhs, rhs, operation, LoopIndex<I-1>()); operation(lhs[I], rhs[I]); } template<std::size_t N, class T, class S, template<class, class> class OP> inline void Unroll(LuVector<N, T>& lhs, const LuVector<N, S>& rhs, OP<T, S> operation, LoopIndex<0>) { operation(lhs[0], rhs[0]); } // SCALAR = VECTOR OP VECTOR (could be cross-element) template<std::size_t I, std::size_t N, class T, class S, template<std::size_t, class, class> class OP> inline void Unroll(T& result, const LuVector<N, T>& lhs, const LuVector<N, S>& rhs, OP<N, T, S> operation, LoopIndex<I>) { Unroll(result, lhs, rhs, operation, LoopIndex<I-1>()); operation(result, lhs, rhs, I); } template<std::size_t N, class T, class S, template<std::size_t, class, class> class OP> inline void Unroll(T& result, const LuVector<N, T>& lhs, const LuVector<N, S>& rhs, OP<N, T, S> operation, LoopIndex<0>) { operation(result, lhs, rhs, 0); } // VECTOR = VECTOR OP VECTOR (could be cross-element) template<std::size_t I, std::size_t N, class T, class S, template<std::size_t, class, class> class OP> inline void Unroll(LuVector<N, T>& result, const LuVector<N, T>& lhs, const LuVector<N, S>& rhs, OP<N, T, S> operation, LoopIndex<I>) { Unroll(result, lhs, rhs, operation, LoopIndex<I-1>()); operation(result, lhs, rhs, I); } template<std::size_t N, class T, class S, template<std::size_t, class, class> class OP> inline void Unroll(LuVector<N, T>& result, const LuVector<N, T>& lhs, const LuVector<N, S>& rhs, OP<N, T, S> operation, LoopIndex<0>) { operation(result, lhs, rhs, 0); } // OSTREAM OP VECTOR template<std::size_t I, std::size_t N, class T, template<class> class OP> inline void Unroll(std::ostream& lhs, const LuVector<N, T>& rhs, const std::string& delimiter, OP<T> operation, LoopIndex<I>) { Unroll(lhs, rhs, delimiter, operation, LoopIndex<I-1>()); operation(lhs, rhs[I], delimiter); } template<std::size_t N, class T, template<class> class OP> inline void Unroll(std::ostream& lhs, const LuVector<N, T>& rhs, const std::string& delimiter, OP<T> operation, LoopIndex<0>) { operation(lhs, rhs[0], delimiter); } // LuVector_Body.hpp template<std::size_t N, class T> class LuVector { public: LuVector() = default; ~LuVector() = default; template<class... S> LuVector(const S&... elem) : _{ static_cast<T>(elem) ...} { } LuVector(const LuVector<N, const T>& other) : _{ other._ } { } template<class S> LuVector(const LuVector<N, S>& other) { Unroll(*this, other, OpCopy<T, S>(), LoopIndex<N-1>()); } template<class S> LuVector(const S& scalar) { Unroll(*this, scalar, OpCopy<T, S>(), LoopIndex<N-1>()); } template<class S> inline LuVector<N, T>& operator =(const LuVector<N, S>& other) { Unroll(*this, other, OpCopy<T, S>(), LoopIndex<N-1>()); return *this; } inline const T& operator [](const std::size_t& idx) const { return _[idx]; } inline T& operator [](const std::size_t& idx) { return _[idx]; } inline std::string ToString() const { std::stringstream ss; ss << "("; Unroll(ss, *this, ",", OpOstream<T>(), LoopIndex<N-2>()); ss << _[N-1] << ")"; return std::string(ss.str()); } private: T _[N]; }; // LuVector_Overload.hpp // OSTREAM << VECTOR template<std::size_t N, class T> std::ostream& operator <<(std::ostream& lhs, const LuVector<N, T>& rhs) { lhs << "("; Unroll(lhs, rhs, ",", OpOstream<T>(), LoopIndex<N-2>()); lhs << rhs[N-1] << ")"; return lhs; } // VECTOR += SCALAR template<std::size_t N, class T, class S> inline LuVector<N, T>& operator +=(LuVector<N, T>& lhs, const S& rhs) { Unroll(lhs, rhs, OpAdd<T, S>(), LoopIndex<N-1>()); return lhs; } // VECTOR -= SCALAR template<std::size_t N, class T, class S> inline LuVector<N, T>& operator -=(LuVector<N, T>& lhs, const S& rhs) { Unroll(lhs, rhs, OpSub<T, S>(), LoopIndex<N-1>()); return lhs; } // VECTOR *= SCALAR template<std::size_t N, class T, class S> inline LuVector<N, T>& operator *=(LuVector<N, T>& lhs, const S& rhs) { Unroll(lhs, rhs, OpMul<T, S>(), LoopIndex<N-1>()); return lhs; } // VECTOR /= SCALAR template<std::size_t N, class T, class S> inline LuVector<N, T>& operator /=(LuVector<N, T>& lhs, const S& rhs) { Unroll(lhs, rhs, OpDiv<T, S>(), LoopIndex<N-1>()); return lhs; } ////////////////////////////////////////////////////////////// // VECTOR += VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T>& operator +=(LuVector<N, T>& lhs, const LuVector<N, S>& rhs) { Unroll(lhs, rhs, OpAdd<T, S>(), LoopIndex<N-1>()); return lhs; } // VECTOR -= VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T>& operator -=(LuVector<N, T>& lhs, const LuVector<N, S>& rhs) { Unroll(lhs, rhs, OpSub<T, S>(), LoopIndex<N-1>()); return lhs; } // VECTOR *= VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T>& operator *=(LuVector<N, T>& lhs, const LuVector<N, S>& rhs) { Unroll(lhs, rhs, OpMul<T, S>(), LoopIndex<N-1>()); return lhs; } // VECTOR /= VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T>& operator /=(LuVector<N, T>& lhs, const LuVector<N, S>& rhs) { Unroll(lhs, rhs, OpDiv<T, S>(), LoopIndex<N-1>()); return lhs; } ////////////////////////////////////////////////////////////// // VECTOR + SCALAR template<std::size_t N, class T, class S> inline LuVector<N, T> operator +(const LuVector<N, T>& lhs, const S& rhs) { LuVector<N, T> result(lhs); return result += rhs; } // SCALAR + VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T> operator +(const T& lhs, const LuVector<N, S>& rhs) { LuVector<N, T> result(lhs); return result += rhs; } // VECTOR - SCALAR template<std::size_t N, class T, class S> inline LuVector<N, T> operator -(const LuVector<N, T>& lhs, const S& rhs) { LuVector<N, T> result(lhs); return result -= rhs; } // SCALAR - VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T> operator -(const T& lhs, const LuVector<N, S>& rhs) { LuVector<N, T> result(lhs); return result -= rhs; } // VECTOR * SCALAR template<std::size_t N, class T, class S> inline LuVector<N, T> operator *(const LuVector<N, T>& lhs, const S& rhs) { LuVector<N, T> result(lhs); return result *= rhs; } // SCALAR * VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T> operator *(const T& lhs, const LuVector<N, S>& rhs) { LuVector<N, T> result(lhs); return result *= rhs; } // VECTOR / SCALAR template<std::size_t N, class T, class S> inline LuVector<N, T> operator /(const LuVector<N, T>& lhs, const S& rhs) { LuVector<N, T> result(lhs); return result /= rhs; } // SCALAR / VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T> operator /(const T& lhs, const LuVector<N, S>& rhs) { LuVector<N, T> result(lhs); return result /= rhs; } ////////////////////////////////////////////////////////////// // VECTOR + VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T> operator +(const LuVector<N, T>& lhs, const LuVector<N, S>& rhs) { LuVector<N, T> result(lhs); return result += rhs; } // VECTOR - VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T> operator -(const LuVector<N, T>& lhs, const LuVector<N, S>& rhs) { LuVector<N, T> result(lhs); return result -= rhs; } // VECTOR * VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T> operator *(const LuVector<N, T>& lhs, const LuVector<N, S>& rhs) { LuVector<N, T> result(lhs); return result *= rhs; } // VECTOR / VECTOR template<std::size_t N, class T, class S> inline LuVector<N, T> operator /(const LuVector<N, T>& lhs, const LuVector<N, S>& rhs) { LuVector<N, T> result(lhs); return result /= rhs; } ////////////////////////////////////////////////////////////// // - VECTOR template<std::size_t N, class T> inline LuVector<N, T> operator -(const LuVector<N, T>& vec) { return T(0) - vec; } ////////////////////////////////////////////////////////////// // LuVector_Math.hpp template<std::size_t N, class T> inline T Sum(const LuVector<N, T>& vec) { T result = 0; Unroll(result, vec, OpAdd<T, T>(), LoopIndex<N-1>()); return result; } // Abs template<std::size_t N, class T> inline LuVector<N, T> Abs(const LuVector<N, T>& vec) { LuVector<N, T> absVec; Unroll(absVec, vec, OpAbs<T, T>(), LoopIndex<N-1>()); return absVec; } // Length template<std::size_t N, class T> inline T Length(const LuVector<N, T>& vec) { T result = 0; Unroll(result, vec, vec, OpDot<N, T, T>(), LoopIndex<N-1>()); return sqrt(result); } // Unit template<std::size_t N, class T> inline LuVector<N, T> Unit(const LuVector<N, T>& vec) { return vec / Length(vec); } ////////////////////////////////////////////////////////////// // Abs Complex template<std::size_t N, class T> inline LuVector<N, T> Abs(const LuVector<N, std::complex<T>>& vec) { LuVector<N, T> absVec; Unroll(absVec, vec, OpAbs<T, std::complex<T>>(), LoopIndex<N-1>()); return absVec; } // Arg Complex template<std::size_t N, class T> inline LuVector<N, T> Arg(const LuVector<N, std::complex<T>>& vec) { LuVector<N, T> argVec; Unroll(argVec, vec, OpArg<T, std::complex<T>>(), LoopIndex<N-1>()); return argVec; } // Length Complex template<std::size_t N, class T> inline T Length(const LuVector<N, std::complex<T>>& vec) { return Length(Abs(vec)); } // Unit Complex template<std::size_t N, class T> inline LuVector<N, std::complex<T>> Unit(const LuVector<N, std::complex<T>>& vec) { return vec / Length(vec); } ////////////////////////////////////////////////////////////// // Min template<std::size_t N, class T, class S> inline LuVector<N, T> Min(const LuVector<N, T>& lhs, const LuVector<N, S>& rhs) { LuVector<N, T> result; Unroll(result, lhs, rhs, OpMin<N, T, S>(), LoopIndex<N-1>()); return result; } // Max template<std::size_t N, class T, class S> inline LuVector<N, T> Max(const LuVector<N, T>& lhs, const LuVector<N, S>& rhs) { LuVector<N, T> result; Unroll(result, lhs, rhs, OpMax<N, T, S>(), LoopIndex<N-1>()); return result; } // Dot template<std::size_t N, class T, class S> inline T Dot(const LuVector<N, T>& lhs, const LuVector<N, S>& rhs) { T result = 0; Unroll(result, lhs, rhs, OpDot<N, T, S>(), LoopIndex<N-1>()); return result; } // Cross template<class T, class S> inline LuVector<3, T> Cross(const LuVector<3, T>& lhs, const LuVector<3, S>& rhs) { return LuVector<3, T>( lhs[1] * rhs[2] - lhs[2] * rhs[1], lhs[2] * rhs[0] - lhs[0] * rhs[2], lhs[0] * rhs[1] - lhs[1] * rhs[0] ); } ////////////////////////////////////////////////////////////// // Reflect template<std::size_t N, class T, class S> inline LuVector<N, T> Reflect(const LuVector<N, T>& vec, const LuVector<N, S>& normal) { return vec - normal * Dot(vec, normal) * 2; } // Rotate... ////////////////////////////////////////////////////////////// // CtsToSph template<class T> inline LuVector<3, T> CtsToSph(const LuVector<3, T>& cts) { T len = Length(cts); return LuVector<3, T>( len, cts[0] == 0 && cts[1] == 0 ? 0 : std::atan2(cts[1], cts[0]), std::acos(cts[2] / len) ); } // SphToCts template<class T> inline LuVector<3, T> SphToCts(const LuVector<3, T>& sph) { T planarVal = sph[0] * std::sin(sph[2]); return LuVector<3, T>( planarVal * std::cos(sph[1]), planarVal * std::sin(sph[1]), sph[0] * std::cos(sph[2]) ); } // CtsToPol template<class T> inline LuVector<2, T> CtsToPol(const LuVector<2, T>& cts) { T len = Length(cts); return LuVector<2, T>( len, cts[0] == 0 && cts[1] == 0 ? 0 : std::atan2(cts[1], cts[0]) ); } // PolToCts template<class T> inline LuVector<2, T> PolToCts(const LuVector<2, T>& pol) { return LuVector<2, T>( pol[0] * std::cos(pol[1]), pol[0] * std::sin(pol[1]) ); } ////////////////////////////////////////////////////////////// // OrthonormalSet N=3 // N: looking outside the sphere at given angles // U: up vector // R: right vector, parallel to XY plane // N = U X R template<class T> inline void OrthonormalSet(const T& angP, const T& angT, LuVector<3, T>& dirN, LuVector<3, T>& dirU, LuVector<3, T>& dirR) { T cp = std::cos(angP); T sp = std::sin(angP); T ct = std::cos(angT); T st = std::sin(angT); dirN[0] = st * cp; dirN[1] = st * sp; dirN[2] = ct; dirR[0] = sp; dirR[1] = -cp; dirR[2] = 0; dirU = Cross(dirR, dirN); } // OrthonormalSet N=2 template<class T> inline void OrthonormalSet(const T& ang, LuVector<2, T>& dirN, LuVector<2, T>& dirR) { T c = std::cos(ang); T s = std::sin(ang); dirN[0] = c; dirN[1] = s; dirR[0] = s; dirR[1] = -c; } // OrthogonalR N=3 template<class T> inline LuVector<3, T> OrthonormalR(const LuVector<3, T>& dirN) { T ang = dirN[0] == 0 && dirN[1] == 0 ? 0 : std::atan2(dirN[1], dirN[0]); T c = std::cos(ang); T s = std::sin(ang); return LuVector<3, T>(s, -c, 0); } // OrthogonalR N=2 template<class T> inline LuVector<2, T> OrthonormalR(const LuVector<2, T>& dirN) { return LuVector<2, T>(dirN[1], -dirN[0]); } // OrthogonalU N=3 template<class T> inline LuVector<3, T> OrthonormalU(const LuVector<3, T>& dirN) { return Cross(OrthogonalR(dirN), dirN); } // LuVector_Geometry.hpp // ProjLine N=3 template<class T> inline LuVector<3, T> ProjLine(const LuVector<3, T>& vec, const LuVector<3, T>&v1, const LuVector<3, T>& v2) { LuVector<3, T> v12 = Unit(v2 - v1); return v1 + Dot(v12, vec - v1) * v12; } // ProjLine N=2 template<class T> inline LuVector<2, T> ProjLine(const LuVector<2, T>& vec, const LuVector<2, T>&v1, const LuVector<2, T>& v2) { LuVector<2, T> v12 = Unit(v2 - v1); return v1 + Dot(v12, vec - v1) * v12; } // ProjLineL N=3 template<class T> inline LuVector<3, T> ProjLineL(const LuVector<3, T>& vec, const LuVector<3, T>&v1, const LuVector<3, T>& lineDir) { return v1 + Dot(lineDir, vec - v1) * lineDir; } // ProjLineL N=2 template<class T> inline LuVector<2, T> ProjLineL(const LuVector<2, T>& vec, const LuVector<2, T>&v1, const LuVector<2, T>& lineDir) { return v1 + Dot(lineDir, vec - v1) * lineDir; } // LineNormal N=3 template<class T> inline LuVector<3, T> LineNormal(const LuVector<3, T>& v1, const LuVector<3, T>& v2) { LuVector<3, T> v12 = Unit(v2 - v1); return OrthogonalR(v12); } // LineNormal N=2 template<class T> inline LuVector<2, T> LineNormal(const LuVector<2, T>& v1, const LuVector<2, T>& v2) { LuVector<2, T> v12 = Unit(v2 - v1); return OrthogonalR(v12); } // LineNormalL N=3 template<class T> inline LuVector<3, T> LineNormalL(const LuVector<3, T>& lineDir) { return OrthogonalR(lineDir); } // LineNormalL N=2 template<class T> inline LuVector<2, T> LineNormalL(const LuVector<2, T>& lineDir) { return OrthogonalR(lineDir); } // LineNormalP N=3 template<class T> inline LuVector<3, T> LineNormalP(const LuVector<3, T>& vec, const LuVector<3, T>& v1, const LuVector<3, T>& v2) { LuVector<3, T> v12 = Unit(v2 - v1); LuVector<3, T> ort = vec - ProjLineL(vec, v1, v12); T len = Length(ort); return len > 0 ? ort / len : LineNormalL(v12); } // LineNormalP N=2 template<class T> inline LuVector<2, T> LineNormalP(const LuVector<2, T>& vec, const LuVector<2, T>& v1, const LuVector<2, T>& v2) { LuVector<2, T> v12 = Unit(v2 - v1); LuVector<2, T> ort = vec - ProjLineL(vec, v1, v12); T len = Length(ort); return len > 0 ? ort / len : LineNormalL(v12); } // LineNormalPL N=3 template<class T> inline LuVector<3, T> LineNormalPL(const LuVector<3, T>& vec, const LuVector<3, T>& v1, const LuVector<3, T>& lineDir) { LuVector<3, T> ort = vec - ProjLineL(vec, v1, lineDir); T len = Length(ort); return len > 0 ? ort / len : LineNormalL(lineDir); } // LineNormalPL N=2 template<class T> inline LuVector<2, T> LineNormalPL(const LuVector<2, T>& vec, const LuVector<2, T>& v1, const LuVector<2, T>& lineDir) { LuVector<2, T> ort = vec - ProjLineL(vec, v1, lineDir); T len = Length(ort); return len > 0 ? ort / len : LineNormalL(lineDir); } ////////////////////////////////////////////////////////////// // ProjPlane template<class T> inline LuVector<3, T> ProjPlane(const LuVector<3, T>& vec, const LuVector<3, T>& v1, const LuVector<3, T>& n) { return vec - Dot(vec - v1, n) * n; } // PlaneNormal template<class T> inline LuVector<3, T> PlaneNormal(const LuVector<3, T>& v1, const LuVector<3, T>& v2, const LuVector<3, T>& v3) { return Unit(Cross(v2 - v1, v3 - v1)); } // PlaneNormalP template<class T> inline LuVector<3, T> PlaneNormalP( const LuVector<3, T>& vec, const LuVector<3, T>& v1, const LuVector<3, T>& v2, const LuVector<3, T>& v3) { LuVector<3, T> n = PlaneNormal(v1, v2, v3); return Dot(n, vec - v1) > 0 ? n : -n; } // PlaneNormalPN template<class T> inline LuVector<3, T> PlaneNormalPN( const LuVector<3, T>& vec, const LuVector<3, T>& v1, const LuVector<3, T>& n) { return Dot(n, vec - v1)> 0 ? n : -n; } }; #endif
24,342
C++
.h
723
26.874136
145
0.542818
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
10,436
types.h
OpenGenus_cosmos/code/string_algorithms/src/finite_automata/c/types.h
/* * Part of Cosmos by OpenGenus. * Author : ABDOUS Kamel */ #ifndef AUTOMATA_TYPES_H #define AUTOMATA_TYPES_H #include <stdbool.h> /* States are labelled by positive integers instead of strings */ typedef int state_id_t; /* A symbol is a single char */ typedef char symbol_t; typedef enum dfs_color_e { WHITE, BLACK } dfs_color_t; /* * State of a finite automaton. */ typedef struct state_s { state_id_t id; /* Indicates if this state is a final state */ bool is_final; } state_t; /* * A single link in a linked-list of state ids. */ typedef struct state_link_s { state_id_t state; struct state_link_s* next; } state_link_t; /* * Allocate a new state_link_t and return a pointer to it. */ state_link_t* alloc_state_link(state_id_t id); #endif // AUTOMATA_TYPES_H
801
C++
.h
38
19.105263
65
0.718667
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,437
dfa.h
OpenGenus_cosmos/code/string_algorithms/src/finite_automata/c/dfa.h
/* * Part of Cosmos by OpenGenus. * Author : ABDOUS Kamel */ #ifndef AUTOMATA_DFA_H #define AUTOMATA_DFA_H #include "types.h" /* * Definition of a DFA. */ typedef struct dfa_s { int alpha_size; state_t* states; int states_nb; state_id_t start_id; /* * This is a transition matrix. * -1 indicates that the transition isn't defined. */ state_id_t** transitions; } dfa_t; /* * Allocate necessary data structure for the given dfa. * States ID's are initialized. * Initialize all transitions to -1. * @return 0 on success, -1 on failure. */ int allocate_dfa(int states_nb, dfa_t* dfa); /* * Free data structures of given DFA. */ void free_dfa(dfa_t* dfa); /* * Remove not accessible and not co-accessible states of dfa. * @return -1 if the resulting automaton is empty, 0 otherwise. */ int remove_useless_states(dfa_t* dfa); /* * Make the dfa complete (all transitions are defined). */ void complete_dfa(dfa_t* dfa); /* * @return 1 if string is on the language of dfa. * 0 otherwise. */ int recognize_string(dfa_t* dfa, char* string); /* * Construct the complement of the given dfa. */ void complement_dfa(dfa_t* dfa); #endif // AUTOMATA_DFA_H
1,204
C++
.h
58
18.775862
63
0.704947
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,438
maxHeap.h
OpenGenus_cosmos/code/data_structures/src/maxHeap/maxHeap.h
#ifndef COSMOS_MAXHEAP_H #define COSMOS_MAXHEAP_H #include <iostream> class maxHeap { private : int* heap; int capacity; int currSize; void heapifyAdd(int idx); void heapifyRemove(int idx); public: maxHeap(int capacity); void insert(int itm); void remove(); void print(); }; #endif //COSMOS_MAXHEAP_H
346
C++
.h
17
16.705882
32
0.7
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,440
array_stack.h
OpenGenus_cosmos/code/data_structures/src/stack/abstract_stack/cpp/array_stack/array_stack.h
#ifndef ARRAYSTACH_H #define ARRAYSTACK_H #include <string> #include <sstream> #include "../istack.h" template<typename T> class ArrayStack : public IStack<T> { private: int capacity; int top; T **elements; void expandArray(); public: ArrayStack(int capacity = 10); ArrayStack(const ArrayStack& stack); ~ArrayStack(); ArrayStack& operator=(const ArrayStack& right); void push(const T& element); T pop(); T peek() const; bool isEmpty() const; std::string toString() const; }; template<typename T> void ArrayStack<T>::expandArray() { if (this->capacity <= this->top) { T ** temp = this->elements; this->capacity = this->capacity * 2; this->elements = new T*[this->capacity]; for (int i = 0; i < this->top; i++) { this->elements[i] = temp[i]; } for (int i = this->top; i < this->capacity; i++) { this->elements[i] = nullptr; } delete [] temp; temp = nullptr; } } template<typename T> ArrayStack<T>::ArrayStack(int capacity) { this->capacity = capacity; this->top = 0; this->elements = new T*[this->capacity]; for (int i = 0; i < this->capacity; i++) { this->elements[i] = nullptr; } } template<typename T> ArrayStack<T>::ArrayStack(const ArrayStack& stack) { this->top = stack.top; this->capacity = stack.capacity; if (stack.elements != nullptr) { this->elements = new T*[this->capacity]; for (int i = 0; i < this->top; i++) { this->elements[i] = new T(*stack.elements[i]); } for (int i = this->top; i < this->capacity; i++) { this->elements[i] = nullptr; } } } template<typename T> ArrayStack<T>::~ArrayStack() { for (int i = 0; i < this->top; i++) { delete this->elements[i]; } delete [] this->elements; } template<typename T> ArrayStack<T>& ArrayStack<T>::operator=(const ArrayStack& right) { if (this == &right) { throw "Self-assigning at operator= "; } this->top = right.top; this->capacity = right.capacity; for (int i = 0; i < this->top; i++) { delete this->elements[i]; } delete [] this->elements; if (right.elements != nullptr) { this->elements = new T*[this->capacity]; for (int i = 0; i < this->top; i++) { this->elements[i] = new T(*right.elements[i]); } for (int i = this->top; i < this->capacity; i++) { this->elements[i] = nullptr; } } return *this; } template<typename T> void ArrayStack<T>::push(const T& element) { this->expandArray(); this->elements[this->top] = new T(element); this->top++; } template<typename T> T ArrayStack<T>::pop() { if (this->isEmpty()) { throw "The stack is empty."; } T temp = *this->elements[this->top - 1]; delete this->elements[this->top - 1]; this->elements[this->top - 1] = nullptr; this->top--; return temp; } template<typename T> T ArrayStack<T>::peek() const { if (this->isEmpty()) { throw "The stack is empty."; } return *this->elements[this->top - 1]; } template<typename T> bool ArrayStack<T>::isEmpty() const { return this->elements[0] == nullptr; } template<typename T> std::string ArrayStack<T>::toString() const { std::stringstream stream; if (!this->isEmpty()) { stream << "The stack looks like; " << std::endl; for (int i = 0; i < this->top; i++) { stream << i << " : " << '[' << *this->elements[i] << ']' << std::endl; } } else { stream << "The stack is empty" << std::endl; } return stream.str(); } #endif
3,806
C++
.h
133
22.827068
82
0.564896
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,441
dlink.h
OpenGenus_cosmos/code/data_structures/src/list/doubly_linked_list/menu_interface/dlink.h
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #define MAX_LENGTH 20 void insert_beg(int num); void insert_end(int num); void insert_at_loc(int num, int loc); void insert_after_value(int num, int val); void delete_beg(); void delete_end(); void delete_node(int loc); void delete_value(int num); void replace_value(int num, int val); void replace_node(int num, int loc); void sortlist(); void delete_dup_vals(); int length(); void display(); void clear(void); typedef struct dlist { int info; struct dlist* next; struct dlist* prev; }dlist; dlist *start = NULL, *curr = NULL, *node = NULL, *pre = NULL; void insert_beg(int num) { node = (dlist*) malloc(sizeof(dlist*)); node->info = num; node->prev = NULL; if (start == NULL) { node->next = NULL; start = node; } else { node->next = start; start->prev = node; start = node; } } void insert_end(int num) { node = (dlist*) malloc(sizeof(dlist*)); node->info = num; node->next = NULL; if (start == NULL) { node->prev = NULL; start = node; } else { curr = start; while (curr->next != NULL) curr = curr->next; curr->next = node; node->prev = curr; } } void insert_at_loc(int num, int loc) { int n = length(); if (loc > n || loc < 0) { printf("Location is invalid!!\n"); return; } node = (dlist*) malloc(sizeof(dlist*)); node->info = num; if (start == NULL) { node->next = NULL; node->prev = NULL; start = node; } else { curr = start; int i = 1; while (curr != NULL && i < loc) { pre = curr; curr = curr->next; i++; } if (pre != NULL) pre->next = node; node->next = curr; node->prev = pre; if(curr != NULL) curr->prev = node; } } void insert_after_value(int num, int val) { node = (dlist*) malloc(sizeof(dlist*)); node->info = num; if (start == NULL) { node->next = NULL; node->prev = NULL; start = node; } else { curr = start; while (curr != NULL && curr->info != val) curr = curr->next; if (curr == NULL) { printf("Value not found!! Please enter again\n"); return; } node->next = curr->next; curr->next->prev = node; curr->next = node; node->prev = curr; } } void delete_beg() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; start = start->next; start->prev = NULL; free(curr); } void delete_end() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; while (curr->next != NULL) { pre = curr; curr = curr->next; } pre->next = NULL; free(curr); } void delete_node(int loc) { if (start == NULL) { printf("List is empty\n"); return; } int n = length(); if (loc > n || loc < 0) { printf("Location is invalid\n"); return; } curr = start; int i = 1; while (curr != NULL && i<loc) { pre = curr; curr = curr->next; i++; } pre->next = curr->next; curr->next->prev = pre; free(curr); } void delete_value(int num) { if (start == NULL) { printf("List is empty\n"); return; } curr = start; if (start->info == num) { start = start->next; start->prev = NULL; free(curr); } curr = start; while (curr != NULL && curr->info != num) { pre = curr; curr = curr->next; } if (curr == NULL) { printf("Value not found! Please try again\n"); return; } pre->next = curr->next; curr->next->prev = pre; free(curr); } void replace_value(int num,int val) { if (start == NULL) { printf("List is empty\n"); return; } curr = start; while (curr != NULL && curr->info != num) curr = curr->next; if (curr == NULL) { printf("Value not found! Please try again\n"); return; } curr->info = val; } void replace_node(int loc, int num) { if (start == NULL) { printf("List is empty\n"); return; } int n = length(); if (loc > n || loc < 0) { printf("Location is invalid!! Try again\n"); return; } curr = start; int i = 1; while (curr != NULL && i<loc) { curr = curr->next; i++; } curr->info = num; } void sortlist() { if (start == NULL) { printf("List is empty\n"); return; } for (curr=start; curr!= NULL; curr=curr->next) { for(pre=curr->next; pre!=NULL; pre=pre->next) { if ((curr->info > pre->info)) { int temp = curr->info; curr->info = pre->info; pre->info = temp; } } } } void delete_dup_vals() { if (start == NULL) { printf("List is empty\n"); return; } sortlist(); curr = start; while (curr->next != NULL) { if(curr->info == curr->next->info) { pre = curr->next->next; free(curr->next); curr->next = pre; pre->prev = curr; } else curr = curr->next; } } int length() { if (start == NULL) return 0; int i = 1; curr = start; while (curr != NULL) { curr = curr->next; i++; } return i; } void display() { if (start == NULL) { printf("The list is empty\n"); return; } curr = start; while (curr != NULL) { printf("%d\n", curr->info); curr = curr->next; } } void display_reverse() { if (start == NULL) { printf("The list is empty\n"); return; } curr = start; while (curr->next != NULL) curr = curr->next; while (curr != NULL) { printf("%d\n", curr->info); curr = curr->prev; } } void writefile(char *filename) { char path[MAX_LENGTH] = "./files/"; strcat(path,filename); FILE *fp; fp = fopen(path,"w"); curr = start; while (curr != NULL) { fprintf(fp,"%d\n", curr->info); curr = curr->next; } fclose(fp); } void readfile(char *filename) { start = NULL; char path[MAX_LENGTH] = "./files/"; strcat(path,filename); FILE *fp; int num; fp = fopen(path, "r"); while(!feof(fp)) { fscanf(fp, "%i\n", &num); insert_end(num); } fclose(fp); } void listfile() { DIR *d = opendir("./files/"); struct dirent *dir; if (d) { printf("Current list of files\n"); while ((dir = readdir(d)) != NULL) { if (strcmp(dir->d_name, "..") == 0 || strcmp(dir->d_name,".") == 0) continue; printf("%s\n", dir->d_name); } closedir(d); } }
5,979
C++
.h
392
12.989796
70
0.611733
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,442
doubly_linked_list.h
OpenGenus_cosmos/code/data_structures/src/list/doubly_linked_list/c/doubly_linked_list.h
#ifndef _D_L_LIST_H_ #define _D_L_LIST_H_ #include <stdint.h> #define SUCCESS 0 #define ERR_NO_LIST -1 #define ERR_EMPTY_LIST -2 #define ERR_MALLOC_FAIL -3 typedef struct node_s { int32_t id; int32_t data; struct node_s *next; struct node_s *prev; } node_t ; typedef struct dllist_s { int32_t len; int32_t tail_id; node_t *head; node_t *tail; } dllist_t; dllist_t * dl_create (); int8_t dl_destroy (dllist_t **l); int8_t dl_insert_beginning (dllist_t *l, int32_t value); int8_t dl_insert_end (dllist_t *l, int32_t value); int8_t dl_insert_after (dllist_t *l, int32_t key, int32_t value); int8_t dl_insert_before (dllist_t *l, int32_t key, int32_t value); int8_t dl_remove_beginning (dllist_t *l); int8_t dl_remove_end (dllist_t *l); int8_t dl_remove_next (dllist_t *l, int32_t key); int8_t dl_remove_prev (dllist_t *l, int32_t key); #endif
1,006
C++
.h
30
31.2
74
0.59814
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,444
link.h
OpenGenus_cosmos/code/data_structures/src/list/singly_linked_list/menu_interface/link.h
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #define MAX_LENGTH 20 typedef struct list { int info; struct list* next; }list; list *start=NULL, *node=NULL, *curr=NULL, *prev=NULL; void insert_beg(int); void insert_end(int); void insert_at_loc(int, int); void insert_after_value(int, int); void delete_beg(); void delete_end(); void delete_node(int); void delete_value(int); void replace_node(int, int); void replace_value(int, int); void delete_dup_vals(); int length(); void display(); void reverse(); void clear(void); void sortlist(); void writefile(char *filename); void readfile(); void insert_beg(int num) { node = (list*)malloc(sizeof(list*)); node->info = num; if (start == NULL) { node->next = NULL; start = node; } else { node->next = start; start = node; } } void insert_end(int num) { node = (list*)malloc(sizeof(list*)); node->info = num; node->next = NULL; if (start == NULL) start = node; else { curr = start; while (curr->next != NULL) curr=curr->next; curr->next=node; } } void insert_at_loc(int num, int loc) { int n = length(); if (loc > n || loc < 0) { printf("Location is invalid!! Try again\n"); return; } node = (list*)malloc(sizeof(list*)); node->info = num; node->next = NULL; if (start == NULL) start = node; else { curr = start; int i = 1; while (curr != NULL && i<loc) { prev = curr; curr = curr->next; i++; } node->next = curr; prev->next = node; } } void insert_after_value(int num, int val) { node = (list*)malloc(sizeof(list*)); node->info = num; if (start == NULL) start = node; else { curr = start; while(curr != NULL && curr->info != val) curr=curr->next; if (curr == NULL) { printf("Value was not found!! Try again\n"); return; } node->next = curr->next; curr->next = node; } } void delete_beg() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; start = start->next; free(curr); } void delete_end() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; while (curr->next != NULL) { prev = curr; curr = curr->next; } prev->next = NULL; free(curr); } void delete_node(int num) { int n = length(); if (num > n || num < 0) { printf("Location is invalid!! Try again\n"); return; } if (start == NULL) { printf("List is empty\n"); return; } curr = start; int i = 1; while (curr != NULL && i < num) { prev = curr; curr = curr->next; i++; } prev->next = curr->next; free(curr); } void delete_value(int num) { if (start == NULL) { printf("List is empty\n"); return; } curr = start; if (start->info == num) { start = start->next; free(curr); } curr = start; while (curr != NULL && curr->info != num) { prev = curr; curr = curr->next; } if (curr == NULL) { printf("Value not found! Try again\n"); return; } prev->next = curr->next; free(curr); } void replace_node(int num, int loc) { int n = length(); if (loc > n || loc < 0) { printf("Location is invalid!! Try again\n"); return; } if (start == NULL) { printf("List is empty\n"); return; } curr = start; int i = 1; while (curr != NULL && i < loc) { curr = curr->next; i++; } curr->info = num; } void replace_value(int num, int val) { if (start == NULL) { printf("List is empty\n"); return; } curr = start; while (curr != NULL && curr->info != val) curr = curr->next; if (curr == NULL) { printf("Value not found! Try again\n"); return; } curr->info = num; } void delete_dup_vals() { if (start == NULL) { printf("List is empty\n"); return; } sortlist(); curr = start; while (curr->next != NULL) { if (curr->info == curr->next->info) { prev = curr->next->next; free(curr->next); curr->next = prev; } else curr = curr->next; } } int length() { if (start == NULL) return (0); int i = 1; curr = start; while (curr != NULL) { curr = curr->next; i++; } return (i); } void display() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; while (curr!=NULL) { printf("%d\n", curr->info); curr = curr->next; } } void reverse() { if (start == NULL) { printf("List is empty\n"); return; } curr = start; prev = curr->next; curr->next = NULL; while (prev->next != NULL) { node = prev->next; prev->next = curr; curr = prev; prev = node; } prev->next = curr; start = prev; } void sortlist() { if (start == NULL) { printf("List is empty\n"); return; } for (curr=start; curr!= NULL; curr=curr->next) { for (prev=curr->next; prev!=NULL; prev=prev->next) { if ((curr->info > prev->info)) { int temp = curr->info; curr->info = prev->info; prev->info = temp; } } } } void writefile(char *filename) { char path[MAX_LENGTH] = "./files/"; strcat(path, filename); FILE *fp; fp = fopen(path, "w"); curr = start; while (curr != NULL) { fprintf(fp,"%d\n", curr->info); curr = curr->next; } fclose(fp); } void readfile(char *filename) { start = NULL; char path[MAX_LENGTH] = "./files/"; strcat(path, filename); FILE *fp; int num; fp = fopen(path, "r"); while (!feof(fp)) { fscanf(fp, "%i\n", &num); insert_end(num); } fclose(fp); } void listfile() { DIR *d = opendir("./files/"); struct dirent *dir; if (d) { printf("Current list of files\n"); while((dir = readdir(d)) != NULL) { if(strcmp(dir->d_name, "..") == 0 || strcmp(dir->d_name,".") == 0) continue; printf("%s\n", dir->d_name); } closedir(d); } }
5,592
C++
.h
370
12.905405
69
0.615325
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,445
btree.h
OpenGenus_cosmos/code/data_structures/src/tree/b_tree/b_tree/b_tree_c/btree.h
// Part of Cosmos by OpenGenus Foundation // Author : ABDOUS Kamel // Implementation of a disk-stored B-Tree #ifndef BTREE_H_INCLUDED #define BTREE_H_INCLUDED #include <stdio.h> #define MIN_DEGREE 2 #define MAX_N ((MIN_DEGREE * 2) - 1) /* Max nb of values stored in a node */ #define MAX_C (MIN_DEGREE * 2) /* Max nb of childs of a node */ #define MAX_S 20 /* Size of the stack */ typedef int TVal; /* This struct contains information about the disk-stored b-tree */ typedef struct { int root; /* Block num of the root */ int nbNodes; int nbVals; int height; /* In the file that contains the b-tree, there's a list of the blocks that are no longer used by the tree. This field contains the block num of the head of this list. If this list is not empty, we use a block of the list when we need a new block instead of allocating a new one. */ int freeBlocksHead; } FileHeader; typedef struct { TVal vals[MAX_N]; int childs[MAX_C]; int nb_n; // Nb values stored in the node } BNode; /* That a static stack */ typedef struct { int head; int adrs[MAX_S]; BNode nodes[MAX_S]; } BStack; /* That's the struct to use to manipulate a b-tree */ typedef struct { FILE* treeFile; FileHeader fileHeader; BStack stack; } BTree; /* * Binary search in a node. * Returns 1 in success and stores the position in i. * Otherwise returns 0 and i contains the position where the value is supposed to be. */ int bnode_search(TVal v, int* i, BNode* n); /* * Inserts v in n and keeps the values sorted. * rc is the right child of the value (-1 if it hasn't). */ void bnode_ins(TVal v, int rc, BNode* n); /* * Deletes v from the node n. */ void bnode_del(TVal v, BNode* n); void inordre(BTree* f, int i); /* * Returns 1 and the block that contains c in buff, and its num in i, and the position of c in j. * If the value doesn't exist, returns 0. */ int btree_find(BTree* bt, TVal c, int* i, int* j, BNode* buff); void btree_ins(BTree* bt, TVal c); // ------------------------------------------------------------------- // void initStack(BStack* stack); void pushStack(BStack* stack, int adr, BNode* n); void popStack(BStack* stack, int* adr, BNode* n); void getStackHead(BStack* stack, int* adr, BNode* n); /* * Function to call to open a disk-stored b-tree. * if mode = 'N' : it creates a new btree. * else (you can put 'O') : it reads the btree stored in fpath. */ BTree* OpenBTree(char* fpath, char mode); /* * Close the btree. * Writes the tree header in the file. */ void CloseBTree(BTree* f); void ReadBlock(BTree* f, BNode* buff, int i); void WriteBlock(BTree* f, BNode* buff, int i); /* * If the freeBlocks list isn't empty, takes the head of the list as a new block. * Else, it allocs a new block on the disk. */ int AllocBlock(BTree* f); /* * This function also adds the block to the freeBlocks list. */ void FreeBlock(BTree* f, BNode* buff, int i); int BTreeRoot(BTree* f); #endif // BTREE_H_INCLUDED
3,018
C++
.h
95
29.368421
97
0.680829
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,446
red_black_tree.h
OpenGenus_cosmos/code/data_structures/src/tree/multiway_tree/red_black_tree/red_black_tree.h
/** * author: JonNRb <jonbetti@gmail.com> * license: GPLv3 * file: @cosmos//code/data_structures/red_black_tree/red_black.h * info: red black tree */ #ifndef COSMOS_RED_BLACK_H_ #define COSMOS_RED_BLACK_H_ #include <stdint.h> /** * this macro subtracts off the offset of |member| within |type| from |ptr|, * allowing you to easily get a pointer to the containing struct of |ptr| * * ┌─────────────┬──────────┬──────┐ * |type| -> │ XXXXXXXXXXX │ |member| │ YYYY │ * └─────────────┴──────────┴──────┘ * ^ ^ * returns |ptr| */ #define container_of(ptr, type, member) \ ({ \ const typeof(((type*)0)->member)* __mptr = \ (const typeof(((type*)0)->member)*)(__mptr); \ (type*)((char*)ptr - __offsetof(type, member)); \ }) /** * node structure to be embedded in your data object. * * NOTE: it is expected that there will be a `uint64_t` immediately following * the embedded node (which will be used as a sorting key). */ typedef struct _cosmos_red_black_node cosmos_red_black_node_t; struct _cosmos_red_black_node { cosmos_red_black_node_t* link[2]; int red; uint64_t sort_key[0]; // place a `uint64_t` sort key immediately after this // struct in the data struct }; /** * represents a whole tree. should be initialized to NULL. */ typedef cosmos_red_black_node_t* cosmos_red_black_tree_t; /** * initializes a node to default values */ void cosmos_red_black_construct(cosmos_red_black_node_t* node); /** * takes a pointer to |tree| and |node| to insert. will update |tree| if * necessary. */ void cosmos_red_black_push(cosmos_red_black_tree_t* tree, cosmos_red_black_node_t* node); /** * takes a pointer to the |tree| and returns a pointer to the minimum node in * the tree, which is removed from |tree| */ cosmos_red_black_node_t* cosmos_red_black_pop_min( cosmos_red_black_tree_t* tree); #endif // COSMOS_RED_BLACK_H_
2,199
C++
.h
59
31.864407
78
0.60673
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,447
path_sum.hpp
OpenGenus_cosmos/code/data_structures/src/tree/binary_tree/binary_tree/path_sum/path_sum.hpp
/* Part of Cosmos by OpenGenus Foundation */ #ifndef path_sum_hpp #define path_sum_hpp #include <memory> #include <vector> #include <functional> #include "../node/node.cpp" template<typename _Ty, typename _Compare = std::equal_to<_Ty>, class _TreeNode = TreeNode<_Ty>> class PathSum { private: template<typename _T> using Node = _TreeNode; template<typename _T> using PNode = std::shared_ptr<Node<_T>>; using size_type = size_t; public: enum class PathType { Whole, Part }; PathSum(PathType py = PathType::Whole) :compare_(_Compare()), path_type_(py) {}; ~PathSum() = default; size_type countPathsOfSum(PNode<_Ty> root, _Ty sum); std::vector<std::vector<_Ty>> getPathsOfSum(PNode<_Ty> root, _Ty sum); private: _Compare compare_; PathType path_type_; void getPathsOfSumUp(PNode<_Ty> root, std::vector<_Ty> prev, _Ty prev_sum, _Ty const &sum, std::vector<std::vector<_Ty>> &res); }; #include "path_sum.cpp" #endif /* path_sum_hpp */
1,121
C++
.h
39
22.871795
95
0.61028
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,448
canny.h
OpenGenus_cosmos/code/artificial_intelligence/src/image_processing/canny/canny.h
// // canny.h // Canny Edge Detector // #ifndef _CANNY_ #define _CANNY_ #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <vector> class canny { private: cv::Mat img; //Original Image cv::Mat grayscaled; // Grayscale cv::Mat gFiltered; // Gradient cv::Mat sFiltered; //Sobel Filtered cv::Mat angles; //Angle Map cv::Mat non; // Non-maxima supp. cv::Mat thres; //Double threshold and final public: canny(std::string); //Constructor cv::Mat toGrayScale(); std::vector<std::vector<double> > createFilter(int, int, double); //Creates a gaussian filter cv::Mat useFilter(cv::Mat, std::vector<std::vector<double> >); //Use some filter cv::Mat sobel(); //Sobel filtering cv::Mat nonMaxSupp(); //Non-maxima supp. cv::Mat threshold(cv::Mat, int, int); //Double threshold and finalize picture }; #endif
885
C++
.h
28
28.714286
94
0.695652
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,450
queue.h
OpenGenus_cosmos/code/operating_system/src/scheduling/round_robin_scheduling/round_robin_c/queue.h
/* * Part of Cosmos by OpenGenus Foundation. * Basic queue. * Author : ABDOUS Kamel */ #ifndef QUEUE_H #define QUEUE_H #include <stdlib.h> typedef int QUEUE_VAL; typedef struct { QUEUE_VAL* vals; size_t n; int head, tail; } queue; int init_queue(queue* q, size_t n); void free_queue(queue* q); int queue_empty(queue* q); int queue_full(queue* q); int enqueue(queue* q, QUEUE_VAL val); QUEUE_VAL dequeue(queue* q); #endif // DEQUEUE
455
C++
.h
28
14.428571
42
0.731884
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,451
mythreads.h
OpenGenus_cosmos/code/operating_system/src/concurrency/peterson_algorithm_for_mutual_exclusion/peterson_algorithm_in_c/mythreads.h
// mythread.h (A wrapper header file with assert // statements) #ifndef __MYTHREADS_h__ #define __MYTHREADS_h__ #include <pthread.h> #include <assert.h> #include <sched.h> void Pthread_mutex_lock(pthread_mutex_t *m) { int rc = pthread_mutex_lock(m); assert(rc == 0); } void Pthread_mutex_unlock(pthread_mutex_t *m) { int rc = pthread_mutex_unlock(m); assert(rc == 0); } void Pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg) { int rc = pthread_create(thread, attr, start_routine, arg); assert(rc == 0); } void Pthread_join(pthread_t thread, void **value_ptr) { int rc = pthread_join(thread, value_ptr); assert(rc == 0); } #endif // __MYTHREADS_h__
751
C++
.h
29
23.206897
66
0.671788
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,452
monitors.h
OpenGenus_cosmos/code/operating_system/src/concurrency/monitors/monitors_system_v/monitors.h
/* * Part of Cosmos by OpenGenus Foundation. * Implementation of Hoare monitors using System V IPC. * Author : ABDOUS Kamel */ #ifndef MONITORS_H #define MONITORS_H #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/sem.h> #include <sys/stat.h> #include <fcntl.h> /* Type of shared memory identificator */ typedef int SHM_ID; /* Type of a semaphore identificator */ typedef int SEM_ID; /* Number of monitor management semaphores */ #define EXTRA_SEMS_NB 2 /* Monitor mutual exclusion semaphore */ #define MTOR_MUTEX 0 /* Monitor signal semaphore */ #define MTOR_SIG_SEM 1 typedef struct { SHM_ID sh_mem; SEM_ID sems_array; } monitor; /* * Create a brand new monitor, with [nb_conds] conditions and a shared memory * of size [shm_size]. * [ftok_path] is used for generating a system V key for both shared memory and semaphores. * [shm_proj] is passed to ftok for shared memory, and [sem_proj] for semaphores. * @return 0 on success, -1 on failure. */ int create_monitor(char* ftok_path, int shm_proj, int sem_proj, int nb_conds, size_t shm_size, monitor* mtor); /* * This function can be used to retrieve a monitor created by another process. * [ftok_path] is used for retrieving a system V key for both shared memory and semaphores. * [shm_proj] is passed to ftok for shared memory, and [sem_proj] for semaphores. * @return 0 on success, -1 on failure. */ int init_monitor(char* ftok_path, int shm_proj, int sem_proj, monitor* mtor); /* * Free allocated semaphores and shared memory for the given monitor. * @return 0 on success, -1 on failure. */ int free_monitor(monitor* mtor); /* * Ask to enter the monitor. * Only one process can be in the monitor. * @return 0 on success, -1 on failure. * Failure means that the demand failed, not that the process doesn't enter. */ int enter_monitor(monitor* mtor); /* * Ask to leave the monitor. * Note that while leaving a monitor, pending processes on signal take precedence * over processes that asked to enter the monitor. * @return 0 on success, -1 on failure. * Failure means that the demand failed, not that the process doesn't enter. */ int exit_monitor(monitor* mtor); /* * @return 1 if cond is empty (no process is waiting on it), * 0 if not empty, -1 on failure. */ int mtor_empty(monitor* mtor, int cond); /* * Cause the process to wait for [cond]. * Note that while leaving a monitor, pending processes on signal take precedence * over processes that asked to enter the monitor. * @return 0 on success, -1 on failure. */ int mtor_wait(monitor* mtor, int cond); /* * If no process is waiting for [cond], do nothing. * If any, wake it and block on signal semaphore. * @return 0 on success, -1 on failure. */ int mtor_signal(monitor* mtor, int cond); /* * Use this function to attach monitor shared memory. * @return Adress of the attached shared memory segment, NULL on failure. */ void* mtor_shmat(monitor* mtor); /* * Use this function to detach monitor shared memory. * @return 0 on success, -1 on failure. */ int mtor_shmdt(void* shm_ptr); #endif // MONITORS_H
3,191
C++
.h
105
28.409524
91
0.729677
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,454
main.cpp
tindy2013_subconverter/src/main.cpp
#include <iostream> #include <string> #include <unistd.h> #include <csignal> #include <sys/types.h> #include <dirent.h> #include "config/ruleset.h" #include "handler/interfaces.h" #include "handler/webget.h" #include "handler/settings.h" #include "script/cron.h" #include "server/socket.h" #include "server/webserver.h" #include "utils/defer.h" #include "utils/file_extra.h" #include "utils/logger.h" #include "utils/network.h" #include "utils/rapidjson_extra.h" #include "utils/system.h" #include "utils/urlencode.h" #include "version.h" //#include "vfs.h" WebServer webServer; #ifndef _WIN32 void SetConsoleTitle(const std::string &title) { system(std::string("echo \"\\033]0;" + title + R"(\007\c")").data()); } #endif // _WIN32 void setcd(std::string &file) { char szTemp[1024] = {}, filename[256] = {}; std::string path; #ifdef _WIN32 char *pname = NULL; DWORD retVal = GetFullPathName(file.data(), 1023, szTemp, &pname); if(!retVal) return; strcpy(filename, pname); strrchr(szTemp, '\\')[1] = '\0'; #else char *ret = realpath(file.data(), szTemp); if(ret == nullptr) return; ret = strcpy(filename, strrchr(szTemp, '/') + 1); if(ret == nullptr) return; strrchr(szTemp, '/')[1] = '\0'; #endif // _WIN32 file.assign(filename); path.assign(szTemp); chdir(path.data()); } void chkArg(int argc, char *argv[]) { for(int i = 1; i < argc; i++) { if(strcmp(argv[i], "-cfw") == 0) { global.CFWChildProcess = true; global.updateRulesetOnRequest = true; } else if(strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "--file") == 0) { if(i < argc - 1) global.prefPath.assign(argv[++i]); } else if(strcmp(argv[i], "-g") == 0 || strcmp(argv[i], "--gen") == 0) { global.generatorMode = true; } else if(strcmp(argv[i], "--artifact") == 0) { if(i < argc - 1) global.generateProfiles.assign(argv[++i]); } else if(strcmp(argv[i], "-l") == 0 || strcmp(argv[i], "--log") == 0) { if(i < argc - 1) if(freopen(argv[++i], "a", stderr) == nullptr) std::cerr<<"Error redirecting output to file.\n"; } } } void signal_handler(int sig) { //std::cerr<<"Interrupt signal "<<sig<<" received. Exiting gracefully...\n"; writeLog(0, "Interrupt signal " + std::to_string(sig) + " received. Exiting gracefully...", LOG_LEVEL_FATAL); switch(sig) { #ifndef _WIN32 case SIGHUP: case SIGQUIT: #endif // _WIN32 case SIGTERM: case SIGINT: webServer.stop_web_server(); break; } } void cron_tick_caller() { if(global.enableCron) cron_tick(); } int main(int argc, char *argv[]) { #ifndef _DEBUG std::string prgpath = argv[0]; setcd(prgpath); //first switch to program directory #endif // _DEBUG if(fileExist("pref.toml")) global.prefPath = "pref.toml"; else if(fileExist("pref.yml")) global.prefPath = "pref.yml"; else if(!fileExist("pref.ini")) { if(fileExist("pref.example.toml")) { fileCopy("pref.example.toml", "pref.toml"); global.prefPath = "pref.toml"; } else if(fileExist("pref.example.yml")) { fileCopy("pref.example.yml", "pref.yml"); global.prefPath = "pref.yml"; } else if(fileExist("pref.example.ini")) fileCopy("pref.example.ini", "pref.ini"); } chkArg(argc, argv); setcd(global.prefPath); //then switch to pref directory writeLog(0, "SubConverter " VERSION " starting up..", LOG_LEVEL_INFO); #ifdef _WIN32 WSADATA wsaData; if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) { //std::cerr<<"WSAStartup failed.\n"; writeLog(0, "WSAStartup failed.", LOG_LEVEL_FATAL); return 1; } UINT origcp = GetConsoleOutputCP(); defer(SetConsoleOutputCP(origcp);) SetConsoleOutputCP(65001); #else signal(SIGPIPE, SIG_IGN); signal(SIGABRT, SIG_IGN); signal(SIGHUP, signal_handler); signal(SIGQUIT, signal_handler); #endif // _WIN32 signal(SIGTERM, signal_handler); signal(SIGINT, signal_handler); SetConsoleTitle("SubConverter " VERSION); readConf(); //vfs::vfs_read("vfs.ini"); if(!global.updateRulesetOnRequest) refreshRulesets(global.customRulesets, global.rulesetsContent); std::string env_api_mode = getEnv("API_MODE"), env_managed_prefix = getEnv("MANAGED_PREFIX"), env_token = getEnv("API_TOKEN"); global.APIMode = tribool().parse(toLower(env_api_mode)).get(global.APIMode); if(!env_managed_prefix.empty()) global.managedConfigPrefix = env_managed_prefix; if(!env_token.empty()) global.accessToken = env_token; if(global.generatorMode) return simpleGenerator(); /* webServer.append_response("GET", "/", "text/plain", [](RESPONSE_CALLBACK_ARGS) -> std::string { return "subconverter " VERSION " backend\n"; }); */ webServer.append_response("GET", "/version", "text/plain", [](RESPONSE_CALLBACK_ARGS) -> std::string { return "subconverter " VERSION " backend\n"; }); webServer.append_response("GET", "/refreshrules", "text/plain", [](RESPONSE_CALLBACK_ARGS) -> std::string { if(!global.accessToken.empty()) { std::string token = getUrlArg(request.argument, "token"); if(token != global.accessToken) { response.status_code = 403; return "Forbidden\n"; } } refreshRulesets(global.customRulesets, global.rulesetsContent); return "done\n"; }); webServer.append_response("GET", "/readconf", "text/plain", [](RESPONSE_CALLBACK_ARGS) -> std::string { if(!global.accessToken.empty()) { std::string token = getUrlArg(request.argument, "token"); if(token != global.accessToken) { response.status_code = 403; return "Forbidden\n"; } } readConf(); if(!global.updateRulesetOnRequest) refreshRulesets(global.customRulesets, global.rulesetsContent); return "done\n"; }); webServer.append_response("POST", "/updateconf", "text/plain", [](RESPONSE_CALLBACK_ARGS) -> std::string { if(!global.accessToken.empty()) { std::string token = getUrlArg(request.argument, "token"); if(token != global.accessToken) { response.status_code = 403; return "Forbidden\n"; } } std::string type = getUrlArg(request.argument, "type"); if(type == "form" || type == "direct") { fileWrite(global.prefPath, request.postdata, true); } else { response.status_code = 501; return "Not Implemented\n"; } readConf(); if(!global.updateRulesetOnRequest) refreshRulesets(global.customRulesets, global.rulesetsContent); return "done\n"; }); webServer.append_response("GET", "/flushcache", "text/plain", [](RESPONSE_CALLBACK_ARGS) -> std::string { if(getUrlArg(request.argument, "token") != global.accessToken) { response.status_code = 403; return "Forbidden"; } flushCache(); return "done"; }); webServer.append_response("GET", "/sub", "text/plain;charset=utf-8", subconverter); webServer.append_response("HEAD", "/sub", "text/plain", subconverter); webServer.append_response("GET", "/sub2clashr", "text/plain;charset=utf-8", simpleToClashR); webServer.append_response("GET", "/surge2clash", "text/plain;charset=utf-8", surgeConfToClash); webServer.append_response("GET", "/getruleset", "text/plain;charset=utf-8", getRuleset); webServer.append_response("GET", "/getprofile", "text/plain;charset=utf-8", getProfile); webServer.append_response("GET", "/render", "text/plain;charset=utf-8", renderTemplate); if(!global.APIMode) { webServer.append_response("GET", "/get", "text/plain;charset=utf-8", [](RESPONSE_CALLBACK_ARGS) -> std::string { std::string url = urlDecode(getUrlArg(request.argument, "url")); return webGet(url, ""); }); webServer.append_response("GET", "/getlocal", "text/plain;charset=utf-8", [](RESPONSE_CALLBACK_ARGS) -> std::string { return fileGet(urlDecode(getUrlArg(request.argument, "path"))); }); } //webServer.append_response("POST", "/create-profile", "text/plain;charset=utf-8", createProfile); //webServer.append_response("GET", "/list-profiles", "text/plain;charset=utf-8", listProfiles); std::string env_port = getEnv("PORT"); if(!env_port.empty()) global.listenPort = to_int(env_port, global.listenPort); listener_args args = {global.listenAddress, global.listenPort, global.maxPendingConns, global.maxConcurThreads, cron_tick_caller, 200}; //std::cout<<"Serving HTTP @ http://"<<listen_address<<":"<<listen_port<<std::endl; writeLog(0, "Startup completed. Serving HTTP @ http://" + global.listenAddress + ":" + std::to_string(global.listenPort), LOG_LEVEL_INFO); webServer.start_web_server_multi(&args); #ifdef _WIN32 WSACleanup(); #endif // _WIN32 return 0; }
9,590
C++
.cpp
274
28.171533
142
0.605408
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,455
script.cpp
tindy2013_subconverter/src/script/script.cpp
#include <string> #include <iostream> #include <duktape.h> #include <duk_module_node.h> #include "utils/string.h" #include "utils/string_hash.h" #include "handler/webget.h" #include "handler/multithread.h" #include "utils/base64/base64.h" #include "utils/network.h" extern int gCacheConfig; extern std::string gProxyConfig; std::string parseProxy(const std::string &source); std::string foldPathString(const std::string &path) { std::string output = path; string_size pos_up, pos_slash, pos_unres = 0; do { pos_up = output.find("../", pos_unres); if(pos_up == output.npos) break; if(pos_up == 0) { pos_unres = pos_up + 3; continue; } pos_slash = output.rfind("/", pos_up - 1); if(pos_slash != output.npos) { pos_slash = output.rfind("/", pos_slash - 1); if(pos_slash != output.npos) output.erase(pos_slash + 1, pos_up - pos_slash + 2); else output.erase(0, pos_up + 3); } else pos_unres = pos_up + 3; } while(pos_up != output.npos); return output; } static int duktape_get_arguments_str(duk_context *ctx, duk_idx_t min_count, duk_idx_t max_count, ...) { duk_idx_t nargs = duk_get_top(ctx); if((min_count >= 0 && nargs < min_count) || (max_count >= 0 && nargs > max_count)) return 0; va_list vl; va_start(vl, max_count); for(duk_idx_t idx = 0; idx < nargs; idx++) { std::string *arg = va_arg(vl, std::string*); if(arg) *arg = duk_safe_to_string(ctx, idx); } va_end(vl); return 1; } duk_ret_t cb_resolve_module(duk_context *ctx) { const char *requested_id = duk_get_string(ctx, 0); const char *parent_id = duk_get_string(ctx, 1); /* calling module */ //const char *resolved_id; std::string resolved_id, parent_path = parent_id; if(!parent_path.empty()) { string_size pos = parent_path.rfind("/"); if(pos != parent_path.npos) resolved_id += parent_path.substr(0, pos + 1); } resolved_id += requested_id; if(!endsWith(resolved_id, ".js")) resolved_id += ".js"; resolved_id = foldPathString(resolved_id); /* Arrive at the canonical module ID somehow. */ if(!fileExist(resolved_id)) duk_push_undefined(ctx); else duk_push_string(ctx, resolved_id.c_str()); return 1; /*nrets*/ } duk_ret_t cb_load_module(duk_context *ctx) { const char *resolved_id = duk_get_string(ctx, 0); std::string module_source = fileGet(resolved_id, true); /* Arrive at the JS source code for the module somehow. */ duk_push_string(ctx, module_source.c_str()); return 1; /*nrets*/ } static duk_ret_t native_print(duk_context *ctx) { duk_push_string(ctx, " "); duk_insert(ctx, 0); duk_join(ctx, duk_get_top(ctx) - 1); printf("%s\n", duk_safe_to_string(ctx, -1)); return 0; } static duk_ret_t fetch(duk_context *ctx) { /* std::string filepath, proxy; duktape_get_arguments_str(ctx, 1, 2, &filepath, &proxy); std::string content = fetchFile(filepath, proxy, gCacheConfig); duk_push_lstring(ctx, content.c_str(), content.size()); */ std::string filepath, proxy, method, postdata, content; if(duktape_get_arguments_str(ctx, 1, 4, &filepath, &proxy, &method, &postdata) == 0) return 0; switch(hash_(method)) { case "POST"_hash: webPost(filepath, postdata, proxy, string_array{}, &content); break; default: content = fetchFile(filepath, proxy, gCacheConfig); break; } duk_push_lstring(ctx, content.c_str(), content.size()); return 1; } static duk_ret_t atob(duk_context *ctx) { std::string data = duk_safe_to_string(ctx, -1); duk_push_string(ctx, base64Encode(data).c_str()); return 1; } static duk_ret_t btoa(duk_context *ctx) { std::string data = duk_safe_to_string(ctx, -1); data = base64Decode(data, true); duk_push_lstring(ctx, data.c_str(), data.size()); return 1; } static duk_ret_t getGeoIP(duk_context *ctx) { std::string address, proxy; duktape_get_arguments_str(ctx, 1, 2, &address, &proxy); if(!isIPv4(address) && !isIPv6(address)) address = hostnameToIPAddr(address); if(address.empty()) duk_push_undefined(ctx); else duk_push_string(ctx, fetchFile("https://api.ip.sb/geoip/" + address, parseProxy(proxy), gCacheConfig).c_str()); return 1; } duk_context *duktape_init() { duk_context *ctx = duk_create_heap_default(); if(!ctx) return NULL; /// init module duk_push_object(ctx); duk_push_c_function(ctx, cb_resolve_module, DUK_VARARGS); duk_put_prop_string(ctx, -2, "resolve"); duk_push_c_function(ctx, cb_load_module, DUK_VARARGS); duk_put_prop_string(ctx, -2, "load"); duk_module_node_init(ctx); duk_push_c_function(ctx, native_print, DUK_VARARGS); duk_put_global_string(ctx, "print"); duk_push_c_function(ctx, fetch, DUK_VARARGS); duk_put_global_string(ctx, "fetch"); duk_push_c_function(ctx, atob, 1); duk_put_global_string(ctx, "atob"); duk_push_c_function(ctx, btoa, 1); duk_put_global_string(ctx, "btoa"); duk_push_c_function(ctx, getGeoIP, DUK_VARARGS); duk_put_global_string(ctx, "geoip"); return ctx; } int duktape_peval(duk_context *ctx, const std::string &script) { return duk_peval_string(ctx, script.c_str()); } int duktape_call_function(duk_context *ctx, const std::string &name, size_t nargs, ...) { duk_get_global_string(ctx, name.c_str()); va_list vl; va_start(vl, nargs); size_t index = 0; while(index < nargs) { std::string *arg = va_arg(vl, std::string*); if(arg != NULL) duk_push_string(ctx, arg->c_str()); else duk_push_undefined(ctx); index++; } va_end(vl); return duk_pcall(ctx, nargs); } int duktape_push_nodeinfo(duk_context *ctx, const nodeInfo &node) { duk_push_object(ctx); duk_push_string(ctx, node.group.c_str()); duk_put_prop_string(ctx, -2, "Group"); duk_push_int(ctx, node.groupID); duk_put_prop_string(ctx, -2, "GroupID"); duk_push_int(ctx, node.id); duk_put_prop_string(ctx, -2, "Index"); duk_push_string(ctx, node.remarks.c_str()); duk_put_prop_string(ctx, -2, "Remark"); duk_push_string(ctx, node.proxyStr.c_str()); duk_put_prop_string(ctx, -2, "ProxyInfo"); return 0; } int duktape_push_nodeinfo_arr(duk_context *ctx, const nodeInfo &node, duk_idx_t index) { duk_push_object(ctx); duk_push_string(ctx, "Group"); duk_push_string(ctx, node.group.c_str()); duk_def_prop(ctx, index - 2, DUK_DEFPROP_HAVE_VALUE); duk_push_string(ctx, "GroupID"); duk_push_int(ctx, node.groupID); duk_def_prop(ctx, index - 2, DUK_DEFPROP_HAVE_VALUE); duk_push_string(ctx, "Index"); duk_push_int(ctx, node.id); duk_def_prop(ctx, index - 2, DUK_DEFPROP_HAVE_VALUE); duk_push_string(ctx, "Remark"); duk_push_string(ctx, node.remarks.c_str()); duk_def_prop(ctx, index - 2, DUK_DEFPROP_HAVE_VALUE); duk_push_string(ctx, "ProxyInfo"); duk_push_string(ctx, node.proxyStr.c_str()); duk_def_prop(ctx, index - 2, DUK_DEFPROP_HAVE_VALUE); return 0; } int duktape_get_res_int(duk_context *ctx) { int retval = duk_to_int(ctx, -1); duk_pop(ctx); return retval; } std::string duktape_get_res_str(duk_context *ctx) { if(duk_is_null_or_undefined(ctx, -1)) return ""; std::string retstr = duk_safe_to_string(ctx, -1); duk_pop(ctx); return retstr; } bool duktape_get_res_bool(duk_context *ctx) { bool ret = duk_to_boolean(ctx, -1); duk_pop(ctx); return ret; } std::string duktape_get_err_stack(duk_context *ctx) { duk_get_prop_string(ctx, -1, "stack"); std::string stackstr = duk_get_string(ctx, -1); duk_pop(ctx); return stackstr; }
7,996
C++
.cpp
252
26.801587
119
0.627542
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,456
cron.cpp
tindy2013_subconverter/src/script/cron.cpp
#include <string> #include <iostream> #include <libcron/Cron.h> #include "config/crontask.h" #include "handler/interfaces.h" #include "handler/multithread.h" #include "handler/settings.h" #include "server/webserver.h" #include "utils/logger.h" #include "utils/rapidjson_extra.h" #include "utils/system.h" #include "script_quickjs.h" libcron::Cron cron; struct script_info { std::string name; time_t begin_time = 0; time_t timeout = 0; }; int timeout_checker(JSRuntime *rt, void *opaque) { script_info info = *static_cast<script_info*>(opaque); if(info.timeout != 0 && time(NULL) >= info.begin_time + info.timeout) /// timeout reached { writeLog(0, "Script '" + info.name + "' has exceeded timeout " + std::to_string(info.timeout) + ", terminate now.", LOG_LEVEL_WARNING); return 1; } return 0; } void refresh_schedule() { cron.clear_schedules(); for(const CronTaskConfig &x : global.cronTasks) { cron.add_schedule(x.Name, x.CronExp, [=](auto &) { qjs::Runtime runtime; qjs::Context context(runtime); try { script_runtime_init(runtime); script_context_init(context); defer(script_cleanup(context);) std::string proxy = parseProxy(global.proxyConfig); std::string script = fetchFile(x.Path, proxy, global.cacheConfig); if(script.empty()) { writeLog(0, "Script '" + x.Name + "' run failed: file is empty or not exist!", LOG_LEVEL_WARNING); return; } script_info info; if(x.Timeout > 0) { info.begin_time = time(NULL); info.timeout = x.Timeout; info.name = x.Name; JS_SetInterruptHandler(JS_GetRuntime(context.ctx), timeout_checker, &info); } context.eval(script); } catch (qjs::exception) { script_print_stack(context); } }); } } std::string list_cron_schedule(RESPONSE_CALLBACK_ARGS) { auto &argument = request.argument; std::string token = getUrlArg(argument, "token"); rapidjson::StringBuffer sb; rapidjson::Writer<rapidjson::StringBuffer> writer(sb); writer.StartObject(); if(token != global.accessToken) { response.status_code = 403; writer.Key("code"); writer.Int(403); writer.Key("data"); writer.String("Unauthorized"); writer.EndObject(); return sb.GetString(); } writer.Key("code"); writer.Int(200); writer.Key("tasks"); writer.StartArray(); for(const CronTaskConfig &x : global.cronTasks) { writer.StartObject(); writer.Key("name"); writer.String(x.Name.data()); writer.Key("cronexp"); writer.String(x.CronExp.data()); writer.Key("path"); writer.String(x.Path.data()); writer.EndObject(); } writer.EndArray(); writer.EndObject(); return sb.GetString(); } size_t cron_tick() { return cron.tick(); }
3,236
C++
.cpp
107
22.411215
143
0.576233
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,457
script_quickjs.cpp
tindy2013_subconverter/src/script/script_quickjs.cpp
#include <string> #include <map> #include <iostream> #include <quickjspp.hpp> #include <utility> #include <quickjs/quickjs-libc.h> #ifdef _WIN32 #include <windows.h> #endif // _WIN32 #include "handler/multithread.h" #include "handler/webget.h" #include "handler/settings.h" #include "parser/config/proxy.h" #include "utils/map_extra.h" #include "utils/system.h" #include "script_quickjs.h" std::string parseProxy(const std::string &source); static const std::string qjs_require_module {R"(import * as std from 'std' import * as os from 'os' let modules = {} let debug = console.log { let _debugOptions = std.getenv('DEBUG') if (typeof _debugOptions == 'undefined' || _debugOptions.split(',').indexOf('require') === -1) { debug = function () {} } } class CJSModule { constructor (id) { this.id = id this._failed = null this._loaded = false this.exports = {} } load () { const __file = this.id const __dir = _basename(this.id) const _require = require let ctx = { exports: {} } // Prevents modules from changing exports Object.seal(ctx) const _mark = '<<SCRIPT>>' let _loaderTemplate = `(function _loader (exports, require, module, __filename, __dirname) {${_mark}})(ctx.exports, _require, ctx, __file, __dir)` let _script = std.loadFile(__file) this._failed = _script === null if (this._failed) { return new Error(`Can't load script ${__file}`) } _script = _loaderTemplate.replace('<<SCRIPT>>', _script) eval(_script) this.exports = ctx.exports this._loaded = true return true } } function _basename (path) { let idx = path.lastIndexOf('/') if (idx === 0) return '/' return path.substring(0, idx) } function _statPath (path) { const [fstat, err] = os.stat(path) return { errno: err, isFile: fstat && (fstat.mode & os.S_IFREG) && true, isDir: fstat && (fstat.mode & os.S_IFDIR) && true } } function _loadModule (path) { debug(`_loadModule# Module ${path}`) const [id, err] = os.realpath(path) if (err) { throw new Error(`Module require error: Can't get real module path for ${path}`) return } debug(`_loadModule# id ${id}`) if (modules.hasOwnProperty(id)) { return modules[id] } let _module = new CJSModule(id) modules[id] = _module let _result = _module.load() if (_result !== true) { throw _result return } return _module } function _lookupModule (path) { let fstat = _statPath(path) debug(`_lookupModule# Looking for ${path}`) // Path found if (fstat.isFile) { debug(`_lookupModule# Found module file`) return path } // Path not found if (fstat.errno) { debug(`_lookupModule# Not found module file`) // Try with '.js' extension if (!path.endsWith('.js') && _statPath(`${path}.js`).isFile) { debug(`_lookupModule# Found appending .js to file name`) return `${path}.js` } return new Error(`Error: Module ${path} not found!`) } // Path found and it isn't a dir if (!fstat.isDir) { return new Error(`Error: Module file type not supported for ${path}`) } // Path it's a dir let _path = null // Real path to module let _tryOthers = true // Keep trying? debug(`_lookupModule# Path is a directory, trying options...`) // Try with package.json for NPM or YARN modules if (_statPath(`${path}/package.json`).isFile) { debug(`_lookupModule# It has package.json, looking for main script...`) let _pkg = JSON.parse(std.loadFile(`${path}/package.json`)) if (_pkg && Object.keys(_pkg).indexOf('main') !== -1 && _pkg.main !== '' && _statPath(`${path}/${_pkg.main}`).isFile) { _tryOthers = false _path = `${path}/${_pkg.main}` debug(`_lookupModule# Found package main script!`) } } // Try other options if (_tryOthers && _statPath(`${path}/index.js`).isFile) { _tryOthers = false _path = `${path}/index.js` debug(`_lookupModule# Found package index.js file`) } if (_tryOthers && _statPath(`${path}/main.js`).isFile) { _tryOthers = false _path = `${path}/main.js` debug(`_lookupModule# Found package main.js file`) } if (_path === null) { return new Error(`Error: Module ${path} is a directory, but not a package`) } debug(`_lookupModule# Found module file: ${_path}`) // Returns what it founded return _path } export function require (path) { if (typeof __filename == 'undefined') { debug('require# Calling from main script') } else { debug(`require# Calling from ${__filename} parent module`) } let _path = _lookupModule(path) // Module not found if (_path instanceof Error) { throw _path return } let _module = _loadModule(_path) return _module.exports })"}; class qjs_fetch_Headers { public: qjs_fetch_Headers() = default; string_icase_map headers; void append(const std::string &key, const std::string &value) { headers[key] = value; } void parse_from_string(const std::string &data) { headers.clear(); string_array all_kv = split(data, "\r\n"); for(std::string &x : all_kv) { size_t pos_colon = x.find(':'); if(pos_colon == std::string::npos) continue; else if(pos_colon >= x.size() - 1) headers[x.substr(0, pos_colon)] = ""; else headers[x.substr(0, pos_colon)] = x.substr(pos_colon + 2, x.size() - pos_colon); } } }; class qjs_fetch_Request { public: qjs_fetch_Request() = default; std::string method = "GET"; std::string url; std::string proxy; qjs_fetch_Headers headers; std::string cookies; std::string postdata; explicit qjs_fetch_Request(std::string url) : url(std::move(url)) {} }; class qjs_fetch_Response { public: qjs_fetch_Response() = default; int status_code = 200; std::string content; std::string cookies; qjs_fetch_Headers headers; }; namespace qjs { namespace detail { using string_map = std::map<std::string, std::string>; using string_icase_map = std::map<std::string, std::string, strICaseComp>; } template<> struct js_traits<detail::string_icase_map> { static detail::string_icase_map unwrap(JSContext *ctx, JSValueConst v) { string_icase_map res; JSPropertyEnum *props = nullptr, *props_begin; uint32_t len = 0; JS_GetOwnPropertyNames(ctx, &props, &len, v, JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY); props_begin = props; while(len > 0) { auto key = JS_AtomToCString(ctx, props->atom); auto val = JS_GetProperty(ctx, v, props->atom); auto valData = JS_ToCString(ctx, val); res[key] = valData; JS_FreeCString(ctx, valData); JS_FreeValue(ctx, val); JS_FreeCString(ctx, key); JS_FreeAtom(ctx, props->atom); props++; len--; } js_free(ctx, props_begin); return res; } static JSValue wrap(JSContext *ctx, const detail::string_icase_map &m) noexcept { auto obj = JS_NewObject(ctx); for(auto &kv : m) { auto value = JS_NewStringLen(ctx, kv.second.c_str(), kv.second.size()); JS_SetPropertyStr(ctx, obj, kv.first.c_str(), value); } return obj; } }; template<> struct js_traits<qjs_fetch_Headers> { static qjs_fetch_Headers unwrap(JSContext *ctx, JSValueConst v) { qjs_fetch_Headers result; result.headers = unwrap_free<detail::string_icase_map>(ctx, v, "headers"); return result; } static JSValue wrap(JSContext *ctx, const qjs_fetch_Headers &h) { auto obj = JS_NewObject(ctx); JS_SetPropertyStr(ctx, obj, "headers", js_traits<detail::string_icase_map>::wrap(ctx, h.headers)); return obj; } }; template<> struct js_traits<qjs_fetch_Request> { static qjs_fetch_Request unwrap(JSContext *ctx, JSValueConst v) { qjs_fetch_Request request; request.method = unwrap_free<std::string>(ctx, v, "method"); request.url = unwrap_free<std::string>(ctx, v, "url"); request.postdata = unwrap_free<std::string>(ctx, v, "data"); request.proxy = unwrap_free<std::string>(ctx, v, "proxy"); request.cookies = unwrap_free<std::string>(ctx, v, "cookies"); request.headers = unwrap_free<qjs_fetch_Headers>(ctx, v, "headers"); return request; } }; template<> struct js_traits<qjs_fetch_Response> { static JSValue wrap(JSContext *ctx, const qjs_fetch_Response &r) noexcept { auto obj = JS_NewObject(ctx); JS_SetPropertyStr(ctx, obj, "status_code", JS_NewInt32(ctx, r.status_code)); JS_SetPropertyStr(ctx, obj, "headers", js_traits<qjs_fetch_Headers>::wrap(ctx, r.headers)); JS_SetPropertyStr(ctx, obj, "data", JS_NewStringLen(ctx, r.content.c_str(), r.content.size())); JS_SetPropertyStr(ctx, obj, "cookies", JS_NewStringLen(ctx, r.cookies.c_str(), r.cookies.size())); return obj; } }; } static std::string makeDataURI(const std::string &content, bool shouldBase64 = false) { if(shouldBase64) return "data:text/plain;base64," + base64Encode(content); else return "data:text/plain," + content; } static qjs_fetch_Response qjs_fetch(qjs_fetch_Request request) { qjs_fetch_Response response; http_method method; switch(hash_(toUpper(request.method))) { case "GET"_hash: method = request.postdata.empty() ? HTTP_GET : HTTP_POST; break; case "POST"_hash: method = HTTP_POST; break; case "PATCH"_hash: method = HTTP_PATCH; break; case "HEAD"_hash: method = HTTP_HEAD; break; default: return response; } std::string response_headers; FetchArgument argument {method, request.url, request.proxy, &request.postdata, &request.headers.headers, &request.cookies, 0}; FetchResult result {&response.status_code, &response.content, &response_headers, &response.cookies}; webGet(argument, result); response.headers.parse_from_string(response_headers); return response; } static std::string qjs_getUrlArg(const std::string &url, const std::string &request) { return getUrlArg(url, request); } std::string getGeoIP(const std::string &address, const std::string &proxy) { return fetchFile("https://api.ip.sb/geoip/" + address, parseProxy(proxy), global.cacheConfig); } void script_runtime_init(qjs::Runtime &runtime) { js_std_init_handlers(runtime.rt); } int ShowMsgbox(const std::string &title, const std::string &content, uint16_t type = 0) { #ifdef _WIN32 if(!type) type = MB_ICONINFORMATION; return MessageBoxA(NULL, utf8ToACP(content).c_str(), utf8ToACP(title).c_str(), type); #else return -1; #endif // _WIN32 } template<typename... Targs> struct Lambda { template<typename Tret, typename T> static Tret lambda_ptr_exec(Targs... args) { return (Tret) (*(T*)fn<T>())(args...); } template<typename Tret = void, typename Tfp = Tret(*)(Targs...), typename T> static Tfp ptr(T& t) { fn<T>(&t); return (Tfp) lambda_ptr_exec<Tret, T>; } template<typename T> static void* fn(void* new_fn = nullptr) { static void* fn; if (new_fn != nullptr) fn = new_fn; return fn; } }; uint32_t currentTime() { return time(nullptr); } int script_context_init(qjs::Context &context) { try { js_init_module_os(context.ctx, "os"); js_init_module_std(context.ctx, "std"); js_std_add_helpers(context.ctx, 0, nullptr); context.eval(qjs_require_module, "<require>", JS_EVAL_TYPE_MODULE); auto &module = context.addModule("interUtils"); module.class_<qjs_fetch_Headers>("Headers") .constructor<>() .fun<&qjs_fetch_Headers::headers>("headers") .fun<&qjs_fetch_Headers::append>("append") .fun<&qjs_fetch_Headers::parse_from_string>("parse"); module.class_<qjs_fetch_Request>("Request") .constructor<>() .fun<&qjs_fetch_Request::method>("method") .fun<&qjs_fetch_Request::url>("url") .fun<&qjs_fetch_Request::proxy>("proxy") .fun<&qjs_fetch_Request::postdata>("data") .fun<&qjs_fetch_Request::headers>("headers") .fun<&qjs_fetch_Request::cookies>("cookies"); module.class_<qjs_fetch_Response>("Response") .constructor<>() .fun<&qjs_fetch_Response::status_code>("code") .fun<&qjs_fetch_Response::content>("data") .fun<&qjs_fetch_Response::cookies>("cookies") .fun<&qjs_fetch_Response::headers>("headers"); module.class_<Proxy>("Proxy") .constructor<>() .fun<&Proxy::Type>("Type") .fun<&Proxy::Id>("Id") .fun<&Proxy::GroupId>("GroupId") .fun<&Proxy::Group>("Group") .fun<&Proxy::Remark>("Remark") .fun<&Proxy::Hostname>("Hostname") .fun<&Proxy::Port>("Port") .fun<&Proxy::Username>("Username") .fun<&Proxy::Password>("Password") .fun<&Proxy::EncryptMethod>("EncryptMethod") .fun<&Proxy::Plugin>("Plugin") .fun<&Proxy::PluginOption>("PluginOption") .fun<&Proxy::Protocol>("Protocol") .fun<&Proxy::ProtocolParam>("ProtocolParam") .fun<&Proxy::OBFS>("OBFS") .fun<&Proxy::OBFSParam>("OBFSParam") .fun<&Proxy::UserId>("UserId") .fun<&Proxy::AlterId>("AlterId") .fun<&Proxy::TransferProtocol>("TransferProtocol") .fun<&Proxy::FakeType>("FakeType") .fun<&Proxy::TLSSecure>("TLSSecure") .fun<&Proxy::Host>("Host") .fun<&Proxy::Path>("Path") .fun<&Proxy::Edge>("Edge") .fun<&Proxy::QUICSecure>("QUICSecure") .fun<&Proxy::QUICSecret>("QUICSecret") .fun<&Proxy::UDP>("UDP") .fun<&Proxy::TCPFastOpen>("TCPFastOpen") .fun<&Proxy::AllowInsecure>("AllowInsecure") .fun<&Proxy::TLS13>("TLS13") .fun<&Proxy::SnellVersion>("SnellVersion") .fun<&Proxy::ServerName>("ServerName") .fun<&Proxy::SelfIP>("SelfIP") .fun<&Proxy::SelfIPv6>("SelfIPv6") .fun<&Proxy::PublicKey>("PublicKey") .fun<&Proxy::PrivateKey>("PrivateKey") .fun<&Proxy::PreSharedKey>("PreSharedKey") .fun<&Proxy::DnsServers>("DnsServers") .fun<&Proxy::Mtu>("Mtu") .fun<&Proxy::AllowedIPs>("AllowedIPs") .fun<&Proxy::KeepAlive>("KeepAlive") .fun<&Proxy::TestUrl>("TestUrl") .fun<&Proxy::ClientId>("ClientId"); context.global().add<&makeDataURI>("makeDataURI") .add<&qjs_fetch>("fetch") .add<&base64Encode>("atob") .add<&base64Decode>("btoa") .add<&currentTime>("time") .add<&sleepMs>("sleep") .add<&ShowMsgbox>("msgbox") .add<&qjs_getUrlArg>("getUrlArg") .add<&fileGet>("fileGet") .add<&fileWrite>("fileWrite"); context.eval(R"( import * as interUtils from 'interUtils' globalThis.Request = interUtils.Request globalThis.Response = interUtils.Response globalThis.Headers = interUtils.Headers globalThis.Proxy = interUtils.Proxy import * as std from 'std' import * as os from 'os' globalThis.std = std globalThis.os = os import { require } from '<require>' globalThis.require = require )", "<import>", JS_EVAL_TYPE_MODULE); return 0; } catch(qjs::exception&) { script_print_stack(context); return 1; } } int script_cleanup(qjs::Context &context) { js_std_loop(context.ctx); js_std_free_handlers(JS_GetRuntime(context.ctx)); return 0; } void script_print_stack(qjs::Context &context) { auto exc = context.getException(); std::cerr << (std::string) exc << std::endl; if((bool) exc["stack"]) std::cerr << (std::string) exc["stack"] << std::endl; }
16,519
C++
.cpp
490
27.185714
148
0.604446
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,458
template_jinja2.cpp
tindy2013_subconverter/src/generator/template/template_jinja2.cpp
#include <string> #include <jinja2cpp/user_callable.h> #include <jinja2cpp/binding/nlohmann_json.h> #include <jinja2cpp/template.h> #include <nlohmann/json.hpp> #include "handler/interfaces.h" #include "utils/regexp.h" #include "templates.h" static inline void parse_json_pointer(nlohmann::json &json, const std::string &path, const std::string &value) { std::string pointer = "/" + replaceAllDistinct(path, ".", "/"); json[nlohmann::json::json_pointer(pointer)] = value; } int render_template(const std::string &content, const template_args &vars, std::string &output, const std::string &include_scope) { jinja2::Template tpl; nlohmann::json data; for(auto &x : vars.global_vars) parse_json_pointer(data["global"], x.first, x.second); for(auto &x : vars.request_params) parse_json_pointer(data["request"], x.first, x.second); for(auto &x : vars.local_vars) parse_json_pointer(data["local"], x.first, x.second); tpl.Load(content); jinja2::ValuesMap valmap = {{"global", jinja2::Reflect(data["global"])}, {"local", jinja2::Reflect(data["local"])}, {"request", jinja2::Reflect(data["request"])}}; valmap["fetch"] = jinja2::MakeCallable(jinja2_webGet, jinja2::ArgInfo{"url"}); valmap["replace"] = jinja2::MakeCallable([](const std::string &src, const std::string &target, const std::string &rep) { return regReplace(src, target, rep); }, jinja2::ArgInfo{"src"}, jinja2::ArgInfo{"target"}, jinja2::ArgInfo{"rep"}); try { output = tpl.RenderAsString(valmap).value(); return 0; } catch (std::exception &e) { output = "Template render failed! Reason: " + std::string(e.what()); return -1; } return -2; }
1,745
C++
.cpp
42
37.02381
167
0.665686
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,459
templates.cpp
tindy2013_subconverter/src/generator/template/templates.cpp
#include <string> #include <map> #include <sstream> #include <filesystem> #include <inja.hpp> #include <nlohmann/json.hpp> #include "handler/interfaces.h" #include "handler/settings.h" #include "handler/webget.h" #include "utils/logger.h" #include "utils/network.h" #include "utils/regexp.h" #include "utils/urlencode.h" #include "utils/yamlcpp_extra.h" #include "templates.h" namespace inja { void convert_dot_to_json_pointer(std::string_view dot, std::string& out) { out = DataNode::convert_dot_to_ptr(dot); } } static inline void parse_json_pointer(nlohmann::json &json, const std::string &path, const std::string &value) { std::string pointer; inja::convert_dot_to_json_pointer(path, pointer); try { json[nlohmann::json::json_pointer(pointer)] = value; } catch (std::exception&) { //ignore broken pointer } } /* std::string parseHostname(inja::Arguments &args) { std::string data = args.at(0)->get<std::string>(), hostname; const std::string matcher = R"(^(?i:hostname\s*?=\s*?)(.*?)\s$)"; string_array urls = split(data, ","); if(!urls.size()) return std::string(); std::string input_content, output_content, proxy = parseProxy(global.proxyConfig); for(std::string &x : urls) { input_content = webGet(x, proxy, global.cacheConfig); regGetMatch(input_content, matcher, 2, 0, &hostname); if(hostname.size()) { output_content += hostname + ","; hostname.clear(); } } string_array vArray = split(output_content, ","); std::set<std::string> hostnames; for(std::string &x : vArray) hostnames.emplace(trim(x)); output_content = std::accumulate(hostnames.begin(), hostnames.end(), std::string(), [](std::string a, std::string b) { return std::move(a) + "," + std::move(b); }); return output_content; }*/ #ifndef NO_WEBGET std::string template_webGet(inja::Arguments &args) { std::string data = args.at(0)->get<std::string>(), proxy = parseProxy(global.proxyConfig); writeLog(0, "Template called fetch with url '" + data + "'.", LOG_LEVEL_INFO); return webGet(data, proxy, global.cacheConfig); } #endif // NO_WEBGET int render_template(const std::string &content, const template_args &vars, std::string &output, const std::string &include_scope) { std::string absolute_scope; try { if(!include_scope.empty()) absolute_scope = std::filesystem::canonical(include_scope).string(); } catch(std::exception &e) { writeLog(0, e.what(), LOG_LEVEL_ERROR); } nlohmann::json data; for(auto &x : vars.global_vars) parse_json_pointer(data["global"], x.first, x.second); std::string all_args; for(auto &x : vars.request_params) { all_args += x.first; if(!x.second.empty()) { parse_json_pointer(data["request"], x.first, x.second); all_args += "=" + x.second; } all_args += "&"; } all_args.erase(all_args.size() - 1); parse_json_pointer(data["request"], "_args", all_args); for(auto &x : vars.local_vars) parse_json_pointer(data["local"], x.first, x.second); inja::Environment env; env.set_trim_blocks(true); env.set_lstrip_blocks(true); env.set_line_statement("#~#"); env.add_callback("UrlEncode", 1, [](inja::Arguments &args) { std::string data = args.at(0)->get<std::string>(); return urlEncode(data); }); env.add_callback("UrlDecode", 1, [](inja::Arguments &args) { std::string data = args.at(0)->get<std::string>(); return urlDecode(data); }); env.add_callback("trim_of", 2, [](inja::Arguments &args) { std::string data = args.at(0)->get<std::string>(), target = args.at(1)->get<std::string>(); if(target.empty()) return data; return trimOf(data, target[0]); }); env.add_callback("trim", 1, [](inja::Arguments &args) { std::string data = args.at(0)->get<std::string>(); return trim(data); }); env.add_callback("find", 2, [](inja::Arguments &args) { std::string src = args.at(0)->get<std::string>(), target = args.at(1)->get<std::string>(); return regFind(src, target); }); env.add_callback("replace", 3, [](inja::Arguments &args) { std::string src = args.at(0)->get<std::string>(), target = args.at(1)->get<std::string>(), rep = args.at(2)->get<std::string>(); if(target.empty() || src.empty()) return src; return regReplace(src, target, rep); }); env.add_callback("set", 2, [&data](inja::Arguments &args) { std::string key = args.at(0)->get<std::string>(), value = args.at(1)->get<std::string>(); parse_json_pointer(data, key, value); return ""; }); env.add_callback("split", 3, [&data](inja::Arguments &args) { std::string content = args.at(0)->get<std::string>(), delim = args.at(1)->get<std::string>(), dest = args.at(2)->get<std::string>(); 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 ""; }); env.add_callback("append", 2, [&data](inja::Arguments &args) { std::string path = args.at(0)->get<std::string>(), value = args.at(1)->get<std::string>(), pointer, output_content; inja::convert_dot_to_json_pointer(path, pointer); try { output_content = data[nlohmann::json::json_pointer(pointer)].get<std::string>(); } catch (std::exception &e) { // non-exist path, ignore } output_content.append(value); data[nlohmann::json::json_pointer(pointer)] = output_content; return ""; }); env.add_callback("getLink", 1, [](inja::Arguments &args) { return global.managedConfigPrefix + args.at(0)->get<std::string>(); }); env.add_callback("startsWith", 2, [](inja::Arguments &args) { return startsWith(args.at(0)->get<std::string>(), args.at(1)->get<std::string>()); }); env.add_callback("endsWith", 2, [](inja::Arguments &args) { return endsWith(args.at(0)->get<std::string>(), args.at(1)->get<std::string>()); }); env.add_callback("or", -1, [](inja::Arguments &args) { for(auto iter = args.begin(); iter != args.end(); iter++) if((*iter)->get<int>()) return true; return false; }); env.add_callback("and", -1, [](inja::Arguments &args) { for(auto iter = args.begin(); iter != args.end(); iter++) if(!(*iter)->get<int>()) return false; return true; }); env.add_callback("bool", 1, [](inja::Arguments &args) { std::string value = args.at(0)->get<std::string>(); std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { return std::tolower(c); }); switch(hash_(value)) { case "true"_hash: case "1"_hash: return 1; default: return 0; } }); env.add_callback("string", 1, [](inja::Arguments &args) { return std::to_string(args.at(0)->get<int>()); }); #ifndef NO_WEBGET env.add_callback("fetch", 1, template_webGet); #endif // NO_WEBGET //env.add_callback("parseHostname", 1, parseHostname); env.set_include_callback([&](const std::string &name, const std::string &template_name) { std::string absolute_path; try { absolute_path = std::filesystem::canonical(template_name).string(); } catch(std::exception &e) { throw inja::FileError(e.what()); } if(!absolute_scope.empty() && !startsWith(absolute_path, absolute_scope)) throw inja::FileError("access denied when trying to include '" + template_name + "': out of scope"); return env.parse(fileGet(template_name, true)); }); env.set_search_included_templates_in_files(false); try { std::stringstream out; env.render_to(out, env.parse(content), data); output = out.str(); return 0; } catch (std::exception &e) { output = "Template render failed! Reason: " + std::string(e.what()); writeLog(0, output, LOG_LEVEL_ERROR); return -1; } return -2; } const std::string clash_script_template = R"(def main(ctx, md): host = md["host"] {% for rule in rules %} {% if rule.set == "true" %}{% include "group_template" %}{% endif %} {% endfor %} {% if exists("geoips") %} geoips = { {{ geoips }} } ip = md["dst_ip"] if ip == "": ip = ctx.resolve_ip(host) if ip == "": ctx.log('[Script] dns lookup error use {{ match_group }}') return "{{ match_group }}" for key in geoips: if ctx.geoip(ip) == key: return geoips[key]{% endif %} return "{{ match_group }}")"; const std::string clash_script_group_template = R"({% if (rule.has_domain == "false" and rule.has_ipcidr == "false") or rule.original == "true" %} if ctx.rule_providers["{{ rule.name }}"].match(md): ctx.log('[Script] matched {{ rule.group }} rule') return "{{ rule.group }}"{% else %}{% if rule.has_domain == "true" %} if ctx.rule_providers["{{ rule.name }}_domain"].match(md): ctx.log('[Script] matched {{ rule.group }} DOMAIN rule') return "{{ rule.group }}"{% endif %} {% if not rule.keyword == "" %}{% include "keyword_template" %}{% endif %} {% if rule.has_ipcidr == "true" %} if ctx.rule_providers["{{ rule.name }}_ipcidr"].match(md): ctx.log('[Script] matched {{ rule.group }} IP rule') return "{{ rule.group }}"{% endif %}{% endif %})"; const std::string clash_script_keyword_template = R"( keywords = [{{ rule.keyword }}] for keyword in keywords: if keyword in host: ctx.log('[Script] matched {{ rule.group }} DOMAIN-KEYWORD rule') return "{{ rule.group }}")"; std::string findFileName(const std::string &path) { string_size pos = path.rfind('/'); if(pos == std::string::npos) { pos = path.rfind('\\'); if(pos == std::string::npos) pos = 0; } string_size pos2 = path.rfind('.'); if(pos2 < pos || pos2 == std::string::npos) pos2 = path.size(); return path.substr(pos + 1, pos2 - pos - 1); } int renderClashScript(YAML::Node &base_rule, std::vector<RulesetContent> &ruleset_content_array, const std::string &remote_path_prefix, bool script, bool overwrite_original_rules, bool clash_classical_ruleset) { nlohmann::json data; std::string match_group, geoips, retrieved_rules; std::string strLine, rule_group, rule_path, rule_path_typed, rule_name, old_rule_name; std::stringstream strStrm; string_array vArray, groups; string_map keywords, urls, names; std::map<std::string, bool> has_domain, has_ipcidr; std::map<std::string, int> ruleset_interval, rule_type; string_array rules; int index = 0; if(!overwrite_original_rules && base_rule["rules"].IsDefined()) rules = safe_as<string_array>(base_rule["rules"]); for(RulesetContent &x : ruleset_content_array) { rule_group = x.rule_group; rule_path = x.rule_path; rule_path_typed = x.rule_path_typed; if(rule_path.empty()) { strLine = x.rule_content.get().substr(2); if(script) { if(startsWith(strLine, "MATCH") || startsWith(strLine, "FINAL")) match_group = rule_group; else if(startsWith(strLine, "GEOIP")) { vArray = split(strLine, ","); if(vArray.size() < 2) continue; geoips += "\"" + vArray[1] + "\": \"" + rule_group + "\","; } continue; } if(startsWith(strLine, "FINAL")) strLine.replace(0, 5, "MATCH"); strLine += "," + rule_group; if(count_least(strLine, ',', 3)) strLine = regReplace(strLine, "^(.*?,.*?)(,.*)(,.*)$", "$1$3$2"); rules.emplace_back(std::move(strLine)); continue; } else { if(x.rule_type == RULESET_CLASH_IPCIDR || x.rule_type == RULESET_CLASH_DOMAIN || x.rule_type == RULESET_CLASH_CLASSICAL) { //rule_name = std::to_string(hash_(rule_group + rule_path)); rule_name = old_rule_name = findFileName(rule_path); int idx = 2; while(std::find(groups.begin(), groups.end(), rule_name) != groups.end()) rule_name = old_rule_name + "_" + std::to_string(idx++); names[rule_name] = rule_group; urls[rule_name] = "*" + rule_path; rule_type[rule_name] = x.rule_type; ruleset_interval[rule_name] = x.update_interval; switch(x.rule_type) { case RULESET_CLASH_IPCIDR: has_ipcidr[rule_name] = true; break; case RULESET_CLASH_DOMAIN: has_domain[rule_name] = true; break; case RULESET_CLASH_CLASSICAL: break; } if(!script) rules.emplace_back("RULE-SET," + rule_name + "," + rule_group); groups.emplace_back(rule_name); continue; } if(!remote_path_prefix.empty()) { if(fileExist(rule_path, true) || isLink(rule_path)) { //rule_name = std::to_string(hash_(rule_group + rule_path)); rule_name = old_rule_name = findFileName(rule_path); int idx = 2; while(std::find(groups.begin(), groups.end(), rule_name) != groups.end()) rule_name = old_rule_name + "_" + std::to_string(idx++); names[rule_name] = rule_group; urls[rule_name] = rule_path_typed; rule_type[rule_name] = x.rule_type; ruleset_interval[rule_name] = x.update_interval; if(clash_classical_ruleset) { if(!script) rules.emplace_back("RULE-SET," + rule_name + "," + rule_group); groups.emplace_back(rule_name); continue; } } else continue; } retrieved_rules = x.rule_content.get(); if(retrieved_rules.empty()) { writeLog(0, "Failed to fetch ruleset or ruleset is empty: '" + x.rule_path + "'!", LOG_LEVEL_WARNING); continue; } retrieved_rules = convertRuleset(retrieved_rules, x.rule_type); char delimiter = getLineBreak(retrieved_rules); strStrm.clear(); strStrm<<retrieved_rules; std::string::size_type lineSize; bool has_no_resolve = false; while(getline(strStrm, strLine, delimiter)) { lineSize = strLine.size(); if(lineSize && strLine[lineSize - 1] == '\r') //remove line break strLine.erase(--lineSize); if(!lineSize || strLine[0] == ';' || strLine[0] == '#' || (lineSize >= 2 && strLine[0] == '/' && strLine[1] == '/')) //empty lines and comments are ignored continue; if(startsWith(strLine, "DOMAIN-KEYWORD,")) { if(script) { vArray = split(strLine, ","); if(vArray.size() < 2) continue; if(keywords.find(rule_name) == keywords.end()) keywords[rule_name] = "\"" + vArray[1] + "\""; else keywords[rule_name] += ",\"" + vArray[1] + "\""; } else { vArray = split(strLine, ","); if(vArray.size() < 2) { strLine = vArray[0] + "," + rule_group; } else { strLine = vArray[0] + "," + vArray[1] + "," + rule_group; if(vArray.size() > 2) strLine += "," + vArray[2]; } rules.emplace_back(strLine); } } else if(!has_domain[rule_name] && (startsWith(strLine, "DOMAIN,") || startsWith(strLine, "DOMAIN-SUFFIX,"))) has_domain[rule_name] = true; else if(!has_ipcidr[rule_name] && (startsWith(strLine, "IP-CIDR,") || startsWith(strLine, "IP-CIDR6,"))) { has_ipcidr[rule_name] = true; if(strLine.find(",no-resolve") != std::string::npos) has_no_resolve = true; } } if(has_domain[rule_name] && !script) rules.emplace_back("RULE-SET," + rule_name + "_domain," + rule_group); if(has_ipcidr[rule_name] && !script) { if(has_no_resolve) rules.emplace_back("RULE-SET," + rule_name + "_ipcidr," + rule_group + ",no-resolve"); else rules.emplace_back("RULE-SET," + rule_name + "_ipcidr," + rule_group); } if(!has_domain[rule_name] && !has_ipcidr[rule_name] && !script) rules.emplace_back("RULE-SET," + rule_name + "," + rule_group); if(std::find(groups.begin(), groups.end(), rule_name) == groups.end()) groups.emplace_back(rule_name); } } for(std::string &x : groups) { std::string url = urls[x], keyword = keywords[x], name = names[x]; bool group_has_domain = has_domain[x], group_has_ipcidr = has_ipcidr[x]; int interval = ruleset_interval[x]; if(group_has_domain) { std::string yaml_key = x; if(rule_type[x] != RULESET_CLASH_DOMAIN) yaml_key += "_domain"; base_rule["rule-providers"][yaml_key]["type"] = "http"; base_rule["rule-providers"][yaml_key]["behavior"] = "domain"; if(url[0] == '*') base_rule["rule-providers"][yaml_key]["url"] = url.substr(1); else base_rule["rule-providers"][yaml_key]["url"] = remote_path_prefix + "/getruleset?type=3&url=" + urlSafeBase64Encode(url); base_rule["rule-providers"][yaml_key]["path"] = "./providers/rule-provider_" + yaml_key + ".yaml"; if(interval) base_rule["rule-providers"][yaml_key]["interval"] = interval; } if(group_has_ipcidr) { std::string yaml_key = x; if(rule_type[x] != RULESET_CLASH_IPCIDR) yaml_key += "_ipcidr"; base_rule["rule-providers"][yaml_key]["type"] = "http"; base_rule["rule-providers"][yaml_key]["behavior"] = "ipcidr"; if(url[0] == '*') base_rule["rule-providers"][yaml_key]["url"] = url.substr(1); else base_rule["rule-providers"][yaml_key]["url"] = remote_path_prefix + "/getruleset?type=4&url=" + urlSafeBase64Encode(url); base_rule["rule-providers"][yaml_key]["path"] = "./providers/rule-provider_" + yaml_key + ".yaml"; if(interval) base_rule["rule-providers"][yaml_key]["interval"] = interval; } if(!group_has_domain && !group_has_ipcidr) { std::string yaml_key = x; base_rule["rule-providers"][yaml_key]["type"] = "http"; base_rule["rule-providers"][yaml_key]["behavior"] = "classical"; if(url[0] == '*') base_rule["rule-providers"][yaml_key]["url"] = url.substr(1); else base_rule["rule-providers"][yaml_key]["url"] = remote_path_prefix + "/getruleset?type=6&url=" + urlSafeBase64Encode(url); base_rule["rule-providers"][yaml_key]["path"] = "./providers/rule-provider_" + yaml_key + ".yaml"; if(interval) base_rule["rule-providers"][yaml_key]["interval"] = interval; } if(script) { std::string json_path = "rules." + std::to_string(index) + "."; parse_json_pointer(data, json_path + "has_domain", group_has_domain ? "true" : "false"); parse_json_pointer(data, json_path + "has_ipcidr", group_has_ipcidr ? "true" : "false"); parse_json_pointer(data, json_path + "name", x); parse_json_pointer(data, json_path + "group", name); parse_json_pointer(data, json_path + "set", "true"); parse_json_pointer(data, json_path + "keyword", keyword); parse_json_pointer(data, json_path + "original", (rule_type[x] == RULESET_CLASH_DOMAIN || rule_type[x] == RULESET_CLASH_IPCIDR) ? "true" : "false"); } index++; } if(script) { if(!geoips.empty()) parse_json_pointer(data, "geoips", geoips.erase(geoips.size() - 1)); parse_json_pointer(data, "match_group", match_group); inja::Environment env; env.include_template("keyword_template", env.parse(clash_script_keyword_template)); env.include_template("group_template", env.parse(clash_script_group_template)); inja::Template tmpl = env.parse(clash_script_template); try { std::string output_content = env.render(tmpl, data); base_rule["script"]["code"] = output_content; } catch (std::exception &e) { writeLog(0, "Error when rendering: " + std::string(e.what()), LOG_TYPE_ERROR); return -1; } } else base_rule["rules"] = rules; return 0; }
22,518
C++
.cpp
544
31.134191
209
0.532146
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,460
nodemanip.cpp
tindy2013_subconverter/src/generator/config/nodemanip.cpp
#include <string> #include <vector> #include <iostream> #include <algorithm> #include "handler/settings.h" #include "handler/webget.h" #include "parser/config/proxy.h" #include "parser/infoparser.h" #include "parser/subparser.h" #include "script/script_quickjs.h" #include "utils/file_extra.h" #include "utils/logger.h" #include "utils/map_extra.h" #include "utils/network.h" #include "utils/regexp.h" #include "utils/urlencode.h" #include "nodemanip.h" #include "subexport.h" extern Settings global; bool applyMatcher(const std::string &rule, std::string &real_rule, const Proxy &node); int explodeConf(const std::string &filepath, std::vector<Proxy> &nodes) { return explodeConfContent(fileGet(filepath), nodes); } void copyNodes(std::vector<Proxy> &source, std::vector<Proxy> &dest) { std::move(source.begin(), source.end(), std::back_inserter(dest)); } int addNodes(std::string link, std::vector<Proxy> &allNodes, int groupID, parse_settings &parse_set) { std::string &proxy = *parse_set.proxy, &subInfo = *parse_set.sub_info; string_array &exclude_remarks = *parse_set.exclude_remarks; string_array &include_remarks = *parse_set.include_remarks; RegexMatchConfigs &stream_rules = *parse_set.stream_rules; RegexMatchConfigs &time_rules = *parse_set.time_rules; string_icase_map *request_headers = parse_set.request_header; bool &authorized = parse_set.authorized; ConfType linkType = ConfType::Unknow; std::vector<Proxy> nodes; Proxy node; std::string strSub, extra_headers, custom_group; // TODO: replace with startsWith if appropriate link = replaceAllDistinct(link, "\"", ""); /// script:filepath,arg1,arg2,... if(authorized) script_safe_runner(parse_set.js_runtime, parse_set.js_context, [&](qjs::Context &ctx) { if(startsWith(link, "script:")) /// process subscription with script { writeLog(0, "Found script link. Start running...", LOG_LEVEL_INFO); string_array args = split(link.substr(7), ","); if(args.size() >= 1) { std::string script = fileGet(args[0], false); try { ctx.eval(script); args.erase(args.begin()); /// remove script path auto parse = (std::function<std::string(const std::string&, const string_array&)>) ctx.eval("parse"); switch(args.size()) { case 0: link = parse("", string_array()); break; case 1: link = parse(args[0], string_array()); break; default: { std::string first = args[0]; args.erase(args.begin()); link = parse(first, args); break; } } } catch(qjs::exception) { script_print_stack(ctx); } } } }, global.scriptCleanContext); /* duk_context *ctx = duktape_init(); defer(duk_destroy_heap(ctx);) duktape_peval(ctx, script); duk_get_global_string(ctx, "parse"); for(size_t i = 1; i < args.size(); i++) duk_push_string(ctx, trim(args[i]).c_str()); if(duk_pcall(ctx, args.size() - 1) == 0) link = duktape_get_res_str(ctx); else { writeLog(0, "Error when trying to evaluate script:\n" + duktape_get_err_stack(ctx), LOG_LEVEL_ERROR); duk_pop(ctx); /// pop err } */ /// tag:group_name,link if(startsWith(link, "tag:")) { string_size pos = link.find(","); if(pos != link.npos) { custom_group = link.substr(4, pos - 4); link.erase(0, pos + 1); } } if(link == "nullnode") { node.GroupId = 0; writeLog(0, "Adding node placeholder..."); allNodes.emplace_back(std::move(node)); return 0; } writeLog(LOG_TYPE_INFO, "Received Link."); if(startsWith(link, "https://t.me/socks") || startsWith(link, "tg://socks")) linkType = ConfType::SOCKS; else if(startsWith(link, "https://t.me/http") || startsWith(link, "tg://http")) linkType = ConfType::HTTP; else if(isLink(link) || startsWith(link, "surge:///install-config")) linkType = ConfType::SUB; else if(startsWith(link, "Netch://")) linkType = ConfType::Netch; else if(fileExist(link)) linkType = ConfType::Local; switch(linkType) { case ConfType::SUB: writeLog(LOG_TYPE_INFO, "Downloading subscription data..."); if(startsWith(link, "surge:///install-config")) //surge config link link = urlDecode(getUrlArg(link, "url")); strSub = webGet(link, proxy, global.cacheSubscription, &extra_headers, request_headers); /* if(strSub.size() == 0) { //try to get it again with system proxy writeLog(LOG_TYPE_WARN, "Cannot download subscription directly. Using system proxy."); strProxy = getSystemProxy(); if(strProxy != "") { strSub = webGet(link, strProxy); } else writeLog(LOG_TYPE_WARN, "No system proxy is set. Skipping."); } */ if(!strSub.empty()) { writeLog(LOG_TYPE_INFO, "Parsing subscription data..."); if(explodeConfContent(strSub, nodes) == 0) { writeLog(LOG_TYPE_ERROR, "Invalid subscription: '" + link + "'!"); return -1; } if(startsWith(strSub, "ssd://")) { getSubInfoFromSSD(strSub, subInfo); } else { if(!getSubInfoFromHeader(extra_headers, subInfo)) getSubInfoFromNodes(nodes, stream_rules, time_rules, subInfo); } filterNodes(nodes, exclude_remarks, include_remarks, groupID); for(Proxy &x : nodes) { x.GroupId = groupID; if(custom_group.size()) x.Group = custom_group; } copyNodes(nodes, allNodes); } else { writeLog(LOG_TYPE_ERROR, "Cannot download subscription data."); return -1; } break; case ConfType::Local: if(!authorized) return -1; writeLog(LOG_TYPE_INFO, "Parsing configuration file data..."); if(explodeConf(link, nodes) == 0) { writeLog(LOG_TYPE_ERROR, "Invalid configuration file!"); return -1; } if(startsWith(strSub, "ssd://")) { getSubInfoFromSSD(strSub, subInfo); } else { getSubInfoFromNodes(nodes, stream_rules, time_rules, subInfo); } filterNodes(nodes, exclude_remarks, include_remarks, groupID); for(Proxy &x : nodes) { x.GroupId = groupID; if(!custom_group.empty()) x.Group = custom_group; } copyNodes(nodes, allNodes); break; default: explode(link, node); if(node.Type == ProxyType::Unknown) { writeLog(LOG_TYPE_ERROR, "No valid link found."); return -1; } node.GroupId = groupID; if(!custom_group.empty()) node.Group = custom_group; allNodes.emplace_back(std::move(node)); } return 0; } bool chkIgnore(const Proxy &node, string_array &exclude_remarks, string_array &include_remarks) { bool excluded = false, included = false; //std::string remarks = UTF8ToACP(node.remarks); //std::string remarks = node.remarks; //writeLog(LOG_TYPE_INFO, "Comparing exclude remarks..."); excluded = std::any_of(exclude_remarks.cbegin(), exclude_remarks.cend(), [&node](const auto &x) { std::string real_rule; if(applyMatcher(x, real_rule, node)) { if(real_rule.empty()) return true; return regFind(node.Remark, real_rule); } else return false; }); if(include_remarks.size() != 0) { //writeLog(LOG_TYPE_INFO, "Comparing include remarks..."); included = std::any_of(include_remarks.cbegin(), include_remarks.cend(), [&node](const auto &x) { std::string real_rule; if(applyMatcher(x, real_rule, node)) { if(real_rule.empty()) return true; return regFind(node.Remark, real_rule); } else return false; }); } else { included = true; } return excluded || !included; } void filterNodes(std::vector<Proxy> &nodes, string_array &exclude_remarks, string_array &include_remarks, int groupID) { int node_index = 0; std::vector<Proxy>::iterator iter = nodes.begin(); while(iter != nodes.end()) { if(chkIgnore(*iter, exclude_remarks, include_remarks)) { writeLog(LOG_TYPE_INFO, "Node " + iter->Group + " - " + iter->Remark + " has been ignored and will not be added."); nodes.erase(iter); } else { writeLog(LOG_TYPE_INFO, "Node " + iter->Group + " - " + iter->Remark + " has been added."); iter->Id = node_index; iter->GroupId = groupID; ++node_index; ++iter; } } /* std::vector<std::unique_ptr<pcre2_code, decltype(&pcre2_code_free)>> exclude_patterns, include_patterns; std::vector<std::unique_ptr<pcre2_match_data, decltype(&pcre2_match_data_free)>> exclude_match_data, include_match_data; unsigned int i = 0; PCRE2_SIZE erroroffset; int errornumber, rc; for(i = 0; i < exclude_remarks.size(); i++) { std::unique_ptr<pcre2_code, decltype(&pcre2_code_free)> pattern(pcre2_compile(reinterpret_cast<const unsigned char*>(exclude_remarks[i].c_str()), exclude_remarks[i].size(), PCRE2_UTF | PCRE2_MULTILINE | PCRE2_ALT_BSUX, &errornumber, &erroroffset, NULL), &pcre2_code_free); if(!pattern) return; exclude_patterns.emplace_back(std::move(pattern)); pcre2_jit_compile(exclude_patterns[i].get(), 0); std::unique_ptr<pcre2_match_data, decltype(&pcre2_match_data_free)> match_data(pcre2_match_data_create_from_pattern(exclude_patterns[i].get(), NULL), &pcre2_match_data_free); exclude_match_data.emplace_back(std::move(match_data)); } for(i = 0; i < include_remarks.size(); i++) { std::unique_ptr<pcre2_code, decltype(&pcre2_code_free)> pattern(pcre2_compile(reinterpret_cast<const unsigned char*>(include_remarks[i].c_str()), include_remarks[i].size(), PCRE2_UTF | PCRE2_MULTILINE | PCRE2_ALT_BSUX, &errornumber, &erroroffset, NULL), &pcre2_code_free); if(!pattern) return; include_patterns.emplace_back(std::move(pattern)); pcre2_jit_compile(include_patterns[i].get(), 0); std::unique_ptr<pcre2_match_data, decltype(&pcre2_match_data_free)> match_data(pcre2_match_data_create_from_pattern(include_patterns[i].get(), NULL), &pcre2_match_data_free); include_match_data.emplace_back(std::move(match_data)); } writeLog(LOG_TYPE_INFO, "Filter started."); while(iter != nodes.end()) { bool excluded = false, included = false; for(i = 0; i < exclude_patterns.size(); i++) { rc = pcre2_match(exclude_patterns[i].get(), reinterpret_cast<const unsigned char*>(iter->remarks.c_str()), iter->remarks.size(), 0, 0, exclude_match_data[i].get(), NULL); if (rc < 0) { switch(rc) { case PCRE2_ERROR_NOMATCH: break; default: return; } } else excluded = true; } if(include_patterns.size() > 0) for(i = 0; i < include_patterns.size(); i++) { rc = pcre2_match(include_patterns[i].get(), reinterpret_cast<const unsigned char*>(iter->remarks.c_str()), iter->remarks.size(), 0, 0, include_match_data[i].get(), NULL); if (rc < 0) { switch(rc) { case PCRE2_ERROR_NOMATCH: break; default: return; } } else included = true; } else included = true; if(excluded || !included) { writeLog(LOG_TYPE_INFO, "Node " + iter->group + " - " + iter->remarks + " has been ignored and will not be added."); nodes.erase(iter); } else { writeLog(LOG_TYPE_INFO, "Node " + iter->group + " - " + iter->remarks + " has been added."); iter->id = node_index; iter->groupID = groupID; ++node_index; ++iter; } } */ writeLog(LOG_TYPE_INFO, "Filter done."); } void nodeRename(Proxy &node, const RegexMatchConfigs &rename_array, extra_settings &ext) { std::string &remark = node.Remark, original_remark = node.Remark, returned_remark, real_rule; for(const RegexMatchConfig &x : rename_array) { if(!x.Script.empty() && ext.authorized) { script_safe_runner(ext.js_runtime, ext.js_context, [&](qjs::Context &ctx) { std::string script = x.Script; if(startsWith(script, "path:")) script = fileGet(script.substr(5), true); try { ctx.eval(script); auto rename = (std::function<std::string(const Proxy&)>) ctx.eval("rename"); returned_remark = rename(node); if(!returned_remark.empty()) remark = returned_remark; } catch (qjs::exception) { script_print_stack(ctx); } }, global.scriptCleanContext); continue; } if(applyMatcher(x.Match, real_rule, node) && real_rule.size()) remark = regReplace(remark, real_rule, x.Replace); } if(remark.empty()) remark = original_remark; return; } std::string removeEmoji(const std::string &orig_remark) { char emoji_id[2] = {(char)-16, (char)-97}; std::string remark = orig_remark; while(true) { if(remark[0] == emoji_id[0] && remark[1] == emoji_id[1]) remark.erase(0, 4); else break; } if(remark.empty()) return orig_remark; return remark; } std::string addEmoji(const Proxy &node, const RegexMatchConfigs &emoji_array, extra_settings &ext) { std::string real_rule, ret; for(const RegexMatchConfig &x : emoji_array) { if(!x.Script.empty() && ext.authorized) { std::string result; script_safe_runner(ext.js_runtime, ext.js_context, [&](qjs::Context &ctx) { std::string script = x.Script; if(startsWith(script, "path:")) script = fileGet(script.substr(5), true); try { ctx.eval(script); auto getEmoji = (std::function<std::string(const Proxy&)>) ctx.eval("getEmoji"); ret = getEmoji(node); if(!ret.empty()) result = ret + " " + node.Remark; } catch (qjs::exception) { script_print_stack(ctx); } }, global.scriptCleanContext); if(!result.empty()) return result; continue; } if(x.Replace.empty()) continue; if(applyMatcher(x.Match, real_rule, node) && real_rule.size() && regFind(node.Remark, real_rule)) return x.Replace + " " + node.Remark; } return node.Remark; } void preprocessNodes(std::vector<Proxy> &nodes, extra_settings &ext) { std::for_each(nodes.begin(), nodes.end(), [&ext](Proxy &x) { if(ext.remove_emoji) x.Remark = trim(removeEmoji(x.Remark)); nodeRename(x, ext.rename_array, ext); if(ext.add_emoji) x.Remark = addEmoji(x, ext.emoji_array, ext); }); if(ext.sort_flag) { bool failed = true; if(ext.sort_script.size() && ext.authorized) { std::string script = ext.sort_script; if(startsWith(script, "path:")) script = fileGet(script.substr(5), false); script_safe_runner(ext.js_runtime, ext.js_context, [&](qjs::Context &ctx) { try { ctx.eval(script); auto compare = (std::function<int(const Proxy&, const Proxy&)>) ctx.eval("compare"); auto comparer = [&](const Proxy &a, const Proxy &b) { if(a.Type == ProxyType::Unknown) return 1; if(b.Type == ProxyType::Unknown) return 0; return compare(a, b); }; std::stable_sort(nodes.begin(), nodes.end(), comparer); failed = false; } catch(qjs::exception) { script_print_stack(ctx); } }, global.scriptCleanContext); } if(failed) std::stable_sort(nodes.begin(), nodes.end(), [](const Proxy &a, const Proxy &b) { return a.Remark < b.Remark; }); } }
18,342
C++
.cpp
491
26.405295
280
0.530491
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,461
ruleconvert.cpp
tindy2013_subconverter/src/generator/config/ruleconvert.cpp
#include <string> #include "handler/settings.h" #include "utils/logger.h" #include "utils/network.h" #include "utils/regexp.h" #include "utils/string.h" #include "utils/rapidjson_extra.h" #include "subexport.h" /// rule type lists #define basic_types "DOMAIN", "DOMAIN-SUFFIX", "DOMAIN-KEYWORD", "IP-CIDR", "SRC-IP-CIDR", "GEOIP", "MATCH", "FINAL" string_array ClashRuleTypes = {basic_types, "IP-CIDR6", "SRC-PORT", "DST-PORT", "PROCESS-NAME"}; string_array Surge2RuleTypes = {basic_types, "IP-CIDR6", "USER-AGENT", "URL-REGEX", "PROCESS-NAME", "IN-PORT", "DEST-PORT", "SRC-IP"}; string_array SurgeRuleTypes = {basic_types, "IP-CIDR6", "USER-AGENT", "URL-REGEX", "AND", "OR", "NOT", "PROCESS-NAME", "IN-PORT", "DEST-PORT", "SRC-IP"}; string_array QuanXRuleTypes = {basic_types, "USER-AGENT", "HOST", "HOST-SUFFIX", "HOST-KEYWORD"}; string_array SurfRuleTypes = {basic_types, "IP-CIDR6", "PROCESS-NAME", "IN-PORT", "DEST-PORT", "SRC-IP"}; string_array SingBoxRuleTypes = {basic_types, "IP-VERSION", "INBOUND", "PROTOCOL", "NETWORK", "GEOSITE", "SRC-GEOIP", "DOMAIN-REGEX", "PROCESS-NAME", "PROCESS-PATH", "PACKAGE-NAME", "PORT", "PORT-RANGE", "SRC-PORT", "SRC-PORT-RANGE", "USER", "USER-ID"}; std::string convertRuleset(const std::string &content, int type) { /// Target: Surge type,pattern[,flag] /// Source: QuanX type,pattern[,group] /// Clash payload:\n - 'ipcidr/domain/classic(Surge-like)' std::string output, strLine; if(type == RULESET_SURGE) return content; if(regFind(content, "^payload:\\r?\\n")) /// Clash { output = regReplace(regReplace(content, "payload:\\r?\\n", "", true), R"(\s?^\s*-\s+('|"?)(.*)\1$)", "\n$2", true); if(type == RULESET_CLASH_CLASSICAL) /// classical type return output; std::stringstream ss; ss << output; char delimiter = getLineBreak(output); output.clear(); string_size pos, lineSize; while(getline(ss, strLine, delimiter)) { strLine = trim(strLine); lineSize = strLine.size(); if(lineSize && strLine[lineSize - 1] == '\r') //remove line break strLine.erase(--lineSize); if(strFind(strLine, "//")) { strLine.erase(strLine.find("//")); strLine = trimWhitespace(strLine); } if(!strLine.empty() && (strLine[0] != ';' && strLine[0] != '#' && !(lineSize >= 2 && strLine[0] == '/' && strLine[1] == '/'))) { pos = strLine.find('/'); if(pos != std::string::npos) /// ipcidr { if(isIPv4(strLine.substr(0, pos))) output += "IP-CIDR,"; else output += "IP-CIDR6,"; } else { if(strLine[0] == '.' || (lineSize >= 2 && strLine[0] == '+' && strLine[1] == '.')) /// suffix { bool keyword_flag = false; while(endsWith(strLine, ".*")) { keyword_flag = true; strLine.erase(strLine.size() - 2); } output += "DOMAIN-"; if(keyword_flag) output += "KEYWORD,"; else output += "SUFFIX,"; strLine.erase(0, 2 - (strLine[0] == '.')); } else output += "DOMAIN,"; } } output += strLine; output += '\n'; } return output; } else /// QuanX { output = regReplace(regReplace(content, "^(?i:host)", "DOMAIN", true), "^(?i:ip6-cidr)", "IP-CIDR6", true); //translate type output = regReplace(output, "^((?i:DOMAIN(?:-(?:SUFFIX|KEYWORD))?|IP-CIDR6?|USER-AGENT),)\\s*?(\\S*?)(?:,(?!no-resolve).*?)(,no-resolve)?$", "\\U$1\\E$2${3:-}", true); //remove group return output; } } static std::string transformRuleToCommon(string_view_array &temp, const std::string &input, const std::string &group, bool no_resolve_only = false) { temp.clear(); std::string strLine; split(temp, input, ','); if(temp.size() < 2) { strLine = temp[0]; strLine += ","; strLine += group; } else { strLine = temp[0]; strLine += ","; strLine += temp[1]; strLine += ","; strLine += group; if(temp.size() > 2 && (!no_resolve_only || temp[2] == "no-resolve")) { strLine += ","; strLine += temp[2]; } } return strLine; } void rulesetToClash(YAML::Node &base_rule, std::vector<RulesetContent> &ruleset_content_array, bool overwrite_original_rules, bool new_field_name) { string_array allRules; std::string rule_group, retrieved_rules, strLine; std::stringstream strStrm; const std::string field_name = new_field_name ? "rules" : "Rule"; YAML::Node rules; size_t total_rules = 0; if(!overwrite_original_rules && base_rule[field_name].IsDefined()) rules = base_rule[field_name]; std::vector<std::string_view> temp(4); for(RulesetContent &x : ruleset_content_array) { if(global.maxAllowedRules && total_rules > global.maxAllowedRules) break; rule_group = x.rule_group; retrieved_rules = x.rule_content.get(); if(retrieved_rules.empty()) { writeLog(0, "Failed to fetch ruleset or ruleset is empty: '" + x.rule_path + "'!", LOG_LEVEL_WARNING); continue; } if(startsWith(retrieved_rules, "[]")) { strLine = retrieved_rules.substr(2); if(startsWith(strLine, "FINAL")) strLine.replace(0, 5, "MATCH"); strLine = transformRuleToCommon(temp, strLine, rule_group); allRules.emplace_back(strLine); total_rules++; continue; } retrieved_rules = convertRuleset(retrieved_rules, x.rule_type); char delimiter = getLineBreak(retrieved_rules); strStrm.clear(); strStrm<<retrieved_rules; std::string::size_type lineSize; while(getline(strStrm, strLine, delimiter)) { if(global.maxAllowedRules && total_rules > global.maxAllowedRules) break; strLine = trimWhitespace(strLine, true, true); //remove whitespaces lineSize = strLine.size(); if(!lineSize || strLine[0] == ';' || strLine[0] == '#' || (lineSize >= 2 && strLine[0] == '/' && strLine[1] == '/')) //empty lines and comments are ignored continue; if(std::none_of(ClashRuleTypes.begin(), ClashRuleTypes.end(), [strLine](const std::string& type){return startsWith(strLine, type);})) continue; if(strFind(strLine, "//")) { strLine.erase(strLine.find("//")); strLine = trimWhitespace(strLine); } strLine = transformRuleToCommon(temp, strLine, rule_group); allRules.emplace_back(strLine); } } for(std::string &x : allRules) { rules.push_back(x); } base_rule[field_name] = rules; } std::string rulesetToClashStr(YAML::Node &base_rule, std::vector<RulesetContent> &ruleset_content_array, bool overwrite_original_rules, bool new_field_name) { std::string rule_group, retrieved_rules, strLine; std::stringstream strStrm; const std::string field_name = new_field_name ? "rules" : "Rule"; std::string output_content = "\n" + field_name + ":\n"; size_t total_rules = 0; if(!overwrite_original_rules && base_rule[field_name].IsDefined()) { for(size_t i = 0; i < base_rule[field_name].size(); i++) output_content += " - " + safe_as<std::string>(base_rule[field_name][i]) + "\n"; } base_rule.remove(field_name); string_view_array temp(4); for(RulesetContent &x : ruleset_content_array) { if(global.maxAllowedRules && total_rules > global.maxAllowedRules) break; rule_group = x.rule_group; retrieved_rules = x.rule_content.get(); if(retrieved_rules.empty()) { writeLog(0, "Failed to fetch ruleset or ruleset is empty: '" + x.rule_path + "'!", LOG_LEVEL_WARNING); continue; } if(startsWith(retrieved_rules, "[]")) { strLine = retrieved_rules.substr(2); if(startsWith(strLine, "FINAL")) strLine.replace(0, 5, "MATCH"); strLine = transformRuleToCommon(temp, strLine, rule_group); output_content += " - " + strLine + "\n"; total_rules++; continue; } retrieved_rules = convertRuleset(retrieved_rules, x.rule_type); char delimiter = getLineBreak(retrieved_rules); strStrm.clear(); strStrm<<retrieved_rules; std::string::size_type lineSize; while(getline(strStrm, strLine, delimiter)) { if(global.maxAllowedRules && total_rules > global.maxAllowedRules) break; strLine = trimWhitespace(strLine, true, true); //remove whitespaces lineSize = strLine.size(); if(!lineSize || strLine[0] == ';' || strLine[0] == '#' || (lineSize >= 2 && strLine[0] == '/' && strLine[1] == '/')) //empty lines and comments are ignored continue; if(std::none_of(ClashRuleTypes.begin(), ClashRuleTypes.end(), [strLine](const std::string& type){ return startsWith(strLine, type); })) continue; if(strFind(strLine, "//")) { strLine.erase(strLine.find("//")); strLine = trimWhitespace(strLine); } strLine = transformRuleToCommon(temp, strLine, rule_group); output_content += " - " + strLine + "\n"; total_rules++; } } return output_content; } void rulesetToSurge(INIReader &base_rule, std::vector<RulesetContent> &ruleset_content_array, int surge_ver, bool overwrite_original_rules, const std::string &remote_path_prefix) { string_array allRules; std::string rule_group, rule_path, rule_path_typed, retrieved_rules, strLine; std::stringstream strStrm; size_t total_rules = 0; switch(surge_ver) //other version: -3 for Surfboard, -4 for Loon { case 0: base_rule.set_current_section("RoutingRule"); //Mellow break; case -1: base_rule.set_current_section("filter_local"); //Quantumult X break; case -2: base_rule.set_current_section("TCP"); //Quantumult break; default: base_rule.set_current_section("Rule"); } if(overwrite_original_rules) { base_rule.erase_section(); switch(surge_ver) { case -1: base_rule.erase_section("filter_remote"); break; case -4: base_rule.erase_section("Remote Rule"); break; default: break; } } const std::string rule_match_regex = "^(.*?,.*?)(,.*)(,.*)$"; string_view_array temp(4); for(RulesetContent &x : ruleset_content_array) { if(global.maxAllowedRules && total_rules > global.maxAllowedRules) break; rule_group = x.rule_group; rule_path = x.rule_path; rule_path_typed = x.rule_path_typed; if(rule_path.empty()) { strLine = x.rule_content.get().substr(2); if(strLine == "MATCH") strLine = "FINAL"; if(surge_ver == -1 || surge_ver == -2) { strLine = transformRuleToCommon(temp, strLine, rule_group, true); } else { if(!startsWith(strLine, "AND") && !startsWith(strLine, "OR") && !startsWith(strLine, "NOT")) strLine = transformRuleToCommon(temp, strLine, rule_group); } strLine = replaceAllDistinct(strLine, ",,", ","); allRules.emplace_back(strLine); total_rules++; continue; } else { 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); continue; } if(fileExist(rule_path)) { if(surge_ver > 2 && !remote_path_prefix.empty()) { strLine = "RULE-SET," + remote_path_prefix + "/getruleset?type=1&url=" + urlSafeBase64Encode(rule_path_typed) + "," + rule_group; if(x.update_interval) strLine += ",update-interval=" + std::to_string(x.update_interval); allRules.emplace_back(strLine); continue; } else if(surge_ver == -1 && !remote_path_prefix.empty()) { 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); continue; } else if(surge_ver == -4 && !remote_path_prefix.empty()) { strLine = remote_path_prefix + "/getruleset?type=1&url=" + urlSafeBase64Encode(rule_path_typed) + "," + rule_group; base_rule.set("Remote Rule", "{NONAME}", strLine); continue; } } else if(isLink(rule_path)) { if(surge_ver > 2) { if(x.rule_type != RULESET_SURGE) { if(!remote_path_prefix.empty()) strLine = "RULE-SET," + remote_path_prefix + "/getruleset?type=1&url=" + urlSafeBase64Encode(rule_path_typed) + "," + rule_group; else continue; } else strLine = "RULE-SET," + rule_path + "," + rule_group; if(x.update_interval) strLine += ",update-interval=" + std::to_string(x.update_interval); allRules.emplace_back(strLine); continue; } else if(surge_ver == -1 && !remote_path_prefix.empty()) { 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); continue; } else if(surge_ver == -4) { strLine = rule_path + "," + rule_group; base_rule.set("Remote Rule", "{NONAME}", strLine); continue; } } else continue; retrieved_rules = x.rule_content.get(); if(retrieved_rules.empty()) { writeLog(0, "Failed to fetch ruleset or ruleset is empty: '" + x.rule_path + "'!", LOG_LEVEL_WARNING); continue; } retrieved_rules = convertRuleset(retrieved_rules, x.rule_type); char delimiter = getLineBreak(retrieved_rules); strStrm.clear(); strStrm<<retrieved_rules; std::string::size_type lineSize; while(getline(strStrm, strLine, delimiter)) { if(global.maxAllowedRules && total_rules > global.maxAllowedRules) break; strLine = trimWhitespace(strLine, true, true); lineSize = strLine.size(); if(!lineSize || strLine[0] == ';' || strLine[0] == '#' || (lineSize >= 2 && strLine[0] == '/' && strLine[1] == '/')) //empty lines and comments are ignored continue; /// remove unsupported types switch(surge_ver) { case -2: if(startsWith(strLine, "IP-CIDR6")) continue; [[fallthrough]]; case -1: if(!std::any_of(QuanXRuleTypes.begin(), QuanXRuleTypes.end(), [strLine](const std::string& type){return startsWith(strLine, type);})) continue; break; case -3: if(!std::any_of(SurfRuleTypes.begin(), SurfRuleTypes.end(), [strLine](const std::string& type){return startsWith(strLine, type);})) continue; break; default: if(surge_ver > 2) { if(!std::any_of(SurgeRuleTypes.begin(), SurgeRuleTypes.end(), [strLine](const std::string& type){return startsWith(strLine, type);})) continue; } else { if(!std::any_of(Surge2RuleTypes.begin(), Surge2RuleTypes.end(), [strLine](const std::string& type){return startsWith(strLine, type);})) continue; } } if(strFind(strLine, "//")) { strLine.erase(strLine.find("//")); strLine = trimWhitespace(strLine); } if(surge_ver == -1 || surge_ver == -2) { if(startsWith(strLine, "IP-CIDR6")) strLine.replace(0, 8, "IP6-CIDR"); strLine = transformRuleToCommon(temp, strLine, rule_group, true); } else { if(!startsWith(strLine, "AND") && !startsWith(strLine, "OR") && !startsWith(strLine, "NOT")) strLine = transformRuleToCommon(temp, strLine, rule_group); } allRules.emplace_back(strLine); total_rules++; } } } for(std::string &x : allRules) { base_rule.set("{NONAME}", x); } } static rapidjson::Value transformRuleToSingBox(std::vector<std::string_view> &args, const std::string& rule, const std::string &group, rapidjson::MemoryPoolAllocator<>& allocator) { args.clear(); split(args, rule, ','); if (args.size() < 2) return rapidjson::Value(rapidjson::kObjectType); auto type = toLower(std::string(args[0])); auto value = toLower(std::string(args[1])); // std::string_view option; // if (args.size() >= 3) option = args[2]; rapidjson::Value rule_obj(rapidjson::kObjectType); type = replaceAllDistinct(type, "-", "_"); type = replaceAllDistinct(type, "ip_cidr6", "ip_cidr"); type = replaceAllDistinct(type, "src_", "source_"); if (type == "match" || type == "final") { rule_obj.AddMember("outbound", rapidjson::Value(value.data(), value.size(), allocator), allocator); } else { rule_obj.AddMember(rapidjson::Value(type.c_str(), allocator), rapidjson::Value(value.data(), value.size(), allocator), allocator); rule_obj.AddMember("outbound", rapidjson::Value(group.c_str(), allocator), allocator); } return rule_obj; } static void appendSingBoxRule(std::vector<std::string_view> &args, rapidjson::Value &rules, const std::string& rule, rapidjson::MemoryPoolAllocator<>& allocator) { using namespace rapidjson_ext; args.clear(); split(args, rule, ','); if (args.size() < 2) return; auto type = args[0]; // std::string_view option; // if (args.size() >= 3) option = args[2]; if (none_of(SingBoxRuleTypes, [&](const std::string& t){ return type == t; })) return; auto realType = toLower(std::string(type)); auto value = toLower(std::string(args[1])); realType = replaceAllDistinct(realType, "-", "_"); realType = replaceAllDistinct(realType, "ip_cidr6", "ip_cidr"); rules | AppendToArray(realType.c_str(), rapidjson::Value(value.c_str(), value.size(), allocator), allocator); } void rulesetToSingBox(rapidjson::Document &base_rule, std::vector<RulesetContent> &ruleset_content_array, bool overwrite_original_rules) { using namespace rapidjson_ext; std::string rule_group, retrieved_rules, strLine, final; std::stringstream strStrm; size_t total_rules = 0; auto &allocator = base_rule.GetAllocator(); rapidjson::Value rules(rapidjson::kArrayType); if (!overwrite_original_rules) { if (base_rule.HasMember("route") && base_rule["route"].HasMember("rules") && base_rule["route"]["rules"].IsArray()) rules.Swap(base_rule["route"]["rules"]); } if (global.singBoxAddClashModes) { auto global_object = buildObject(allocator, "clash_mode", "Global", "outbound", "GLOBAL"); auto direct_object = buildObject(allocator, "clash_mode", "Direct", "outbound", "DIRECT"); rules.PushBack(global_object, allocator); rules.PushBack(direct_object, allocator); } auto dns_object = buildObject(allocator, "protocol", "dns", "outbound", "dns-out"); rules.PushBack(dns_object, allocator); std::vector<std::string_view> temp(4); for(RulesetContent &x : ruleset_content_array) { if(global.maxAllowedRules && total_rules > global.maxAllowedRules) break; rule_group = x.rule_group; retrieved_rules = x.rule_content.get(); if(retrieved_rules.empty()) { writeLog(0, "Failed to fetch ruleset or ruleset is empty: '" + x.rule_path + "'!", LOG_LEVEL_WARNING); continue; } if(startsWith(retrieved_rules, "[]")) { strLine = retrieved_rules.substr(2); if(startsWith(strLine, "FINAL") || startsWith(strLine, "MATCH")) { final = rule_group; continue; } rules.PushBack(transformRuleToSingBox(temp, strLine, rule_group, allocator), allocator); total_rules++; continue; } retrieved_rules = convertRuleset(retrieved_rules, x.rule_type); char delimiter = getLineBreak(retrieved_rules); strStrm.clear(); strStrm<<retrieved_rules; std::string::size_type lineSize; rapidjson::Value rule(rapidjson::kObjectType); while(getline(strStrm, strLine, delimiter)) { if(global.maxAllowedRules && total_rules > global.maxAllowedRules) break; strLine = trimWhitespace(strLine, true, true); //remove whitespaces lineSize = strLine.size(); if(!lineSize || strLine[0] == ';' || strLine[0] == '#' || (lineSize >= 2 && strLine[0] == '/' && strLine[1] == '/')) //empty lines and comments are ignored continue; if(strFind(strLine, "//")) { strLine.erase(strLine.find("//")); strLine = trimWhitespace(strLine); } appendSingBoxRule(temp, rule, strLine, allocator); } if (rule.ObjectEmpty()) continue; rule.AddMember("outbound", rapidjson::Value(rule_group.c_str(), allocator), allocator); rules.PushBack(rule, allocator); } if (!base_rule.HasMember("route")) base_rule.AddMember("route", rapidjson::Value(rapidjson::kObjectType), allocator); auto finalValue = rapidjson::Value(final.c_str(), allocator); base_rule["route"] | AddMemberOrReplace("rules", rules, allocator) | AddMemberOrReplace("final", finalValue, allocator); }
24,379
C++
.cpp
558
32.137993
253
0.5383
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,462
subexport.cpp
tindy2013_subconverter/src/generator/config/subexport.cpp
#include <algorithm> #include <iostream> #include <numeric> #include <cmath> #include <climits> #include "config/regmatch.h" #include "generator/config/subexport.h" #include "generator/template/templates.h" #include "handler/settings.h" #include "parser/config/proxy.h" #include "script/script_quickjs.h" #include "utils/bitwise.h" #include "utils/file_extra.h" #include "utils/ini_reader/ini_reader.h" #include "utils/logger.h" #include "utils/network.h" #include "utils/rapidjson_extra.h" #include "utils/regexp.h" #include "utils/stl_extra.h" #include "utils/urlencode.h" #include "utils/yamlcpp_extra.h" #include "nodemanip.h" #include "ruleconvert.h" extern string_array ss_ciphers, ssr_ciphers; const string_array clashr_protocols = {"origin", "auth_sha1_v4", "auth_aes128_md5", "auth_aes128_sha1", "auth_chain_a", "auth_chain_b"}; const string_array clashr_obfs = {"plain", "http_simple", "http_post", "random_head", "tls1.2_ticket_auth", "tls1.2_ticket_fastauth"}; const string_array clash_ssr_ciphers = {"rc4-md5", "aes-128-ctr", "aes-192-ctr", "aes-256-ctr", "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", "chacha20-ietf", "xchacha20", "none"}; std::string vmessLinkConstruct(const std::string &remarks, const std::string &add, const std::string &port, const std::string &type, const std::string &id, const std::string &aid, const std::string &net, const std::string &path, const std::string &host, const std::string &tls) { rapidjson::StringBuffer sb; rapidjson::Writer<rapidjson::StringBuffer> writer(sb); writer.StartObject(); writer.Key("v"); writer.String("2"); writer.Key("ps"); writer.String(remarks.data()); writer.Key("add"); writer.String(add.data()); writer.Key("port"); writer.String(port.data()); writer.Key("type"); writer.String(type.empty() ? "none" : type.data()); writer.Key("id"); writer.String(id.data()); writer.Key("aid"); writer.String(aid.data()); writer.Key("net"); writer.String(net.empty() ? "tcp" : net.data()); writer.Key("path"); writer.String(path.data()); writer.Key("host"); writer.String(host.data()); writer.Key("tls"); writer.String(tls.data()); writer.EndObject(); return sb.GetString(); } bool matchRange(const std::string &range, int target) { string_array vArray = split(range, ","); bool match = false; std::string range_begin_str, range_end_str; int range_begin, range_end; static const std::string reg_num = "-?\\d+", reg_range = "(\\d+)-(\\d+)", reg_not = "\\!-?(\\d+)", reg_not_range = "\\!(\\d+)-(\\d+)", reg_less = "(\\d+)-", reg_more = "(\\d+)\\+"; for(std::string &x : vArray) { if(regMatch(x, reg_num)) { if(to_int(x, INT_MAX) == target) match = true; } else if(regMatch(x, reg_range)) { regGetMatch(x, reg_range, 3, 0, &range_begin_str, &range_end_str); range_begin = to_int(range_begin_str, INT_MAX); range_end = to_int(range_end_str, INT_MIN); if(target >= range_begin && target <= range_end) match = true; } else if(regMatch(x, reg_not)) { match = true; if(to_int(regReplace(x, reg_not, "$1"), INT_MAX) == target) match = false; } else if(regMatch(x, reg_not_range)) { match = true; regGetMatch(x, reg_range, 3, 0, &range_begin_str, &range_end_str); range_begin = to_int(range_begin_str, INT_MAX); range_end = to_int(range_end_str, INT_MIN); if(target >= range_begin && target <= range_end) match = false; } else if(regMatch(x, reg_less)) { if(to_int(regReplace(x, reg_less, "$1"), INT_MAX) >= target) match = true; } else if(regMatch(x, reg_more)) { if(to_int(regReplace(x, reg_more, "$1"), INT_MIN) <= target) match = true; } } return match; } bool applyMatcher(const std::string &rule, std::string &real_rule, const Proxy &node) { std::string target, ret_real_rule; static const std::string groupid_regex = R"(^!!(?:GROUPID|INSERT)=([\d\-+!,]+)(?:!!(.*))?$)", group_regex = R"(^!!(?:GROUP)=(.+?)(?:!!(.*))?$)"; static const std::string type_regex = R"(^!!(?:TYPE)=(.+?)(?:!!(.*))?$)", port_regex = R"(^!!(?:PORT)=(.+?)(?:!!(.*))?$)", server_regex = R"(^!!(?:SERVER)=(.+?)(?:!!(.*))?$)"; static const std::map<ProxyType, const char *> types = {{ProxyType::Shadowsocks, "SS"}, {ProxyType::ShadowsocksR, "SSR"}, {ProxyType::VMess, "VMESS"}, {ProxyType::Trojan, "TROJAN"}, {ProxyType::Snell, "SNELL"}, {ProxyType::HTTP, "HTTP"}, {ProxyType::HTTPS, "HTTPS"}, {ProxyType::SOCKS5, "SOCKS5"}, {ProxyType::WireGuard, "WIREGUARD"}}; if(startsWith(rule, "!!GROUP=")) { regGetMatch(rule, group_regex, 3, 0, &target, &ret_real_rule); real_rule = ret_real_rule; return regFind(node.Group, target); } else if(startsWith(rule, "!!GROUPID=") || startsWith(rule, "!!INSERT=")) { int dir = startsWith(rule, "!!INSERT=") ? -1 : 1; regGetMatch(rule, groupid_regex, 3, 0, &target, &ret_real_rule); real_rule = ret_real_rule; return matchRange(target, dir * node.GroupId); } else if(startsWith(rule, "!!TYPE=")) { regGetMatch(rule, type_regex, 3, 0, &target, &ret_real_rule); real_rule = ret_real_rule; if(node.Type == ProxyType::Unknown) return false; return regMatch(types.at(node.Type), target); } else if(startsWith(rule, "!!PORT=")) { regGetMatch(rule, port_regex, 3, 0, &target, &ret_real_rule); real_rule = ret_real_rule; return matchRange(target, node.Port); } else if(startsWith(rule, "!!SERVER=")) { regGetMatch(rule, server_regex, 3, 0, &target, &ret_real_rule); real_rule = ret_real_rule; return regFind(node.Hostname, target); } else real_rule = rule; return true; } void processRemark(std::string &remark, const string_array &remarks_list, bool proc_comma = true) { // Replace every '=' with '-' in the remark string to avoid parse errors from the clients. // Surge is tested to yield an error when handling '=' in the remark string, // not sure if other clients have the same problem. std::replace(remark.begin(), remark.end(), '=', '-'); if(proc_comma) { if(remark.find(',') != std::string::npos) { remark.insert(0, "\""); remark.append("\""); } } std::string tempRemark = remark; int cnt = 2; while(std::find(remarks_list.cbegin(), remarks_list.cend(), tempRemark) != remarks_list.cend()) { tempRemark = remark + " " + std::to_string(cnt); cnt++; } remark = tempRemark; } void groupGenerate(const std::string &rule, std::vector<Proxy> &nodelist, string_array &filtered_nodelist, bool add_direct, extra_settings &ext) { std::string real_rule; if(startsWith(rule, "[]") && add_direct) { filtered_nodelist.emplace_back(rule.substr(2)); } #ifndef NO_JS_RUNTIME else if(startsWith(rule, "script:") && ext.authorized) { script_safe_runner(ext.js_runtime, ext.js_context, [&](qjs::Context &ctx){ std::string script = fileGet(rule.substr(7), true); try { ctx.eval(script); auto filter = (std::function<std::string(const std::vector<Proxy>&)>) ctx.eval("filter"); std::string result_list = filter(nodelist); filtered_nodelist = split(regTrim(result_list), "\n"); } catch (qjs::exception) { script_print_stack(ctx); } }, global.scriptCleanContext); } #endif // NO_JS_RUNTIME else { for(Proxy &x : nodelist) { if(applyMatcher(rule, real_rule, x) && (real_rule.empty() || regFind(x.Remark, real_rule)) && std::find(filtered_nodelist.begin(), filtered_nodelist.end(), x.Remark) == filtered_nodelist.end()) filtered_nodelist.emplace_back(x.Remark); } } } void proxyToClash(std::vector<Proxy> &nodes, YAML::Node &yamlnode, const ProxyGroupConfigs &extra_proxy_group, bool clashR, extra_settings &ext) { YAML::Node proxies, original_groups; std::vector<Proxy> nodelist; string_array remarks_list; /// proxies style bool proxy_block = false, proxy_compact = false, group_block = false, group_compact = false; switch(hash_(ext.clash_proxies_style)) { case "block"_hash: proxy_block = true; break; default: case "flow"_hash: break; case "compact"_hash: proxy_compact = true; break; } switch(hash_(ext.clash_proxy_groups_style)) { case "block"_hash: group_block = true; break; default: case "flow"_hash: break; case "compact"_hash: group_compact = true; break; } for(Proxy &x : nodes) { YAML::Node singleproxy; std::string type = getProxyTypeName(x.Type); std::string pluginopts = replaceAllDistinct(x.PluginOption, ";", "&"); if(ext.append_proxy_type) x.Remark = "[" + type + "] " + x.Remark; processRemark(x.Remark, remarks_list, false); tribool udp = ext.udp; tribool scv = ext.skip_cert_verify; udp.define(x.UDP); scv.define(x.AllowInsecure); singleproxy["name"] = x.Remark; singleproxy["server"] = x.Hostname; singleproxy["port"] = x.Port; switch(x.Type) { case ProxyType::Shadowsocks: //latest clash core removed support for chacha20 encryption if(ext.filter_deprecated && x.EncryptMethod == "chacha20") continue; singleproxy["type"] = "ss"; singleproxy["cipher"] = x.EncryptMethod; singleproxy["password"] = x.Password; if(std::all_of(x.Password.begin(), x.Password.end(), ::isdigit) && !x.Password.empty()) singleproxy["password"].SetTag("str"); switch(hash_(x.Plugin)) { case "simple-obfs"_hash: case "obfs-local"_hash: singleproxy["plugin"] = "obfs"; singleproxy["plugin-opts"]["mode"] = urlDecode(getUrlArg(pluginopts, "obfs")); singleproxy["plugin-opts"]["host"] = urlDecode(getUrlArg(pluginopts, "obfs-host")); break; case "v2ray-plugin"_hash: singleproxy["plugin"] = "v2ray-plugin"; singleproxy["plugin-opts"]["mode"] = getUrlArg(pluginopts, "mode"); singleproxy["plugin-opts"]["host"] = getUrlArg(pluginopts, "host"); singleproxy["plugin-opts"]["path"] = getUrlArg(pluginopts, "path"); singleproxy["plugin-opts"]["tls"] = pluginopts.find("tls") != std::string::npos; singleproxy["plugin-opts"]["mux"] = pluginopts.find("mux") != std::string::npos; if(!scv.is_undef()) singleproxy["plugin-opts"]["skip-cert-verify"] = scv.get(); break; } break; case ProxyType::VMess: singleproxy["type"] = "vmess"; singleproxy["uuid"] = x.UserId; singleproxy["alterId"] = x.AlterId; singleproxy["cipher"] = x.EncryptMethod; singleproxy["tls"] = x.TLSSecure; if(!scv.is_undef()) singleproxy["skip-cert-verify"] = scv.get(); if(!x.ServerName.empty()) singleproxy["servername"] = x.ServerName; switch(hash_(x.TransferProtocol)) { case "tcp"_hash: break; case "ws"_hash: singleproxy["network"] = x.TransferProtocol; if(ext.clash_new_field_name) { singleproxy["ws-opts"]["path"] = x.Path; if(!x.Host.empty()) singleproxy["ws-opts"]["headers"]["Host"] = x.Host; if(!x.Edge.empty()) singleproxy["ws-opts"]["headers"]["Edge"] = x.Edge; } else { singleproxy["ws-path"] = x.Path; if(!x.Host.empty()) singleproxy["ws-headers"]["Host"] = x.Host; if(!x.Edge.empty()) singleproxy["ws-headers"]["Edge"] = x.Edge; } break; case "http"_hash: singleproxy["network"] = x.TransferProtocol; singleproxy["http-opts"]["method"] = "GET"; singleproxy["http-opts"]["path"].push_back(x.Path); if(!x.Host.empty()) singleproxy["http-opts"]["headers"]["Host"].push_back(x.Host); if(!x.Edge.empty()) singleproxy["http-opts"]["headers"]["Edge"].push_back(x.Edge); break; case "h2"_hash: singleproxy["network"] = x.TransferProtocol; singleproxy["h2-opts"]["path"] = x.Path; if(!x.Host.empty()) singleproxy["h2-opts"]["host"].push_back(x.Host); break; case "grpc"_hash: singleproxy["network"] = x.TransferProtocol; singleproxy["servername"] = x.Host; singleproxy["grpc-opts"]["grpc-service-name"] = x.Path; break; default: continue; } break; case ProxyType::ShadowsocksR: //ignoring all nodes with unsupported obfs, protocols and encryption if(ext.filter_deprecated) { if(!clashR && std::find(clash_ssr_ciphers.cbegin(), clash_ssr_ciphers.cend(), x.EncryptMethod) == clash_ssr_ciphers.cend()) continue; if(std::find(clashr_protocols.cbegin(), clashr_protocols.cend(), x.Protocol) == clashr_protocols.cend()) continue; if(std::find(clashr_obfs.cbegin(), clashr_obfs.cend(), x.OBFS) == clashr_obfs.cend()) continue; } singleproxy["type"] = "ssr"; singleproxy["cipher"] = x.EncryptMethod == "none" ? "dummy" : x.EncryptMethod; singleproxy["password"] = x.Password; if(std::all_of(x.Password.begin(), x.Password.end(), ::isdigit) && !x.Password.empty()) singleproxy["password"].SetTag("str"); singleproxy["protocol"] = x.Protocol; singleproxy["obfs"] = x.OBFS; if(clashR) { singleproxy["protocolparam"] = x.ProtocolParam; singleproxy["obfsparam"] = x.OBFSParam; } else { singleproxy["protocol-param"] = x.ProtocolParam; singleproxy["obfs-param"] = x.OBFSParam; } break; case ProxyType::SOCKS5: singleproxy["type"] = "socks5"; if(!x.Username.empty()) singleproxy["username"] = x.Username; if(!x.Password.empty()) { singleproxy["password"] = x.Password; if(std::all_of(x.Password.begin(), x.Password.end(), ::isdigit)) singleproxy["password"].SetTag("str"); } if(!scv.is_undef()) singleproxy["skip-cert-verify"] = scv.get(); break; case ProxyType::HTTP: case ProxyType::HTTPS: singleproxy["type"] = "http"; if(!x.Username.empty()) singleproxy["username"] = x.Username; if(!x.Password.empty()) { singleproxy["password"] = x.Password; if(std::all_of(x.Password.begin(), x.Password.end(), ::isdigit)) singleproxy["password"].SetTag("str"); } singleproxy["tls"] = x.TLSSecure; if(!scv.is_undef()) singleproxy["skip-cert-verify"] = scv.get(); break; case ProxyType::Trojan: singleproxy["type"] = "trojan"; singleproxy["password"] = x.Password; if(!x.Host.empty()) singleproxy["sni"] = x.Host; if(std::all_of(x.Password.begin(), x.Password.end(), ::isdigit) && !x.Password.empty()) singleproxy["password"].SetTag("str"); if(!scv.is_undef()) singleproxy["skip-cert-verify"] = scv.get(); switch(hash_(x.TransferProtocol)) { case "tcp"_hash: break; case "grpc"_hash: singleproxy["network"] = x.TransferProtocol; if(!x.Path.empty()) singleproxy["grpc-opts"]["grpc-service-name"] = x.Path; break; case "ws"_hash: singleproxy["network"] = x.TransferProtocol; singleproxy["ws-opts"]["path"] = x.Path; if(!x.Host.empty()) singleproxy["ws-opts"]["headers"]["Host"] = x.Host; break; } break; case ProxyType::Snell: if (x.SnellVersion >= 4) continue; singleproxy["type"] = "snell"; singleproxy["psk"] = x.Password; if(x.SnellVersion != 0) singleproxy["version"] = x.SnellVersion; if(!x.OBFS.empty()) { singleproxy["obfs-opts"]["mode"] = x.OBFS; if(!x.Host.empty()) singleproxy["obfs-opts"]["host"] = x.Host; } if(std::all_of(x.Password.begin(), x.Password.end(), ::isdigit) && !x.Password.empty()) singleproxy["password"].SetTag("str"); break; case ProxyType::WireGuard: singleproxy["type"] = "wireguard"; singleproxy["public-key"] = x.PublicKey; singleproxy["private-key"] = x.PrivateKey; singleproxy["ip"] = x.SelfIP; if(!x.SelfIPv6.empty()) singleproxy["ipv6"] = x.SelfIPv6; if(!x.PreSharedKey.empty()) singleproxy["preshared-key"] = x.PreSharedKey; if(!x.DnsServers.empty()) singleproxy["dns"] = x.DnsServers; if(x.Mtu > 0) singleproxy["mtu"] = x.Mtu; break; default: continue; } // UDP is not supported yet in clash using snell // sees in https://dreamacro.github.io/clash/configuration/outbound.html#snell if(udp && x.Type != ProxyType::Snell) singleproxy["udp"] = true; if(proxy_block) singleproxy.SetStyle(YAML::EmitterStyle::Block); else singleproxy.SetStyle(YAML::EmitterStyle::Flow); proxies.push_back(singleproxy); remarks_list.emplace_back(x.Remark); nodelist.emplace_back(x); } if(proxy_compact) proxies.SetStyle(YAML::EmitterStyle::Flow); if(ext.nodelist) { YAML::Node provider; provider["proxies"] = proxies; yamlnode.reset(provider); return; } if(ext.clash_new_field_name) yamlnode["proxies"] = proxies; else yamlnode["Proxy"] = proxies; for(const ProxyGroupConfig &x : extra_proxy_group) { YAML::Node singlegroup; string_array filtered_nodelist; singlegroup["name"] = x.Name; if (x.Type == ProxyGroupType::Smart) singlegroup["type"] = "url-test"; else singlegroup["type"] = x.TypeStr(); switch(x.Type) { case ProxyGroupType::Select: case ProxyGroupType::Relay: break; case ProxyGroupType::LoadBalance: singlegroup["strategy"] = x.StrategyStr(); [[fallthrough]]; case ProxyGroupType::Smart: [[fallthrough]]; case ProxyGroupType::URLTest: if(!x.Lazy.is_undef()) singlegroup["lazy"] = x.Lazy.get(); [[fallthrough]]; case ProxyGroupType::Fallback: singlegroup["url"] = x.Url; if(x.Interval > 0) singlegroup["interval"] = x.Interval; if(x.Tolerance > 0) singlegroup["tolerance"] = x.Tolerance; break; default: continue; } if(!x.DisableUdp.is_undef()) singlegroup["disable-udp"] = x.DisableUdp.get(); for(const auto& y : x.Proxies) groupGenerate(y, nodelist, filtered_nodelist, true, ext); if(!x.UsingProvider.empty()) singlegroup["use"] = x.UsingProvider; else { if(filtered_nodelist.empty()) filtered_nodelist.emplace_back("DIRECT"); } if(!filtered_nodelist.empty()) singlegroup["proxies"] = filtered_nodelist; if(group_block) singlegroup.SetStyle(YAML::EmitterStyle::Block); else singlegroup.SetStyle(YAML::EmitterStyle::Flow); bool replace_flag = false; for(auto && original_group : original_groups) { if(original_group["name"].as<std::string>() == x.Name) { original_group.reset(singlegroup); replace_flag = true; break; } } if(!replace_flag) original_groups.push_back(singlegroup); } if(group_compact) original_groups.SetStyle(YAML::EmitterStyle::Flow); if(ext.clash_new_field_name) yamlnode["proxy-groups"] = original_groups; else yamlnode["Proxy Group"] = original_groups; } std::string proxyToClash(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, bool clashR, extra_settings &ext) { YAML::Node yamlnode; try { yamlnode = YAML::Load(base_conf); } catch (std::exception &e) { writeLog(0, std::string("Clash base loader failed with error: ") + e.what(), LOG_LEVEL_ERROR); return ""; } proxyToClash(nodes, yamlnode, extra_proxy_group, clashR, ext); if(ext.nodelist) return YAML::Dump(yamlnode); /* if(ext.enable_rule_generator) rulesetToClash(yamlnode, ruleset_content_array, ext.overwrite_original_rules, ext.clash_new_field_name); return YAML::Dump(yamlnode); */ if(!ext.enable_rule_generator) return YAML::Dump(yamlnode); if(!ext.managed_config_prefix.empty() || ext.clash_script) { if(yamlnode["mode"].IsDefined()) { if(ext.clash_new_field_name) yamlnode["mode"] = ext.clash_script ? "script" : "rule"; else yamlnode["mode"] = ext.clash_script ? "Script" : "Rule"; } renderClashScript(yamlnode, ruleset_content_array, ext.managed_config_prefix, ext.clash_script, ext.overwrite_original_rules, ext.clash_classical_ruleset); return YAML::Dump(yamlnode); } std::string output_content = rulesetToClashStr(yamlnode, ruleset_content_array, ext.overwrite_original_rules, ext.clash_new_field_name); output_content.insert(0, YAML::Dump(yamlnode)); //rulesetToClash(yamlnode, ruleset_content_array, ext.overwrite_original_rules, ext.clash_new_field_name); //std::string output_content = YAML::Dump(yamlnode); return output_content; } // peer = (public-key = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=, allowed-ips = "0.0.0.0/0, ::/0", endpoint = engage.cloudflareclient.com:2408, client-id = 139/184/125),(public-key = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=, endpoint = engage.cloudflareclient.com:2408) std::string generatePeer(Proxy &node, bool client_id_as_reserved = false) { std::string result; result += "public-key = " + node.PublicKey; result += ", endpoint = " + node.Hostname + ":" + std::to_string(node.Port); if(!node.AllowedIPs.empty()) result += ", allowed-ips = \"" + node.AllowedIPs + "\""; if(!node.ClientId.empty()) { if(client_id_as_reserved) result += ", reserved = [" + node.ClientId + "]"; else result += ", client-id = " + node.ClientId; } return result; } std::string proxyToSurge(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, int surge_ver, extra_settings &ext) { INIReader ini; std::string output_nodelist; std::vector<Proxy> nodelist; unsigned short local_port = 1080; string_array remarks_list; ini.store_any_line = true; // filter out sections that requires direct-save 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.get_last_error(), LOG_LEVEL_ERROR); return ""; } ini.set_current_section("Proxy"); ini.erase_section(); ini.set("{NONAME}", "DIRECT = direct"); for(Proxy &x : nodes) { if(ext.append_proxy_type) { std::string type = getProxyTypeName(x.Type); x.Remark = "[" + type + "] " + x.Remark; } processRemark(x.Remark, remarks_list); std::string &hostname = x.Hostname, &username = x.Username, &password = x.Password, &method = x.EncryptMethod, &id = x.UserId, &transproto = x.TransferProtocol, &host = x.Host, &edge = x.Edge, &path = x.Path, &protocol = x.Protocol, &protoparam = x.ProtocolParam, &obfs = x.OBFS, &obfsparam = x.OBFSParam, &plugin = x.Plugin, &pluginopts = x.PluginOption, &underlying_proxy = x.UnderlyingProxy; std::string port = std::to_string(x.Port); bool &tlssecure = x.TLSSecure; 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); std::string proxy, section, real_section; string_array args, headers; std::stringstream ss; switch (x.Type) { case ProxyType::Shadowsocks: if(surge_ver >= 3 || surge_ver == -3) { proxy = "ss, " + hostname + ", " + port + ", encrypt-method=" + method + ", password=" + password; } else { proxy = "custom, " + hostname + ", " + port + ", " + method + ", " + password + ", https://github.com/pobizhe/SSEncrypt/raw/master/SSEncrypt.module"; } if(!plugin.empty()) { switch(hash_(plugin)) { case "simple-obfs"_hash: case "obfs-local"_hash: if(!pluginopts.empty()) proxy += "," + replaceAllDistinct(pluginopts, ";", ","); break; default: continue; } } break; case ProxyType::VMess: if(surge_ver < 4 && surge_ver != -3) continue; proxy = "vmess, " + hostname + ", " + port + ", username=" + id + ", tls=" + (tlssecure ? "true" : "false") + ", vmess-aead=" + (x.AlterId == 0 ? "true" : "false"); if(tlssecure && !tls13.is_undef()) proxy += ", tls13=" + std::string(tls13 ? "true" : "false"); switch(hash_(transproto)) { case "tcp"_hash: break; case "ws"_hash: if(host.empty()) proxy += ", ws=true, ws-path=" + path + ", sni=" + hostname; else proxy += ", ws=true, ws-path=" + path + ", sni=" + host; if(!host.empty()) headers.push_back("Host:" + host); if(!edge.empty()) headers.push_back("Edge:" + edge); if(!headers.empty()) proxy += ", ws-headers=" + join(headers, "|"); break; default: continue; } if(!scv.is_undef()) proxy += ", skip-cert-verify=" + scv.get_str(); break; case ProxyType::ShadowsocksR: if(ext.surge_ssr_path.empty() || surge_ver < 2) continue; proxy = "external, exec=\"" + ext.surge_ssr_path + "\", args=\""; args = {"-l", std::to_string(local_port), "-s", hostname, "-p", port, "-m", method, "-k", password, "-o", obfs, "-O", protocol}; if(!obfsparam.empty()) { args.emplace_back("-g"); args.emplace_back(std::move(obfsparam)); } if(!protoparam.empty()) { args.emplace_back("-G"); args.emplace_back(std::move(protoparam)); } proxy += join(args, "\", args=\""); proxy += "\", local-port=" + std::to_string(local_port); if(isIPv4(hostname) || isIPv6(hostname)) proxy += ", addresses=" + hostname; else if(global.surgeResolveHostname) proxy += ", addresses=" + hostnameToIPAddr(hostname); local_port++; break; case ProxyType::SOCKS5: proxy = "socks5, " + hostname + ", " + port; if(!username.empty()) proxy += ", username=" + username; if(!password.empty()) proxy += ", password=" + password; if(!scv.is_undef()) proxy += ", skip-cert-verify=" + scv.get_str(); break; case ProxyType::HTTPS: if(surge_ver == -3) { proxy = "https, " + hostname + ", " + port + ", " + username + ", " + password; if(!scv.is_undef()) proxy += ", skip-cert-verify=" + scv.get_str(); break; } [[fallthrough]]; case ProxyType::HTTP: proxy = "http, " + hostname + ", " + port; if(!username.empty()) proxy += ", username=" + username; if(!password.empty()) proxy += ", password=" + password; proxy += std::string(", tls=") + (x.TLSSecure ? "true" : "false"); if(!scv.is_undef()) proxy += ", skip-cert-verify=" + scv.get_str(); break; case ProxyType::Trojan: if(surge_ver < 4 && surge_ver != -3) continue; proxy = "trojan, " + hostname + ", " + port + ", password=" + password; if(x.SnellVersion != 0) proxy += ", version=" + std::to_string(x.SnellVersion); if(!host.empty()) proxy += ", sni=" + host; if(!scv.is_undef()) proxy += ", skip-cert-verify=" + scv.get_str(); break; case ProxyType::Snell: proxy = "snell, " + hostname + ", " + port + ", psk=" + password; if(!obfs.empty()) { proxy += ", obfs=" + obfs; if(!host.empty()) proxy += ", obfs-host=" + host; } if(x.SnellVersion != 0) proxy += ", version=" + std::to_string(x.SnellVersion); break; case ProxyType::WireGuard: if(surge_ver < 4 && surge_ver != -3) continue; ss << std::hex << hash_(x.Remark); section = ss.str().substr(0, 5); real_section = "WireGuard " + section; proxy = "wireguard, section-name=" + section; if(!x.TestUrl.empty()) proxy += ", test-url=" + x.TestUrl; ini.set(real_section, "private-key", x.PrivateKey); ini.set(real_section, "self-ip", x.SelfIP); if(!x.SelfIPv6.empty()) ini.set(real_section, "self-ip-v6", x.SelfIPv6); if(!x.PreSharedKey.empty()) ini.set(real_section, "preshared-key", x.PreSharedKey); if(!x.DnsServers.empty()) ini.set(real_section, "dns-server", join(x.DnsServers, ",")); if(x.Mtu > 0) ini.set(real_section, "mtu", std::to_string(x.Mtu)); if(x.KeepAlive > 0) ini.set(real_section, "keepalive", std::to_string(x.KeepAlive)); ini.set(real_section, "peer", "(" + generatePeer(x) + ")"); break; default: continue; } if(!tfo.is_undef()) proxy += ", tfo=" + tfo.get_str(); if(!udp.is_undef()) proxy += ", udp-relay=" + udp.get_str(); if (underlying_proxy != "") proxy += ", underlying-proxy=" + underlying_proxy; if (ext.nodelist) output_nodelist += x.Remark + " = " + proxy + "\n"; else { ini.set("{NONAME}", x.Remark + " = " + proxy); nodelist.emplace_back(x); } remarks_list.emplace_back(x.Remark); } if(ext.nodelist) return output_nodelist; ini.set_current_section("Proxy Group"); ini.erase_section(); for(const ProxyGroupConfig &x : extra_proxy_group) { string_array filtered_nodelist; std::string group; switch(x.Type) { case ProxyGroupType::Select: case ProxyGroupType::Smart: case ProxyGroupType::URLTest: case ProxyGroupType::Fallback: break; case ProxyGroupType::LoadBalance: if(surge_ver < 1 && surge_ver != -3) continue; break; case ProxyGroupType::SSID: 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; } for(const auto &y : x.Proxies) groupGenerate(y, nodelist, filtered_nodelist, true, ext); if(filtered_nodelist.empty()) filtered_nodelist.emplace_back("DIRECT"); if(filtered_nodelist.size() == 1) { group = toLower(filtered_nodelist[0]); switch(hash_(group)) { case "direct"_hash: case "reject"_hash: case "reject-tinygif"_hash: ini.set("Proxy", "{NONAME}", x.Name + " = " + group); continue; } } group = x.TypeStr() + ","; group += join(filtered_nodelist, ","); if(x.Type == ProxyGroupType::URLTest || x.Type == ProxyGroupType::Fallback || x.Type == ProxyGroupType::LoadBalance) { group += ",url=" + x.Url + ",interval=" + std::to_string(x.Interval); if(x.Tolerance > 0) group += ",tolerance=" + std::to_string(x.Tolerance); if(x.Timeout > 0) group += ",timeout=" + std::to_string(x.Timeout); if(!x.Persistent.is_undef()) group += ",persistent=" + x.Persistent.get_str(); if(!x.EvaluateBeforeUse.is_undef()) group += ",evaluate-before-use=" + x.EvaluateBeforeUse.get_str(); } 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.to_string(); } std::string proxyToSingle(std::vector<Proxy> &nodes, int types, extra_settings &ext) { /// types: SS=1 SSR=2 VMess=4 Trojan=8 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) { 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); std::string aid = std::to_string(x.AlterId); switch(x.Type) { case ProxyType::Shadowsocks: if(ss) { proxyStr = "ss://" + urlSafeBase64Encode(method + ":" + password) + "@" + hostname + ":" + port; if(!plugin.empty() && !pluginopts.empty()) { proxyStr += "/?plugin=" + urlEncode(plugin + ";" + pluginopts); } proxyStr += "#" + urlEncode(remark); } else if(ssr) { if(std::find(ssr_ciphers.begin(), ssr_ciphers.end(), method) != ssr_ciphers.end() && plugin.empty()) proxyStr = "ssr://" + urlSafeBase64Encode(hostname + ":" + port + ":origin:" + method + ":plain:" + urlSafeBase64Encode(password) \ + "/?group=" + urlSafeBase64Encode(x.Group) + "&remarks=" + urlSafeBase64Encode(remark)); } else continue; break; case ProxyType::ShadowsocksR: if(ssr) { proxyStr = "ssr://" + urlSafeBase64Encode(hostname + ":" + port + ":" + protocol + ":" + method + ":" + obfs + ":" + urlSafeBase64Encode(password) \ + "/?group=" + urlSafeBase64Encode(x.Group) + "&remarks=" + urlSafeBase64Encode(remark) \ + "&obfsparam=" + urlSafeBase64Encode(obfsparam) + "&protoparam=" + urlSafeBase64Encode(protoparam)); } else if(ss) { if(std::find(ss_ciphers.begin(), ss_ciphers.end(), method) != ss_ciphers.end() && protocol == "origin" && obfs == "plain") proxyStr = "ss://" + urlSafeBase64Encode(method + ":" + password) + "@" + hostname + ":" + port + "#" + urlEncode(remark); } else continue; break; case ProxyType::VMess: if(!vmess) continue; proxyStr = "vmess://" + base64Encode(vmessLinkConstruct(remark, hostname, port, faketype, id, aid, transproto, path, host, tlssecure ? "tls" : "")); break; case ProxyType::Trojan: if(!trojan) continue; proxyStr = "trojan://" + password + "@" + hostname + ":" + port + "?allowInsecure=" + (x.AllowInsecure.get() ? "1" : "0"); if(!host.empty()) proxyStr += "&sni=" + host; if(transproto == "ws") { proxyStr += "&ws=1"; if(!path.empty()) proxyStr += "&wspath=" + urlEncode(path); } proxyStr += "#" + urlEncode(remark); break; default: continue; } allLinks += proxyStr + "\n"; } if(ext.nodelist) return allLinks; else return base64Encode(allLinks); } std::string proxyToSSSub(std::string base_conf, std::vector<Proxy> &nodes, extra_settings &ext) { using namespace rapidjson_ext; rapidjson::Document base; auto &alloc = base.GetAllocator(); base_conf = trimWhitespace(base_conf); if(base_conf.empty()) base_conf = "{}"; rapidjson::ParseResult result = base.Parse(base_conf.data()); if (!result) writeLog(0, std::string("SIP008 base loader failed with error: ") + rapidjson::GetParseError_En(result.Code()) + " (" + std::to_string(result.Offset()) + ")", LOG_LEVEL_ERROR); rapidjson::Value proxies(rapidjson::kArrayType); for(Proxy &x : nodes) { 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; std::string &pluginopts = x.PluginOption; std::string &protocol = x.Protocol; std::string &obfs = x.OBFS; switch(x.Type) { case ProxyType::Shadowsocks: if(plugin == "simple-obfs") plugin = "obfs-local"; break; case ProxyType::ShadowsocksR: if(std::find(ss_ciphers.begin(), ss_ciphers.end(), method) == ss_ciphers.end() || protocol != "origin" || obfs != "plain") continue; break; default: continue; } rapidjson::Value proxy(rapidjson::kObjectType); proxy.CopyFrom(base, alloc) | AddMemberOrReplace("remarks", rapidjson::Value(remark.c_str(), remark.size()), alloc) | AddMemberOrReplace("server", rapidjson::Value(hostname.c_str(), hostname.size()), alloc) | AddMemberOrReplace("server_port", rapidjson::Value(x.Port), alloc) | AddMemberOrReplace("method", rapidjson::Value(method.c_str(), method.size()), alloc) | AddMemberOrReplace("password", rapidjson::Value(password.c_str(), password.size()), alloc) | AddMemberOrReplace("plugin", rapidjson::Value(plugin.c_str(), plugin.size()), alloc) | AddMemberOrReplace("plugin_opts", rapidjson::Value(pluginopts.c_str(), pluginopts.size()), alloc); proxies.PushBack(proxy, alloc); } return proxies | SerializeObject(); } std::string proxyToQuan(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { INIReader ini; ini.store_any_line = true; if(!ext.nodelist && ini.parse(base_conf) != 0) { 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); if(ext.nodelist) { string_array allnodes; std::string allLinks; ini.get_all("SERVER", "{NONAME}", allnodes); if(!allnodes.empty()) allLinks = join(allnodes, "\n"); return base64Encode(allLinks); } return ini.to_string(); } void proxyToQuan(std::vector<Proxy> &nodes, INIReader &ini, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { std::string proxyStr; std::vector<Proxy> nodelist; string_array remarks_list; ini.set_current_section("SERVER"); ini.erase_section(); for(Proxy &x : nodes) { if(ext.append_proxy_type) { std::string type = getProxyTypeName(x.Type); x.Remark = "[" + type + "] " + x.Remark; } processRemark(x.Remark, remarks_list); std::string &hostname = x.Hostname, &method = x.EncryptMethod, &password = x.Password, &id = x.UserId, &transproto = x.TransferProtocol, &host = x.Host, &path = x.Path, &edge = x.Edge, &protocol = x.Protocol, &protoparam = x.ProtocolParam, &obfs = x.OBFS, &obfsparam = x.OBFSParam, &plugin = x.Plugin, &pluginopts = x.PluginOption, &username = x.Username; std::string port = std::to_string(x.Port); bool &tlssecure = x.TLSSecure; tribool scv; switch(x.Type) { case ProxyType::VMess: scv = ext.skip_cert_verify; scv.define(x.AllowInsecure); if(method == "auto") method = "chacha20-ietf-poly1305"; proxyStr = x.Remark + " = vmess, " + hostname + ", " + port + ", " + method + ", \"" + id + "\", group=" + x.Group; if(tlssecure) { proxyStr += ", over-tls=true, tls-host=" + host; if(!scv.is_undef()) proxyStr += ", certificate=" + std::string(scv.get() ? "0" : "1"); } if(transproto == "ws") { proxyStr += ", obfs=ws, obfs-path=\"" + path + "\", obfs-header=\"Host: " + host; if(!edge.empty()) proxyStr += "[Rr][Nn]Edge: " + edge; proxyStr += "\""; } if(ext.nodelist) proxyStr = "vmess://" + urlSafeBase64Encode(proxyStr); break; case ProxyType::ShadowsocksR: if(ext.nodelist) { proxyStr = "ssr://" + urlSafeBase64Encode(hostname + ":" + port + ":" + protocol + ":" + method + ":" + obfs + ":" + urlSafeBase64Encode(password) \ + "/?group=" + urlSafeBase64Encode(x.Group) + "&remarks=" + urlSafeBase64Encode(x.Remark) \ + "&obfsparam=" + urlSafeBase64Encode(obfsparam) + "&protoparam=" + urlSafeBase64Encode(protoparam)); } else { proxyStr = x.Remark + " = shadowsocksr, " + hostname + ", " + port + ", " + method + ", \"" + password + "\", group=" + x.Group + ", protocol=" + protocol + ", obfs=" + obfs; if(!protoparam.empty()) proxyStr += ", protocol_param=" + protoparam; if(!obfsparam.empty()) proxyStr += ", obfs_param=" + obfsparam; } break; case ProxyType::Shadowsocks: if(ext.nodelist) { proxyStr = "ss://" + urlSafeBase64Encode(method + ":" + password) + "@" + hostname + ":" + port; if(!plugin.empty() && !pluginopts.empty()) { proxyStr += "/?plugin=" + urlEncode(plugin + ";" + pluginopts); } proxyStr += "&group=" + urlSafeBase64Encode(x.Group) + "#" + urlEncode(x.Remark); } else { proxyStr = x.Remark + " = shadowsocks, " + hostname + ", " + port + ", " + method + ", \"" + password + "\", group=" + x.Group; if(plugin == "obfs-local" && !pluginopts.empty()) { proxyStr += ", " + replaceAllDistinct(pluginopts, ";", ", "); } } break; case ProxyType::HTTP: case ProxyType::HTTPS: proxyStr = x.Remark + " = http, upstream-proxy-address=" + hostname + ", upstream-proxy-port=" + port + ", group=" + x.Group; if(!username.empty() && !password.empty()) proxyStr += ", upstream-proxy-auth=true, upstream-proxy-username=" + username + ", upstream-proxy-password=" + password; else proxyStr += ", upstream-proxy-auth=false"; if(tlssecure) { proxyStr += ", over-tls=true"; if(!host.empty()) proxyStr += ", tls-host=" + host; if(!scv.is_undef()) proxyStr += ", certificate=" + std::string(scv.get() ? "0" : "1"); } if(ext.nodelist) proxyStr = "http://" + urlSafeBase64Encode(proxyStr); break; case ProxyType::SOCKS5: proxyStr = x.Remark + " = socks, upstream-proxy-address=" + hostname + ", upstream-proxy-port=" + port + ", group=" + x.Group; if(!username.empty() && !password.empty()) proxyStr += ", upstream-proxy-auth=true, upstream-proxy-username=" + username + ", upstream-proxy-password=" + password; else proxyStr += ", upstream-proxy-auth=false"; if(tlssecure) { proxyStr += ", over-tls=true"; if(!host.empty()) proxyStr += ", tls-host=" + host; if(!scv.is_undef()) proxyStr += ", certificate=" + std::string(scv.get() ? "0" : "1"); } if(ext.nodelist) proxyStr = "socks://" + urlSafeBase64Encode(proxyStr); break; default: continue; } ini.set("{NONAME}", proxyStr); remarks_list.emplace_back(x.Remark); nodelist.emplace_back(x); } if(ext.nodelist) return; ini.set_current_section("POLICY"); ini.erase_section(); for(const ProxyGroupConfig &x : extra_proxy_group) { string_array filtered_nodelist; std::string type; std::string singlegroup; std::string name, proxies; switch(x.Type) { case ProxyGroupType::Select: case ProxyGroupType::Fallback: type = "static"; break; case ProxyGroupType::URLTest: type = "auto"; break; case ProxyGroupType::LoadBalance: type = "balance, round-robin"; break; case ProxyGroupType::SSID: { singlegroup = x.Name + " : wifi = " + x.Proxies[0]; std::string content, celluar, celluar_matcher = R"(^(.*?),?celluar\s?=\s?(.*?)(,.*)$)", rem_a, rem_b; for(auto iter = x.Proxies.begin() + 1; iter != x.Proxies.end(); iter++) { if(regGetMatch(*iter, celluar_matcher, 4, 0, &rem_a, &celluar, &rem_b)) { content += *iter + "\n"; continue; } content += rem_a + rem_b + "\n"; } if(!celluar.empty()) singlegroup += ", celluar = " + celluar; singlegroup += "\n" + replaceAllDistinct(trimOf(content, ','), ",", "\n"); ini.set("{NONAME}", base64Encode(singlegroup)); //insert order } continue; default: continue; } for(const auto &y : x.Proxies) groupGenerate(y, nodelist, filtered_nodelist, true, ext); if(filtered_nodelist.empty()) filtered_nodelist.emplace_back("direct"); if(filtered_nodelist.size() < 2) // force groups with 1 node to be static type = "static"; proxies = join(filtered_nodelist, "\n"); singlegroup = x.Name + " : " + type; if(type == "static") singlegroup += ", " + filtered_nodelist[0]; singlegroup += "\n" + proxies + "\n"; ini.set("{NONAME}", base64Encode(singlegroup)); } if(ext.enable_rule_generator) rulesetToSurge(ini, ruleset_content_array, -2, ext.overwrite_original_rules, ""); } std::string proxyToQuanX(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { INIReader ini; ini.store_any_line = true; 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.get_last_error(), LOG_LEVEL_ERROR); return ""; } proxyToQuanX(nodes, ini, ruleset_content_array, extra_proxy_group, ext); if(ext.nodelist) { string_array allnodes; std::string allLinks; ini.get_all("server_local", "{NONAME}", allnodes); if(!allnodes.empty()) allLinks = join(allnodes, "\n"); return allLinks; } return ini.to_string(); } void proxyToQuanX(std::vector<Proxy> &nodes, INIReader &ini, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { std::string proxyStr; tribool udp, tfo, scv, tls13; std::vector<Proxy> nodelist; string_array remarks_list; ini.set_current_section("server_local"); ini.erase_section(); for(Proxy &x : nodes) { if(ext.append_proxy_type) { std::string type = getProxyTypeName(x.Type); x.Remark = "[" + type + "] " + x.Remark; } processRemark(x.Remark, remarks_list); std::string &hostname = x.Hostname, &method = x.EncryptMethod, &id = x.UserId, &transproto = x.TransferProtocol, &host = x.Host, &path = x.Path, &password = x.Password, &plugin = x.Plugin, &pluginopts = x.PluginOption, &protocol = x.Protocol, &protoparam = x.ProtocolParam, &obfs = x.OBFS, &obfsparam = x.OBFSParam, &username = x.Username; 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; udp.define(x.UDP); tfo.define(x.TCPFastOpen); scv.define(x.AllowInsecure); tls13.define(x.TLS13); switch(x.Type) { case ProxyType::VMess: if(method == "auto") method = "chacha20-ietf-poly1305"; proxyStr = "vmess = " + hostname + ":" + port + ", method=" + method + ", password=" + id; if (x.AlterId != 0) proxyStr += ", aead=false"; if(tlssecure && !tls13.is_undef()) proxyStr += ", tls13=" + std::string(tls13 ? "true" : "false"); if(transproto == "ws") { if(tlssecure) proxyStr += ", obfs=wss"; else proxyStr += ", obfs=ws"; proxyStr += ", obfs-host=" + host + ", obfs-uri=" + path; } else if(tlssecure) proxyStr += ", obfs=over-tls, obfs-host=" + host; break; case ProxyType::Shadowsocks: proxyStr = "shadowsocks = " + hostname + ":" + port + ", method=" + method + ", password=" + password; if(!plugin.empty()) { switch(hash_(plugin)) { case "simple-obfs"_hash: case "obfs-local"_hash: if(!pluginopts.empty()) proxyStr += ", " + replaceAllDistinct(pluginopts, ";", ", "); break; case "v2ray-plugin"_hash: pluginopts = replaceAllDistinct(pluginopts, ";", "&"); plugin = getUrlArg(pluginopts, "mode") == "websocket" ? "ws" : ""; host = getUrlArg(pluginopts, "host"); path = getUrlArg(pluginopts, "path"); tlssecure = pluginopts.find("tls") != std::string::npos; if(tlssecure && plugin == "ws") { plugin += 's'; if(!tls13.is_undef()) proxyStr += ", tls13=" + std::string(tls13 ? "true" : "false"); } proxyStr += ", obfs=" + plugin; if(!host.empty()) proxyStr += ", obfs-host=" + host; if(!path.empty()) proxyStr += ", obfs-uri=" + path; break; default: continue; } } break; case ProxyType::ShadowsocksR: proxyStr = "shadowsocks = " + hostname + ":" + port + ", method=" + method + ", password=" + password + ", ssr-protocol=" + protocol; if(!protoparam.empty()) proxyStr += ", ssr-protocol-param=" + protoparam; proxyStr += ", obfs=" + obfs; if(!obfsparam.empty()) proxyStr += ", obfs-host=" + obfsparam; break; case ProxyType::HTTP: case ProxyType::HTTPS: proxyStr = "http = " + hostname + ":" + port + ", username=" + (username.empty() ? "none" : username) + ", password=" + (password.empty() ? "none" : password); if(tlssecure) { proxyStr += ", over-tls=true"; if(!tls13.is_undef()) proxyStr += ", tls13=" + std::string(tls13 ? "true" : "false"); } else { proxyStr += ", over-tls=false"; } break; case ProxyType::Trojan: proxyStr = "trojan = " + hostname + ":" + port + ", password=" + password; if(tlssecure) { proxyStr += ", over-tls=true, tls-host=" + host; if(!tls13.is_undef()) proxyStr += ", tls13=" + std::string(tls13 ? "true" : "false"); } else { proxyStr += ", over-tls=false"; } break; case ProxyType::SOCKS5: proxyStr = "socks5 = " + hostname + ":" + port; if(!username.empty() && !password.empty()) { proxyStr += ", username=" + username + ", password=" + password; if(tlssecure) { proxyStr += ", over-tls=true, tls-host=" + host; if(!tls13.is_undef()) proxyStr += ", tls13=" + std::string(tls13 ? "true" : "false"); } else { proxyStr += ", over-tls=false"; } } break; default: continue; } if(!tfo.is_undef()) proxyStr += ", fast-open=" + tfo.get_str(); if(!udp.is_undef()) proxyStr += ", udp-relay=" + udp.get_str(); if(tlssecure && !scv.is_undef() && (x.Type != ProxyType::Shadowsocks && x.Type != ProxyType::ShadowsocksR)) proxyStr += ", tls-verification=" + scv.reverse().get_str(); proxyStr += ", tag=" + x.Remark; ini.set("{NONAME}", proxyStr); remarks_list.emplace_back(x.Remark); nodelist.emplace_back(x); } if(ext.nodelist) return; string_multimap original_groups; ini.set_current_section("policy"); ini.get_items(original_groups); ini.erase_section(); for(const ProxyGroupConfig &x : extra_proxy_group) { std::string type; string_array filtered_nodelist; switch(x.Type) { case ProxyGroupType::Select: type = "static"; break; case ProxyGroupType::URLTest: type = "url-latency-benchmark"; break; case ProxyGroupType::Fallback: type = "available"; break; case ProxyGroupType::LoadBalance: type = "round-robin"; break; case ProxyGroupType::SSID: type = "ssid"; for(const auto & proxy : x.Proxies) filtered_nodelist.emplace_back(replaceAllDistinct(proxy, "=", ":")); break; default: continue; } if(x.Type != ProxyGroupType::SSID) { for(const auto &y : x.Proxies) groupGenerate(y, nodelist, filtered_nodelist, true, ext); if(filtered_nodelist.empty()) filtered_nodelist.emplace_back("direct"); if(filtered_nodelist.size() < 2) // force groups with 1 node to be static type = "static"; } auto iter = std::find_if(original_groups.begin(), original_groups.end(), [&](const string_multimap::value_type &n) { std::string groupdata = n.second; std::string::size_type cpos = groupdata.find(','); if(cpos != std::string::npos) return trim(groupdata.substr(0, cpos)) == x.Name; else return false; }); if(iter != original_groups.end()) { string_array vArray = split(iter->second, ","); if(vArray.size() > 1) { if(trim(vArray[vArray.size() - 1]).find("img-url") == 0) filtered_nodelist.emplace_back(trim(vArray[vArray.size() - 1])); } } std::string proxies = join(filtered_nodelist, ", "); std::string singlegroup = type + "=" + x.Name + ", " + proxies; if(x.Type != ProxyGroupType::Select && x.Type != ProxyGroupType::SSID) { singlegroup += ", check-interval=" + std::to_string(x.Interval); if(x.Tolerance > 0) singlegroup += ", tolerance=" + std::to_string(x.Tolerance); } ini.set("{NONAME}", singlegroup); } if(ext.enable_rule_generator) rulesetToSurge(ini, ruleset_content_array, -1, ext.overwrite_original_rules, ext.managed_config_prefix); } std::string proxyToSSD(std::vector<Proxy> &nodes, std::string &group, std::string &userinfo, extra_settings &ext) { rapidjson::StringBuffer sb; rapidjson::Writer<rapidjson::StringBuffer> writer(sb); int index = 0; if(group.empty()) group = "SSD"; writer.StartObject(); writer.Key("airport"); writer.String(group.data()); writer.Key("port"); writer.Int(1); writer.Key("encryption"); writer.String("aes-128-gcm"); writer.Key("password"); writer.String("password"); if(!userinfo.empty()) { std::string data = replaceAllDistinct(userinfo, "; ", "&"); std::string upload = getUrlArg(data, "upload"), download = getUrlArg(data, "download"), total = getUrlArg(data, "total"), expiry = getUrlArg(data, "expire"); double used = (to_number(upload, 0.0) + to_number(download, 0.0)) / std::pow(1024, 3) * 1.0, tot = to_number(total, 0.0) / std::pow(1024, 3) * 1.0; writer.Key("traffic_used"); writer.Double(used); writer.Key("traffic_total"); writer.Double(tot); if(!expiry.empty()) { const time_t rawtime = to_int(expiry); char buffer[30]; struct tm *dt = localtime(&rawtime); strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M", dt); writer.Key("expiry"); writer.String(buffer); } } writer.Key("servers"); writer.StartArray(); for(Proxy &x : nodes) { std::string &hostname = x.Hostname, &password = x.Password, &method = x.EncryptMethod, &plugin = x.Plugin, &pluginopts = x.PluginOption, &protocol = x.Protocol, &obfs = x.OBFS; switch(x.Type) { case ProxyType::Shadowsocks: if(plugin == "obfs-local") plugin = "simple-obfs"; writer.StartObject(); writer.Key("server"); writer.String(hostname.data()); writer.Key("port"); writer.Int(x.Port); writer.Key("encryption"); writer.String(method.data()); writer.Key("password"); writer.String(password.data()); writer.Key("plugin"); writer.String(plugin.data()); writer.Key("plugin_options"); writer.String(pluginopts.data()); writer.Key("remarks"); writer.String(x.Remark.data()); writer.Key("id"); writer.Int(index); writer.EndObject(); break; case ProxyType::ShadowsocksR: if(std::count(ss_ciphers.begin(), ss_ciphers.end(), method) > 0 && protocol == "origin" && obfs == "plain") { writer.StartObject(); writer.Key("server"); writer.String(hostname.data()); writer.Key("port"); writer.Int(x.Port); writer.Key("encryption"); writer.String(method.data()); writer.Key("password"); writer.String(password.data()); writer.Key("remarks"); writer.String(x.Remark.data()); writer.Key("id"); writer.Int(index); writer.EndObject(); break; } else continue; default: continue; } index++; } writer.EndArray(); writer.EndObject(); return "ssd://" + base64Encode(sb.GetString()); } std::string proxyToMellow(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { INIReader ini; ini.store_any_line = true; if(ini.parse(base_conf) != 0) { 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.to_string(); } void proxyToMellow(std::vector<Proxy> &nodes, INIReader &ini, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { std::string proxy; std::string 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<Proxy> nodelist; string_array vArray, remarks_list; ini.set_current_section("Endpoint"); for(Proxy &x : nodes) { if(ext.append_proxy_type) { std::string type = getProxyTypeName(x.Type); x.Remark = "[" + type + "] " + x.Remark; } processRemark(x.Remark, remarks_list); std::string &hostname = x.Hostname, port = std::to_string(x.Port); tfo = ext.tfo; scv = ext.skip_cert_verify; tfo.define(x.TCPFastOpen); scv.define(x.AllowInsecure); switch(x.Type) { case ProxyType::Shadowsocks: if(!x.Plugin.empty()) continue; proxy = x.Remark + ", ss, ss://" + urlSafeBase64Encode(method + ":" + password) + "@" + hostname + ":" + port; break; case ProxyType::VMess: proxy = x.Remark + ", vmess1, vmess1://" + id + "@" + hostname + ":" + port; if(!path.empty()) proxy += path; proxy += "?network=" + transproto; switch(hash_(transproto)) { case "ws"_hash: proxy += "&ws.host=" + urlEncode(host); break; case "http"_hash: if(!host.empty()) proxy += "&http.host=" + urlEncode(host); break; case "quic"_hash: if(!quicsecure.empty()) proxy += "&quic.security=" + quicsecure + "&quic.key=" + quicsecret; break; case "kcp"_hash: case "tcp"_hash: break; } proxy += "&tls=" + tlssecure; if(tlssecure == "true") { if(!host.empty()) proxy += "&tls.servername=" + urlEncode(host); } if(!scv.is_undef()) proxy += "&tls.allowinsecure=" + scv.get_str(); if(!tfo.is_undef()) proxy += "&sockopt.tcpfastopen=" + tfo.get_str(); break; case ProxyType::SOCKS5: proxy = x.Remark + ", builtin, socks, address=" + hostname + ", port=" + port + ", user=" + username + ", pass=" + password; break; case ProxyType::HTTP: proxy = x.Remark + ", builtin, http, address=" + hostname + ", port=" + port + ", user=" + username + ", pass=" + password; break; default: continue; } ini.set("{NONAME}", proxy); remarks_list.emplace_back(x.Remark); nodelist.emplace_back(x); } ini.set_current_section("EndpointGroup"); for(const ProxyGroupConfig &x : extra_proxy_group) { string_array filtered_nodelist; url.clear(); proxy.clear(); switch(x.Type) { case ProxyGroupType::Select: case ProxyGroupType::URLTest: case ProxyGroupType::Fallback: case ProxyGroupType::LoadBalance: break; default: continue; } for(const auto &y : x.Proxies) groupGenerate(y, nodelist, filtered_nodelist, false, ext); if(filtered_nodelist.empty()) { if(remarks_list.empty()) filtered_nodelist.emplace_back("DIRECT"); else filtered_nodelist = remarks_list; } //don't process these for now /* proxy = vArray[1]; for(std::string &x : filtered_nodelist) proxy += "," + x; if(vArray[1] == "url-test" || vArray[1] == "fallback" || vArray[1] == "load-balance") proxy += ",url=" + url; */ proxy = x.Name + ", "; /* for(std::string &y : filtered_nodelist) proxy += y + ":"; proxy = proxy.substr(0, proxy.size() - 1); */ proxy += join(filtered_nodelist, ":"); proxy += ", latency, interval=300, timeout=6"; //use hard-coded values for now ini.set("{NONAME}", proxy); //insert order } if(ext.enable_rule_generator) rulesetToSurge(ini, ruleset_content_array, 0, ext.overwrite_original_rules, ""); } std::string proxyToLoon(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { INIReader ini; std::string output_nodelist; std::vector<Proxy> nodelist; string_array remarks_list; ini.store_any_line = true; ini.add_direct_save_section("Plugin"); if(ini.parse(base_conf) != INIREADER_EXCEPTION_NONE && !ext.nodelist) { writeLog(0, "Loon base loader failed with error: " + ini.get_last_error(), LOG_LEVEL_ERROR); return ""; } ini.set_current_section("Proxy"); ini.erase_section(); for(Proxy &x : nodes) { if(ext.append_proxy_type) { std::string type = getProxyTypeName(x.Type); x.Remark = "[" + type + "] " + x.Remark; } processRemark(x.Remark, remarks_list); std::string &hostname = x.Hostname, &username = x.Username, &password = x.Password, &method = x.EncryptMethod, &plugin = x.Plugin, &pluginopts = x.PluginOption, &id = x.UserId, &transproto = x.TransferProtocol, &host = x.Host, &path = x.Path, &protocol = x.Protocol, &protoparam = x.ProtocolParam, &obfs = x.OBFS, &obfsparam = x.OBFSParam; std::string port = std::to_string(x.Port), aid = std::to_string(x.AlterId); bool &tlssecure = x.TLSSecure; tribool scv = ext.skip_cert_verify; scv.define(x.AllowInsecure); std::string proxy; switch(x.Type) { case ProxyType::Shadowsocks: proxy = "Shadowsocks," + hostname + "," + port + "," + method + ",\"" + password + "\""; if(plugin == "simple-obfs" || plugin == "obfs-local") { if(!pluginopts.empty()) proxy += "," + replaceAllDistinct(replaceAllDistinct(pluginopts, ";obfs-host=", ","), "obfs=", ""); } else if(!plugin.empty()) continue; break; case ProxyType::VMess: if(method == "auto") method = "chacha20-ietf-poly1305"; proxy = "vmess," + hostname + "," + port + "," + method + ",\"" + id + "\",over-tls=" + (tlssecure ? "true" : "false"); if(tlssecure) proxy += ",tls-name=" + host; switch(hash_(transproto)) { case "tcp"_hash: proxy += ",transport=tcp"; break; case "ws"_hash: proxy += ",transport=ws,path=" + path + ",host=" + host; break; default: continue; } if(!scv.is_undef()) proxy += ",skip-cert-verify=" + std::string(scv.get() ? "true" : "false"); break; case ProxyType::ShadowsocksR: proxy = "ShadowsocksR," + hostname + "," + port + "," + method + ",\"" + password + "\",protocol=" + protocol + ",protocol-param=" + protoparam + ",obfs=" + obfs + ",obfs-param=" + obfsparam; break; case ProxyType::HTTP: 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 + "\""; if(!host.empty()) proxy += ",tls-name=" + host; if(!scv.is_undef()) proxy += ",skip-cert-verify=" + std::string(scv.get() ? "true" : "false"); break; case ProxyType::SOCKS5: proxy = "socks5," + hostname + "," + port; if (!username.empty() && !password.empty()) proxy += "," + username + ",\"" + password + "\""; proxy += ",over-tls=" + std::string(tlssecure ? "true" : "false"); if (tlssecure) { if(!host.empty()) proxy += ",tls-name=" + host; if(!scv.is_undef()) proxy += ",skip-cert-verify=" + std::string(scv.get() ? "true" : "false"); } break; case ProxyType::WireGuard: proxy = "wireguard, interface-ip=" + x.SelfIP; if(!x.SelfIPv6.empty()) proxy += ", interface-ipv6=" + x.SelfIPv6; proxy += ", private-key=" + x.PrivateKey; for(const auto &y : x.DnsServers) { if(isIPv4(y)) proxy += ", dns=" + y; else if(isIPv6(y)) proxy += ", dnsv6=" + y; } if(x.Mtu > 0) proxy += ", mtu=" + std::to_string(x.Mtu); if(x.KeepAlive > 0) proxy += ", keepalive=" + std::to_string(x.KeepAlive); proxy += ", peers=[{" + generatePeer(x, true) + "}]"; break; default: continue; } if(ext.tfo) proxy += ",fast-open=true"; if(ext.udp) proxy += ",udp=true"; if(ext.nodelist) output_nodelist += x.Remark + " = " + proxy + "\n"; else { ini.set("{NONAME}", x.Remark + " = " + proxy); nodelist.emplace_back(x); remarks_list.emplace_back(x.Remark); } } if(ext.nodelist) return output_nodelist; string_multimap original_groups; ini.set_current_section("Proxy Group"); ini.get_items(original_groups); ini.erase_section(); for(const ProxyGroupConfig &x : extra_proxy_group) { 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; 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; } for(const auto &y : x.Proxies) groupGenerate(y, nodelist, filtered_nodelist, true, ext); if(filtered_nodelist.empty()) filtered_nodelist.emplace_back("DIRECT"); auto iter = std::find_if(original_groups.begin(), original_groups.end(), [&](const string_multimap::value_type &n) { return trim(n.first) == x.Name; }); if(iter != original_groups.end()) { string_array vArray = split(iter->second, ","); if(vArray.size() > 1) { if(trim(vArray[vArray.size() - 1]).find("img-url") == 0) filtered_nodelist.emplace_back(trim(vArray[vArray.size() - 1])); } } group = x.TypeStr() + ","; /* for(std::string &y : filtered_nodelist) group += "," + y; */ 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 += ",algorithm=" + std::string(x.Strategy == BalanceStrategy::RoundRobin ? "round-robin" : "pcc"); if(x.Timeout > 0) group += ",max-timeout=" + std::to_string(x.Timeout); } if(x.Type == ProxyGroupType::URLTest) { if(x.Tolerance > 0) group += ",tolerance=" + std::to_string(x.Tolerance); } if(x.Type == ProxyGroupType::Fallback) group += ",max-timeout=" + std::to_string(x.Timeout); } 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.to_string(); } static std::string formatSingBoxInterval(Integer interval) { std::string result; if(interval >= 3600) { result += std::to_string(interval / 3600) + "h"; interval %= 3600; } if(interval >= 60) { result += std::to_string(interval / 60) + "m"; interval %= 60; } if(interval > 0) result += std::to_string(interval) + "s"; return result; } static rapidjson::Value buildSingBoxTransport(const Proxy& proxy, rapidjson::MemoryPoolAllocator<>& allocator) { rapidjson::Value transport(rapidjson::kObjectType); switch (hash_(proxy.TransferProtocol)) { case "http"_hash: { if (!proxy.Host.empty()) transport.AddMember("host", rapidjson::StringRef(proxy.Host.c_str()), allocator); [[fallthrough]]; } case "ws"_hash: { transport.AddMember("type", rapidjson::StringRef(proxy.TransferProtocol.c_str()), allocator); if (proxy.Path.empty()) transport.AddMember("path", "/", allocator); else transport.AddMember("path", rapidjson::StringRef(proxy.Path.c_str()), allocator); rapidjson::Value headers(rapidjson::kObjectType); if (!proxy.Host.empty()) headers.AddMember("Host", rapidjson::StringRef(proxy.Host.c_str()), allocator); if (!proxy.Edge.empty()) headers.AddMember("Edge", rapidjson::StringRef(proxy.Edge.c_str()), allocator); transport.AddMember("headers", headers, allocator); break; } case "grpc"_hash: { transport.AddMember("type", "grpc", allocator); if (!proxy.Path.empty()) transport.AddMember("service_name", rapidjson::StringRef(proxy.Path.c_str()), allocator); break; } default: break; } return transport; } static void addSingBoxCommonMembers(rapidjson::Value &proxy, const Proxy &x, const rapidjson::GenericStringRef<rapidjson::Value::Ch> &type, rapidjson::MemoryPoolAllocator<> &allocator) { proxy.AddMember("type", type, allocator); proxy.AddMember("tag", rapidjson::StringRef(x.Remark.c_str()), allocator); proxy.AddMember("server", rapidjson::StringRef(x.Hostname.c_str()), allocator); proxy.AddMember("server_port", x.Port, allocator); } static rapidjson::Value stringArrayToJsonArray(const std::string &array, const std::string &delimiter, rapidjson::MemoryPoolAllocator<> &allocator) { rapidjson::Value result(rapidjson::kArrayType); string_array vArray = split(array, delimiter); for (const auto &x : vArray) result.PushBack(rapidjson::Value(trim(x).c_str(), allocator), allocator); return result; } void proxyToSingBox(std::vector<Proxy> &nodes, rapidjson::Document &json, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { using namespace rapidjson_ext; rapidjson::Document::AllocatorType &allocator = json.GetAllocator(); rapidjson::Value outbounds(rapidjson::kArrayType), route(rapidjson::kArrayType); std::vector<Proxy> nodelist; string_array remarks_list; if (!ext.nodelist) { auto direct = buildObject(allocator, "type", "direct", "tag", "DIRECT"); outbounds.PushBack(direct, allocator); auto reject = buildObject(allocator, "type", "block", "tag", "REJECT"); outbounds.PushBack(reject, allocator); auto dns = buildObject(allocator, "type", "dns", "tag", "dns-out"); outbounds.PushBack(dns, allocator); } for (Proxy &x : nodes) { std::string type = getProxyTypeName(x.Type); if (ext.append_proxy_type) x.Remark = "[" + type + "] " + x.Remark; processRemark(x.Remark, remarks_list, false); tribool udp = ext.udp, tfo = ext.tfo, scv = ext.skip_cert_verify; udp.define(x.UDP); tfo.define(x.TCPFastOpen); scv.define(x.AllowInsecure); rapidjson::Value proxy(rapidjson::kObjectType); switch (x.Type) { case ProxyType::Shadowsocks: { addSingBoxCommonMembers(proxy, x, "shadowsocks", allocator); proxy.AddMember("method", rapidjson::StringRef(x.EncryptMethod.c_str()), allocator); proxy.AddMember("password", rapidjson::StringRef(x.Password.c_str()), allocator); if(!x.Plugin.empty() && !x.PluginOption.empty()) { if (x.Plugin == "simple-obfs") x.Plugin = "obfs-local"; proxy.AddMember("plugin", rapidjson::StringRef(x.Plugin.c_str()), allocator); proxy.AddMember("plugin_opts", rapidjson::StringRef(x.PluginOption.c_str()), allocator); } break; } case ProxyType::ShadowsocksR: { addSingBoxCommonMembers(proxy, x, "shadowsocksr", allocator); proxy.AddMember("method", rapidjson::StringRef(x.EncryptMethod.c_str()), allocator); proxy.AddMember("password", rapidjson::StringRef(x.Password.c_str()), allocator); proxy.AddMember("protocol", rapidjson::StringRef(x.Protocol.c_str()), allocator); proxy.AddMember("protocol_param", rapidjson::StringRef(x.ProtocolParam.c_str()), allocator); proxy.AddMember("obfs", rapidjson::StringRef(x.OBFS.c_str()), allocator); proxy.AddMember("obfs_param", rapidjson::StringRef(x.OBFSParam.c_str()), allocator); break; } case ProxyType::VMess: { addSingBoxCommonMembers(proxy, x, "vmess", allocator); proxy.AddMember("uuid", rapidjson::StringRef(x.UserId.c_str()), allocator); proxy.AddMember("alter_id", x.AlterId, allocator); proxy.AddMember("security", rapidjson::StringRef(x.EncryptMethod.c_str()), allocator); auto transport = buildSingBoxTransport(x, allocator); if (!transport.ObjectEmpty()) proxy.AddMember("transport", transport, allocator); break; } case ProxyType::Trojan: { addSingBoxCommonMembers(proxy, x, "trojan", allocator); proxy.AddMember("password", rapidjson::StringRef(x.Password.c_str()), allocator); auto transport = buildSingBoxTransport(x, allocator); if (!transport.ObjectEmpty()) proxy.AddMember("transport", transport, allocator); break; } case ProxyType::WireGuard: { proxy.AddMember("type", "wireguard", allocator); proxy.AddMember("tag", rapidjson::StringRef(x.Remark.c_str()), allocator); rapidjson::Value addresses(rapidjson::kArrayType); addresses.PushBack(rapidjson::StringRef(x.SelfIP.c_str()), allocator); if (!x.SelfIPv6.empty()) addresses.PushBack(rapidjson::StringRef(x.SelfIPv6.c_str()), allocator); proxy.AddMember("local_address", addresses, allocator); proxy.AddMember("private_key", rapidjson::StringRef(x.PrivateKey.c_str()), allocator); rapidjson::Value peer(rapidjson::kObjectType); peer.AddMember("server", rapidjson::StringRef(x.Hostname.c_str()), allocator); peer.AddMember("server_port", x.Port, allocator); peer.AddMember("public_key", rapidjson::StringRef(x.PublicKey.c_str()), allocator); if (!x.PreSharedKey.empty()) peer.AddMember("pre_shared_key", rapidjson::StringRef(x.PreSharedKey.c_str()), allocator); if (!x.AllowedIPs.empty()) { auto allowed_ips = stringArrayToJsonArray(x.AllowedIPs, ",", allocator); peer.AddMember("allowed_ips", allowed_ips, allocator); } if (!x.ClientId.empty()) { auto reserved = stringArrayToJsonArray(x.ClientId, ",", allocator); peer.AddMember("reserved", reserved, allocator); } rapidjson::Value peers(rapidjson::kArrayType); peers.PushBack(peer, allocator); proxy.AddMember("peers", peers, allocator); proxy.AddMember("mtu", x.Mtu, allocator); break; } case ProxyType::HTTP: case ProxyType::HTTPS: { addSingBoxCommonMembers(proxy, x, "http", allocator); proxy.AddMember("username", rapidjson::StringRef(x.Username.c_str()), allocator); proxy.AddMember("password", rapidjson::StringRef(x.Password.c_str()), allocator); break; } case ProxyType::SOCKS5: { addSingBoxCommonMembers(proxy, x, "socks", allocator); proxy.AddMember("version", "5", allocator); proxy.AddMember("username", rapidjson::StringRef(x.Username.c_str()), allocator); proxy.AddMember("password", rapidjson::StringRef(x.Password.c_str()), allocator); break; } default: continue; } if (x.TLSSecure) { rapidjson::Value tls(rapidjson::kObjectType); tls.AddMember("enabled", true, allocator); if (!x.ServerName.empty()) tls.AddMember("server_name", rapidjson::StringRef(x.ServerName.c_str()), allocator); else if (!x.Host.empty()) tls.AddMember("server_name", rapidjson::StringRef(x.Host.c_str()), allocator); tls.AddMember("insecure", buildBooleanValue(scv), allocator); proxy.AddMember("tls", tls, allocator); } if (!udp.is_undef() && !udp) { proxy.AddMember("network", "tcp", allocator); } if (!tfo.is_undef()) { proxy.AddMember("tcp_fast_open", buildBooleanValue(tfo), allocator); } nodelist.push_back(x); remarks_list.emplace_back(x.Remark); outbounds.PushBack(proxy, allocator); } if (ext.nodelist) { json | AddMemberOrReplace("outbounds", outbounds, allocator); return; } for (const ProxyGroupConfig &x: extra_proxy_group) { string_array filtered_nodelist; std::string type; switch (x.Type) { case ProxyGroupType::Select: { type = "selector"; break; } case ProxyGroupType::URLTest: case ProxyGroupType::Fallback: case ProxyGroupType::LoadBalance: { type = "urltest"; break; } default: continue; } for (const auto &y : x.Proxies) groupGenerate(y, nodelist, filtered_nodelist, true, ext); if (filtered_nodelist.empty()) filtered_nodelist.emplace_back("DIRECT"); rapidjson::Value group(rapidjson::kObjectType); group.AddMember("type", rapidjson::Value(type.c_str(), allocator), allocator); group.AddMember("tag", rapidjson::Value(x.Name.c_str(), allocator), allocator); rapidjson::Value group_outbounds(rapidjson::kArrayType); for (const std::string& y: filtered_nodelist) { group_outbounds.PushBack(rapidjson::Value(y.c_str(), allocator), allocator); } group.AddMember("outbounds", group_outbounds, allocator); if (x.Type == ProxyGroupType::URLTest) { group.AddMember("url", rapidjson::Value(x.Url.c_str(), allocator), allocator); group.AddMember("interval", rapidjson::Value(formatSingBoxInterval(x.Interval).c_str(), allocator), allocator); if (x.Tolerance > 0) group.AddMember("tolerance", x.Tolerance, allocator); } outbounds.PushBack(group, allocator); } if (global.singBoxAddClashModes) { auto global_group = rapidjson::Value(rapidjson::kObjectType); global_group.AddMember("type", "selector", allocator); global_group.AddMember("tag", "GLOBAL", allocator); global_group.AddMember("outbounds", rapidjson::Value(rapidjson::kArrayType), allocator); global_group["outbounds"].PushBack("DIRECT", allocator); for (auto &x: remarks_list) { global_group["outbounds"].PushBack(rapidjson::Value(x.c_str(), allocator), allocator); } outbounds.PushBack(global_group, allocator); } json | AddMemberOrReplace("outbounds", outbounds, allocator); } std::string proxyToSingBox(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext) { using namespace rapidjson_ext; rapidjson::Document json; if (!ext.nodelist) { json.Parse(base_conf.data()); if (json.HasParseError()) { writeLog(0, "sing-box base loader failed with error: " + std::string(rapidjson::GetParseError_En(json.GetParseError())), LOG_LEVEL_ERROR); return ""; } } else { json.SetObject(); } proxyToSingBox(nodes, json, ruleset_content_array, extra_proxy_group, ext); if(ext.nodelist || !ext.enable_rule_generator) return json | SerializeObject(); rulesetToSingBox(json, ruleset_content_array, ext.overwrite_original_rules); return json | SerializeObject(); }
93,425
C++
.cpp
2,199
31.019554
402
0.531684
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,463
wrapper.cpp
tindy2013_subconverter/src/lib/wrapper.cpp
#include "handler/settings.h" #include <string> Settings global; bool fileExist(const std::string&, bool) { return false; } std::string fileGet(const std::string&, bool) { return ""; }
187
C++
.cpp
5
36
60
0.733333
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,464
subparser.cpp
tindy2013_subconverter/src/parser/subparser.cpp
#include <string> #include <map> #include "utils/base64/base64.h" #include "utils/ini_reader/ini_reader.h" #include "utils/network.h" #include "utils/rapidjson_extra.h" #include "utils/regexp.h" #include "utils/string.h" #include "utils/string_hash.h" #include "utils/urlencode.h" #include "utils/yamlcpp_extra.h" #include "config/proxy.h" #include "subparser.h" using namespace rapidjson; using namespace rapidjson_ext; using namespace YAML; string_array ss_ciphers = {"rc4-md5", "aes-128-gcm", "aes-192-gcm", "aes-256-gcm", "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", "aes-128-ctr", "aes-192-ctr", "aes-256-ctr", "camellia-128-cfb", "camellia-192-cfb", "camellia-256-cfb", "bf-cfb", "chacha20-ietf-poly1305", "xchacha20-ietf-poly1305", "salsa20", "chacha20", "chacha20-ietf", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305", "2022-blake3-chacha12-poly1305", "2022-blake3-chacha8-poly1305"}; string_array ssr_ciphers = {"none", "table", "rc4", "rc4-md5", "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", "aes-128-ctr", "aes-192-ctr", "aes-256-ctr", "bf-cfb", "camellia-128-cfb", "camellia-192-cfb", "camellia-256-cfb", "cast5-cfb", "des-cfb", "idea-cfb", "rc2-cfb", "seed-cfb", "salsa20", "chacha20", "chacha20-ietf"}; std::map<std::string, std::string> parsedMD5; std::string modSSMD5 = "f7653207090ce3389115e9c88541afe0"; //remake from speedtestutil void commonConstruct(Proxy &node, ProxyType type, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const tribool &udp, const tribool &tfo, const tribool &scv, const tribool &tls13, const std::string& underlying_proxy) { node.Type = type; node.Group = group; node.Remark = remarks; node.Hostname = server; node.UnderlyingProxy = underlying_proxy; node.Port = to_int(port); node.UDP = udp; node.TCPFastOpen = tfo; node.AllowInsecure = scv; node.TLS13 = tls13; } void vmessConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &add, const std::string &port, const std::string &type, const std::string &id, const std::string &aid, const std::string &net, const std::string &cipher, const std::string &path, const std::string &host, const std::string &edge, const std::string &tls, const std::string &sni, tribool udp, tribool tfo, tribool scv, tribool tls13, const std::string& underlying_proxy) { commonConstruct(node, ProxyType::VMess, group, remarks, add, port, udp, tfo, scv, tls13, underlying_proxy); node.UserId = id.empty() ? "00000000-0000-0000-0000-000000000000" : id; node.AlterId = to_int(aid); node.EncryptMethod = cipher; node.TransferProtocol = net.empty() ? "tcp" : net; node.Edge = edge; node.ServerName = sni; if(net == "quic") { node.QUICSecure = host; node.QUICSecret = path; } else { node.Host = (host.empty() && !isIPv4(add) && !isIPv6(add)) ? add.data() : trim(host); node.Path = path.empty() ? "/" : trim(path); } node.FakeType = type; node.TLSSecure = tls == "tls"; } void ssrConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &protocol, const std::string &method, const std::string &obfs, const std::string &password, const std::string &obfsparam, const std::string &protoparam, tribool udp, tribool tfo, tribool scv,const std::string& underlying_proxy) { commonConstruct(node, ProxyType::ShadowsocksR, group, remarks, server, port, udp, tfo, scv, tribool(), underlying_proxy); node.Password = password; node.EncryptMethod = method; node.Protocol = protocol; node.ProtocolParam = protoparam; node.OBFS = obfs; node.OBFSParam = obfsparam; } void ssConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &password, const std::string &method, const std::string &plugin, const std::string &pluginopts, tribool udp, tribool tfo, tribool scv, tribool tls13, const std::string& underlying_proxy) { commonConstruct(node, ProxyType::Shadowsocks, group, remarks, server, port, udp, tfo, scv, tls13, underlying_proxy); node.Password = password; node.EncryptMethod = method; node.Plugin = plugin; node.PluginOption = pluginopts; } void socksConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &username, const std::string &password, tribool udp, tribool tfo, tribool scv, const std::string& underlying_proxy) { commonConstruct(node, ProxyType::SOCKS5, group, remarks, server, port, udp, tfo, scv, tribool(), underlying_proxy); node.Username = username; node.Password = password; } void httpConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &username, const std::string &password, bool tls, tribool tfo, tribool scv, tribool tls13,const std::string& underlying_proxy) { commonConstruct(node, tls ? ProxyType::HTTPS : ProxyType::HTTP, group, remarks, server, port, tribool(), tfo, scv, tls13, underlying_proxy); node.Username = username; node.Password = password; node.TLSSecure = tls; } void trojanConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &password, const std::string &network, const std::string &host, const std::string &path, bool tlssecure, tribool udp, tribool tfo, tribool scv, tribool tls13, const std::string& underlying_proxy) { commonConstruct(node, ProxyType::Trojan, group, remarks, server, port, udp, tfo, scv, tls13, underlying_proxy); node.Password = password; node.Host = host; node.TLSSecure = tlssecure; node.TransferProtocol = network.empty() ? "tcp" : network; node.Path = path; } void snellConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &password, const std::string &obfs, const std::string &host, uint16_t version, tribool udp, tribool tfo, tribool scv, const std::string& underlying_proxy) { commonConstruct(node, ProxyType::Snell, group, remarks, server, port, udp, tfo, scv, tribool(), underlying_proxy); node.Password = password; node.OBFS = obfs; node.Host = host; node.SnellVersion = version; } void wireguardConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &selfIp, const std::string &selfIpv6, const std::string &privKey, const std::string &pubKey, const std::string &psk, const string_array &dns, const std::string &mtu, const std::string &keepalive, const std::string &testUrl, const std::string &clientId, const tribool &udp, const std::string& underlying_proxy) { commonConstruct(node, ProxyType::WireGuard, group, remarks, server, port, udp, tribool(), tribool(), tribool(), underlying_proxy); node.SelfIP = selfIp; node.SelfIPv6 = selfIpv6; node.PrivateKey = privKey; node.PublicKey = pubKey; node.PreSharedKey = psk; node.DnsServers = dns; node.Mtu = to_int(mtu); node.KeepAlive = to_int(keepalive); node.TestUrl = testUrl; node.ClientId = clientId; } void explodeVmess(std::string vmess, Proxy &node) { std::string version, ps, add, port, type, id, aid, net, path, host, tls, sni; Document jsondata; std::vector<std::string> vArray; if(regMatch(vmess, "vmess://([A-Za-z0-9-_]+)\\?(.*)")) //shadowrocket style link { explodeShadowrocket(vmess, node); return; } else if(regMatch(vmess, "vmess://(.*?)@(.*)")) { explodeStdVMess(vmess, node); return; } else if(regMatch(vmess, "vmess1://(.*?)\\?(.*)")) //kitsunebi style link { explodeKitsunebi(vmess, node); return; } vmess = urlSafeBase64Decode(regReplace(vmess, "(vmess|vmess1)://", "")); if(regMatch(vmess, "(.*?) = (.*)")) { explodeQuan(vmess, node); return; } jsondata.Parse(vmess.data()); if(jsondata.HasParseError() || !jsondata.IsObject()) return; version = "1"; //link without version will treat as version 1 GetMember(jsondata, "v", version); //try to get version GetMember(jsondata, "ps", ps); GetMember(jsondata, "add", add); port = GetMember(jsondata, "port"); if(port == "0") return; GetMember(jsondata, "type", type); GetMember(jsondata, "id", id); GetMember(jsondata, "aid", aid); GetMember(jsondata, "net", net); GetMember(jsondata, "tls", tls); GetMember(jsondata, "host", host); GetMember(jsondata, "sni", sni); switch(to_int(version)) { case 1: if(!host.empty()) { vArray = split(host, ";"); if(vArray.size() == 2) { host = vArray[0]; path = vArray[1]; } } break; case 2: path = GetMember(jsondata, "path"); break; } add = trim(add); vmessConstruct(node, V2RAY_DEFAULT_GROUP, ps, add, port, type, id, aid, net, "auto", path, host, "", tls, sni); } void explodeVmessConf(std::string content, std::vector<Proxy> &nodes) { Document json; rapidjson::Value nodejson, settings; std::string group, ps, add, port, type, id, aid, net, path, host, edge, tls, cipher, subid, sni; tribool udp, tfo, scv; int configType; uint32_t index = nodes.size(); std::map<std::string, std::string> subdata; std::map<std::string, std::string>::iterator iter; std::string streamset = "streamSettings", tcpset = "tcpSettings", wsset = "wsSettings"; regGetMatch(content, "((?i)streamsettings)", 2, 0, &streamset); regGetMatch(content, "((?i)tcpsettings)", 2, 0, &tcpset); regGetMatch(content, "((?1)wssettings)", 2, 0, &wsset); json.Parse(content.data()); if(json.HasParseError() || !json.IsObject()) return; try { if(json.HasMember("outbounds")) //single config { if(json["outbounds"].Size() > 0 && json["outbounds"][0].HasMember("settings") && json["outbounds"][0]["settings"].HasMember("vnext") && json["outbounds"][0]["settings"]["vnext"].Size() > 0) { Proxy node; nodejson = json["outbounds"][0]; add = GetMember(nodejson["settings"]["vnext"][0], "address"); port = GetMember(nodejson["settings"]["vnext"][0], "port"); if(port == "0") return; if(nodejson["settings"]["vnext"][0]["users"].Size()) { id = GetMember(nodejson["settings"]["vnext"][0]["users"][0], "id"); aid = GetMember(nodejson["settings"]["vnext"][0]["users"][0], "alterId"); cipher = GetMember(nodejson["settings"]["vnext"][0]["users"][0], "security"); } if(nodejson.HasMember(streamset.data())) { net = GetMember(nodejson[streamset.data()], "network"); tls = GetMember(nodejson[streamset.data()], "security"); if(net == "ws") { if(nodejson[streamset.data()].HasMember(wsset.data())) settings = nodejson[streamset.data()][wsset.data()]; else settings.RemoveAllMembers(); path = GetMember(settings, "path"); if(settings.HasMember("headers")) { host = GetMember(settings["headers"], "Host"); edge = GetMember(settings["headers"], "Edge"); } } if(nodejson[streamset.data()].HasMember(tcpset.data())) settings = nodejson[streamset.data()][tcpset.data()]; else settings.RemoveAllMembers(); if(settings.IsObject() && settings.HasMember("header")) { type = GetMember(settings["header"], "type"); if(type == "http") { if(settings["header"].HasMember("request")) { if(settings["header"]["request"].HasMember("path") && settings["header"]["request"]["path"].Size()) settings["header"]["request"]["path"][0] >> path; if(settings["header"]["request"].HasMember("headers")) { host = GetMember(settings["header"]["request"]["headers"], "Host"); edge = GetMember(settings["header"]["request"]["headers"], "Edge"); } } } } } vmessConstruct(node, V2RAY_DEFAULT_GROUP, add + ":" + port, add, port, type, id, aid, net, cipher, path, host, edge, tls, "", udp, tfo, scv); nodes.emplace_back(std::move(node)); } return; } } catch(std::exception & e) { //writeLog(0, "VMessConf parser throws an error. Leaving...", LOG_LEVEL_WARNING); //return; //ignore throw; } //read all subscribe remark as group name for(uint32_t i = 0; i < json["subItem"].Size(); i++) subdata.insert(std::pair<std::string, std::string>(json["subItem"][i]["id"].GetString(), json["subItem"][i]["remarks"].GetString())); for(uint32_t i = 0; i < json["vmess"].Size(); i++) { Proxy node; if(json["vmess"][i]["address"].IsNull() || json["vmess"][i]["port"].IsNull() || json["vmess"][i]["id"].IsNull()) continue; //common info json["vmess"][i]["remarks"] >> ps; json["vmess"][i]["address"] >> add; port = GetMember(json["vmess"][i], "port"); if(port == "0") continue; json["vmess"][i]["subid"] >> subid; if(!subid.empty()) { iter = subdata.find(subid); if(iter != subdata.end()) group = iter->second; } if(ps.empty()) ps = add + ":" + port; scv = GetMember(json["vmess"][i], "allowInsecure"); json["vmess"][i]["configType"] >> configType; switch(configType) { case 1: //vmess config json["vmess"][i]["headerType"] >> type; json["vmess"][i]["id"] >> id; json["vmess"][i]["alterId"] >> aid; json["vmess"][i]["network"] >> net; json["vmess"][i]["path"] >> path; json["vmess"][i]["requestHost"] >> host; json["vmess"][i]["streamSecurity"] >> tls; json["vmess"][i]["security"] >> cipher; json["vmess"][i]["sni"] >> sni; vmessConstruct(node, V2RAY_DEFAULT_GROUP, ps, add, port, type, id, aid, net, cipher, path, host, "", tls, sni, udp, tfo, scv); break; case 3: //ss config json["vmess"][i]["id"] >> id; json["vmess"][i]["security"] >> cipher; ssConstruct(node, SS_DEFAULT_GROUP, ps, add, port, id, cipher, "", "", udp, tfo, scv); break; case 4: //socks config socksConstruct(node, SOCKS_DEFAULT_GROUP, ps, add, port, "", "", udp, tfo, scv); break; default: continue; } node.Id = index; nodes.emplace_back(std::move(node)); index++; } } void explodeSS(std::string ss, Proxy &node) { std::string ps, password, method, server, port, plugins, plugin, pluginopts, addition, group = SS_DEFAULT_GROUP, secret; //std::vector<std::string> args, secret; ss = replaceAllDistinct(ss.substr(5), "/?", "?"); if(strFind(ss, "#")) { auto sspos = ss.find('#'); ps = urlDecode(ss.substr(sspos + 1)); ss.erase(sspos); } if(strFind(ss, "?")) { addition = ss.substr(ss.find('?') + 1); plugins = urlDecode(getUrlArg(addition, "plugin")); auto pluginpos = plugins.find(';'); plugin = plugins.substr(0, pluginpos); pluginopts = plugins.substr(pluginpos + 1); group = getUrlArg(addition, "group"); if(!group.empty()) group = urlSafeBase64Decode(group); ss.erase(ss.find('?')); } if(strFind(ss, "@")) { if(regGetMatch(ss, "(\\S+?)@(\\S+):(\\d+)", 4, 0, &secret, &server, &port)) return; if(regGetMatch(urlSafeBase64Decode(secret), "(\\S+?):(\\S+)", 3, 0, &method, &password)) return; } else { if(regGetMatch(urlSafeBase64Decode(ss), "(\\S+?):(\\S+)@(\\S+):(\\d+)", 5, 0, &method, &password, &server, &port)) return; } if(port == "0") return; if(ps.empty()) ps = server + ":" + port; ssConstruct(node, group, ps, server, port, password, method, plugin, pluginopts); } void explodeSSD(std::string link, std::vector<Proxy> &nodes) { Document jsondata; uint32_t index = nodes.size(), listType = 0, listCount = 0; std::string group, port, method, password, server, remarks; std::string plugin, pluginopts; std::map<uint32_t, std::string> node_map; link = urlSafeBase64Decode(link.substr(6)); jsondata.Parse(link.c_str()); if(jsondata.HasParseError() || !jsondata.IsObject()) return; if(!jsondata.HasMember("servers")) return; GetMember(jsondata, "airport", group); if(jsondata["servers"].IsArray()) { listType = 0; listCount = jsondata["servers"].Size(); } else if(jsondata["servers"].IsObject()) { listType = 1; listCount = jsondata["servers"].MemberCount(); uint32_t node_index = 0; for(rapidjson::Value::MemberIterator iter = jsondata["servers"].MemberBegin(); iter != jsondata["servers"].MemberEnd(); iter++) { node_map.emplace(node_index, iter->name.GetString()); node_index++; } } else return; rapidjson::Value singlenode; for(uint32_t i = 0; i < listCount; i++) { //get default info port = GetMember(jsondata, "port"); method = GetMember(jsondata, "encryption"); password = GetMember(jsondata, "password"); plugin = GetMember(jsondata, "plugin"); pluginopts = GetMember(jsondata, "plugin_options"); //get server-specific info switch(listType) { case 0: singlenode = jsondata["servers"][i]; break; case 1: singlenode = jsondata["servers"].FindMember(node_map[i].data())->value; break; default: continue; } singlenode["server"] >> server; GetMember(singlenode, "remarks", remarks); GetMember(singlenode, "port", port); GetMember(singlenode, "encryption", method); GetMember(singlenode, "password", password); GetMember(singlenode, "plugin", plugin); GetMember(singlenode, "plugin_options", pluginopts); if(port == "0") continue; Proxy node; ssConstruct(node, group, remarks, server, port, password, method, plugin, pluginopts); node.Id = index; nodes.emplace_back(std::move(node)); index++; } } void explodeSSAndroid(std::string ss, std::vector<Proxy> &nodes) { std::string ps, password, method, server, port, group = SS_DEFAULT_GROUP; std::string plugin, pluginopts; Document json; auto index = nodes.size(); //first add some extra data before parsing ss = "{\"nodes\":" + ss + "}"; json.Parse(ss.data()); if(json.HasParseError() || !json.IsObject()) return; for(uint32_t i = 0; i < json["nodes"].Size(); i++) { Proxy node; server = GetMember(json["nodes"][i], "server"); if(server.empty()) continue; ps = GetMember(json["nodes"][i], "remarks"); port = GetMember(json["nodes"][i], "server_port"); if(port == "0") continue; if(ps.empty()) ps = server + ":" + port; password = GetMember(json["nodes"][i], "password"); method = GetMember(json["nodes"][i], "method"); plugin = GetMember(json["nodes"][i], "plugin"); pluginopts = GetMember(json["nodes"][i], "plugin_opts"); ssConstruct(node, group, ps, server, port, password, method, plugin, pluginopts); node.Id = index; nodes.emplace_back(std::move(node)); index++; } } void explodeSSConf(std::string content, std::vector<Proxy> &nodes) { Document json; std::string ps, password, method, server, port, plugin, pluginopts, group = SS_DEFAULT_GROUP; auto index = nodes.size(); json.Parse(content.data()); if(json.HasParseError() || !json.IsObject()) return; const char *section = json.HasMember("version") && json.HasMember("servers") ? "servers" : "configs"; if(!json.HasMember(section)) return; GetMember(json, "remarks", group); for(uint32_t i = 0; i < json[section].Size(); i++) { Proxy node; ps = GetMember(json[section][i], "remarks"); port = GetMember(json[section][i], "server_port"); if(port == "0") continue; if(ps.empty()) ps = server + ":" + port; password = GetMember(json[section][i], "password"); method = GetMember(json[section][i], "method"); server = GetMember(json[section][i], "server"); plugin = GetMember(json[section][i], "plugin"); pluginopts = GetMember(json[section][i], "plugin_opts"); node.Id = index; ssConstruct(node, group, ps, server, port, password, method, plugin, pluginopts); nodes.emplace_back(std::move(node)); index++; } } void explodeSSR(std::string ssr, Proxy &node) { std::string strobfs; std::string remarks, group, server, port, method, password, protocol, protoparam, obfs, obfsparam; ssr = replaceAllDistinct(ssr.substr(6), "\r", ""); ssr = urlSafeBase64Decode(ssr); if(strFind(ssr, "/?")) { strobfs = ssr.substr(ssr.find("/?") + 2); ssr = ssr.substr(0, ssr.find("/?")); group = urlSafeBase64Decode(getUrlArg(strobfs, "group")); remarks = urlSafeBase64Decode(getUrlArg(strobfs, "remarks")); obfsparam = regReplace(urlSafeBase64Decode(getUrlArg(strobfs, "obfsparam")), "\\s", ""); protoparam = regReplace(urlSafeBase64Decode(getUrlArg(strobfs, "protoparam")), "\\s", ""); } if(regGetMatch(ssr, "(\\S+):(\\d+?):(\\S+?):(\\S+?):(\\S+?):(\\S+)", 7, 0, &server, &port, &protocol, &method, &obfs, &password)) return; password = urlSafeBase64Decode(password); if(port == "0") return; if(group.empty()) group = SSR_DEFAULT_GROUP; if(remarks.empty()) remarks = server + ":" + port; if(find(ss_ciphers.begin(), ss_ciphers.end(), method) != ss_ciphers.end() && (obfs.empty() || obfs == "plain") && (protocol.empty() || protocol == "origin")) { ssConstruct(node, group, remarks, server, port, password, method, "", ""); } else { ssrConstruct(node, group, remarks, server, port, protocol, method, obfs, password, obfsparam, protoparam); } } void explodeSSRConf(std::string content, std::vector<Proxy> &nodes) { Document json; std::string remarks, group, server, port, method, password, protocol, protoparam, obfs, obfsparam, plugin, pluginopts; auto index = nodes.size(); json.Parse(content.data()); if(json.HasParseError() || !json.IsObject()) return; if(json.HasMember("local_port") && json.HasMember("local_address")) //single libev config { Proxy node; server = GetMember(json, "server"); port = GetMember(json, "server_port"); remarks = server + ":" + port; method = GetMember(json, "method"); obfs = GetMember(json, "obfs"); protocol = GetMember(json, "protocol"); if(find(ss_ciphers.begin(), ss_ciphers.end(), method) != ss_ciphers.end() && (obfs.empty() || obfs == "plain") && (protocol.empty() || protocol == "origin")) { plugin = GetMember(json, "plugin"); pluginopts = GetMember(json, "plugin_opts"); ssConstruct(node, SS_DEFAULT_GROUP, remarks, server, port, password, method, plugin, pluginopts); } else { protoparam = GetMember(json, "protocol_param"); obfsparam = GetMember(json, "obfs_param"); ssrConstruct(node, SSR_DEFAULT_GROUP, remarks, server, port, protocol, method, obfs, password, obfsparam, protoparam); } nodes.emplace_back(std::move(node)); return; } for(uint32_t i = 0; i < json["configs"].Size(); i++) { Proxy node; group = GetMember(json["configs"][i], "group"); if(group.empty()) group = SSR_DEFAULT_GROUP; remarks = GetMember(json["configs"][i], "remarks"); server = GetMember(json["configs"][i], "server"); port = GetMember(json["configs"][i], "server_port"); if(port == "0") continue; if(remarks.empty()) remarks = server + ":" + port; password = GetMember(json["configs"][i], "password"); method = GetMember(json["configs"][i], "method"); protocol = GetMember(json["configs"][i], "protocol"); protoparam = GetMember(json["configs"][i], "protocolparam"); obfs = GetMember(json["configs"][i], "obfs"); obfsparam = GetMember(json["configs"][i], "obfsparam"); ssrConstruct(node, group, remarks, server, port, protocol, method, obfs, password, obfsparam, protoparam); node.Id = index; nodes.emplace_back(std::move(node)); index++; } } void explodeSocks(std::string link, Proxy &node) { std::string group, remarks, server, port, username, password; if(strFind(link, "socks://")) //v2rayn socks link { if(strFind(link, "#")) { auto pos = link.find('#'); remarks = urlDecode(link.substr(pos + 1)); link.erase(pos); } link = urlSafeBase64Decode(link.substr(8)); if(strFind(link, "@")) { auto userinfo = split(link, '@'); if(userinfo.size() < 2) return; link = userinfo[1]; userinfo = split(userinfo[0], ':'); if(userinfo.size() < 2) return; username = userinfo[0]; password = userinfo[1]; } auto arguments = split(link, ':'); if(arguments.size() < 2) return; server = arguments[0]; port = arguments[1]; } else if(strFind(link, "https://t.me/socks") || strFind(link, "tg://socks")) //telegram style socks link { server = getUrlArg(link, "server"); port = getUrlArg(link, "port"); username = urlDecode(getUrlArg(link, "user")); password = urlDecode(getUrlArg(link, "pass")); remarks = urlDecode(getUrlArg(link, "remarks")); group = urlDecode(getUrlArg(link, "group")); } if(group.empty()) group = SOCKS_DEFAULT_GROUP; if(remarks.empty()) remarks = server + ":" + port; if(port == "0") return; socksConstruct(node, group, remarks, server, port, username, password); } void explodeHTTP(const std::string &link, Proxy &node) { std::string group, remarks, server, port, username, password; server = getUrlArg(link, "server"); port = getUrlArg(link, "port"); username = urlDecode(getUrlArg(link, "user")); password = urlDecode(getUrlArg(link, "pass")); remarks = urlDecode(getUrlArg(link, "remarks")); group = urlDecode(getUrlArg(link, "group")); if(group.empty()) group = HTTP_DEFAULT_GROUP; if(remarks.empty()) remarks = server + ":" + port; if(port == "0") return; httpConstruct(node, group, remarks, server, port, username, password, strFind(link, "/https")); } void explodeHTTPSub(std::string link, Proxy &node) { std::string group, remarks, server, port, username, password; std::string addition; bool tls = strFind(link, "https://"); auto pos = link.find('?'); if(pos != std::string::npos) { addition = link.substr(pos + 1); link.erase(pos); remarks = urlDecode(getUrlArg(addition, "remarks")); group = urlDecode(getUrlArg(addition, "group")); } link.erase(0, link.find("://") + 3); link = urlSafeBase64Decode(link); if(strFind(link, "@")) { if(regGetMatch(link, "(.*?):(.*?)@(.*):(.*)", 5, 0, &username, &password, &server, &port)) return; } else { if(regGetMatch(link, "(.*):(.*)", 3, 0, &server, &port)) return; } if(group.empty()) group = HTTP_DEFAULT_GROUP; if(remarks.empty()) remarks = server + ":" + port; if(port == "0") return; httpConstruct(node, group, remarks, server, port, username, password, tls); } void explodeTrojan(std::string trojan, Proxy &node) { std::string server, port, psk, addition, group, remark, host, path, network; tribool tfo, scv; trojan.erase(0, 9); string_size pos = trojan.rfind('#'); if(pos != std::string::npos) { remark = urlDecode(trojan.substr(pos + 1)); trojan.erase(pos); } pos = trojan.find('?'); if(pos != std::string::npos) { addition = trojan.substr(pos + 1); trojan.erase(pos); } if(regGetMatch(trojan, "(.*?)@(.*):(.*)", 4, 0, &psk, &server, &port)) return; if(port == "0") return; host = getUrlArg(addition, "sni"); if(host.empty()) host = getUrlArg(addition, "peer"); tfo = getUrlArg(addition, "tfo"); scv = getUrlArg(addition, "allowInsecure"); group = urlDecode(getUrlArg(addition, "group")); if(getUrlArg(addition, "ws") == "1") { path = getUrlArg(addition, "wspath"); network = "ws"; } // support the trojan link format used by v2ryaN and X-ui. // format: trojan://{password}@{server}:{port}?type=ws&security=tls&path={path (urlencoded)}&sni={host}#{name} else if(getUrlArg(addition, "type") == "ws") { path = getUrlArg(addition, "path"); if(path.substr(0, 3) == "%2F") path = urlDecode(path); network = "ws"; } if(remark.empty()) remark = server + ":" + port; if(group.empty()) group = TROJAN_DEFAULT_GROUP; trojanConstruct(node, group, remark, server, port, psk, network, host, path, true, tribool(), tfo, scv); } void explodeQuan(const std::string &quan, Proxy &node) { std::string strTemp, itemName, itemVal; std::string group = V2RAY_DEFAULT_GROUP, ps, add, port, cipher, type = "none", id, aid = "0", net = "tcp", path, host, edge, tls; string_array configs, vArray, headers; strTemp = regReplace(quan, "(.*?) = (.*)", "$1,$2"); configs = split(strTemp, ","); if(configs[1] == "vmess") { if(configs.size() < 6) return; ps = trim(configs[0]); add = trim(configs[2]); port = trim(configs[3]); if(port == "0") return; cipher = trim(configs[4]); id = trim(replaceAllDistinct(configs[5], "\"", "")); //read link for(uint32_t i = 6; i < configs.size(); i++) { vArray = split(configs[i], "="); if(vArray.size() < 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "group"_hash: group = itemVal; break; case "over-tls"_hash: tls = itemVal == "true" ? "tls" : ""; break; case "tls-host"_hash: host = itemVal; break; case "obfs-path"_hash: path = replaceAllDistinct(itemVal, "\"", ""); break; case "obfs-header"_hash: headers = split(replaceAllDistinct(replaceAllDistinct(itemVal, "\"", ""), "[Rr][Nn]", "|"), "|"); for(std::string &x : headers) { if(regFind(x, "(?i)Host: ")) host = x.substr(6); else if(regFind(x, "(?i)Edge: ")) edge = x.substr(6); } break; case "obfs"_hash: if(itemVal == "ws") net = "ws"; break; default: continue; } } if(path.empty()) path = "/"; vmessConstruct(node, group, ps, add, port, type, id, aid, net, cipher, path, host, edge, tls, ""); } } void explodeNetch(std::string netch, Proxy &node) { Document json; std::string type, group, remark, address, port, username, password, method, plugin, pluginopts; std::string protocol, protoparam, obfs, obfsparam, id, aid, transprot, faketype, host, edge, path, tls, sni; tribool udp, tfo, scv; netch = urlSafeBase64Decode(netch.substr(8)); json.Parse(netch.data()); if(json.HasParseError() || !json.IsObject()) return; type = GetMember(json, "Type"); group = GetMember(json, "Group"); remark = GetMember(json, "Remark"); address = GetMember(json, "Hostname"); udp = GetMember(json, "EnableUDP"); tfo = GetMember(json, "EnableTFO"); scv = GetMember(json, "AllowInsecure"); port = GetMember(json, "Port"); if(port == "0") return; method = GetMember(json, "EncryptMethod"); password = GetMember(json, "Password"); if(remark.empty()) remark = address + ":" + port; switch(hash_(type)) { case "SS"_hash: plugin = GetMember(json, "Plugin"); pluginopts = GetMember(json, "PluginOption"); if(group.empty()) group = SS_DEFAULT_GROUP; ssConstruct(node, group, remark, address, port, password, method, plugin, pluginopts, udp, tfo, scv); break; case "SSR"_hash: protocol = GetMember(json, "Protocol"); obfs = GetMember(json, "OBFS"); if(find(ss_ciphers.begin(), ss_ciphers.end(), method) != ss_ciphers.end() && (obfs.empty() || obfs == "plain") && (protocol.empty() || protocol == "origin")) { plugin = GetMember(json, "Plugin"); pluginopts = GetMember(json, "PluginOption"); if(group.empty()) group = SS_DEFAULT_GROUP; ssConstruct(node, group, remark, address, port, password, method, plugin, pluginopts, udp, tfo, scv); } else { protoparam = GetMember(json, "ProtocolParam"); obfsparam = GetMember(json, "OBFSParam"); if(group.empty()) group = SSR_DEFAULT_GROUP; ssrConstruct(node, group, remark, address, port, protocol, method, obfs, password, obfsparam, protoparam, udp, tfo, scv); } break; case "VMess"_hash: id = GetMember(json, "UserID"); aid = GetMember(json, "AlterID"); transprot = GetMember(json, "TransferProtocol"); faketype = GetMember(json, "FakeType"); host = GetMember(json, "Host"); path = GetMember(json, "Path"); edge = GetMember(json, "Edge"); tls = GetMember(json, "TLSSecure"); sni = GetMember(json, "ServerName"); if(group.empty()) group = V2RAY_DEFAULT_GROUP; vmessConstruct(node, group, remark, address, port, faketype, id, aid, transprot, method, path, host, edge, tls, sni, udp, tfo, scv); break; case "Socks5"_hash: username = GetMember(json, "Username"); if(group.empty()) group = SOCKS_DEFAULT_GROUP; socksConstruct(node, group, remark, address, port, username, password, udp, tfo, scv); break; case "HTTP"_hash: case "HTTPS"_hash: if(group.empty()) group = HTTP_DEFAULT_GROUP; httpConstruct(node, group, remark, address, port, username, password, type == "HTTPS", tfo, scv); break; case "Trojan"_hash: host = GetMember(json, "Host"); path = GetMember(json, "Path"); transprot = GetMember(json, "TransferProtocol"); tls = GetMember(json, "TLSSecure"); if(group.empty()) group = TROJAN_DEFAULT_GROUP; trojanConstruct(node, group, remark, address, port, password, transprot, host, path, tls == "true", udp, tfo, scv); break; case "Snell"_hash: obfs = GetMember(json, "OBFS"); host = GetMember(json, "Host"); aid = GetMember(json, "SnellVersion"); if(group.empty()) group = SNELL_DEFAULT_GROUP; snellConstruct(node, group, remark, address, port, password, obfs, host, to_int(aid, 0), udp, tfo, scv); break; default: return; } } void explodeClash(Node yamlnode, std::vector<Proxy> &nodes) { std::string proxytype, ps, server, port, cipher, group, password, underlying_proxy; //common std::string type = "none", id, aid = "0", net = "tcp", path, host, edge, tls, sni; //vmess std::string plugin, pluginopts, pluginopts_mode, pluginopts_host, pluginopts_mux; //ss std::string protocol, protoparam, obfs, obfsparam; //ssr std::string user; //socks std::string ip, ipv6, private_key, public_key, mtu; //wireguard string_array dns_server; tribool udp, tfo, scv; Node singleproxy; uint32_t index = nodes.size(); const std::string section = yamlnode["proxies"].IsDefined() ? "proxies" : "Proxy"; for(uint32_t i = 0; i < yamlnode[section].size(); i++) { Proxy node; singleproxy = yamlnode[section][i]; singleproxy["type"] >>= proxytype; singleproxy["name"] >>= ps; singleproxy["server"] >>= server; singleproxy["port"] >>= port; singleproxy["underlying-proxy"] >>= underlying_proxy; if(port.empty() || port == "0") continue; udp = safe_as<std::string>(singleproxy["udp"]); scv = safe_as<std::string>(singleproxy["skip-cert-verify"]); switch(hash_(proxytype)) { case "vmess"_hash: group = V2RAY_DEFAULT_GROUP; singleproxy["uuid"] >>= id; singleproxy["alterId"] >>= aid; singleproxy["cipher"] >>= cipher; net = singleproxy["network"].IsDefined() ? safe_as<std::string>(singleproxy["network"]) : "tcp"; singleproxy["servername"] >>= sni; switch(hash_(net)) { case "http"_hash: singleproxy["http-opts"]["path"][0] >>= path; singleproxy["http-opts"]["headers"]["Host"][0] >>= host; edge.clear(); break; case "ws"_hash: if(singleproxy["ws-opts"].IsDefined()) { path = singleproxy["ws-opts"]["path"].IsDefined() ? safe_as<std::string>(singleproxy["ws-opts"]["path"]) : "/"; singleproxy["ws-opts"]["headers"]["Host"] >>= host; singleproxy["ws-opts"]["headers"]["Edge"] >>= edge; } else { path = singleproxy["ws-path"].IsDefined() ? safe_as<std::string>(singleproxy["ws-path"]) : "/"; singleproxy["ws-headers"]["Host"] >>= host; singleproxy["ws-headers"]["Edge"] >>= edge; } break; case "h2"_hash: singleproxy["h2-opts"]["path"] >>= path; singleproxy["h2-opts"]["host"][0] >>= host; edge.clear(); break; case "grpc"_hash: singleproxy["servername"] >>= host; singleproxy["grpc-opts"]["grpc-service-name"] >>= path; edge.clear(); break; } tls = safe_as<std::string>(singleproxy["tls"]) == "true" ? "tls" : ""; vmessConstruct(node, group, ps, server, port, "", id, aid, net, cipher, path, host, edge, tls, sni, udp, tfo, scv, tribool(), underlying_proxy); break; case "ss"_hash: group = SS_DEFAULT_GROUP; singleproxy["cipher"] >>= cipher; singleproxy["password"] >>= password; if(singleproxy["plugin"].IsDefined()) { switch(hash_(safe_as<std::string>(singleproxy["plugin"]))) { case "obfs"_hash: plugin = "obfs-local"; if(singleproxy["plugin-opts"].IsDefined()) { singleproxy["plugin-opts"]["mode"] >>= pluginopts_mode; singleproxy["plugin-opts"]["host"] >>= pluginopts_host; } break; case "v2ray-plugin"_hash: plugin = "v2ray-plugin"; if(singleproxy["plugin-opts"].IsDefined()) { singleproxy["plugin-opts"]["mode"] >>= pluginopts_mode; singleproxy["plugin-opts"]["host"] >>= pluginopts_host; tls = safe_as<bool>(singleproxy["plugin-opts"]["tls"]) ? "tls;" : ""; singleproxy["plugin-opts"]["path"] >>= path; pluginopts_mux = safe_as<bool>(singleproxy["plugin-opts"]["mux"]) ? "mux=4;" : ""; } break; default: break; } } else if(singleproxy["obfs"].IsDefined()) { plugin = "obfs-local"; singleproxy["obfs"] >>= pluginopts_mode; singleproxy["obfs-host"] >>= pluginopts_host; } else plugin.clear(); switch(hash_(plugin)) { case "simple-obfs"_hash: case "obfs-local"_hash: pluginopts = "obfs=" + pluginopts_mode; pluginopts += pluginopts_host.empty() ? "" : ";obfs-host=" + pluginopts_host; break; case "v2ray-plugin"_hash: pluginopts = "mode=" + pluginopts_mode + ";" + tls + pluginopts_mux; if(!pluginopts_host.empty()) pluginopts += "host=" + pluginopts_host + ";"; if(!path.empty()) pluginopts += "path=" + path + ";"; if(!pluginopts_mux.empty()) pluginopts += "mux=" + pluginopts_mux + ";"; break; } //support for go-shadowsocks2 if(cipher == "AEAD_CHACHA20_POLY1305") cipher = "chacha20-ietf-poly1305"; else if(strFind(cipher, "AEAD")) { cipher = replaceAllDistinct(replaceAllDistinct(cipher, "AEAD_", ""), "_", "-"); std::transform(cipher.begin(), cipher.end(), cipher.begin(), ::tolower); } ssConstruct(node, group, ps, server, port, password, cipher, plugin, pluginopts, udp, tfo, scv, tribool(), underlying_proxy); break; case "socks5"_hash: group = SOCKS_DEFAULT_GROUP; singleproxy["username"] >>= user; singleproxy["password"] >>= password; socksConstruct(node, group, ps, server, port, user, password, tribool(), tribool(), tribool(), underlying_proxy); break; case "ssr"_hash: group = SSR_DEFAULT_GROUP; singleproxy["cipher"] >>= cipher; if(cipher == "dummy") cipher = "none"; singleproxy["password"] >>= password; singleproxy["protocol"] >>= protocol; singleproxy["obfs"] >>= obfs; if(singleproxy["protocol-param"].IsDefined()) singleproxy["protocol-param"] >>= protoparam; else singleproxy["protocolparam"] >>= protoparam; if(singleproxy["obfs-param"].IsDefined()) singleproxy["obfs-param"] >>= obfsparam; else singleproxy["obfsparam"] >>= obfsparam; ssrConstruct(node, group, ps, server, port, protocol, cipher, obfs, password, obfsparam, protoparam, udp, tfo, scv, underlying_proxy); break; case "http"_hash: group = HTTP_DEFAULT_GROUP; singleproxy["username"] >>= user; singleproxy["password"] >>= password; singleproxy["tls"] >>= tls; httpConstruct(node, group, ps, server, port, user, password, tls == "true", tfo, scv, tribool(), underlying_proxy); break; case "trojan"_hash: group = TROJAN_DEFAULT_GROUP; singleproxy["password"] >>= password; singleproxy["sni"] >>= host; singleproxy["network"] >>= net; switch(hash_(net)) { case "grpc"_hash: singleproxy["grpc-opts"]["grpc-service-name"] >>= path; break; case "ws"_hash: singleproxy["ws-opts"]["path"] >>= path; break; default: net = "tcp"; path.clear(); break; } trojanConstruct(node, group, ps, server, port, password, net, host, path, true, udp, tfo, scv, tribool(), underlying_proxy); break; case "snell"_hash: group = SNELL_DEFAULT_GROUP; singleproxy["psk"] >> password; singleproxy["obfs-opts"]["mode"] >>= obfs; singleproxy["obfs-opts"]["host"] >>= host; singleproxy["version"] >>= aid; snellConstruct(node, group, ps, server, port, password, obfs, host, to_int(aid, 0), udp, tfo, scv, underlying_proxy); break; case "wireguard"_hash: group = WG_DEFAULT_GROUP; singleproxy["public-key"] >>= public_key; singleproxy["private-key"] >>= private_key; singleproxy["dns"] >>= dns_server; singleproxy["mtu"] >>= mtu; singleproxy["preshared-key"] >>= password; singleproxy["ip"] >>= ip; singleproxy["ipv6"] >>= ipv6; wireguardConstruct(node, group, ps, server, port, ip, ipv6, private_key, public_key, password, dns_server, mtu, "0", "", "", udp, underlying_proxy); break; default: continue; } node.Id = index; nodes.emplace_back(std::move(node)); index++; } } void explodeStdVMess(std::string vmess, Proxy &node) { std::string add, port, type, id, aid, net, path, host, tls, remarks; std::string addition; vmess = vmess.substr(8); string_size pos; pos = vmess.rfind('#'); if(pos != std::string::npos) { remarks = urlDecode(vmess.substr(pos + 1)); vmess.erase(pos); } const std::string stdvmess_matcher = R"(^([a-z]+)(?:\+([a-z]+))?:([\da-f]{4}(?:[\da-f]{4}-){4}[\da-f]{12})-(\d+)@(.+):(\d+)(?:\/?\?(.*))?$)"; if(regGetMatch(vmess, stdvmess_matcher, 8, 0, &net, &tls, &id, &aid, &add, &port, &addition)) return; switch(hash_(net)) { case "tcp"_hash: case "kcp"_hash: type = getUrlArg(addition, "type"); break; case "http"_hash: case "ws"_hash: host = getUrlArg(addition, "host"); path = getUrlArg(addition, "path"); break; case "quic"_hash: type = getUrlArg(addition, "security"); host = getUrlArg(addition, "type"); path = getUrlArg(addition, "key"); break; default: return; } if(remarks.empty()) remarks = add + ":" + port; vmessConstruct(node, V2RAY_DEFAULT_GROUP, remarks, add, port, type, id, aid, net, "auto", path, host, "", tls, ""); } void explodeShadowrocket(std::string rocket, Proxy &node) { std::string add, port, type, id, aid, net = "tcp", path, host, tls, cipher, remarks; std::string obfs; //for other style of link std::string addition; rocket = rocket.substr(8); string_size pos = rocket.find('?'); addition = rocket.substr(pos + 1); rocket.erase(pos); if(regGetMatch(urlSafeBase64Decode(rocket), "(.*?):(.*)@(.*):(.*)", 5, 0, &cipher, &id, &add, &port)) return; if(port == "0") return; remarks = urlDecode(getUrlArg(addition, "remarks")); obfs = getUrlArg(addition, "obfs"); if(!obfs.empty()) { if(obfs == "websocket") { net = "ws"; host = getUrlArg(addition, "obfsParam"); path = getUrlArg(addition, "path"); } } else { net = getUrlArg(addition, "network"); host = getUrlArg(addition, "wsHost"); path = getUrlArg(addition, "wspath"); } tls = getUrlArg(addition, "tls") == "1" ? "tls" : ""; aid = getUrlArg(addition, "aid"); if(aid.empty()) aid = "0"; if(remarks.empty()) remarks = add + ":" + port; vmessConstruct(node, V2RAY_DEFAULT_GROUP, remarks, add, port, type, id, aid, net, cipher, path, host, "", tls, ""); } void explodeKitsunebi(std::string kit, Proxy &node) { std::string add, port, type, id, aid = "0", net = "tcp", path, host, tls, cipher = "auto", remarks; std::string addition; string_size pos; kit = kit.substr(9); pos = kit.find('#'); if(pos != std::string::npos) { remarks = kit.substr(pos + 1); kit = kit.substr(0, pos); } pos = kit.find('?'); addition = kit.substr(pos + 1); kit = kit.substr(0, pos); if(regGetMatch(kit, "(.*?)@(.*):(.*)", 4, 0, &id, &add, &port)) return; pos = port.find('/'); if(pos != std::string::npos) { path = port.substr(pos); port.erase(pos); } if(port == "0") return; net = getUrlArg(addition, "network"); tls = getUrlArg(addition, "tls") == "true" ? "tls" : ""; host = getUrlArg(addition, "ws.host"); if(remarks.empty()) remarks = add + ":" + port; vmessConstruct(node, V2RAY_DEFAULT_GROUP, remarks, add, port, type, id, aid, net, cipher, path, host, "", tls, ""); } // peer = (public-key = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=, allowed-ips = "0.0.0.0/0, ::/0", endpoint = engage.cloudflareclient.com:2408, client-id = 139/184/125),(public-key = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=, endpoint = engage.cloudflareclient.com:2408) void parsePeers(Proxy &node, const std::string &data) { auto peers = regGetAllMatch(data, R"(\((.*?)\))", true); if(peers.empty()) return; auto peer = peers[0]; auto peerdata = regGetAllMatch(peer, R"(([a-z-]+) ?= ?([^" ),]+|".*?"),? ?)", true); if(peerdata.size() % 2 != 0) return; for(size_t i = 0; i < peerdata.size(); i += 2) { auto key = peerdata[i]; auto val = peerdata[i + 1]; switch(hash_(key)) { case "public-key"_hash: node.PublicKey = val; break; case "endpoint"_hash: node.Hostname = val.substr(0, val.rfind(':')); node.Port = to_int(val.substr(val.rfind(':') + 1)); break; case "client-id"_hash: node.ClientId = val; break; case "allowed-ips"_hash: node.AllowedIPs = trimOf(val, '"'); break; default: break; } } } bool explodeSurge(std::string surge, std::vector<Proxy> &nodes) { std::multimap<std::string, std::string> proxies; uint32_t i, index = nodes.size(); INIReader ini; /* if(!strFind(surge, "[Proxy]")) return false; */ ini.store_isolated_line = true; ini.keep_empty_section = false; ini.allow_dup_section_titles = true; ini.set_isolated_items_section("Proxy"); ini.add_direct_save_section("Proxy"); if(surge.find("[Proxy]") != surge.npos) surge = regReplace(surge, R"(^[\S\s]*?\[)", "[", false); ini.parse(surge); if(!ini.section_exist("Proxy")) return false; ini.enter_section("Proxy"); ini.get_items(proxies); const std::string proxystr = "(.*?)\\s*=\\s*(.*)"; for(auto &x : proxies) { std::string remarks, server, port, method, username, password; //common std::string plugin, pluginopts, pluginopts_mode, pluginopts_host, mod_url, mod_md5; //ss std::string id, net, tls, host, edge, path; //v2 std::string protocol, protoparam; //ssr std::string section, ip, ipv6, private_key, public_key, mtu, test_url, client_id, peer, keepalive; //wireguard string_array dns_servers; string_multimap wireguard_config; std::string version, aead = "1"; std::string itemName, itemVal, config; std::vector<std::string> configs, vArray, headers, header; tribool udp, tfo, scv, tls13; Proxy node; /* remarks = regReplace(x.second, proxystr, "$1"); configs = split(regReplace(x.second, proxystr, "$2"), ","); */ regGetMatch(x.second, proxystr, 3, 0, &remarks, &config); configs = split(config, ","); if(configs.size() < 3) continue; switch(hash_(configs[0])) { case "direct"_hash: case "reject"_hash: case "reject-tinygif"_hash: continue; case "custom"_hash: //surge 2 style custom proxy //remove module detection to speed up parsing and compatible with broken module /* mod_url = trim(configs[5]); if(parsedMD5.count(mod_url) > 0) { mod_md5 = parsedMD5[mod_url]; //read calculated MD5 from map } else { mod_md5 = getMD5(webGet(mod_url)); //retrieve module and calculate MD5 parsedMD5.insert(std::pair<std::string, std::string>(mod_url, mod_md5)); //save unrecognized module MD5 to map } */ //if(mod_md5 == modSSMD5) //is SSEncrypt module { if(configs.size() < 5) continue; server = trim(configs[1]); port = trim(configs[2]); if(port == "0") continue; method = trim(configs[3]); password = trim(configs[4]); for(i = 6; i < configs.size(); i++) { vArray = split(configs[i], "="); if(vArray.size() < 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "obfs"_hash: plugin = "simple-obfs"; pluginopts_mode = itemVal; break; case "obfs-host"_hash: pluginopts_host = itemVal; break; case "udp-relay"_hash: udp = itemVal; break; case "tfo"_hash: tfo = itemVal; break; default: continue; } } if(!plugin.empty()) { pluginopts = "obfs=" + pluginopts_mode; pluginopts += pluginopts_host.empty() ? "" : ";obfs-host=" + pluginopts_host; } ssConstruct(node, SS_DEFAULT_GROUP, remarks, server, port, password, method, plugin, pluginopts, udp, tfo, scv); } //else // continue; break; case "ss"_hash: //surge 3 style ss proxy server = trim(configs[1]); port = trim(configs[2]); if(port == "0") continue; for(i = 3; i < configs.size(); i++) { vArray = split(configs[i], "="); if(vArray.size() < 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "encrypt-method"_hash: method = itemVal; break; case "password"_hash: password = itemVal; break; case "obfs"_hash: plugin = "simple-obfs"; pluginopts_mode = itemVal; break; case "obfs-host"_hash: pluginopts_host = itemVal; break; case "udp-relay"_hash: udp = itemVal; break; case "tfo"_hash: tfo = itemVal; break; default: continue; } } if(!plugin.empty()) { pluginopts = "obfs=" + pluginopts_mode; pluginopts += pluginopts_host.empty() ? "" : ";obfs-host=" + pluginopts_host; } ssConstruct(node, SS_DEFAULT_GROUP, remarks, server, port, password, method, plugin, pluginopts, udp, tfo, scv); break; case "socks5"_hash: //surge 3 style socks5 proxy server = trim(configs[1]); port = trim(configs[2]); if(port == "0") continue; if(configs.size() >= 5) { username = trim(configs[3]); password = trim(configs[4]); } for(i = 5; i < configs.size(); i++) { vArray = split(configs[i], "="); if(vArray.size() < 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "udp-relay"_hash: udp = itemVal; break; case "tfo"_hash: tfo = itemVal; break; case "skip-cert-verify"_hash: scv = itemVal; break; default: continue; } } socksConstruct(node, SOCKS_DEFAULT_GROUP, remarks, server, port, username, password, udp, tfo, scv); break; case "vmess"_hash: //surge 4 style vmess proxy server = trim(configs[1]); port = trim(configs[2]); if(port == "0") continue; net = "tcp"; method = "auto"; for(i = 3; i < configs.size(); i++) { vArray = split(configs[i], "="); if(vArray.size() != 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "username"_hash: id = itemVal; break; case "ws"_hash: net = itemVal == "true" ? "ws" : "tcp"; break; case "tls"_hash: tls = itemVal == "true" ? "tls" : ""; break; case "ws-path"_hash: path = itemVal; break; case "obfs-host"_hash: host = itemVal; break; case "ws-headers"_hash: headers = split(itemVal, "|"); for(auto &y : headers) { header = split(trim(y), ":"); if(header.size() != 2) continue; else if(regMatch(header[0], "(?i)host")) host = trimQuote(header[1]); else if(regMatch(header[0], "(?i)edge")) edge = trimQuote(header[1]); } break; case "udp-relay"_hash: udp = itemVal; break; case "tfo"_hash: tfo = itemVal; break; case "skip-cert-verify"_hash: scv = itemVal; break; case "tls13"_hash: tls13 = itemVal; break; case "vmess-aead"_hash: aead = itemVal == "true" ? "0" : "1"; default: continue; } } vmessConstruct(node, V2RAY_DEFAULT_GROUP, remarks, server, port, "", id, aead, net, method, path, host, edge, tls, "", udp, tfo, scv, tls13); break; case "http"_hash: //http proxy server = trim(configs[1]); port = trim(configs[2]); if(port == "0") continue; for(i = 3; i < configs.size(); i++) { vArray = split(configs[i], "="); if(vArray.size() < 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "username"_hash: username = itemVal; break; case "password"_hash: password = itemVal; break; case "skip-cert-verify"_hash: scv = itemVal; break; default: continue; } } httpConstruct(node, HTTP_DEFAULT_GROUP, remarks, server, port, username, password, false, tfo, scv); break; case "trojan"_hash: // surge 4 style trojan proxy server = trim(configs[1]); port = trim(configs[2]); if(port == "0") continue; for(i = 3; i < configs.size(); i++) { vArray = split(configs[i], "="); if(vArray.size() != 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "password"_hash: password = itemVal; break; case "sni"_hash: host = itemVal; break; case "udp-relay"_hash: udp = itemVal; break; case "tfo"_hash: tfo = itemVal; break; case "skip-cert-verify"_hash: scv = itemVal; break; default: continue; } } trojanConstruct(node, TROJAN_DEFAULT_GROUP, remarks, server, port, password, "", host, "", true, udp, tfo, scv); break; case "snell"_hash: server = trim(configs[1]); port = trim(configs[2]); if(port == "0") continue; for(i = 3; i < configs.size(); i++) { vArray = split(configs[i], "="); if(vArray.size() != 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "psk"_hash: password = itemVal; break; case "obfs"_hash: plugin = itemVal; break; case "obfs-host"_hash: host = itemVal; break; case "udp-relay"_hash: udp = itemVal; break; case "tfo"_hash: tfo = itemVal; break; case "skip-cert-verify"_hash: scv = itemVal; break; case "version"_hash: version = itemVal; break; default: continue; } } snellConstruct(node, SNELL_DEFAULT_GROUP, remarks, server, port, password, plugin, host, to_int(version, 0), udp, tfo, scv); break; case "wireguard"_hash: for (i = 1; i < configs.size(); i++) { vArray = split(trim(configs[i]), "="); if(vArray.size() != 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "section-name"_hash: section = itemVal; break; case "test-url"_hash: test_url = itemVal; break; } } if(section.empty()) continue; ini.get_items("WireGuard " + section, wireguard_config); if(wireguard_config.empty()) continue; for (auto &c : wireguard_config) { itemName = trim(c.first); itemVal = trim(c.second); switch(hash_(itemName)) { case "self-ip"_hash: ip = itemVal; break; case "self-ip-v6"_hash: ipv6 = itemVal; break; case "private-key"_hash: private_key = itemVal; break; case "dns-server"_hash: vArray = split(itemVal, ","); for (auto &y : vArray) dns_servers.emplace_back(trim(y)); break; case "mtu"_hash: mtu = itemVal; break; case "peer"_hash: peer = itemVal; break; case "keepalive"_hash: keepalive = itemVal; break; } } wireguardConstruct(node, WG_DEFAULT_GROUP, remarks, "", "0", ip, ipv6, private_key, "", "", dns_servers, mtu, keepalive, test_url, "", udp, ""); parsePeers(node, peer); break; default: switch(hash_(remarks)) { case "shadowsocks"_hash: //quantumult x style ss/ssr link server = trim(configs[0].substr(0, configs[0].rfind(":"))); port = trim(configs[0].substr(configs[0].rfind(":") + 1)); if(port == "0") continue; for(i = 1; i < configs.size(); i++) { vArray = split(trim(configs[i]), "="); if(vArray.size() != 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "method"_hash: method = itemVal; break; case "password"_hash: password = itemVal; break; case "tag"_hash: remarks = itemVal; break; case "ssr-protocol"_hash: protocol = itemVal; break; case "ssr-protocol-param"_hash: protoparam = itemVal; break; case "obfs"_hash: { switch(hash_(itemVal)) { case "http"_hash: case "tls"_hash: plugin = "simple-obfs"; pluginopts_mode = itemVal; break; case "wss"_hash: tls = "tls"; [[fallthrough]]; case "ws"_hash: pluginopts_mode = "websocket"; plugin = "v2ray-plugin"; break; default: pluginopts_mode = itemVal; } break; } case "obfs-host"_hash: pluginopts_host = itemVal; break; case "obfs-uri"_hash: path = itemVal; break; case "udp-relay"_hash: udp = itemVal; break; case "fast-open"_hash: tfo = itemVal; break; case "tls13"_hash: tls13 = itemVal; break; default: continue; } } if(remarks.empty()) remarks = server + ":" + port; switch(hash_(plugin)) { case "simple-obfs"_hash: pluginopts = "obfs=" + pluginopts_mode; if(!pluginopts_host.empty()) pluginopts += ";obfs-host=" + pluginopts_host; break; case "v2ray-plugin"_hash: if(pluginopts_host.empty() && !isIPv4(server) && !isIPv6(server)) pluginopts_host = server; pluginopts = "mode=" + pluginopts_mode; if(!pluginopts_host.empty()) pluginopts += ";host=" + pluginopts_host; if(!path.empty()) pluginopts += ";path=" + path; pluginopts += ";" + tls; break; } if(!protocol.empty()) { ssrConstruct(node, SSR_DEFAULT_GROUP, remarks, server, port, protocol, method, pluginopts_mode, password, pluginopts_host, protoparam, udp, tfo, scv); } else { ssConstruct(node, SS_DEFAULT_GROUP, remarks, server, port, password, method, plugin, pluginopts, udp, tfo, scv, tls13); } break; case "vmess"_hash: //quantumult x style vmess link server = trim(configs[0].substr(0, configs[0].rfind(":"))); port = trim(configs[0].substr(configs[0].rfind(":") + 1)); if(port == "0") continue; net = "tcp"; for(i = 1; i < configs.size(); i++) { vArray = split(trim(configs[i]), "="); if(vArray.size() != 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "method"_hash: method = itemVal; break; case "password"_hash: id = itemVal; break; case "tag"_hash: remarks = itemVal; break; case "obfs"_hash: switch(hash_(itemVal)) { case "ws"_hash: net = "ws"; break; case "over-tls"_hash: tls = "tls"; break; case "wss"_hash: net = "ws"; tls = "tls"; break; } break; case "obfs-host"_hash: host = itemVal; break; case "obfs-uri"_hash: path = itemVal; break; case "over-tls"_hash: tls = itemVal == "true" ? "tls" : ""; break; case "udp-relay"_hash: udp = itemVal; break; case "fast-open"_hash: tfo = itemVal; break; case "tls13"_hash: tls13 = itemVal; break; case "aead"_hash: aead = itemVal == "true" ? "0" : "1"; default: continue; } } if(remarks.empty()) remarks = server + ":" + port; vmessConstruct(node, V2RAY_DEFAULT_GROUP, remarks, server, port, "", id, aead, net, method, path, host, "", tls, "", udp, tfo, scv, tls13); break; case "trojan"_hash: //quantumult x style trojan link server = trim(configs[0].substr(0, configs[0].rfind(':'))); port = trim(configs[0].substr(configs[0].rfind(':') + 1)); if(port == "0") continue; for(i = 1; i < configs.size(); i++) { vArray = split(trim(configs[i]), "="); if(vArray.size() != 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "password"_hash: password = itemVal; break; case "tag"_hash: remarks = itemVal; break; case "over-tls"_hash: tls = itemVal; break; case "tls-host"_hash: host = itemVal; break; case "udp-relay"_hash: udp = itemVal; break; case "fast-open"_hash: tfo = itemVal; break; case "tls-verification"_hash: scv = itemVal == "false"; break; case "tls13"_hash: tls13 = itemVal; break; default: continue; } } if(remarks.empty()) remarks = server + ":" + port; trojanConstruct(node, TROJAN_DEFAULT_GROUP, remarks, server, port, password, "", host, "", tls == "true", udp, tfo, scv, tls13); break; case "http"_hash: //quantumult x style http links server = trim(configs[0].substr(0, configs[0].rfind(':'))); port = trim(configs[0].substr(configs[0].rfind(':') + 1)); if(port == "0") continue; for(i = 1; i < configs.size(); i++) { vArray = split(trim(configs[i]), "="); if(vArray.size() != 2) continue; itemName = trim(vArray[0]); itemVal = trim(vArray[1]); switch(hash_(itemName)) { case "username"_hash: username = itemVal; break; case "password"_hash: password = itemVal; break; case "tag"_hash: remarks = itemVal; break; case "over-tls"_hash: tls = itemVal; break; case "tls-verification"_hash: scv = itemVal == "false"; break; case "tls13"_hash: tls13 = itemVal; break; case "fast-open"_hash: tfo = itemVal; break; default: continue; } } if(remarks.empty()) remarks = server + ":" + port; if(username == "none") username.clear(); if(password == "none") password.clear(); httpConstruct(node, HTTP_DEFAULT_GROUP, remarks, server, port, username, password, tls == "true", tfo, scv, tls13); break; default: continue; } break; } node.Id = index; nodes.emplace_back(std::move(node)); index++; } return index; } void explodeSSTap(std::string sstap, std::vector<Proxy> &nodes) { std::string configType, group, remarks, server, port; std::string cipher; std::string user, pass; std::string protocol, protoparam, obfs, obfsparam; Document json; uint32_t index = nodes.size(); json.Parse(sstap.data()); if(json.HasParseError() || !json.IsObject()) return; for(uint32_t i = 0; i < json["configs"].Size(); i++) { Proxy node; json["configs"][i]["group"] >> group; json["configs"][i]["remarks"] >> remarks; json["configs"][i]["server"] >> server; port = GetMember(json["configs"][i], "server_port"); if(port == "0") continue; if(remarks.empty()) remarks = server + ":" + port; json["configs"][i]["password"] >> pass; json["configs"][i]["type"] >> configType; switch(to_int(configType, 0)) { case 5: //socks 5 json["configs"][i]["username"] >> user; socksConstruct(node, group, remarks, server, port, user, pass); break; case 6: //ss/ssr json["configs"][i]["protocol"] >> protocol; json["configs"][i]["obfs"] >> obfs; json["configs"][i]["method"] >> cipher; if(find(ss_ciphers.begin(), ss_ciphers.end(), cipher) != ss_ciphers.end() && protocol == "origin" && obfs == "plain") //is ss { ssConstruct(node, group, remarks, server, port, pass, cipher, "", ""); } else //is ssr cipher { json["configs"][i]["obfsparam"] >> obfsparam; json["configs"][i]["protocolparam"] >> protoparam; ssrConstruct(node, group, remarks, server, port, protocol, cipher, obfs, pass, obfsparam, protoparam); } break; default: continue; } node.Id = index; nodes.emplace_back(std::move(node)); index++; } } void explodeNetchConf(std::string netch, std::vector<Proxy> &nodes) { Document json; uint32_t index = nodes.size(); json.Parse(netch.data()); if(json.HasParseError() || !json.IsObject()) return; if(!json.HasMember("Server")) return; for(uint32_t i = 0; i < json["Server"].Size(); i++) { Proxy node; explodeNetch("Netch://" + base64Encode(json["Server"][i] | SerializeObject()), node); node.Id = index; nodes.emplace_back(std::move(node)); index++; } } int explodeConfContent(const std::string &content, std::vector<Proxy> &nodes) { ConfType filetype = ConfType::Unknow; if(strFind(content, "\"version\"")) filetype = ConfType::SS; else if(strFind(content, "\"serverSubscribes\"")) filetype = ConfType::SSR; else if(strFind(content, "\"uiItem\"") || strFind(content, "vnext")) filetype = ConfType::V2Ray; else if(strFind(content, "\"proxy_apps\"")) filetype = ConfType::SSConf; else if(strFind(content, "\"idInUse\"")) filetype = ConfType::SSTap; else if(strFind(content, "\"local_address\"") && strFind(content, "\"local_port\"")) filetype = ConfType::SSR; //use ssr config parser else if(strFind(content, "\"ModeFileNameType\"")) filetype = ConfType::Netch; switch(filetype) { case ConfType::SS: explodeSSConf(content, nodes); break; case ConfType::SSR: explodeSSRConf(content, nodes); break; case ConfType::V2Ray: explodeVmessConf(content, nodes); break; case ConfType::SSConf: explodeSSAndroid(content, nodes); break; case ConfType::SSTap: explodeSSTap(content, nodes); break; case ConfType::Netch: explodeNetchConf(content, nodes); break; default: //try to parse as a local subscription explodeSub(content, nodes); } return !nodes.empty(); } void explode(const std::string &link, Proxy &node) { if(startsWith(link, "ssr://")) explodeSSR(link, node); else if(startsWith(link, "vmess://") || startsWith(link, "vmess1://")) explodeVmess(link, node); else if(startsWith(link, "ss://")) explodeSS(link, node); else if(startsWith(link, "socks://") || startsWith(link, "https://t.me/socks") || startsWith(link, "tg://socks")) explodeSocks(link, node); else if(startsWith(link, "https://t.me/http") || startsWith(link, "tg://http")) //telegram style http link explodeHTTP(link, node); else if(startsWith(link, "Netch://")) explodeNetch(link, node); else if(startsWith(link, "trojan://")) explodeTrojan(link, node); else if(isLink(link)) explodeHTTPSub(link, node); } void explodeSub(std::string sub, std::vector<Proxy> &nodes) { std::stringstream strstream; std::string strLink; bool processed = false; //try to parse as SSD configuration if(startsWith(sub, "ssd://")) { explodeSSD(sub, nodes); processed = true; } //try to parse as clash configuration try { if(!processed && regFind(sub, "\"?(Proxy|proxies)\"?:")) { regGetMatch(sub, R"(^(?:Proxy|proxies):$\s(?:(?:^ +?.*$| *?-.*$|)\s?)+)", 1, &sub); Node yamlnode = Load(sub); if(yamlnode.size() && (yamlnode["Proxy"].IsDefined() || yamlnode["proxies"].IsDefined())) { explodeClash(yamlnode, nodes); processed = true; } } } catch (std::exception &e) { //writeLog(0, e.what(), LOG_LEVEL_DEBUG); //ignore throw; } //try to parse as surge configuration if(!processed && explodeSurge(sub, nodes)) { processed = true; } //try to parse as normal subscription if(!processed) { sub = urlSafeBase64Decode(sub); if(regFind(sub, "(vmess|shadowsocks|http|trojan)\\s*?=")) { if(explodeSurge(sub, nodes)) return; } strstream << sub; char delimiter = count(sub.begin(), sub.end(), '\n') < 1 ? count(sub.begin(), sub.end(), '\r') < 1 ? ' ' : '\r' : '\n'; while(getline(strstream, strLink, delimiter)) { Proxy node; if(strLink.rfind('\r') != std::string::npos) strLink.erase(strLink.size() - 1); explode(strLink, node); if(strLink.empty() || node.Type == ProxyType::Unknown) { continue; } nodes.emplace_back(std::move(node)); } } }
85,352
C++
.cpp
2,130
28.0723
488
0.505887
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,465
infoparser.cpp
tindy2013_subconverter/src/parser/infoparser.cpp
#include <string> #include <vector> #include <cmath> #include <ctime> #include "config/regmatch.h" #include "parser/config/proxy.h" #include "utils/base64/base64.h" #include "utils/rapidjson_extra.h" #include "utils/regexp.h" #include "utils/string.h" unsigned long long streamToInt(const std::string &stream) { if(stream.empty()) return 0; double streamval = 1.0; std::vector<std::string> units = {"B", "KB", "MB", "GB", "TB", "PB", "EB"}; size_t index = units.size(); do { index--; if(endsWith(stream, units[index])) { streamval = std::pow(1024, index) * to_number<float>(stream.substr(0, stream.size() - units[index].size()), 0.0); break; } } while(index != 0); return (unsigned long long)streamval; } static inline double percentToDouble(const std::string &percent) { return stof(percent.substr(0, percent.size() - 1)) / 100.0; } time_t dateStringToTimestamp(std::string date) { time_t rawtime; time(&rawtime); if(startsWith(date, "left=")) { time_t seconds_left = 0; date.erase(0, 5); if(endsWith(date, "d")) { date.erase(date.size() - 1); seconds_left = to_number<double>(date, 0.0) * 86400.0; } return rawtime + seconds_left; } else { struct tm *expire_time; std::vector<std::string> date_array = split(date, ":"); if(date_array.size() != 6) return 0; expire_time = localtime(&rawtime); expire_time->tm_year = to_int(date_array[0], 1900) - 1900; expire_time->tm_mon = to_int(date_array[1], 1) - 1; expire_time->tm_mday = to_int(date_array[2]); expire_time->tm_hour = to_int(date_array[3]); expire_time->tm_min = to_int(date_array[4]); expire_time->tm_sec = to_int(date_array[5]); return mktime(expire_time); } } bool getSubInfoFromHeader(const std::string &header, std::string &result) { std::string pattern = R"(^(?i:Subscription-UserInfo): (.*?)\s*?$)", retStr; if(regFind(header, pattern)) { regGetMatch(header, pattern, 2, 0, &retStr); if(!retStr.empty()) { result = retStr; return true; } } return false; } bool getSubInfoFromNodes(const std::vector<Proxy> &nodes, const RegexMatchConfigs &stream_rules, const RegexMatchConfigs &time_rules, std::string &result) { std::string remarks, stream_info, time_info, retStr; for(const Proxy &x : nodes) { remarks = x.Remark; if(stream_info.empty()) { for(const RegexMatchConfig &y : stream_rules) { if(regMatch(remarks, y.Match)) { retStr = regReplace(remarks, y.Match, y.Replace); if(retStr != remarks) { stream_info = retStr; break; } } else continue; } } remarks = x.Remark; if(time_info.empty()) { for(const RegexMatchConfig &y : time_rules) { if(regMatch(remarks, y.Match)) { retStr = regReplace(remarks, y.Match, y.Replace); if(retStr != remarks) { time_info = retStr; break; } } else continue; } } if(!stream_info.empty() && !time_info.empty()) break; } if(stream_info.empty() && time_info.empty()) return false; //calculate how much stream left unsigned long long total = 0, left, used = 0, expire = 0; std::string total_str = getUrlArg(stream_info, "total"), left_str = getUrlArg(stream_info, "left"), used_str = getUrlArg(stream_info, "used"); if(strFind(total_str, "%")) { if(!used_str.empty()) { used = streamToInt(used_str); total = used / (1 - percentToDouble(total_str)); } else if(!left_str.empty()) { left = streamToInt(left_str); total = left / percentToDouble(total_str); if (left > total) left = 0; used = total - left; } } else { total = streamToInt(total_str); if(!used_str.empty()) { used = streamToInt(used_str); } else if(!left_str.empty()) { left = streamToInt(left_str); if (left > total) left = 0; used = total - left; } } result = "upload=0; download=" + std::to_string(used) + "; total=" + std::to_string(total) + ";"; //calculate expire time expire = dateStringToTimestamp(time_info); if(expire) result += " expire=" + std::to_string(expire) + ";"; return true; } bool getSubInfoFromSSD(const std::string &sub, std::string &result) { rapidjson::Document json; json.Parse(urlSafeBase64Decode(sub.substr(6)).data()); if(json.HasParseError()) return false; std::string used_str = GetMember(json, "traffic_used"), total_str = GetMember(json, "traffic_total"), expire_str = GetMember(json, "expiry"); if(used_str.empty() || total_str.empty()) return false; unsigned long long used = stod(used_str) * std::pow(1024, 3), total = stod(total_str) * std::pow(1024, 3), expire; result = "upload=0; download=" + std::to_string(used) + "; total=" + std::to_string(total) + ";"; expire = dateStringToTimestamp(regReplace(expire_str, "(\\d+)-(\\d+)-(\\d+) (.*)", "$1:$2:$3:$4")); if(expire) result += " expire=" + std::to_string(expire) + ";"; return true; }
5,892
C++
.cpp
179
24.301676
154
0.539515
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,466
string.cpp
tindy2013_subconverter/src/utils/string.cpp
#include <algorithm> #include <numeric> #include <sstream> #include <string> #include <vector> #include <cstdlib> #include <ctime> #include <random> #include "string.h" #include "map_extra.h" std::vector<std::string> split(const std::string &s, const std::string &separator) { string_size bpos = 0, epos = s.find(separator); std::vector<std::string> result; while(bpos < s.size()) { if(epos == std::string::npos) epos = s.size(); result.push_back(s.substr(bpos, epos - bpos)); bpos = epos + separator.size(); epos = s.find(separator, bpos); } return result; } void split(std::vector<std::string_view> &result, std::string_view s, char separator) { string_size bpos = 0, epos = s.find(separator); while(bpos < s.size()) { if(epos == std::string_view::npos) epos = s.size(); result.push_back(s.substr(bpos, epos - bpos)); bpos = epos + 1; epos = s.find(separator, bpos); } } std::vector<std::string_view> split(std::string_view s, char separator) { std::vector<std::string_view> result; split(result, s, separator); return result; } std::string UTF8ToCodePoint(const std::string &data) { std::stringstream ss; for(string_size i = 0; i < data.size(); i++) { int charcode = data[i] & 0xff; if((charcode >> 7) == 0) { ss<<data[i]; } else if((charcode >> 5) == 6) { ss<<"\\u"<<std::hex<<((data[i + 1] & 0x3f) | (data[i] & 0x1f) << 6); i++; } else if((charcode >> 4) == 14) { ss<<"\\u"<<std::hex<<((data[i + 2] & 0x3f) | (data[i + 1] & 0x3f) << 6 | (data[i] & 0xf) << 12); i += 2; } else if((charcode >> 3) == 30) { ss<<"\\u"<<std::hex<<((data[i + 3] & 0x3f) | (data[i + 2] & 0x3f) << 6 | (data[i + 1] & 0x3f) << 12 | (data[i] & 0x7) << 18); i += 3; } } return ss.str(); } std::string toLower(const std::string &str) { std::string result; std::transform(str.begin(), str.end(), std::back_inserter(result), [](unsigned char c) { return std::tolower(c); }); return result; } std::string toUpper(const std::string &str) { std::string result; std::transform(str.begin(), str.end(), std::back_inserter(result), [](unsigned char c) { return std::toupper(c); }); return result; } void processEscapeChar(std::string &str) { string_size pos = str.find('\\'); while(pos != std::string::npos) { if(pos == str.size()) break; switch(str[pos + 1]) { case 'n': str.replace(pos, 2, "\n"); break; case 'r': str.replace(pos, 2, "\r"); break; case 't': str.replace(pos, 2, "\t"); break; default: /// ignore others for backward compatibility //str.erase(pos, 1); break; } pos = str.find('\\', pos + 1); } } void processEscapeCharReverse(std::string &str) { string_size pos = 0; while(pos < str.size()) { switch(str[pos]) { case '\n': str.replace(pos, 1, "\\n"); break; case '\r': str.replace(pos, 1, "\\r"); break; case '\t': str.replace(pos, 1, "\\t"); break; default: /// ignore others for backward compatibility break; } pos++; } } int parseCommaKeyValue(const std::string &input, const std::string &separator, string_pair_array &result) { string_size bpos = 0, epos = input.find(separator); std::string kv; while(bpos < input.size()) { if(epos == std::string::npos) epos = input.size(); else if(epos && input[epos - 1] == '\\') { kv += input.substr(bpos, epos - bpos - 1); kv += separator; bpos = epos + 1; epos = input.find(separator, bpos); continue; } kv += input.substr(bpos, epos - bpos); string_size eqpos = kv.find('='); if(eqpos == std::string::npos) result.emplace_back("{NONAME}", kv); else result.emplace_back(kv.substr(0, eqpos), kv.substr(eqpos + 1)); kv.clear(); bpos = epos + 1; epos = input.find(separator, bpos); } if(!kv.empty()) { string_size eqpos = kv.find('='); if(eqpos == std::string::npos) result.emplace_back("{NONAME}", kv); else result.emplace_back(kv.substr(0, eqpos), kv.substr(eqpos + 1)); } return 0; } void trimSelfOf(std::string &str, char target, bool before, bool after) { if (!before && !after) return; std::string::size_type pos = str.size() - 1; if (after) pos = str.find_last_not_of(target); if (pos != std::string::npos) str.erase(pos + 1); if (before) pos = str.find_first_not_of(target); str.erase(0, pos); } std::string trimOf(const std::string& str, char target, bool before, bool after) { if (!before && !after) return str; std::string::size_type pos = 0; if (before) pos = str.find_first_not_of(target); if (pos == std::string::npos) { return str; } std::string::size_type pos2 = str.size() - 1; if (after) pos2 = str.find_last_not_of(target); if (pos2 != std::string::npos) { return str.substr(pos, pos2 - pos + 1); } return str.substr(pos); } std::string trim(const std::string& str, bool before, bool after) { return trimOf(str, ' ', before, after); } std::string trimQuote(const std::string &str, bool before, bool after) { return trimOf(str, '\"', before, after); } std::string trimWhitespace(const std::string &str, bool before, bool after) { static std::string whitespaces(" \t\f\v\n\r"); string_size bpos = 0, epos = str.size(); if(after) { epos = str.find_last_not_of(whitespaces); if(epos == std::string::npos) return ""; } if(before) { bpos = str.find_first_not_of(whitespaces); if(bpos == std::string::npos) return ""; } return str.substr(bpos, epos - bpos + 1); } std::string getUrlArg(const std::string &url, const std::string &request) { //std::smatch result; /* if (regex_search(url.cbegin(), url.cend(), result, std::regex(request + "=(.*?)&"))) { return result[1]; } else if (regex_search(url.cbegin(), url.cend(), result, std::regex(request + "=(.*)"))) { return result[1]; } else { return std::string(); } */ /* std::string::size_type spos = url.find("?"); if(spos != url.npos) url.erase(0, spos + 1); string_array vArray, arglist = split(url, "&"); for(std::string &x : arglist) { std::string::size_type epos = x.find("="); if(epos != x.npos) { if(x.substr(0, epos) == request) return x.substr(epos + 1); } } */ std::string pattern = request + "="; std::string::size_type pos = url.size(); while(pos) { pos = url.rfind(pattern, pos); if(pos != std::string::npos) { if(pos == 0 || url[pos - 1] == '&' || url[pos - 1] == '?') { pos += pattern.size(); return url.substr(pos, url.find('&', pos) - pos); } } else break; pos--; } return ""; } std::string getUrlArg(const string_multimap &args, const std::string &request) { auto it = args.find(request); if(it != args.end()) return it->second; return ""; } std::string replaceAllDistinct(std::string str, const std::string &old_value, const std::string &new_value) { for(std::string::size_type pos(0); pos != std::string::npos; pos += new_value.length()) { if((pos = str.find(old_value, pos)) != std::string::npos) str.replace(pos, old_value.length(), new_value); else break; } return str; } void removeUTF8BOM(std::string &data) { if(data.compare(0, 3, "\xEF\xBB\xBF") == 0) data = data.substr(3); } bool isStrUTF8(const std::string &data) { const char *str = data.c_str(); unsigned int nBytes = 0; for (unsigned int i = 0; str[i] != '\0'; ++i) { unsigned char chr = *(str + i); if (nBytes == 0) { if (chr >= 0x80) { if (chr >= 0xFC && chr <= 0xFD) nBytes = 6; else if (chr >= 0xF8) nBytes = 5; else if (chr >= 0xF0) nBytes = 4; else if (chr >= 0xE0) nBytes = 3; else if (chr >= 0xC0) nBytes = 2; else return false; nBytes--; } } else { if ((chr & 0xC0) != 0x80) return false; nBytes--; } } if (nBytes != 0) return false; return true; } std::string randomStr(int len) { std::string retData; std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, 61); for(int i = 0; i < len; i++) { int r = dis(gen); if (r < 26) { retData.push_back('a' + r); } else if (r < 52) { retData.push_back('A' + r - 26); } else { retData.push_back('0' + r - 52); } } return retData; } int to_int(const std::string &str, int def_value) { if(str.empty()) return def_value; /* int retval = 0; char c; std::stringstream ss(str); if(!(ss >> retval)) return def_value; else if(ss >> c) return def_value; else return retval; */ return std::atoi(str.data()); } std::string join(const string_array &arr, const std::string &delimiter) { if(arr.empty()) return ""; if(arr.size() == 1) return arr[0]; return std::accumulate(arr.begin() + 1, arr.end(), arr[0], [&](const std::string &a, const std::string &b) {return a + delimiter + b; }); }
10,477
C++
.cpp
386
20.049223
141
0.51187
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,467
network.cpp
tindy2013_subconverter/src/utils/network.cpp
#include <string> #include <vector> #include <sstream> #include "server/socket.h" #include "string.h" #include "regexp.h" std::string hostnameToIPAddr(const std::string &host) { int retVal; std::string retAddr; char cAddr[128] = {}; struct sockaddr_in *target; struct sockaddr_in6 *target6; struct addrinfo hint = {}, *retAddrInfo, *cur; retVal = getaddrinfo(host.data(), NULL, &hint, &retAddrInfo); if(retVal != 0) { freeaddrinfo(retAddrInfo); return ""; } for(cur = retAddrInfo; cur != NULL; cur = cur->ai_next) { if(cur->ai_family == AF_INET) { target = reinterpret_cast<struct sockaddr_in *>(cur->ai_addr); inet_ntop(AF_INET, &target->sin_addr, cAddr, sizeof(cAddr)); break; } else if(cur->ai_family == AF_INET6) { target6 = reinterpret_cast<struct sockaddr_in6 *>(cur->ai_addr); inet_ntop(AF_INET6, &target6->sin6_addr, cAddr, sizeof(cAddr)); break; } } retAddr.assign(cAddr); freeaddrinfo(retAddrInfo); return retAddr; } bool isIPv4(const std::string &address) { return regMatch(address, "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"); } bool isIPv6(const std::string &address) { std::vector<std::string> regLists = {"^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$", "^((?:[0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4})*)?)::((?:([0-9A-Fa-f]{1,4}:)*[0-9A-Fa-f]{1,4})?)$", "^(::(?:[0-9A-Fa-f]{1,4})(?::[0-9A-Fa-f]{1,4}){5})|((?:[0-9A-Fa-f]{1,4})(?::[0-9A-Fa-f]{1,4}){5}::)$"}; for(unsigned int i = 0; i < regLists.size(); i++) { if(regMatch(address, regLists[i])) return true; } return false; } void urlParse(std::string &url, std::string &host, std::string &path, int &port, bool &isTLS) { std::vector<std::string> args; string_size pos; if(regMatch(url, "^https://(.*)")) isTLS = true; url = regReplace(url, "^(http|https)://", ""); pos = url.find("/"); if(pos == url.npos) { host = url; path = "/"; } else { host = url.substr(0, pos); path = url.substr(pos); } pos = host.rfind(":"); if(regFind(host, "\\[(.*)\\]")) //IPv6 { args = split(regReplace(host, "\\[(.*)\\](.*)", "$1,$2"), ","); if(args.size() == 2) //with port port = to_int(args[1].substr(1)); host = args[0]; } else if(pos != host.npos) { port = to_int(host.substr(pos + 1)); host = host.substr(0, pos); } if(port == 0) { if(isTLS) port = 443; else port = 80; } } std::string getFormData(const std::string &raw_data) { std::stringstream strstrm; std::string line; std::string boundary; std::string file; /* actual file content */ int i = 0; strstrm<<raw_data; while (std::getline(strstrm, line)) { if(i == 0) boundary = line.substr(0, line.length() - 1); // Get boundary else if(startsWith(line, boundary)) break; // The end else if(line.length() == 1) { // Time to get raw data char c; int bl = boundary.length(); bool endfile = false; char buffer[256]; while(!endfile) { int j = 0; while(j < 256 && strstrm.get(c) && !endfile) { buffer[j] = c; int k = 0; // Verify if we are at the end while(boundary[bl - 1 - k] == buffer[j - k]) { if(k >= bl - 1) { // We are at the end of the file endfile = true; break; } k++; } j++; } file.append(buffer, j); j = 0; }; file.erase(file.length() - bl); break; } i++; } return file; }
4,231
C++
.cpp
143
20.755245
284
0.467615
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,468
regexp.cpp
tindy2013_subconverter/src/utils/regexp.cpp
#include <string> #include <cstdarg> /* #ifdef USE_STD_REGEX #include <regex> #else */ #include <jpcre2.hpp> using jp = jpcre2::select<char>; //#endif // USE_STD_REGEX #include "regexp.h" /* #ifdef USE_STD_REGEX bool regValid(const std::string &reg) { try { std::regex r(reg, std::regex::ECMAScript); return true; } catch (std::regex_error &e) { return false; } } bool regFind(const std::string &src, const std::string &match) { try { std::regex::flag_type flags = std::regex::extended | std::regex::ECMAScript; std::string target = match; if(match.find("(?i)") == 0) { target.erase(0, 4); flags |= std::regex::icase; } std::regex reg(target, flags); return regex_search(src, reg); } catch (std::regex_error &e) { return false; } } std::string regReplace(const std::string &src, const std::string &match, const std::string &rep) { std::string result = ""; try { std::regex::flag_type flags = std::regex::extended | std::regex::ECMAScript; std::string target = match; if(match.find("(?i)") == 0) { target.erase(0, 4); flags |= std::regex::icase; } std::regex reg(target, flags); regex_replace(back_inserter(result), src.begin(), src.end(), reg, rep); } catch (std::regex_error &e) { result = src; } return result; } bool regMatch(const std::string &src, const std::string &match) { try { std::regex::flag_type flags = std::regex::extended | std::regex::ECMAScript; std::string target = match; if(match.find("(?i)") == 0) { target.erase(0, 4); flags |= std::regex::icase; } std::regex reg(target, flags); return regex_match(src, reg); } catch (std::regex_error &e) { return false; } } int regGetMatch(const std::string &src, const std::string &match, size_t group_count, ...) { try { std::regex::flag_type flags = std::regex::extended | std::regex::ECMAScript; std::string target = match; if(match.find("(?i)") == 0) { target.erase(0, 4); flags |= std::regex::icase; } std::regex reg(target, flags); std::smatch result; if(regex_search(src.cbegin(), src.cend(), result, reg)) { if(result.size() < group_count - 1) return -1; va_list vl; va_start(vl, group_count); size_t index = 0; while(group_count) { std::string* arg = va_arg(vl, std::string*); if(arg != NULL) *arg = std::move(result[index]); index++; group_count--; } va_end(vl); } else return -2; return 0; } catch (std::regex_error&) { return -3; } } #else */ bool regMatch(const std::string &src, const std::string &match) { jp::Regex reg; reg.setPattern(match).addModifier("m").addPcre2Option(PCRE2_ANCHORED|PCRE2_ENDANCHORED|PCRE2_UTF).compile(); if(!reg) return false; return reg.match(src, "g"); } bool regFind(const std::string &src, const std::string &match) { jp::Regex reg; reg.setPattern(match).addModifier("m").addPcre2Option(PCRE2_UTF|PCRE2_ALT_BSUX).compile(); if(!reg) return false; return reg.match(src, "g"); } std::string regReplace(const std::string &src, const std::string &match, const std::string &rep, bool global, bool multiline) { jp::Regex reg; reg.setPattern(match).addModifier(multiline ? "m" : "").addPcre2Option(PCRE2_UTF|PCRE2_MULTILINE|PCRE2_ALT_BSUX).compile(); if(!reg) return src; return reg.replace(src, rep, global ? "gEx" : "Ex"); } bool regValid(const std::string &reg) { jp::Regex r; r.setPattern(reg).addPcre2Option(PCRE2_UTF|PCRE2_ALT_BSUX).compile(); return !!r; } int regGetMatch(const std::string &src, const std::string &match, size_t group_count, ...) { auto result = regGetAllMatch(src, match, false); if(result.empty()) return -1; va_list vl; va_start(vl, group_count); size_t index = 0; while(group_count) { std::string* arg = va_arg(vl, std::string*); if(arg != nullptr) *arg = std::move(result[index]); index++; group_count--; if(result.size() <= index) break; } va_end(vl); return 0; } std::vector<std::string> regGetAllMatch(const std::string &src, const std::string &match, bool group_only) { jp::Regex reg; reg.setPattern(match).addModifier("m").addPcre2Option(PCRE2_UTF|PCRE2_ALT_BSUX).compile(); jp::VecNum vec_num; jp::RegexMatch rm; size_t count = rm.setRegexObject(&reg).setSubject(src).setNumberedSubstringVector(&vec_num).setModifier("gm").match(); std::vector<std::string> result; if(!count) return result; size_t begin = 0; if(group_only) begin = 1; size_t index = begin, match_index = 0; while(true) { if(vec_num.size() <= match_index) break; if(vec_num[match_index].size() <= index) { match_index++; index = begin; continue; } result.push_back(std::move(vec_num[match_index][index])); index++; } return result; } //#endif // USE_STD_REGEX std::string regTrim(const std::string &src) { return regReplace(src, R"(^\s*([\s\S]*)\s*$)", "$1", false, false); }
5,711
C++
.cpp
210
20.790476
127
0.567627
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,469
logger.cpp
tindy2013_subconverter/src/utils/logger.cpp
#include <string> #include <iostream> #include <thread> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include "handler/settings.h" #include "defer.h" #include "lock.h" #include "logger.h" std::string getTime(int type) { time_t lt; char tmpbuf[32], cMillis[7]; std::string format; timeval tv = {}; gettimeofday(&tv, nullptr); snprintf(cMillis, 7, "%.6ld", (long)tv.tv_usec); lt = time(nullptr); struct tm *local = localtime(&lt); switch(type) { case 1: format = "%Y%m%d-%H%M%S"; break; case 2: format = "%Y/%m/%d %a %H:%M:%S."; format += cMillis; break; case 3: default: format = "%Y-%m-%d %H:%M:%S"; break; } strftime(tmpbuf, 32, format.data(), local); return {tmpbuf}; } static std::string get_thread_name() { static std::atomic_int counter = 0; static std::map<std::thread::id, std::string> thread_names; static RWLock lock; std::thread::id id = std::this_thread::get_id(); lock.readLock(); if (thread_names.find(id) != thread_names.end()) { defer(lock.readUnlock();) return thread_names[id]; } lock.readUnlock(); lock.writeLock(); std::string name = "Thread-" + std::to_string(++counter); thread_names[id] = name; lock.writeUnlock(); return name; } std::mutex log_mutex; void writeLog(int type, const std::string &content, int level) { if(level > global.logLevel) return; std::lock_guard<std::mutex> lock(log_mutex); const char *levels[] = {"[FATL]", "[ERRO]", "[WARN]", "[INFO]", "[DEBG]", "[VERB]"}; std::cerr<<getTime(2)<<" ["<<getpid()<<" "<<get_thread_name()<<"]"<<levels[level % 6]; std::cerr<<" "<<content<<"\n"; } #ifdef __GNUG__ #include <cstdlib> #include <memory> #include <cxxabi.h> std::string demangle(const char* name) { int status = -4; std::unique_ptr<char, void(*)(void*)> res { abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free }; return (status == 0) ? res.get() : name; } #else std::string demangle(const char* name) { return name; } #endif
2,170
C++
.cpp
85
21.341176
90
0.598361
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,470
system.cpp
tindy2013_subconverter/src/utils/system.cpp
#include <string> #include <vector> #include <memory> #include <chrono> #include <thread> #include <stdlib.h> #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // _WIN32 #include "string.h" void sleepMs(int interval) { /* #ifdef _WIN32 Sleep(interval); #else // Portable sleep for platforms other than Windows. struct timeval wait = { 0, interval * 1000 }; select(0, NULL, NULL, NULL, &wait); #endif */ //upgrade to c++11 standard std::this_thread::sleep_for(std::chrono::milliseconds(interval)); } std::string getEnv(const std::string &name) { std::string retVal; #ifdef _WIN32 char chrData[1024] = {}; if(GetEnvironmentVariable(name.c_str(), chrData, 1023)) retVal.assign(chrData); #else char *env = getenv(name.c_str()); if(env != NULL) retVal.assign(env); #endif // _WIN32 return retVal; } std::string getSystemProxy() { #ifdef _WIN32 HKEY key; auto ret = RegOpenKeyEx(HKEY_CURRENT_USER, R"(Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings)", 0, KEY_ALL_ACCESS, &key); if(ret != ERROR_SUCCESS) { //std::cout << "open failed: " << ret << std::endl; return ""; } DWORD values_count, max_value_name_len, max_value_len; ret = RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, &values_count, &max_value_name_len, &max_value_len, NULL, NULL); if(ret != ERROR_SUCCESS) { //std::cout << "query failed" << std::endl; return ""; } std::vector<std::tuple<std::shared_ptr<char>, DWORD, std::shared_ptr<BYTE>>> values; for(DWORD i = 0; i < values_count; i++) { std::shared_ptr<char> value_name(new char[max_value_name_len + 1], std::default_delete<char[]>()); DWORD value_name_len = max_value_name_len + 1; DWORD value_type, value_len; RegEnumValue(key, i, value_name.get(), &value_name_len, NULL, &value_type, NULL, &value_len); std::shared_ptr<BYTE> value(new BYTE[value_len], std::default_delete<BYTE[]>()); value_name_len = max_value_name_len + 1; RegEnumValue(key, i, value_name.get(), &value_name_len, NULL, &value_type, value.get(), &value_len); values.push_back(std::make_tuple(value_name, value_type, value)); } DWORD ProxyEnable = 0; for (auto x : values) { if (strcmp(std::get<0>(x).get(), "ProxyEnable") == 0) { ProxyEnable = *(DWORD*)(std::get<2>(x).get()); } } if (ProxyEnable) { for (auto x : values) { if (strcmp(std::get<0>(x).get(), "ProxyServer") == 0) { //std::cout << "ProxyServer: " << (char*)(std::get<2>(x).get()) << std::endl; return std::string((char*)(std::get<2>(x).get())); } } } /* else { //std::cout << "Proxy not Enabled" << std::endl; } */ //return 0; return ""; #else string_array proxy_env = {"all_proxy", "ALL_PROXY", "http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY"}; for(std::string &x : proxy_env) { char* proxy = getenv(x.c_str()); if(proxy != NULL) return std::string(proxy); } return ""; #endif // _WIN32 }
3,387
C++
.cpp
108
24.833333
142
0.565749
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,471
urlencode.cpp
tindy2013_subconverter/src/utils/urlencode.cpp
#include <string> #include "string.h" unsigned char toHex(unsigned char x) { return x > 9 ? x + 55 : x + 48; } unsigned char fromHex(unsigned char x) { unsigned char y; if (x >= 'A' && x <= 'Z') y = x - 'A' + 10; else if (x >= 'a' && x <= 'z') y = x - 'a' + 10; else if (x >= '0' && x <= '9') y = x - '0'; else y = x; return y; } std::string urlEncode(const std::string& str) { std::string strTemp = ""; string_size length = str.length(); for (string_size i = 0; i < length; i++) { if (isalnum((unsigned char)str[i]) || (str[i] == '-') || (str[i] == '_') || (str[i] == '.') || (str[i] == '~')) strTemp += str[i]; else { strTemp += '%'; strTemp += toHex((unsigned char)str[i] >> 4); strTemp += toHex((unsigned char)str[i] % 16); } } return strTemp; } std::string urlDecode(const std::string& str) { std::string strTemp; string_size length = str.length(); for (string_size i = 0; i < length; i++) { if (str[i] == '+') strTemp += ' '; else if (str[i] == '%') { if(i + 2 >= length) return strTemp; if(isalnum(str[i + 1]) && isalnum(str[i + 2])) { unsigned char high = fromHex((unsigned char)str[++i]); unsigned char low = fromHex((unsigned char)str[++i]); strTemp += high * 16 + low; } else strTemp += str[i]; } else strTemp += str[i]; } return strTemp; } std::string joinArguments(const string_multimap &args) { std::string strTemp; for (auto &p: args) { strTemp += p.first + "=" + urlEncode(p.second) + "&"; } if (!strTemp.empty()) { strTemp.pop_back(); } return strTemp; }
1,983
C++
.cpp
79
17.64557
70
0.448894
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,472
codepage.cpp
tindy2013_subconverter/src/utils/codepage.cpp
#include <string> #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // _WIN32 // ANSI code page (GBK on 936) to UTF8 std::string acpToUTF8(const std::string &str_src) { #ifdef _WIN32 const char* strGBK = str_src.c_str(); int len = MultiByteToWideChar(CP_ACP, 0, strGBK, -1, NULL, 0); wchar_t* wstr = new wchar_t[len + 1]; memset(wstr, 0, len + 1); MultiByteToWideChar(CP_ACP, 0, strGBK, -1, wstr, len); len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL); char* str = new char[len + 1]; memset(str, 0, len + 1); WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL); std::string strTemp = str; delete[] wstr; delete[] str; return strTemp; #else return str_src; #endif // _WIN32 /* std::vector<wchar_t> buffer(str_src.size()); #ifdef _MSC_VER std::locale loc("zh-CN"); #else std::locale loc{"zh_CN.GB2312"}; #endif // _MSC_VER wchar_t *pwszNew = nullptr; const char *pszNew = nullptr; mbstate_t state = {}; int res = std::use_facet<std::codecvt<wchar_t, char, mbstate_t> > (loc).in(state, str_src.data(), str_src.data() + str_src.size(), pszNew, buffer.data(), buffer.data() + buffer.size(), pwszNew); if(res == std::codecvt_base::ok) { std::wstring_convert<std::codecvt_utf8<wchar_t>> cutf8; return cutf8.to_bytes(std::wstring(buffer.data(), pwszNew)); } return str_src; */ } // UTF8 to ANSI code page (GBK on 936) std::string utf8ToACP(const std::string &str_src) { #ifdef _WIN32 const char* strUTF8 = str_src.data(); int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, NULL, 0); wchar_t* wszGBK = new wchar_t[len + 1]; memset(wszGBK, 0, len * 2 + 2); MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, wszGBK, len); len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL); char* szGBK = new char[len + 1]; memset(szGBK, 0, len + 1); WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL); std::string strTemp(szGBK); if (wszGBK) delete[] wszGBK; if (szGBK) delete[] szGBK; return strTemp; #else return str_src; #endif }
2,200
C++
.cpp
69
27.869565
76
0.631876
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,473
file.cpp
tindy2013_subconverter/src/utils/file.cpp
#include <string> #include <fstream> #include <sys/stat.h> #include "utils/string.h" bool isInScope(const std::string &path) { #ifdef _WIN32 if(path.find(":\\") != path.npos || path.find("..") != path.npos) return false; #else if(startsWith(path, "/") || path.find("..") != path.npos) return false; #endif // _WIN32 return true; } // TODO: Add preprocessor option to disable (open web service safety) std::string fileGet(const std::string &path, bool scope_limit) { std::string content; if(scope_limit && !isInScope(path)) return ""; std::FILE *fp = std::fopen(path.c_str(), "rb"); if(fp) { std::fseek(fp, 0, SEEK_END); long tot = std::ftell(fp); /* char *data = new char[tot + 1]; data[tot] = '\0'; std::rewind(fp); std::fread(&data[0], 1, tot, fp); std::fclose(fp); content.assign(data, tot); delete[] data; */ content.resize(tot); std::rewind(fp); std::fread(&content[0], 1, tot, fp); std::fclose(fp); } /* std::stringstream sstream; std::ifstream infile; infile.open(path, std::ios::binary); if(infile) { sstream<<infile.rdbuf(); infile.close(); content = sstream.str(); } */ return content; } bool fileExist(const std::string &path, bool scope_limit) { //using c++17 standard, but may cause problem on clang //return std::filesystem::exists(path); if(scope_limit && !isInScope(path)) return false; struct stat st; return stat(path.data(), &st) == 0 && S_ISREG(st.st_mode); } bool fileCopy(const std::string &source, const std::string &dest) { std::ifstream infile; std::ofstream outfile; infile.open(source, std::ios::binary); if(!infile) return false; outfile.open(dest, std::ios::binary); if(!outfile) return false; try { outfile<<infile.rdbuf(); } catch (std::exception &e) { return false; } infile.close(); outfile.close(); return true; } int fileWrite(const std::string &path, const std::string &content, bool overwrite) { /* std::fstream outfile; std::ios_base::openmode mode = overwrite ? std::ios_base::out : std::ios_base::app; mode |= std::ios_base::binary; outfile.open(path, mode); outfile << content; outfile.close(); return 0; */ const char *mode = overwrite ? "wb" : "ab"; std::FILE *fp = std::fopen(path.c_str(), mode); std::fwrite(content.c_str(), 1, content.size(), fp); std::fclose(fp); return 0; }
2,648
C++
.cpp
101
21.009901
87
0.589441
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,474
base64.cpp
tindy2013_subconverter/src/utils/base64/base64.cpp
#include <string> #include "utils/string.h" static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; std::string base64Encode(const std::string &string_to_encode) { char const* bytes_to_encode = string_to_encode.data(); unsigned int in_len = string_to_encode.size(); std::string ret; int i = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { int j; for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ < 3)) ret += '='; } return ret; } std::string base64Decode(const std::string &encoded_string, bool accept_urlsafe) { string_size in_len = encoded_string.size(); string_size i = 0; string_size in_ = 0; unsigned char char_array_4[4], char_array_3[3], uchar; static unsigned char dtable[256], itable[256], table_ready = 0; std::string ret; // Should not need thread_local with the flag... if (!table_ready) { // No memset needed for static/TLS for (string_size k = 0; k < base64_chars.length(); k++) { uchar = base64_chars[k]; // make compiler happy dtable[uchar] = k; // decode (find) itable[uchar] = 1; // is_base64 } const unsigned char dash = '-', add = '+', under = '_', slash = '/'; // Add urlsafe table dtable[dash] = dtable[add]; itable[dash] = 2; dtable[under] = dtable[slash]; itable[under] = 2; table_ready = 1; } while (in_len-- && (encoded_string[in_] != '=')) { uchar = encoded_string[in_]; // make compiler happy if (!(accept_urlsafe ? itable[uchar] : (itable[uchar] == 1))) // break away from the while condition { ret += uchar; // not base64 encoded data, copy to result in_++; i = 0; continue; } char_array_4[i++] = uchar; in_++; if (i == 4) { for (string_size j = 0; j < 4; j++) char_array_4[j] = dtable[char_array_4[j]]; char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (string_size j = i; j <4; j++) char_array_4[j] = 0; for (string_size j = 0; j <4; j++) char_array_4[j] = dtable[char_array_4[j]]; char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (string_size j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; } std::string urlSafeBase64Reverse(const std::string &encoded_string) { return replaceAllDistinct(replaceAllDistinct(encoded_string, "-", "+"), "_", "/"); } std::string urlSafeBase64Apply(const std::string &encoded_string) { return replaceAllDistinct(replaceAllDistinct(replaceAllDistinct(encoded_string, "+", "-"), "/", "_"), "=", ""); } std::string urlSafeBase64Decode(const std::string &encoded_string) { return base64Decode(encoded_string, true); } std::string urlSafeBase64Encode(const std::string &string_to_encode) { return urlSafeBase64Apply(base64Encode(string_to_encode)); }
4,603
C++
.cpp
122
30.081967
115
0.524023
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,476
interfaces.cpp
tindy2013_subconverter/src/handler/interfaces.cpp
#include <iostream> #include <string> #include <mutex> #include <numeric> #include <yaml-cpp/yaml.h> #include "config/binding.h" #include "generator/config/nodemanip.h" #include "generator/config/ruleconvert.h" #include "generator/config/subexport.h" #include "generator/template/templates.h" #include "script/script_quickjs.h" #include "server/webserver.h" #include "utils/base64/base64.h" #include "utils/file_extra.h" #include "utils/ini_reader/ini_reader.h" #include "utils/logger.h" #include "utils/network.h" #include "utils/regexp.h" #include "utils/stl_extra.h" #include "utils/string.h" #include "utils/string_hash.h" #include "utils/system.h" #include "utils/urlencode.h" #include "interfaces.h" #include "multithread.h" #include "settings.h" #include "upload.h" #include "webget.h" extern WebServer webServer; string_array gRegexBlacklist = {"(.*)*"}; std::string parseProxy(const std::string &source) { std::string proxy = source; if(source == "SYSTEM") proxy = getSystemProxy(); else if(source == "NONE") proxy = ""; return proxy; } extern string_array ClashRuleTypes, SurgeRuleTypes, QuanXRuleTypes; struct UAProfile { std::string head; std::string version_match; std::string version_target; std::string target; tribool clash_new_name = tribool(); int surge_ver = -1; }; const std::vector<UAProfile> UAMatchList = { {"ClashForAndroid","\\/([0-9.]+)","2.0","clash",true}, {"ClashForAndroid","\\/([0-9.]+)R","","clashr",false}, {"ClashForAndroid","","","clash",false}, {"ClashforWindows","\\/([0-9.]+)","0.11","clash",true}, {"ClashforWindows","","","clash",false}, {"clash-verge","","","clash",true}, {"ClashX Pro","","","clash",true}, {"ClashX","\\/([0-9.]+)","0.13","clash",true}, {"Clash","","","clash",true}, {"Kitsunebi","","","v2ray"}, {"Loon","","","loon"}, {"Pharos","","","mixed"}, {"Potatso","","","mixed"}, {"Quantumult%20X","","","quanx"}, {"Quantumult","","","quan"}, {"Qv2ray","","","v2ray"}, {"Shadowrocket","","","mixed"}, {"Surfboard","","","surfboard"}, {"Surge","\\/([0-9.]+).*x86","906","surge",false,4}, /// Surge for Mac (supports VMess) {"Surge","\\/([0-9.]+).*x86","368","surge",false,3}, /// Surge for Mac (supports new rule types and Shadowsocks without plugin) {"Surge","\\/([0-9.]+)","1419","surge",false,4}, /// Surge iOS 4 (first version) {"Surge","\\/([0-9.]+)","900","surge",false,3}, /// Surge iOS 3 (approx) {"Surge","","","surge",false,2}, /// any version of Surge as fallback {"Trojan-Qt5","","","trojan"}, {"V2rayU","","","v2ray"}, {"V2RayX","","","v2ray"} }; bool verGreaterEqual(const std::string& src_ver, const std::string& target_ver) { std::istringstream src_stream(src_ver), target_stream(target_ver); int src_part, target_part; char dot; while (src_stream >> src_part) { if (target_stream >> target_part) { if (src_part < target_part) { return false; } else if (src_part > target_part) { return true; } // Skip the dot separator in both streams src_stream >> dot; target_stream >> dot; } else { // If we run out of target parts, the source version is greater only if it has more parts return true; } } // If we get here, the common parts are equal, so check if target_ver has more parts return !bool(target_stream >> target_part); } void matchUserAgent(const std::string &user_agent, std::string &target, tribool &clash_new_name, int &surge_ver) { if(user_agent.empty()) return; for(const UAProfile &x : UAMatchList) { if(startsWith(user_agent, x.head)) { if(!x.version_match.empty()) { std::string version; if(regGetMatch(user_agent, x.version_match, 2, 0, &version)) continue; if(!x.version_target.empty() && !verGreaterEqual(version, x.version_target)) continue; } target = x.target; clash_new_name = x.clash_new_name; if(x.surge_ver != -1) surge_ver = x.surge_ver; return; } } } std::string getRuleset(RESPONSE_CALLBACK_ARGS) { auto &argument = request.argument; int *status_code = &response.status_code; /// type: 1 for Surge, 2 for Quantumult X, 3 for Clash domain rule-provider, 4 for Clash ipcidr rule-provider, 5 for Surge DOMAIN-SET, 6 for Clash classical ruleset std::string url = urlSafeBase64Decode(getUrlArg(argument, "url")), type = getUrlArg(argument, "type"), group = urlSafeBase64Decode(getUrlArg(argument, "group")); std::string output_content, dummy; int type_int = to_int(type, 0); if(url.empty() || type.empty() || (type_int == 2 && group.empty()) || (type_int < 1 || type_int > 6)) { *status_code = 400; return "Invalid request!"; } std::string proxy = parseProxy(global.proxyRuleset); string_array vArray = split(url, "|"); for(std::string &x : vArray) x.insert(0, "ruleset,"); std::vector<RulesetContent> rca; RulesetConfigs confs = INIBinding::from<RulesetConfig>::from_ini(vArray); refreshRulesets(confs, rca); for(RulesetContent &x : rca) { std::string content = x.rule_content.get(); output_content += convertRuleset(content, x.rule_type); } if(output_content.empty()) { *status_code = 400; return "Invalid request!"; } std::string strLine; std::stringstream ss; const std::string rule_match_regex = "^(.*?,.*?)(,.*)(,.*)$"; ss << output_content; char delimiter = getLineBreak(output_content); std::string::size_type lineSize, posb, pose; auto filterLine = [&]() { posb = 0; pose = strLine.find(','); if(pose == std::string::npos) return 1; posb = pose + 1; pose = strLine.find(',', posb); if(pose == std::string::npos) { pose = strLine.size(); if(strLine[pose - 1] == '\r') pose--; } pose -= posb; return 0; }; lineSize = output_content.size(); output_content.clear(); output_content.reserve(lineSize); if(type_int == 3 || type_int == 4 || type_int == 6) output_content = "payload:\n"; while(getline(ss, strLine, delimiter)) { if(strFind(strLine, "//")) { strLine.erase(strLine.find("//")); strLine = trimWhitespace(strLine); } switch(type_int) { case 2: if(!std::any_of(QuanXRuleTypes.begin(), QuanXRuleTypes.end(), [&strLine](const std::string& type){return startsWith(strLine, type);})) continue; break; case 1: if(!std::any_of(SurgeRuleTypes.begin(), SurgeRuleTypes.end(), [&strLine](const std::string& type){return startsWith(strLine, type);})) continue; break; case 3: if(!startsWith(strLine, "DOMAIN-SUFFIX,") && !startsWith(strLine, "DOMAIN,")) continue; if(filterLine()) continue; output_content += " - '"; if(strLine[posb - 2] == 'X') output_content += "+."; output_content += strLine.substr(posb, pose); output_content += "'\n"; continue; case 4: if(!startsWith(strLine, "IP-CIDR,") && !startsWith(strLine, "IP-CIDR6,")) continue; if(filterLine()) continue; output_content += " - '"; output_content += strLine.substr(posb, pose); output_content += "'\n"; continue; case 5: if(!startsWith(strLine, "DOMAIN-SUFFIX,") && !startsWith(strLine, "DOMAIN,")) continue; if(filterLine()) continue; if(strLine[posb - 2] == 'X') output_content += '.'; output_content += strLine.substr(posb, pose); output_content += '\n'; continue; case 6: if(!std::any_of(ClashRuleTypes.begin(), ClashRuleTypes.end(), [&strLine](const std::string& type){return startsWith(strLine, type);})) continue; output_content += " - "; default: break; } lineSize = strLine.size(); if(lineSize && strLine[lineSize - 1] == '\r') //remove line break strLine.erase(--lineSize); if(!strLine.empty() && (strLine[0] != ';' && strLine[0] != '#' && !(lineSize >= 2 && strLine[0] == '/' && strLine[1] == '/'))) { if(type_int == 2) { if(startsWith(strLine, "IP-CIDR6")) strLine.replace(0, 8, "IP6-CIDR"); strLine += "," + group; if(count_least(strLine, ',', 3) && regReplace(strLine, rule_match_regex, "$2") == ",no-resolve") strLine = regReplace(strLine, rule_match_regex, "$1$3$2"); else strLine = regReplace(strLine, rule_match_regex, "$1$3"); } } output_content += strLine; output_content += '\n'; } if(output_content == "payload:\n") { switch(type_int) { case 3: output_content += " - '--placeholder--'"; break; case 4: output_content += " - '0.0.0.0/32'"; break; case 6: output_content += " - 'DOMAIN,--placeholder--'"; break; } } return output_content; } void checkExternalBase(const std::string &path, std::string &dest) { if(isLink(path) || (startsWith(path, global.basePath) && fileExist(path))) dest = path; } std::string subconverter(RESPONSE_CALLBACK_ARGS) { auto &argument = request.argument; int *status_code = &response.status_code; std::string argTarget = getUrlArg(argument, "target"), argSurgeVer = getUrlArg(argument, "ver"); tribool argClashNewField = getUrlArg(argument, "new_name"); int intSurgeVer = !argSurgeVer.empty() ? to_int(argSurgeVer, 3) : 3; if(argTarget == "auto") matchUserAgent(request.headers["User-Agent"], argTarget, argClashNewField, intSurgeVer); /// don't try to load groups or rulesets when generating simple subscriptions bool lSimpleSubscription = false; switch(hash_(argTarget)) { case "ss"_hash: case "ssd"_hash: case "ssr"_hash: case "sssub"_hash: case "v2ray"_hash: case "trojan"_hash: case "mixed"_hash: lSimpleSubscription = true; break; case "clash"_hash: case "clashr"_hash: case "surge"_hash: case "quan"_hash: case "quanx"_hash: case "loon"_hash: case "surfboard"_hash: case "mellow"_hash: case "singbox"_hash: break; default: *status_code = 400; return "Invalid target!"; } //check if we need to read configuration if(global.reloadConfOnRequest && (!global.APIMode || global.CFWChildProcess) && !global.generatorMode) readConf(); /// string values std::string argUrl = getUrlArg(argument, "url"); std::string argGroupName = getUrlArg(argument, "group"), argUploadPath = getUrlArg(argument, "upload_path"); std::string argIncludeRemark = getUrlArg(argument, "include"), argExcludeRemark = getUrlArg(argument, "exclude"); std::string argCustomGroups = urlSafeBase64Decode(getUrlArg(argument, "groups")), argCustomRulesets = urlSafeBase64Decode(getUrlArg(argument, "ruleset")), argExternalConfig = getUrlArg(argument, "config"); std::string argDeviceID = getUrlArg(argument, "dev_id"), argFilename = getUrlArg(argument, "filename"), argUpdateInterval = getUrlArg(argument, "interval"), argUpdateStrict = getUrlArg(argument, "strict"); std::string argRenames = getUrlArg(argument, "rename"), argFilterScript = getUrlArg(argument, "filter_script"); /// switches with default value tribool argUpload = getUrlArg(argument, "upload"), argEmoji = getUrlArg(argument, "emoji"), argAddEmoji = getUrlArg(argument, "add_emoji"), argRemoveEmoji = getUrlArg(argument, "remove_emoji"); tribool argAppendType = getUrlArg(argument, "append_type"), argTFO = getUrlArg(argument, "tfo"), argUDP = getUrlArg(argument, "udp"), argGenNodeList = getUrlArg(argument, "list"); tribool argSort = getUrlArg(argument, "sort"), argUseSortScript = getUrlArg(argument, "sort_script"); tribool argGenClashScript = getUrlArg(argument, "script"), argEnableInsert = getUrlArg(argument, "insert"); tribool argSkipCertVerify = getUrlArg(argument, "scv"), argFilterDeprecated = getUrlArg(argument, "fdn"), argExpandRulesets = getUrlArg(argument, "expand"), argAppendUserinfo = getUrlArg(argument, "append_info"); tribool argPrependInsert = getUrlArg(argument, "prepend"), argGenClassicalRuleProvider = getUrlArg(argument, "classic"), argTLS13 = getUrlArg(argument, "tls13"); std::string base_content, output_content; ProxyGroupConfigs lCustomProxyGroups = global.customProxyGroups; RulesetConfigs lCustomRulesets = global.customRulesets; string_array lIncludeRemarks = global.includeRemarks, lExcludeRemarks = global.excludeRemarks; std::vector<RulesetContent> lRulesetContent; extra_settings ext; std::string subInfo, dummy; int interval = !argUpdateInterval.empty() ? to_int(argUpdateInterval, global.updateInterval) : global.updateInterval; bool authorized = !global.APIMode || getUrlArg(argument, "token") == global.accessToken, strict = !argUpdateStrict.empty() ? argUpdateStrict == "true" : global.updateStrict; if(std::find(gRegexBlacklist.cbegin(), gRegexBlacklist.cend(), argIncludeRemark) != gRegexBlacklist.cend() || std::find(gRegexBlacklist.cbegin(), gRegexBlacklist.cend(), argExcludeRemark) != gRegexBlacklist.cend()) return "Invalid request!"; /// for external configuration std::string lClashBase = global.clashBase, lSurgeBase = global.surgeBase, lMellowBase = global.mellowBase, lSurfboardBase = global.surfboardBase; std::string lQuanBase = global.quanBase, lQuanXBase = global.quanXBase, lLoonBase = global.loonBase, lSSSubBase = global.SSSubBase; std::string lSingBoxBase = global.singBoxBase; /// validate urls argEnableInsert.define(global.enableInsert); if(argUrl.empty() && (!global.APIMode || authorized)) argUrl = global.defaultUrls; if((argUrl.empty() && !(!global.insertUrls.empty() && argEnableInsert)) || argTarget.empty()) { *status_code = 400; return "Invalid request!"; } /// load request arguments as template variables // string_array req_args = split(argument, "&"); // string_map req_arg_map; // for(std::string &x : req_args) // { // string_size pos = x.find("="); // if(pos == x.npos) // { // req_arg_map[x] = ""; // continue; // } // if(x.substr(0, pos) == "token") // continue; // req_arg_map[x.substr(0, pos)] = x.substr(pos + 1); // } string_map req_arg_map; for (auto &x : argument) { if(x.first == "token") continue; req_arg_map[x.first] = x.second; } req_arg_map["target"] = argTarget; req_arg_map["ver"] = std::to_string(intSurgeVer); /// save template variables template_args tpl_args; tpl_args.global_vars = global.templateVars; tpl_args.request_params = req_arg_map; /// check for proxy settings std::string proxy = parseProxy(global.proxySubscription); /// check other flags ext.authorized = authorized; ext.append_proxy_type = argAppendType.get(global.appendType); if((argTarget == "clash" || argTarget == "clashr") && argGenClashScript.is_undef()) argExpandRulesets.define(true); ext.clash_proxies_style = global.clashProxiesStyle; ext.clash_proxy_groups_style = global.clashProxyGroupsStyle; /// read preference from argument, assign global var if not in argument ext.tfo.define(argTFO).define(global.TFOFlag); ext.udp.define(argUDP).define(global.UDPFlag); ext.skip_cert_verify.define(argSkipCertVerify).define(global.skipCertVerify); ext.tls13.define(argTLS13).define(global.TLS13Flag); ext.sort_flag = argSort.get(global.enableSort); argUseSortScript.define(!global.sortScript.empty()); if(ext.sort_flag && argUseSortScript) ext.sort_script = global.sortScript; ext.filter_deprecated = argFilterDeprecated.get(global.filterDeprecated); ext.clash_new_field_name = argClashNewField.get(global.clashUseNewField); ext.clash_script = argGenClashScript.get(); ext.clash_classical_ruleset = argGenClassicalRuleProvider.get(); if(!argExpandRulesets) ext.clash_new_field_name = true; else ext.clash_script = false; ext.nodelist = argGenNodeList; ext.surge_ssr_path = global.surgeSSRPath; ext.quanx_dev_id = !argDeviceID.empty() ? argDeviceID : global.quanXDevID; ext.enable_rule_generator = global.enableRuleGen; ext.overwrite_original_rules = global.overwriteOriginalRules; if(!argExpandRulesets) ext.managed_config_prefix = global.managedConfigPrefix; /// load external configuration if(argExternalConfig.empty()) argExternalConfig = global.defaultExtConfig; if(!argExternalConfig.empty()) { //std::cerr<<"External configuration file provided. Loading...\n"; writeLog(0, "External configuration file provided. Loading...", LOG_LEVEL_INFO); ExternalConfig extconf; extconf.tpl_args = &tpl_args; if(loadExternalConfig(argExternalConfig, extconf) == 0) { if(!ext.nodelist) { checkExternalBase(extconf.sssub_rule_base, lSSSubBase); if(!lSimpleSubscription) { checkExternalBase(extconf.clash_rule_base, lClashBase); checkExternalBase(extconf.surge_rule_base, lSurgeBase); checkExternalBase(extconf.surfboard_rule_base, lSurfboardBase); checkExternalBase(extconf.mellow_rule_base, lMellowBase); checkExternalBase(extconf.quan_rule_base, lQuanBase); checkExternalBase(extconf.quanx_rule_base, lQuanXBase); checkExternalBase(extconf.loon_rule_base, lLoonBase); checkExternalBase(extconf.singbox_rule_base, lSingBoxBase); if(!extconf.surge_ruleset.empty()) lCustomRulesets = extconf.surge_ruleset; if(!extconf.custom_proxy_group.empty()) lCustomProxyGroups = extconf.custom_proxy_group; ext.enable_rule_generator = extconf.enable_rule_generator; ext.overwrite_original_rules = extconf.overwrite_original_rules; } } if(!extconf.rename.empty()) ext.rename_array = extconf.rename; if(!extconf.emoji.empty()) ext.emoji_array = extconf.emoji; if(!extconf.include.empty()) lIncludeRemarks = extconf.include; if(!extconf.exclude.empty()) lExcludeRemarks = extconf.exclude; argAddEmoji.define(extconf.add_emoji); argRemoveEmoji.define(extconf.remove_old_emoji); } } else { if(!lSimpleSubscription) { /// loading custom groups if(!argCustomGroups.empty() && !ext.nodelist) { string_array vArray = split(argCustomGroups, "@"); lCustomProxyGroups = INIBinding::from<ProxyGroupConfig>::from_ini(vArray); } /// loading custom rulesets if(!argCustomRulesets.empty() && !ext.nodelist) { string_array vArray = split(argCustomRulesets, "@"); lCustomRulesets = INIBinding::from<RulesetConfig>::from_ini(vArray); } } } if(ext.enable_rule_generator && !ext.nodelist && !lSimpleSubscription) { if(lCustomRulesets != global.customRulesets) refreshRulesets(lCustomRulesets, lRulesetContent); else { if(global.updateRulesetOnRequest) refreshRulesets(global.customRulesets, global.rulesetsContent); lRulesetContent = global.rulesetsContent; } } if(!argEmoji.is_undef()) { argAddEmoji.set(argEmoji); argRemoveEmoji.set(true); } ext.add_emoji = argAddEmoji.get(global.addEmoji); ext.remove_emoji = argRemoveEmoji.get(global.removeEmoji); if(ext.add_emoji && ext.emoji_array.empty()) ext.emoji_array = safe_get_emojis(); if(!argRenames.empty()) ext.rename_array = INIBinding::from<RegexMatchConfig>::from_ini(split(argRenames, "`"), "@"); else if(ext.rename_array.empty()) ext.rename_array = safe_get_renames(); /// check custom include/exclude settings if(!argIncludeRemark.empty() && regValid(argIncludeRemark)) lIncludeRemarks = string_array{argIncludeRemark}; if(!argExcludeRemark.empty() && regValid(argExcludeRemark)) lExcludeRemarks = string_array{argExcludeRemark}; /// initialize script runtime if(authorized && !global.scriptCleanContext) { ext.js_runtime = new qjs::Runtime(); script_runtime_init(*ext.js_runtime); ext.js_context = new qjs::Context(*ext.js_runtime); script_context_init(*ext.js_context); } //start parsing urls RegexMatchConfigs stream_temp = safe_get_streams(), time_temp = safe_get_times(); //loading urls string_array urls; std::vector<Proxy> nodes, insert_nodes; int groupID = 0; parse_settings parse_set; parse_set.proxy = &proxy; parse_set.exclude_remarks = &lExcludeRemarks; parse_set.include_remarks = &lIncludeRemarks; parse_set.stream_rules = &stream_temp; parse_set.time_rules = &time_temp; parse_set.sub_info = &subInfo; parse_set.authorized = authorized; parse_set.request_header = &request.headers; parse_set.js_runtime = ext.js_runtime; parse_set.js_context = ext.js_context; if(!global.insertUrls.empty() && argEnableInsert) { groupID = -1; urls = split(global.insertUrls, "|"); importItems(urls, true); for(std::string &x : urls) { x = regTrim(x); writeLog(0, "Fetching node data from url '" + x + "'.", LOG_LEVEL_INFO); if(addNodes(x, insert_nodes, groupID, parse_set) == -1) { if(global.skipFailedLinks) writeLog(0, "The following link doesn't contain any valid node info: " + x, LOG_LEVEL_WARNING); else { *status_code = 400; return "The following link doesn't contain any valid node info: " + x; } } groupID--; } } urls = split(argUrl, "|"); importItems(urls, true); groupID = 0; for(std::string &x : urls) { x = regTrim(x); //std::cerr<<"Fetching node data from url '"<<x<<"'."<<std::endl; writeLog(0, "Fetching node data from url '" + x + "'.", LOG_LEVEL_INFO); if(addNodes(x, nodes, groupID, parse_set) == -1) { if(global.skipFailedLinks) writeLog(0, "The following link doesn't contain any valid node info: " + x, LOG_LEVEL_WARNING); else { *status_code = 400; return "The following link doesn't contain any valid node info: " + x; } } groupID++; } //exit if found nothing if(nodes.empty() && insert_nodes.empty()) { *status_code = 400; return "No nodes were found!"; } if(!subInfo.empty() && argAppendUserinfo.get(global.appendUserinfo)) response.headers.emplace("Subscription-UserInfo", subInfo); if(request.method == "HEAD") return ""; argPrependInsert.define(global.prependInsert); if(argPrependInsert) { std::move(nodes.begin(), nodes.end(), std::back_inserter(insert_nodes)); nodes.swap(insert_nodes); } else { std::move(insert_nodes.begin(), insert_nodes.end(), std::back_inserter(nodes)); } //run filter script std::string filterScript = global.filterScript; if(authorized && !argFilterScript.empty()) filterScript = argFilterScript; if(!filterScript.empty()) { if(startsWith(filterScript, "path:")) filterScript = fileGet(filterScript.substr(5), false); /* duk_context *ctx = duktape_init(); if(ctx) { defer(duk_destroy_heap(ctx);) if(duktape_peval(ctx, filterScript) == 0) { auto filter = [&](const Proxy &x) { duk_get_global_string(ctx, "filter"); duktape_push_Proxy(ctx, x); duk_pcall(ctx, 1); return !duktape_get_res_bool(ctx); }; nodes.erase(std::remove_if(nodes.begin(), nodes.end(), filter), nodes.end()); } else { writeLog(0, "Error when trying to parse script:\n" + duktape_get_err_stack(ctx), LOG_LEVEL_ERROR); duk_pop(ctx); /// pop err } } */ script_safe_runner(ext.js_runtime, ext.js_context, [&](qjs::Context &ctx) { try { ctx.eval(filterScript); auto filter = (std::function<bool(const Proxy&)>) ctx.eval("filter"); nodes.erase(std::remove_if(nodes.begin(), nodes.end(), filter), nodes.end()); } catch(qjs::exception) { script_print_stack(ctx); } }, global.scriptCleanContext); } //check custom group name if(!argGroupName.empty()) for(Proxy &x : nodes) x.Group = argGroupName; //do pre-process now preprocessNodes(nodes, ext); /* //insert node info to template int index = 0; std::string template_node_prefix; for(Proxy &x : nodes) { template_node_prefix = std::to_string(index) + "."; tpl_args.node_list[template_node_prefix + "remarks"] = x.remarks; tpl_args.node_list[template_node_prefix + "group"] = x.Group; tpl_args.node_list[template_node_prefix + "groupid"] = std::to_string(x.GroupId); index++; } */ ProxyGroupConfigs dummy_group; std::vector<RulesetContent> dummy_ruleset; std::string managed_url = base64Decode(getUrlArg(argument, "profile_data")); if(managed_url.empty()) managed_url = global.managedConfigPrefix + "/sub?" + joinArguments(argument); //std::cerr<<"Generate target: "; proxy = parseProxy(global.proxyConfig); switch(hash_(argTarget)) { case "clash"_hash: case "clashr"_hash: writeLog(0, argTarget == "clashr" ? "Generate target: ClashR" : "Generate target: Clash", LOG_LEVEL_INFO); tpl_args.local_vars["clash.new_field_name"] = ext.clash_new_field_name ? "true" : "false"; response.headers["profile-update-interval"] = std::to_string(interval / 3600); if(ext.nodelist) { YAML::Node yamlnode; proxyToClash(nodes, yamlnode, dummy_group, argTarget == "clashr", ext); output_content = YAML::Dump(yamlnode); } else { if(render_template(fetchFile(lClashBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } output_content = proxyToClash(nodes, base_content, lRulesetContent, lCustomProxyGroups, argTarget == "clashr", ext); } if(argUpload) uploadGist(argTarget, argUploadPath, output_content, false); break; case "surge"_hash: writeLog(0, "Generate target: Surge " + std::to_string(intSurgeVer), LOG_LEVEL_INFO); if(ext.nodelist) { output_content = proxyToSurge(nodes, base_content, dummy_ruleset, dummy_group, intSurgeVer, ext); if(argUpload) uploadGist("surge" + argSurgeVer + "list", argUploadPath, output_content, true); } else { if(render_template(fetchFile(lSurgeBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } output_content = proxyToSurge(nodes, base_content, lRulesetContent, lCustomProxyGroups, intSurgeVer, ext); if(argUpload) uploadGist("surge" + argSurgeVer, argUploadPath, output_content, true); if(global.writeManagedConfig && !global.managedConfigPrefix.empty()) output_content = "#!MANAGED-CONFIG " + managed_url + (interval ? " interval=" + std::to_string(interval) : "") \ + " strict=" + std::string(strict ? "true" : "false") + "\n\n" + output_content; } break; case "surfboard"_hash: writeLog(0, "Generate target: Surfboard", LOG_LEVEL_INFO); if(render_template(fetchFile(lSurfboardBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } output_content = proxyToSurge(nodes, base_content, lRulesetContent, lCustomProxyGroups, -3, ext); if(argUpload) uploadGist("surfboard", argUploadPath, output_content, true); if(global.writeManagedConfig && !global.managedConfigPrefix.empty()) output_content = "#!MANAGED-CONFIG " + managed_url + (interval ? " interval=" + std::to_string(interval) : "") \ + " strict=" + std::string(strict ? "true" : "false") + "\n\n" + output_content; break; case "mellow"_hash: writeLog(0, "Generate target: Mellow", LOG_LEVEL_INFO); if(render_template(fetchFile(lMellowBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } output_content = proxyToMellow(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext); if(argUpload) uploadGist("mellow", argUploadPath, output_content, true); break; case "sssub"_hash: writeLog(0, "Generate target: SS Subscription", LOG_LEVEL_INFO); if(render_template(fetchFile(lSSSubBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } output_content = proxyToSSSub(base_content, nodes, ext); if(argUpload) uploadGist("sssub", argUploadPath, output_content, false); break; case "ss"_hash: writeLog(0, "Generate target: SS", LOG_LEVEL_INFO); output_content = proxyToSingle(nodes, 1, ext); if(argUpload) uploadGist("ss", argUploadPath, output_content, false); break; case "ssr"_hash: writeLog(0, "Generate target: SSR", LOG_LEVEL_INFO); output_content = proxyToSingle(nodes, 2, ext); if(argUpload) uploadGist("ssr", argUploadPath, output_content, false); break; case "v2ray"_hash: writeLog(0, "Generate target: v2rayN", LOG_LEVEL_INFO); output_content = proxyToSingle(nodes, 4, ext); if(argUpload) uploadGist("v2ray", argUploadPath, output_content, false); break; case "trojan"_hash: writeLog(0, "Generate target: Trojan", LOG_LEVEL_INFO); output_content = proxyToSingle(nodes, 8, ext); if(argUpload) uploadGist("trojan", argUploadPath, output_content, false); break; case "mixed"_hash: writeLog(0, "Generate target: Standard Subscription", LOG_LEVEL_INFO); output_content = proxyToSingle(nodes, 15, ext); if(argUpload) uploadGist("sub", argUploadPath, output_content, false); break; case "quan"_hash: writeLog(0, "Generate target: Quantumult", LOG_LEVEL_INFO); if(!ext.nodelist) { if(render_template(fetchFile(lQuanBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } } output_content = proxyToQuan(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext); if(argUpload) uploadGist("quan", argUploadPath, output_content, false); break; case "quanx"_hash: writeLog(0, "Generate target: Quantumult X", LOG_LEVEL_INFO); if(!ext.nodelist) { if(render_template(fetchFile(lQuanXBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } } output_content = proxyToQuanX(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext); if(argUpload) uploadGist("quanx", argUploadPath, output_content, false); break; case "loon"_hash: writeLog(0, "Generate target: Loon", LOG_LEVEL_INFO); if(!ext.nodelist) { if(render_template(fetchFile(lLoonBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } } output_content = proxyToLoon(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext); if(argUpload) uploadGist("loon", argUploadPath, output_content, false); break; case "ssd"_hash: writeLog(0, "Generate target: SSD", LOG_LEVEL_INFO); output_content = proxyToSSD(nodes, argGroupName, subInfo, ext); if(argUpload) uploadGist("ssd", argUploadPath, output_content, false); break; case "singbox"_hash: writeLog(0, "Generate target: sing-box", LOG_LEVEL_INFO); if(!ext.nodelist) { if(render_template(fetchFile(lSingBoxBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } } output_content = proxyToSingBox(nodes, base_content, lRulesetContent, lCustomProxyGroups, ext); if(argUpload) uploadGist("singbox", argUploadPath, output_content, false); break; default: writeLog(0, "Generate target: Unspecified", LOG_LEVEL_INFO); *status_code = 500; return "Unrecognized target"; } writeLog(0, "Generate completed.", LOG_LEVEL_INFO); if(!argFilename.empty()) response.headers.emplace("Content-Disposition", "attachment; filename=\"" + argFilename + "\"; filename*=utf-8''" + urlEncode(argFilename)); return output_content; } std::string simpleToClashR(RESPONSE_CALLBACK_ARGS) { auto argument = joinArguments(request.argument); int *status_code = &response.status_code; std::string url = argument.size() <= 8 ? "" : argument.substr(8); if(url.empty() || argument.substr(0, 8) != "sublink=") { *status_code = 400; return "Invalid request!"; } if(url == "sublink") { *status_code = 400; return "Please insert your subscription link instead of clicking the default link."; } request.argument.emplace("target", "clashr"); request.argument.emplace("url", url); return subconverter(request, response); } std::string surgeConfToClash(RESPONSE_CALLBACK_ARGS) { auto argument = joinArguments(request.argument); int *status_code = &response.status_code; INIReader ini; string_array dummy_str_array; std::vector<Proxy> nodes; std::string base_content, url = argument.size() <= 5 ? "" : argument.substr(5); const std::string proxygroup_name = global.clashUseNewField ? "proxy-groups" : "Proxy Group", rule_name = global.clashUseNewField ? "rules" : "Rule"; ini.store_any_line = true; if(url.empty()) url = global.defaultUrls; if(url.empty() || argument.substr(0, 5) != "link=") { *status_code = 400; return "Invalid request!"; } if(url == "link") { *status_code = 400; return "Please insert your subscription link instead of clicking the default link."; } writeLog(0, "SurgeConfToClash called with url '" + url + "'.", LOG_LEVEL_INFO); std::string proxy = parseProxy(global.proxyConfig); YAML::Node clash; template_args tpl_args; tpl_args.global_vars = global.templateVars; tpl_args.local_vars["clash.new_field_name"] = global.clashUseNewField ? "true" : "false"; tpl_args.request_params["target"] = "clash"; tpl_args.request_params["url"] = url; if(render_template(fetchFile(global.clashBase, proxy, global.cacheConfig), tpl_args, base_content, global.templatePath) != 0) { *status_code = 400; return base_content; } clash = YAML::Load(base_content); base_content = fetchFile(url, proxy, global.cacheConfig); if(ini.parse(base_content) != INIREADER_EXCEPTION_NONE) { std::string errmsg = "Parsing Surge config failed! Reason: " + ini.get_last_error(); //std::cerr<<errmsg<<"\n"; writeLog(0, errmsg, LOG_LEVEL_ERROR); *status_code = 400; return errmsg; } if(!ini.section_exist("Proxy") || !ini.section_exist("Proxy Group") || !ini.section_exist("Rule")) { std::string errmsg = "Incomplete surge config! Missing critical sections!"; //std::cerr<<errmsg<<"\n"; writeLog(0, errmsg, LOG_LEVEL_ERROR); *status_code = 400; return errmsg; } //scan groups first, get potential policy-path string_multimap section; ini.get_items("Proxy Group", section); std::string name, type, content; string_array links; links.emplace_back(url); YAML::Node singlegroup; for(auto &x : section) { singlegroup.reset(); name = x.first; content = x.second; dummy_str_array = split(content, ","); if(dummy_str_array.empty()) continue; type = dummy_str_array[0]; if(!(type == "select" || type == "url-test" || type == "fallback" || type == "load-balance")) //remove unsupported types continue; singlegroup["name"] = name; singlegroup["type"] = type; for(unsigned int i = 1; i < dummy_str_array.size(); i++) { if(startsWith(dummy_str_array[i], "url")) singlegroup["url"] = trim(dummy_str_array[i].substr(dummy_str_array[i].find('=') + 1)); else if(startsWith(dummy_str_array[i], "interval")) singlegroup["interval"] = trim(dummy_str_array[i].substr(dummy_str_array[i].find('=') + 1)); else if(startsWith(dummy_str_array[i], "policy-path")) links.emplace_back(trim(dummy_str_array[i].substr(dummy_str_array[i].find('=') + 1))); else singlegroup["proxies"].push_back(trim(dummy_str_array[i])); } clash[proxygroup_name].push_back(singlegroup); } proxy = parseProxy(global.proxySubscription); eraseElements(dummy_str_array); RegexMatchConfigs dummy_regex_array; std::string subInfo; parse_settings parse_set; parse_set.proxy = &proxy; parse_set.exclude_remarks = parse_set.include_remarks = &dummy_str_array; parse_set.stream_rules = parse_set.time_rules = &dummy_regex_array; parse_set.request_header = &request.headers; parse_set.sub_info = &subInfo; parse_set.authorized = !global.APIMode; for(std::string &x : links) { //std::cerr<<"Fetching node data from url '"<<x<<"'."<<std::endl; writeLog(0, "Fetching node data from url '" + x + "'.", LOG_LEVEL_INFO); if(addNodes(x, nodes, 0, parse_set) == -1) { if(global.skipFailedLinks) writeLog(0, "The following link doesn't contain any valid node info: " + x, LOG_LEVEL_WARNING); else { *status_code = 400; return "The following link doesn't contain any valid node info: " + x; } } } //exit if found nothing if(nodes.empty()) { *status_code = 400; return "No nodes were found!"; } extra_settings ext; ext.sort_flag = global.enableSort; ext.filter_deprecated = global.filterDeprecated; ext.clash_new_field_name = global.clashUseNewField; ext.udp = global.UDPFlag; ext.tfo = global.TFOFlag; ext.skip_cert_verify = global.skipCertVerify; ext.tls13 = global.TLS13Flag; ext.clash_proxies_style = global.clashProxiesStyle; ext.clash_proxy_groups_style = global.clashProxyGroupsStyle; ProxyGroupConfigs dummy_groups; proxyToClash(nodes, clash, dummy_groups, false, ext); section.clear(); ini.get_items("Proxy", section); for(auto &x : section) { singlegroup.reset(); name = x.first; content = x.second; dummy_str_array = split(content, ","); if(dummy_str_array.empty()) continue; content = trim(dummy_str_array[0]); switch(hash_(content)) { case "direct"_hash: singlegroup["name"] = name; singlegroup["type"] = "select"; singlegroup["proxies"].push_back("DIRECT"); break; case "reject"_hash: case "reject-tinygif"_hash: singlegroup["name"] = name; singlegroup["type"] = "select"; singlegroup["proxies"].push_back("REJECT"); break; default: continue; } clash[proxygroup_name].push_back(singlegroup); } eraseElements(dummy_str_array); ini.get_all("Rule", "{NONAME}", dummy_str_array); YAML::Node rule; string_array strArray; std::string strLine; std::stringstream ss; std::string::size_type lineSize; for(std::string &x : dummy_str_array) { if(startsWith(x, "RULE-SET")) { strArray = split(x, ","); if(strArray.size() != 3) continue; content = webGet(strArray[1], proxy, global.cacheRuleset); if(content.empty()) continue; ss << content; char delimiter = getLineBreak(content); while(getline(ss, strLine, delimiter)) { lineSize = strLine.size(); if(lineSize && strLine[lineSize - 1] == '\r') //remove line break strLine.erase(--lineSize); if(!lineSize || strLine[0] == ';' || strLine[0] == '#' || (lineSize >= 2 && strLine[0] == '/' && strLine[1] == '/')) //empty lines and comments are ignored continue; else if(!std::any_of(ClashRuleTypes.begin(), ClashRuleTypes.end(), [&strLine](const std::string& type){return startsWith(strLine, type);})) //remove unsupported types continue; strLine += strArray[2]; if(count_least(strLine, ',', 3)) strLine = regReplace(strLine, "^(.*?,.*?)(,.*)(,.*)$", "$1$3$2"); rule.push_back(strLine); } ss.clear(); continue; } else if(!std::any_of(ClashRuleTypes.begin(), ClashRuleTypes.end(), [&strLine](const std::string& type){return startsWith(strLine, type);})) continue; rule.push_back(x); } clash[rule_name] = rule; response.headers["profile-update-interval"] = std::to_string(global.updateInterval / 3600); writeLog(0, "Conversion completed.", LOG_LEVEL_INFO); return YAML::Dump(clash); } std::string getProfile(RESPONSE_CALLBACK_ARGS) { auto &argument = request.argument; int *status_code = &response.status_code; std::string name = getUrlArg(argument, "name"), token = getUrlArg(argument, "token"); string_array profiles = split(name, "|"); if(token.empty() || profiles.empty()) { *status_code = 403; return "Forbidden"; } std::string profile_content; name = profiles[0]; /*if(vfs::vfs_exist(name)) { profile_content = vfs::vfs_get(name); } else */ if(fileExist(name)) { profile_content = fileGet(name, true); } else { *status_code = 404; return "Profile not found"; } //std::cerr<<"Trying to load profile '" + name + "'.\n"; writeLog(0, "Trying to load profile '" + name + "'.", LOG_LEVEL_INFO); INIReader ini; if(ini.parse(profile_content) != INIREADER_EXCEPTION_NONE && !ini.section_exist("Profile")) { //std::cerr<<"Load profile failed! Reason: "<<ini.get_last_error()<<"\n"; writeLog(0, "Load profile failed! Reason: " + ini.get_last_error(), LOG_LEVEL_ERROR); *status_code = 500; return "Broken profile!"; } //std::cerr<<"Trying to parse profile '" + name + "'.\n"; writeLog(0, "Trying to parse profile '" + name + "'.", LOG_LEVEL_INFO); string_multimap contents; ini.get_items("Profile", contents); if(contents.empty()) { //std::cerr<<"Load profile failed! Reason: Empty Profile section\n"; writeLog(0, "Load profile failed! Reason: Empty Profile section", LOG_LEVEL_ERROR); *status_code = 500; return "Broken profile!"; } auto profile_token = contents.find("profile_token"); if(profiles.size() == 1 && profile_token != contents.end()) { if(token != profile_token->second) { *status_code = 403; return "Forbidden"; } token = global.accessToken; } else { if(token != global.accessToken) { *status_code = 403; return "Forbidden"; } } /// check if more than one profile is provided if(profiles.size() > 1) { writeLog(0, "Multiple profiles are provided. Trying to combine profiles...", LOG_TYPE_INFO); std::string all_urls, url; auto iter = contents.find("url"); if(iter != contents.end()) all_urls = iter->second; for(size_t i = 1; i < profiles.size(); i++) { name = profiles[i]; if(!fileExist(name)) { writeLog(0, "Ignoring non-exist profile '" + name + "'...", LOG_LEVEL_WARNING); continue; } if(ini.parse_file(name) != INIREADER_EXCEPTION_NONE && !ini.section_exist("Profile")) { writeLog(0, "Ignoring broken profile '" + name + "'...", LOG_LEVEL_WARNING); continue; } url = ini.get("Profile", "url"); if(!url.empty()) { all_urls += "|" + url; writeLog(0, "Profile url from '" + name + "' added.", LOG_LEVEL_INFO); } else { writeLog(0, "Profile '" + name + "' does not have url key. Skipping...", LOG_LEVEL_INFO); } } iter->second = all_urls; } contents.emplace("token", token); contents.emplace("profile_data", base64Encode(global.managedConfigPrefix + "/getprofile?" + joinArguments(argument))); std::copy(argument.cbegin(), argument.cend(), std::inserter(contents, contents.end())); request.argument = contents; return subconverter(request, response); } /* std::string jinja2_webGet(const std::string &url) { std::string proxy = parseProxy(global.proxyConfig); writeLog(0, "Template called fetch with url '" + url + "'.", LOG_LEVEL_INFO); return webGet(url, proxy, global.cacheConfig); }*/ inline std::string intToStream(unsigned long long stream) { char chrs[16] = {}, units[6] = {' ', 'K', 'M', 'G', 'T', 'P'}; double streamval = stream; unsigned int level = 0; while(streamval > 1024.0) { if(level >= 5) break; level++; streamval /= 1024.0; } snprintf(chrs, 15, "%.2f %cB", streamval, units[level]); return {chrs}; } std::string subInfoToMessage(std::string subinfo) { using ull = unsigned long long; subinfo = replaceAllDistinct(subinfo, "; ", "&"); std::string retdata, useddata = "N/A", totaldata = "N/A", expirydata = "N/A"; std::string upload = getUrlArg(subinfo, "upload"), download = getUrlArg(subinfo, "download"), total = getUrlArg(subinfo, "total"), expire = getUrlArg(subinfo, "expire"); ull used = to_number<ull>(upload, 0) + to_number<ull>(download, 0), tot = to_number<ull>(total, 0); auto expiry = to_number<time_t>(expire, 0); if(used != 0) useddata = intToStream(used); if(tot != 0) totaldata = intToStream(tot); if(expiry != 0) { char buffer[30]; struct tm *dt = localtime(&expiry); strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M", dt); expirydata.assign(buffer); } if(useddata == "N/A" && totaldata == "N/A" && expirydata == "N/A") retdata = "Not Available"; else retdata += "Stream Used: " + useddata + " Stream Total: " + totaldata + " Expiry Time: " + expirydata; return retdata; } int simpleGenerator() { //std::cerr<<"\nReading generator configuration...\n"; writeLog(0, "Reading generator configuration...", LOG_LEVEL_INFO); std::string config = fileGet("generate.ini"), path, profile, content; if(config.empty()) { //std::cerr<<"Generator configuration not found or empty!\n"; writeLog(0, "Generator configuration not found or empty!", LOG_LEVEL_ERROR); return -1; } INIReader ini; if(ini.parse(config) != INIREADER_EXCEPTION_NONE) { //std::cerr<<"Generator configuration broken! Reason:"<<ini.get_last_error()<<"\n"; writeLog(0, "Generator configuration broken! Reason:" + ini.get_last_error(), LOG_LEVEL_ERROR); return -2; } //std::cerr<<"Read generator configuration completed.\n\n"; writeLog(0, "Read generator configuration completed.\n", LOG_LEVEL_INFO); string_array sections = ini.get_section_names(); if(!global.generateProfiles.empty()) { //std::cerr<<"Generating with specific artifacts: \""<<gen_profile<<"\"...\n"; writeLog(0, "Generating with specific artifacts: \"" + global.generateProfiles + "\"...", LOG_LEVEL_INFO); string_array targets = split(global.generateProfiles, ","), new_targets; for(std::string &x : targets) { x = trim(x); if(std::find(sections.cbegin(), sections.cend(), x) != sections.cend()) new_targets.emplace_back(std::move(x)); else { //std::cerr<<"Artifact \""<<x<<"\" not found in generator settings!\n"; writeLog(0, "Artifact \"" + x + "\" not found in generator settings!", LOG_LEVEL_ERROR); return -3; } } sections = new_targets; sections.shrink_to_fit(); } else //std::cerr<<"Generating all artifacts...\n"; writeLog(0, "Generating all artifacts...", LOG_LEVEL_INFO); string_multimap allItems; std::string proxy = parseProxy(global.proxySubscription); for(std::string &x : sections) { Request request; Response response; response.status_code = 200; //std::cerr<<"Generating artifact '"<<x<<"'...\n"; writeLog(0, "Generating artifact '" + x + "'...", LOG_LEVEL_INFO); ini.enter_section(x); if(ini.item_exist("path")) path = ini.get("path"); else { //std::cerr<<"Artifact '"<<x<<"' output path missing! Skipping...\n\n"; writeLog(0, "Artifact '" + x + "' output path missing! Skipping...\n", LOG_LEVEL_ERROR); continue; } if(ini.item_exist("profile")) { profile = ini.get("profile"); request.argument.emplace("name", profile); request.argument.emplace("token", global.accessToken); request.argument.emplace("expand", "true"); content = getProfile(request, response); } else { if(ini.get_bool("direct")) { std::string url = ini.get("url"); content = fetchFile(url, proxy, global.cacheSubscription); if(content.empty()) { //std::cerr<<"Artifact '"<<x<<"' generate ERROR! Please check your link.\n\n"; writeLog(0, "Artifact '" + x + "' generate ERROR! Please check your link.\n", LOG_LEVEL_ERROR); if(sections.size() == 1) return -1; } // add UTF-8 BOM fileWrite(path, "\xEF\xBB\xBF" + content, true); continue; } ini.get_items(allItems); allItems.emplace("expand", "true"); for(auto &y : allItems) { if(y.first == "path") continue; request.argument.emplace(y.first, y.second); } content = subconverter(request, response); } if(response.status_code != 200) { //std::cerr<<"Artifact '"<<x<<"' generate ERROR! Reason: "<<content<<"\n\n"; writeLog(0, "Artifact '" + x + "' generate ERROR! Reason: " + content + "\n", LOG_LEVEL_ERROR); if(sections.size() == 1) return -1; continue; } fileWrite(path, content, true); auto iter = std::find_if(response.headers.begin(), response.headers.end(), [](auto y){ return y.first == "Subscription-UserInfo"; }); if(iter != response.headers.end()) writeLog(0, "User Info for artifact '" + x + "': " + subInfoToMessage(iter->second), LOG_LEVEL_INFO); //std::cerr<<"Artifact '"<<x<<"' generate SUCCESS!\n\n"; writeLog(0, "Artifact '" + x + "' generate SUCCESS!\n", LOG_LEVEL_INFO); eraseElements(response.headers); } //std::cerr<<"All artifact generated. Exiting...\n"; writeLog(0, "All artifact generated. Exiting...", LOG_LEVEL_INFO); return 0; } std::string renderTemplate(RESPONSE_CALLBACK_ARGS) { auto &argument = request.argument; int *status_code = &response.status_code; std::string path = getUrlArg(argument, "path"); writeLog(0, "Trying to render template '" + path + "'...", LOG_LEVEL_INFO); if(!startsWith(path, global.templatePath) || !fileExist(path)) { *status_code = 404; return "Not found"; } std::string template_content = fetchFile(path, parseProxy(global.proxyConfig), global.cacheConfig); if(template_content.empty()) { *status_code = 400; return "File empty or out of scope"; } template_args tpl_args; tpl_args.global_vars = global.templateVars; //load request arguments as template variables string_map req_arg_map; for (auto &x : argument) { req_arg_map[x.first] = x.second; } tpl_args.request_params = req_arg_map; std::string output_content; if(render_template(template_content, tpl_args, output_content, global.templatePath) != 0) { *status_code = 400; writeLog(0, "Render failed with error.", LOG_LEVEL_WARNING); } else writeLog(0, "Render completed.", LOG_LEVEL_INFO); return output_content; }
56,417
C++
.cpp
1,364
32.719941
218
0.59605
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,477
webget.cpp
tindy2013_subconverter/src/handler/webget.cpp
#include <iostream> #include <unistd.h> #include <sys/stat.h> //#include <mutex> #include <thread> #include <atomic> #include <curl/curl.h> #include "handler/settings.h" #include "utils/base64/base64.h" #include "utils/defer.h" #include "utils/file_extra.h" #include "utils/lock.h" #include "utils/logger.h" #include "utils/urlencode.h" #include "version.h" #include "webget.h" #ifdef _WIN32 #ifndef _stat #define _stat stat #endif // _stat #endif // _WIN32 /* using guarded_mutex = std::lock_guard<std::mutex>; std::mutex cache_rw_lock; */ RWLock cache_rw_lock; //std::string user_agent_str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"; static auto user_agent_str = "subconverter/" VERSION " cURL/" LIBCURL_VERSION; struct curl_progress_data { long size_limit = 0L; }; static inline void curl_init() { static bool init = false; if(!init) { curl_global_init(CURL_GLOBAL_ALL); init = true; } } static int writer(char *data, size_t size, size_t nmemb, std::string *writerData) { if(writerData == nullptr) return 0; writerData->append(data, size*nmemb); return static_cast<int>(size * nmemb); } static int dummy_writer(char *, size_t size, size_t nmemb, void *) { /// dummy writer, do not save anything return static_cast<int>(size * nmemb); } //static int size_checker(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) static int size_checker(void *clientp, curl_off_t, curl_off_t dlnow, curl_off_t, curl_off_t) { if(clientp) { auto *data = reinterpret_cast<curl_progress_data*>(clientp); if(data->size_limit) { if(dlnow > data->size_limit) return 1; } } return 0; } static int logger(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { (void)handle; (void)userptr; std::string prefix; switch(type) { case CURLINFO_TEXT: prefix = "CURL_INFO: "; break; case CURLINFO_HEADER_IN: prefix = "CURL_HEADER: < "; break; case CURLINFO_HEADER_OUT: prefix = "CURL_HEADER: > "; break; case CURLINFO_DATA_IN: case CURLINFO_DATA_OUT: default: return 0; } std::string content(data, size); if(content.find("\r\n") != std::string::npos) { string_array lines = split(content, "\r\n"); for(auto &x : lines) { std::string log_content = prefix; log_content += x; writeLog(0, log_content, LOG_LEVEL_VERBOSE); } } else { std::string log_content = prefix; log_content += trimWhitespace(content); writeLog(0, log_content, LOG_LEVEL_VERBOSE); } return 0; } static inline void curl_set_common_options(CURL *curl_handle, const char *url, curl_progress_data *data) { curl_easy_setopt(curl_handle, CURLOPT_URL, url); curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, global.logLevel == LOG_LEVEL_VERBOSE ? 1L : 0L); curl_easy_setopt(curl_handle, CURLOPT_DEBUGFUNCTION, logger); curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 0L); curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl_handle, CURLOPT_MAXREDIRS, 20L); curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 15L); curl_easy_setopt(curl_handle, CURLOPT_COOKIEFILE, ""); if(data) { if(data->size_limit) curl_easy_setopt(curl_handle, CURLOPT_MAXFILESIZE, data->size_limit); curl_easy_setopt(curl_handle, CURLOPT_XFERINFOFUNCTION, size_checker); curl_easy_setopt(curl_handle, CURLOPT_XFERINFODATA, data); } } //static std::string curlGet(const std::string &url, const std::string &proxy, std::string &response_headers, CURLcode &return_code, const string_map &request_headers) static int curlGet(const FetchArgument &argument, FetchResult &result) { CURL *curl_handle; std::string *data = result.content, new_url = argument.url; curl_slist *header_list = nullptr; defer(curl_slist_free_all(header_list);) long retVal; curl_init(); curl_handle = curl_easy_init(); if(!argument.proxy.empty()) { if(startsWith(argument.proxy, "cors:")) { header_list = curl_slist_append(header_list, "X-Requested-With: subconverter " VERSION); new_url = argument.proxy.substr(5) + argument.url; } else curl_easy_setopt(curl_handle, CURLOPT_PROXY, argument.proxy.data()); } curl_progress_data limit; limit.size_limit = global.maxAllowedDownloadSize; curl_set_common_options(curl_handle, new_url.data(), &limit); header_list = curl_slist_append(header_list, "Content-Type: application/json;charset=utf-8"); if(argument.request_headers) { for(auto &x : *argument.request_headers) { auto header = x.first + ": " + x.second; header_list = curl_slist_append(header_list, header.data()); } if(!argument.request_headers->contains("User-Agent")) curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, user_agent_str); } header_list = curl_slist_append(header_list, "SubConverter-Request: 1"); header_list = curl_slist_append(header_list, "SubConverter-Version: " VERSION); if(header_list) curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, header_list); if(result.content) { curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, result.content); } else curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, dummy_writer); if(result.response_headers) { curl_easy_setopt(curl_handle, CURLOPT_HEADERFUNCTION, writer); curl_easy_setopt(curl_handle, CURLOPT_HEADERDATA, result.response_headers); } else curl_easy_setopt(curl_handle, CURLOPT_HEADERFUNCTION, dummy_writer); if(argument.cookies) { string_array cookies = split(*argument.cookies, "\r\n"); for(auto &x : cookies) curl_easy_setopt(curl_handle, CURLOPT_COOKIELIST, x.c_str()); } switch(argument.method) { case HTTP_POST: curl_easy_setopt(curl_handle, CURLOPT_POST, 1L); if(argument.post_data) { curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, argument.post_data->data()); curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE, argument.post_data->size()); } break; case HTTP_PATCH: curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, "PATCH"); if(argument.post_data) { curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, argument.post_data->data()); curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE, argument.post_data->size()); } break; case HTTP_HEAD: curl_easy_setopt(curl_handle, CURLOPT_NOBODY, 1L); break; case HTTP_GET: break; } unsigned int fail_count = 0, max_fails = 1; while(true) { retVal = curl_easy_perform(curl_handle); if(retVal == CURLE_OK || max_fails <= fail_count || global.APIMode) break; else fail_count++; } long code = 0; curl_easy_getinfo(curl_handle, CURLINFO_HTTP_CODE, &code); *result.status_code = code; if(result.cookies) { curl_slist *cookies = nullptr; curl_easy_getinfo(curl_handle, CURLINFO_COOKIELIST, &cookies); if(cookies) { auto each = cookies; while(each) { result.cookies->append(each->data); *result.cookies += "\r\n"; each = each->next; } } curl_slist_free_all(cookies); } curl_easy_cleanup(curl_handle); if(data && !argument.keep_resp_on_fail) { if(retVal != CURLE_OK || *result.status_code != 200) data->clear(); data->shrink_to_fit(); } return *result.status_code; } // data:[<mediatype>][;base64],<data> static std::string dataGet(const std::string &url) { if (!startsWith(url, "data:")) return ""; std::string::size_type comma = url.find(','); if (comma == std::string::npos || comma == url.size() - 1) return ""; std::string data = urlDecode(url.substr(comma + 1)); if (endsWith(url.substr(0, comma), ";base64")) { return urlSafeBase64Decode(data); } else { return data; } } std::string buildSocks5ProxyString(const std::string &addr, int port, const std::string &username, const std::string &password) { std::string authstr = username.size() && password.size() ? username + ":" + password + "@" : ""; std::string proxystr = "socks5://" + authstr + addr + ":" + std::to_string(port); return proxystr; } std::string webGet(const std::string &url, const std::string &proxy, unsigned int cache_ttl, std::string *response_headers, string_icase_map *request_headers) { int return_code = 0; std::string content; FetchArgument argument {HTTP_GET, url, proxy, nullptr, request_headers, nullptr, cache_ttl}; FetchResult fetch_res {&return_code, &content, response_headers, nullptr}; if (startsWith(url, "data:")) return dataGet(url); // cache system if(cache_ttl > 0) { md("cache"); const std::string url_md5 = getMD5(url); const std::string path = "cache/" + url_md5, path_header = path + "_header"; struct stat result {}; if(stat(path.data(), &result) == 0) // cache exist { time_t mtime = result.st_mtime, now = time(nullptr); // get cache modified time and current time if(difftime(now, mtime) <= cache_ttl) // within TTL { writeLog(0, "CACHE HIT: '" + url + "', using local cache."); //guarded_mutex guard(cache_rw_lock); cache_rw_lock.readLock(); defer(cache_rw_lock.readUnlock();) if(response_headers) *response_headers = fileGet(path_header, true); return fileGet(path, true); } writeLog(0, "CACHE MISS: '" + url + "', TTL timeout, creating new cache."); // out of TTL } else writeLog(0, "CACHE NOT EXIST: '" + url + "', creating new cache."); //content = curlGet(url, proxy, response_headers, return_code); // try to fetch data curlGet(argument, fetch_res); if(return_code == 200) // success, save new cache { //guarded_mutex guard(cache_rw_lock); cache_rw_lock.writeLock(); defer(cache_rw_lock.writeUnlock();) fileWrite(path, content, true); if(response_headers) fileWrite(path_header, *response_headers, true); } else { if(fileExist(path) && global.serveCacheOnFetchFail) // failed, check if cache exist { writeLog(0, "Fetch failed. Serving cached content."); // cache exist, serving cache //guarded_mutex guard(cache_rw_lock); cache_rw_lock.readLock(); defer(cache_rw_lock.readUnlock();) content = fileGet(path, true); if(response_headers) *response_headers = fileGet(path_header, true); } else writeLog(0, "Fetch failed. No local cache available."); // cache not exist or not allow to serve cache, serving nothing } return content; } //return curlGet(url, proxy, response_headers, return_code); curlGet(argument, fetch_res); return content; } void flushCache() { //guarded_mutex guard(cache_rw_lock); cache_rw_lock.writeLock(); defer(cache_rw_lock.writeUnlock();) operateFiles("cache", [](const std::string &file){ remove(("cache/" + file).data()); return 0; }); } int webPost(const std::string &url, const std::string &data, const std::string &proxy, const string_icase_map &request_headers, std::string *retData) { //return curlPost(url, data, proxy, request_headers, retData); int return_code = 0; FetchArgument argument {HTTP_POST, url, proxy, &data, &request_headers, nullptr, 0, true}; FetchResult fetch_res {&return_code, retData, nullptr, nullptr}; return webGet(argument, fetch_res); } int webPatch(const std::string &url, const std::string &data, const std::string &proxy, const string_icase_map &request_headers, std::string *retData) { //return curlPatch(url, data, proxy, request_headers, retData); int return_code = 0; FetchArgument argument {HTTP_PATCH, url, proxy, &data, &request_headers, nullptr, 0, true}; FetchResult fetch_res {&return_code, retData, nullptr, nullptr}; return webGet(argument, fetch_res); } int webHead(const std::string &url, const std::string &proxy, const string_icase_map &request_headers, std::string &response_headers) { //return curlHead(url, proxy, request_headers, response_headers); int return_code = 0; FetchArgument argument {HTTP_HEAD, url, proxy, nullptr, &request_headers, nullptr, 0}; FetchResult fetch_res {&return_code, nullptr, &response_headers, nullptr}; return webGet(argument, fetch_res); } string_array headers_map_to_array(const string_map &headers) { string_array result; for(auto &kv : headers) result.push_back(kv.first + ": " + kv.second); return result; } int webGet(const FetchArgument& argument, FetchResult &result) { return curlGet(argument, result); }
13,922
C++
.cpp
374
30.580214
167
0.6338
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,478
settings.cpp
tindy2013_subconverter/src/handler/settings.cpp
#include <string> #include <mutex> #include <toml.hpp> #include "config/binding.h" #include "handler/webget.h" #include "script/cron.h" #include "server/webserver.h" #include "utils/logger.h" #include "utils/network.h" #include "interfaces.h" #include "multithread.h" #include "settings.h" //multi-thread lock std::mutex gMutexConfigure; Settings global; extern WebServer webServer; const std::map<std::string, ruleset_type> RulesetTypes = {{"clash-domain:", RULESET_CLASH_DOMAIN}, {"clash-ipcidr:", RULESET_CLASH_IPCIDR}, {"clash-classic:", RULESET_CLASH_CLASSICAL}, \ {"quanx:", RULESET_QUANX}, {"surge:", RULESET_SURGE}}; int importItems(string_array &target, bool scope_limit) { string_array result; std::stringstream ss; std::string path, content, strLine; unsigned int itemCount = 0; for(std::string &x : target) { if(x.find("!!import:") == std::string::npos) { result.emplace_back(x); continue; } path = x.substr(x.find(":") + 1); writeLog(0, "Trying to import items from " + path); std::string proxy = parseProxy(global.proxyConfig); if(fileExist(path)) content = fileGet(path, scope_limit); else if(isLink(path)) content = webGet(path, proxy, global.cacheConfig); else writeLog(0, "File not found or not a valid URL: " + path, LOG_LEVEL_ERROR); if(content.empty()) return -1; ss << content; char delimiter = getLineBreak(content); std::string::size_type lineSize; while(getline(ss, strLine, delimiter)) { lineSize = strLine.size(); if(lineSize && strLine[lineSize - 1] == '\r') //remove line break strLine.erase(--lineSize); if(!lineSize || strLine[0] == ';' || strLine[0] == '#' || (lineSize >= 2 && strLine[0] == '/' && strLine[1] == '/')) //empty lines and comments are ignored continue; result.emplace_back(std::move(strLine)); itemCount++; } ss.clear(); } target.swap(result); writeLog(0, "Imported " + std::to_string(itemCount) + " item(s)."); return 0; } toml::value parseToml(const std::string &content, const std::string &fname) { std::istringstream is(content); return toml::parse(is, fname); } void importItems(std::vector<toml::value> &root, const std::string &import_key, bool scope_limit = true) { std::string content; std::vector<toml::value> newRoot; auto iter = root.begin(); size_t count = 0; std::string proxy = parseProxy(global.proxyConfig); while(iter != root.end()) { auto& table = iter->as_table(); if(table.find("import") == table.end()) newRoot.emplace_back(std::move(*iter)); else { const std::string &path = toml::get<std::string>(table.at("import")); writeLog(0, "Trying to import items from " + path); if(fileExist(path)) content = fileGet(path, scope_limit); else if(isLink(path)) content = webGet(path, proxy, global.cacheConfig); else writeLog(0, "File not found or not a valid URL: " + path, LOG_LEVEL_ERROR); if(!content.empty()) { auto items = parseToml(content, path); auto list = toml::find<std::vector<toml::value>>(items, import_key); count += list.size(); std::move(list.begin(), list.end(), std::back_inserter(newRoot)); } } iter++; } root.swap(newRoot); writeLog(0, "Imported " + std::to_string(count) + " item(s)."); } void readRegexMatch(YAML::Node node, const std::string &delimiter, string_array &dest, bool scope_limit = true) { for(auto && object : node) { std::string script, url, match, rep, strLine; object["script"] >>= script; if(!script.empty()) { dest.emplace_back("!!script:" + script); continue; } object["import"] >>= url; if(!url.empty()) { dest.emplace_back("!!import:" + url); continue; } object["match"] >>= match; object["replace"] >>= rep; if(!match.empty() && !rep.empty()) strLine = match + delimiter + rep; else continue; dest.emplace_back(std::move(strLine)); } importItems(dest, scope_limit); } void readEmoji(YAML::Node node, string_array &dest, bool scope_limit = true) { for(auto && object : node) { std::string script, url, match, rep, strLine; object["script"] >>= script; if(!script.empty()) { dest.emplace_back("!!script:" + script); continue; } object["import"] >>= url; if(!url.empty()) { url = "!!import:" + url; dest.emplace_back(url); continue; } object["match"] >>= match; object["emoji"] >>= rep; if(!match.empty() && !rep.empty()) strLine = match + "," + rep; else continue; dest.emplace_back(std::move(strLine)); } importItems(dest, scope_limit); } void readGroup(YAML::Node node, string_array &dest, bool scope_limit = true) { for(YAML::Node && object : node) { string_array tempArray; std::string name, type; object["import"] >>= name; if(!name.empty()) { dest.emplace_back("!!import:" + name); continue; } std::string url = "http://www.gstatic.com/generate_204", interval = "300", tolerance, timeout; object["name"] >>= name; object["type"] >>= type; tempArray.emplace_back(name); tempArray.emplace_back(type); object["url"] >>= url; object["interval"] >>= interval; object["tolerance"] >>= tolerance; object["timeout"] >>= timeout; for(std::size_t j = 0; j < object["rule"].size(); j++) tempArray.emplace_back(safe_as<std::string>(object["rule"][j])); switch(hash_(type)) { case "select"_hash: if(tempArray.size() < 3) continue; break; case "ssid"_hash: if(tempArray.size() < 4) continue; break; default: if(tempArray.size() < 3) continue; tempArray.emplace_back(url); tempArray.emplace_back(interval + "," + timeout + "," + tolerance); } std::string strLine = join(tempArray, "`"); dest.emplace_back(std::move(strLine)); } importItems(dest, scope_limit); } void readRuleset(YAML::Node node, string_array &dest, bool scope_limit = true) { for(auto && object : node) { std::string strLine, name, url, group, interval; object["import"] >>= name; if(!name.empty()) { dest.emplace_back("!!import:" + name); continue; } object["ruleset"] >>= url; object["group"] >>= group; object["rule"] >>= name; object["interval"] >>= interval; if(!url.empty()) { strLine = group + "," + url; if(!interval.empty()) strLine += "," + interval; } else if(!name.empty()) strLine = group + ",[]" + name; else continue; dest.emplace_back(std::move(strLine)); } importItems(dest, scope_limit); } void refreshRulesets(RulesetConfigs &ruleset_list, std::vector<RulesetContent> &ruleset_content_array) { eraseElements(ruleset_content_array); std::string rule_group, rule_url, rule_url_typed, interval; RulesetContent rc; std::string proxy = parseProxy(global.proxyRuleset); for(RulesetConfig &x : ruleset_list) { rule_group = x.Group; rule_url = x.Url; std::string::size_type pos = x.Url.find("[]"); if(pos != std::string::npos) { writeLog(0, "Adding rule '" + rule_url.substr(pos + 2) + "," + rule_group + "'.", LOG_LEVEL_INFO); rc = {rule_group, "", "", RULESET_SURGE, std::async(std::launch::async, [=](){return rule_url.substr(pos);}), 0}; } else { ruleset_type type = RULESET_SURGE; rule_url_typed = rule_url; auto iter = std::find_if(RulesetTypes.begin(), RulesetTypes.end(), [rule_url](auto y){ return startsWith(rule_url, y.first); }); if(iter != RulesetTypes.end()) { rule_url.erase(0, iter->first.size()); type = iter->second; } writeLog(0, "Updating ruleset url '" + rule_url + "' with group '" + rule_group + "'.", LOG_LEVEL_INFO); rc = {rule_group, rule_url, rule_url_typed, type, fetchFileAsync(rule_url, proxy, global.cacheRuleset, true, global.asyncFetchRuleset), x.Interval}; } ruleset_content_array.emplace_back(std::move(rc)); } ruleset_content_array.shrink_to_fit(); } void readYAMLConf(YAML::Node &node) { YAML::Node section = node["common"]; std::string strLine; string_array tempArray; section["api_mode"] >> global.APIMode; section["api_access_token"] >> global.accessToken; if(section["default_url"].IsSequence()) { section["default_url"] >> tempArray; if(tempArray.size()) { strLine = std::accumulate(std::next(tempArray.begin()), tempArray.end(), tempArray[0], [](std::string a, std::string b) { return std::move(a) + "|" + std::move(b); }); global.defaultUrls = strLine; eraseElements(tempArray); } } global.enableInsert = safe_as<std::string>(section["enable_insert"]); if(section["insert_url"].IsSequence()) { section["insert_url"] >> tempArray; if(tempArray.size()) { strLine = std::accumulate(std::next(tempArray.begin()), tempArray.end(), tempArray[0], [](std::string a, std::string b) { return std::move(a) + "|" + std::move(b); }); global.insertUrls = strLine; eraseElements(tempArray); } } section["prepend_insert_url"] >> global.prependInsert; if(section["exclude_remarks"].IsSequence()) section["exclude_remarks"] >> global.excludeRemarks; if(section["include_remarks"].IsSequence()) section["include_remarks"] >> global.includeRemarks; global.filterScript = safe_as<bool>(section["enable_filter"]) ? safe_as<std::string>(section["filter_script"]) : ""; section["base_path"] >> global.basePath; section["clash_rule_base"] >> global.clashBase; section["surge_rule_base"] >> global.surgeBase; section["surfboard_rule_base"] >> global.surfboardBase; section["mellow_rule_base"] >> global.mellowBase; section["quan_rule_base"] >> global.quanBase; section["quanx_rule_base"] >> global.quanXBase; section["loon_rule_base"] >> global.loonBase; section["sssub_rule_base"] >> global.SSSubBase; section["singbox_rule_base"] >> global.singBoxBase; section["default_external_config"] >> global.defaultExtConfig; section["append_proxy_type"] >> global.appendType; section["proxy_config"] >> global.proxyConfig; section["proxy_ruleset"] >> global.proxyRuleset; section["proxy_subscription"] >> global.proxySubscription; section["reload_conf_on_request"] >> global.reloadConfOnRequest; if(node["userinfo"].IsDefined()) { section = node["userinfo"]; if(section["stream_rule"].IsSequence()) { readRegexMatch(section["stream_rule"], "|", tempArray, false); auto configs = INIBinding::from<RegexMatchConfig>::from_ini(tempArray, "|"); safe_set_streams(configs); eraseElements(tempArray); } if(section["time_rule"].IsSequence()) { readRegexMatch(section["time_rule"], "|", tempArray, false); auto configs = INIBinding::from<RegexMatchConfig>::from_ini(tempArray, "|"); safe_set_times(configs); eraseElements(tempArray); } } if(node["node_pref"].IsDefined()) { section = node["node_pref"]; /* section["udp_flag"] >> udp_flag; section["tcp_fast_open_flag"] >> tfo_flag; section["skip_cert_verify_flag"] >> scv_flag; */ global.UDPFlag.set(safe_as<std::string>(section["udp_flag"])); global.TFOFlag.set(safe_as<std::string>(section["tcp_fast_open_flag"])); global.skipCertVerify.set(safe_as<std::string>(section["skip_cert_verify_flag"])); global.TLS13Flag.set(safe_as<std::string>(section["tls13_flag"])); section["sort_flag"] >> global.enableSort; section["sort_script"] >> global.sortScript; section["filter_deprecated_nodes"] >> global.filterDeprecated; section["append_sub_userinfo"] >> global.appendUserinfo; section["clash_use_new_field_name"] >> global.clashUseNewField; section["clash_proxies_style"] >> global.clashProxiesStyle; section["clash_proxy_groups_style"] >> global.clashProxyGroupsStyle; section["singbox_add_clash_modes"] >> global.singBoxAddClashModes; } if(section["rename_node"].IsSequence()) { readRegexMatch(section["rename_node"], "@", tempArray, false); auto configs = INIBinding::from<RegexMatchConfig>::from_ini(tempArray, "@"); safe_set_renames(configs); eraseElements(tempArray); } if(node["managed_config"].IsDefined()) { section = node["managed_config"]; section["write_managed_config"] >> global.writeManagedConfig; section["managed_config_prefix"] >> global.managedConfigPrefix; section["config_update_interval"] >> global.updateInterval; section["config_update_strict"] >> global.updateStrict; section["quanx_device_id"] >> global.quanXDevID; } if(node["surge_external_proxy"].IsDefined()) { node["surge_external_proxy"]["surge_ssr_path"] >> global.surgeSSRPath; node["surge_external_proxy"]["resolve_hostname"] >> global.surgeResolveHostname; } if(node["emojis"].IsDefined()) { section = node["emojis"]; section["add_emoji"] >> global.addEmoji; section["remove_old_emoji"] >> global.removeEmoji; if(section["rules"].IsSequence()) { readEmoji(section["rules"], tempArray, false); auto configs = INIBinding::from<RegexMatchConfig>::from_ini(tempArray, ","); safe_set_emojis(configs); eraseElements(tempArray); } } const char *rulesets_title = node["rulesets"].IsDefined() ? "rulesets" : "ruleset"; if(node[rulesets_title].IsDefined()) { section = node[rulesets_title]; section["enabled"] >> global.enableRuleGen; if(!global.enableRuleGen) { global.overwriteOriginalRules = false; global.updateRulesetOnRequest = false; } else { section["overwrite_original_rules"] >> global.overwriteOriginalRules; section["update_ruleset_on_request"] >> global.updateRulesetOnRequest; } const char *ruleset_title = section["rulesets"].IsDefined() ? "rulesets" : "surge_ruleset"; if(section[ruleset_title].IsSequence()) { string_array vArray; readRuleset(section[ruleset_title], vArray, false); global.customRulesets = INIBinding::from<RulesetConfig>::from_ini(vArray); } } const char *groups_title = node["proxy_groups"].IsDefined() ? "proxy_groups" : "proxy_group"; if(node[groups_title].IsDefined() && node[groups_title]["custom_proxy_group"].IsDefined()) { string_array vArray; readGroup(node[groups_title]["custom_proxy_group"], vArray, false); global.customProxyGroups = INIBinding::from<ProxyGroupConfig>::from_ini(vArray); } if(node["template"].IsDefined()) { node["template"]["template_path"] >> global.templatePath; if(node["template"]["globals"].IsSequence()) { eraseElements(global.templateVars); for(size_t i = 0; i < node["template"]["globals"].size(); i++) { std::string key, value; node["template"]["globals"][i]["key"] >> key; node["template"]["globals"][i]["value"] >> value; global.templateVars[key] = value; } } } if(node["aliases"].IsSequence()) { webServer.reset_redirect(); for(size_t i = 0; i < node["aliases"].size(); i++) { std::string uri, target; node["aliases"][i]["uri"] >> uri; node["aliases"][i]["target"] >> target; webServer.append_redirect(uri, target); } } if(node["tasks"].IsSequence()) { string_array vArray; for(size_t i = 0; i < node["tasks"].size(); i++) { std::string name, exp, path, timeout; node["tasks"][i]["import"] >> name; if(name.size()) { vArray.emplace_back("!!import:" + name); continue; } node["tasks"][i]["name"] >> name; node["tasks"][i]["cronexp"] >> exp; node["tasks"][i]["path"] >> path; node["tasks"][i]["timeout"] >> timeout; strLine = name + "`" + exp + "`" + path + "`" + timeout; vArray.emplace_back(std::move(strLine)); } importItems(vArray, false); global.enableCron = !vArray.empty(); global.cronTasks = INIBinding::from<CronTaskConfig>::from_ini(vArray); refresh_schedule(); } if(node["server"].IsDefined()) { node["server"]["listen"] >> global.listenAddress; node["server"]["port"] >> global.listenPort; node["server"]["serve_file_root"] >>= webServer.serve_file_root; webServer.serve_file = !webServer.serve_file_root.empty(); } if(node["advanced"].IsDefined()) { std::string log_level; node["advanced"]["log_level"] >> log_level; node["advanced"]["print_debug_info"] >> global.printDbgInfo; if(global.printDbgInfo) global.logLevel = LOG_LEVEL_VERBOSE; else { switch(hash_(log_level)) { case "warn"_hash: global.logLevel = LOG_LEVEL_WARNING; break; case "error"_hash: global.logLevel = LOG_LEVEL_ERROR; break; case "fatal"_hash: global.logLevel = LOG_LEVEL_FATAL; break; case "verbose"_hash: global.logLevel = LOG_LEVEL_VERBOSE; break; case "debug"_hash: global.logLevel = LOG_LEVEL_DEBUG; break; default: global.logLevel = LOG_LEVEL_INFO; } } node["advanced"]["max_pending_connections"] >> global.maxPendingConns; node["advanced"]["max_concurrent_threads"] >> global.maxConcurThreads; node["advanced"]["max_allowed_rulesets"] >> global.maxAllowedRulesets; node["advanced"]["max_allowed_rules"] >> global.maxAllowedRules; node["advanced"]["max_allowed_download_size"] >> global.maxAllowedDownloadSize; if(node["advanced"]["enable_cache"].IsDefined()) { if(safe_as<bool>(node["advanced"]["enable_cache"])) { node["advanced"]["cache_subscription"] >> global.cacheSubscription; node["advanced"]["cache_config"] >> global.cacheConfig; node["advanced"]["cache_ruleset"] >> global.cacheRuleset; node["advanced"]["serve_cache_on_fetch_fail"] >> global.serveCacheOnFetchFail; } else global.cacheSubscription = global.cacheConfig = global.cacheRuleset = 0; //disable cache } node["advanced"]["script_clean_context"] >> global.scriptCleanContext; node["advanced"]["async_fetch_ruleset"] >> global.asyncFetchRuleset; node["advanced"]["skip_failed_links"] >> global.skipFailedLinks; } writeLog(0, "Load preference settings in YAML format completed.", LOG_LEVEL_INFO); } template <class T, class... U> void find_if_exist(const toml::value &v, const toml::key &k, T& target, U&&... args) { if(v.contains(k)) target = toml::find<T>(v, k); if constexpr (sizeof...(args) > 0) find_if_exist(v, std::forward<U>(args)...); } void operate_toml_kv_table(const std::vector<toml::table> &arr, const toml::key &key_name, const toml::key &value_name, std::function<void (const toml::value&, const toml::value&)> binary_op) { for(const toml::table &table : arr) { const auto &key = table.at(key_name), &value = table.at(value_name); binary_op(key, value); } } void readTOMLConf(toml::value &root) { auto section_common = toml::find(root, "common"); string_array default_url, insert_url; find_if_exist(section_common, "default_url", default_url, "insert_url", insert_url); global.defaultUrls = join(default_url, "|"); global.insertUrls = join(insert_url, "|"); bool filter = false; find_if_exist(section_common, "api_mode", global.APIMode, "api_access_token", global.accessToken, "exclude_remarks", global.excludeRemarks, "include_remarks", global.includeRemarks, "enable_insert", global.enableInsert, "prepend_insert_url", global.prependInsert, "enable_filter", filter, "default_external_config", global.defaultExtConfig, "base_path", global.basePath, "clash_rule_base", global.clashBase, "surge_rule_base", global.surgeBase, "surfboard_rule_base", global.surfboardBase, "mellow_rule_base", global.mellowBase, "quan_rule_base", global.quanBase, "quanx_rule_base", global.quanXBase, "loon_rule_base", global.loonBase, "sssub_rule_base", global.SSSubBase, "singbox_rule_base", global.singBoxBase, "proxy_config", global.proxyConfig, "proxy_ruleset", global.proxyRuleset, "proxy_subscription", global.proxySubscription, "append_proxy_type", global.appendType, "reload_conf_on_request", global.reloadConfOnRequest ); if(filter) find_if_exist(section_common, "filter_script", global.filterScript); else global.filterScript.clear(); safe_set_streams(toml::find_or<RegexMatchConfigs>(root, "userinfo", "stream_rule", RegexMatchConfigs{})); safe_set_times(toml::find_or<RegexMatchConfigs>(root, "userinfo", "time_rule", RegexMatchConfigs{})); auto section_node_pref = toml::find(root, "node_pref"); find_if_exist(section_node_pref, "udp_flag", global.UDPFlag, "tcp_fast_open_flag", global.TFOFlag, "skip_cert_verify_flag", global.skipCertVerify, "tls13_flag", global.TLS13Flag, "sort_flag", global.enableSort, "sort_script", global.sortScript, "filter_deprecated_nodes", global.filterDeprecated, "append_sub_userinfo", global.appendUserinfo, "clash_use_new_field_name", global.clashUseNewField, "clash_proxies_style", global.clashProxiesStyle, "clash_proxy_groups_style", global.clashProxyGroupsStyle, "singbox_add_clash_modes", global.singBoxAddClashModes ); auto renameconfs = toml::find_or<std::vector<toml::value>>(section_node_pref, "rename_node", {}); importItems(renameconfs, "rename_node", false); safe_set_renames(toml::get<RegexMatchConfigs>(toml::value(renameconfs))); auto section_managed = toml::find(root, "managed_config"); find_if_exist(section_managed, "write_managed_config", global.writeManagedConfig, "managed_config_prefix", global.managedConfigPrefix, "config_update_interval", global.updateInterval, "config_update_strict", global.updateStrict, "quanx_device_id", global.quanXDevID ); auto section_surge_external = toml::find(root, "surge_external_proxy"); find_if_exist(section_surge_external, "surge_ssr_path", global.surgeSSRPath, "resolve_hostname", global.surgeResolveHostname ); auto section_emojis = toml::find(root, "emojis"); find_if_exist(section_emojis, "add_emoji", global.addEmoji, "remove_old_emoji", global.removeEmoji ); auto emojiconfs = toml::find_or<std::vector<toml::value>>(section_emojis, "emoji", {}); importItems(emojiconfs, "emoji", false); safe_set_emojis(toml::get<RegexMatchConfigs>(toml::value(emojiconfs))); auto groups = toml::find_or<std::vector<toml::value>>(root, "custom_groups", {}); importItems(groups, "custom_groups", false); global.customProxyGroups = toml::get<ProxyGroupConfigs>(toml::value(groups)); auto section_ruleset = toml::find(root, "ruleset"); find_if_exist(section_ruleset, "enabled", global.enableRuleGen, "overwrite_original_rules", global.overwriteOriginalRules, "update_ruleset_on_request", global.updateRulesetOnRequest ); auto rulesets = toml::find_or<std::vector<toml::value>>(root, "rulesets", {}); importItems(rulesets, "rulesets", false); global.customRulesets = toml::get<RulesetConfigs>(toml::value(rulesets)); auto section_template = toml::find(root, "template"); global.templatePath = toml::find_or(section_template, "template_path", "template"); eraseElements(global.templateVars); operate_toml_kv_table(toml::find_or<std::vector<toml::table>>(section_template, "globals", {}), "key", "value", [&](const toml::value &key, const toml::value &value) { global.templateVars[key.as_string()] = value.as_string(); }); webServer.reset_redirect(); operate_toml_kv_table(toml::find_or<std::vector<toml::table>>(root, "aliases", {}), "uri", "target", [&](const toml::value &key, const toml::value &value) { webServer.append_redirect(key.as_string(), value.as_string()); }); auto tasks = toml::find_or<std::vector<toml::value>>(root, "tasks", {}); importItems(tasks, "tasks", false); global.cronTasks = toml::get<CronTaskConfigs>(toml::value(tasks)); refresh_schedule(); auto section_server = toml::find(root, "server"); find_if_exist(section_server, "listen", global.listenAddress, "port", global.listenPort, "serve_file_root", webServer.serve_file_root ); webServer.serve_file = !webServer.serve_file_root.empty(); auto section_advanced = toml::find(root, "advanced"); std::string log_level; bool enable_cache = true; int cache_subscription = global.cacheSubscription, cache_config = global.cacheConfig, cache_ruleset = global.cacheRuleset; find_if_exist(section_advanced, "log_level", log_level, "print_debug_info", global.printDbgInfo, "max_pending_connections", global.maxPendingConns, "max_concurrent_threads", global.maxConcurThreads, "max_allowed_rulesets", global.maxAllowedRulesets, "max_allowed_rules", global.maxAllowedRules, "max_allowed_download_size", global.maxAllowedDownloadSize, "enable_cache", enable_cache, "cache_subscription", cache_subscription, "cache_config", cache_config, "cache_ruleset", cache_ruleset, "script_clean_context", global.scriptCleanContext, "async_fetch_ruleset", global.asyncFetchRuleset, "skip_failed_links", global.skipFailedLinks ); if(global.printDbgInfo) global.logLevel = LOG_LEVEL_VERBOSE; else { switch(hash_(log_level)) { case "warn"_hash: global.logLevel = LOG_LEVEL_WARNING; break; case "error"_hash: global.logLevel = LOG_LEVEL_ERROR; break; case "fatal"_hash: global.logLevel = LOG_LEVEL_FATAL; break; case "verbose"_hash: global.logLevel = LOG_LEVEL_VERBOSE; break; case "debug"_hash: global.logLevel = LOG_LEVEL_DEBUG; break; default: global.logLevel = LOG_LEVEL_INFO; } } if(enable_cache) { global.cacheSubscription = cache_subscription; global.cacheConfig = cache_config; global.cacheRuleset = cache_ruleset; } else { global.cacheSubscription = global.cacheConfig = global.cacheRuleset = 0; } writeLog(0, "Load preference settings in TOML format completed.", LOG_LEVEL_INFO); } void readConf() { guarded_mutex guard(gMutexConfigure); writeLog(0, "Loading preference settings...", LOG_LEVEL_INFO); eraseElements(global.excludeRemarks); eraseElements(global.includeRemarks); eraseElements(global.customProxyGroups); eraseElements(global.customRulesets); try { std::string prefdata = fileGet(global.prefPath, false); if(prefdata.find("common:") != std::string::npos) { YAML::Node yaml = YAML::Load(prefdata); if(yaml.size() && yaml["common"]) return readYAMLConf(yaml); } toml::value conf = parseToml(prefdata, global.prefPath); if(!conf.is_uninitialized() && toml::find_or<int>(conf, "version", 0)) return readTOMLConf(conf); } catch (YAML::Exception &e) { //ignore yaml parse error writeLog(0, e.what(), LOG_LEVEL_DEBUG); writeLog(0, "Unable to load preference settings as YAML.", LOG_LEVEL_DEBUG); } catch (toml::exception &e) { //ignore toml parse error writeLog(0, e.what(), LOG_LEVEL_DEBUG); writeLog(0, "Unable to load preference settings as TOML.", LOG_LEVEL_DEBUG); } INIReader ini; ini.allow_dup_section_titles = true; //ini.do_utf8_to_gbk = true; int retVal = ini.parse_file(global.prefPath); if(retVal != INIREADER_EXCEPTION_NONE) { writeLog(0, "Unable to load preference settings as INI. Reason: " + ini.get_last_error(), LOG_LEVEL_FATAL); return; } string_array tempArray; ini.enter_section("common"); ini.get_bool_if_exist("api_mode", global.APIMode); ini.get_if_exist("api_access_token", global.accessToken); ini.get_if_exist("default_url", global.defaultUrls); global.enableInsert = ini.get("enable_insert"); ini.get_if_exist("insert_url", global.insertUrls); ini.get_bool_if_exist("prepend_insert_url", global.prependInsert); if(ini.item_prefix_exist("exclude_remarks")) ini.get_all("exclude_remarks", global.excludeRemarks); if(ini.item_prefix_exist("include_remarks")) ini.get_all("include_remarks", global.includeRemarks); global.filterScript = ini.get_bool("enable_filter") ? ini.get("filter_script") : ""; ini.get_if_exist("base_path", global.basePath); ini.get_if_exist("clash_rule_base", global.clashBase); ini.get_if_exist("surge_rule_base", global.surgeBase); ini.get_if_exist("surfboard_rule_base", global.surfboardBase); ini.get_if_exist("mellow_rule_base", global.mellowBase); ini.get_if_exist("quan_rule_base", global.quanBase); ini.get_if_exist("quanx_rule_base", global.quanXBase); ini.get_if_exist("loon_rule_base", global.loonBase); ini.get_if_exist("sssub_rule_base", global.SSSubBase); ini.get_if_exist("singbox_rule_base", global.singBoxBase); ini.get_if_exist("default_external_config", global.defaultExtConfig); ini.get_bool_if_exist("append_proxy_type", global.appendType); ini.get_if_exist("proxy_config", global.proxyConfig); ini.get_if_exist("proxy_ruleset", global.proxyRuleset); ini.get_if_exist("proxy_subscription", global.proxySubscription); ini.get_bool_if_exist("reload_conf_on_request", global.reloadConfOnRequest); if(ini.section_exist("surge_external_proxy")) { ini.enter_section("surge_external_proxy"); ini.get_if_exist("surge_ssr_path", global.surgeSSRPath); ini.get_bool_if_exist("resolve_hostname", global.surgeResolveHostname); } if(ini.section_exist("node_pref")) { ini.enter_section("node_pref"); /* ini.GetBoolIfExist("udp_flag", udp_flag); ini.get_bool_if_exist("tcp_fast_open_flag", tfo_flag); ini.get_bool_if_exist("skip_cert_verify_flag", scv_flag); */ global.UDPFlag.set(ini.get("udp_flag")); global.TFOFlag.set(ini.get("tcp_fast_open_flag")); global.skipCertVerify.set(ini.get("skip_cert_verify_flag")); global.TLS13Flag.set(ini.get("tls13_flag")); ini.get_bool_if_exist("sort_flag", global.enableSort); global.sortScript = ini.get("sort_script"); ini.get_bool_if_exist("filter_deprecated_nodes", global.filterDeprecated); ini.get_bool_if_exist("append_sub_userinfo", global.appendUserinfo); ini.get_bool_if_exist("clash_use_new_field_name", global.clashUseNewField); ini.get_if_exist("clash_proxies_style", global.clashProxiesStyle); ini.get_if_exist("clash_proxy_groups_style", global.clashProxyGroupsStyle); ini.get_bool_if_exist("singbox_add_clash_modes", global.singBoxAddClashModes); if(ini.item_prefix_exist("rename_node")) { ini.get_all("rename_node", tempArray); importItems(tempArray, false); auto configs = INIBinding::from<RegexMatchConfig>::from_ini(tempArray, "@"); safe_set_renames(configs); eraseElements(tempArray); } } if(ini.section_exist("userinfo")) { ini.enter_section("userinfo"); if(ini.item_prefix_exist("stream_rule")) { ini.get_all("stream_rule", tempArray); importItems(tempArray, false); auto configs = INIBinding::from<RegexMatchConfig>::from_ini(tempArray, "|"); safe_set_streams(configs); eraseElements(tempArray); } if(ini.item_prefix_exist("time_rule")) { ini.get_all("time_rule", tempArray); importItems(tempArray, false); auto configs = INIBinding::from<RegexMatchConfig>::from_ini(tempArray, "|"); safe_set_times(configs); eraseElements(tempArray); } } 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.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.get_all("rule", tempArray); importItems(tempArray, false); auto configs = INIBinding::from<RegexMatchConfig>::from_ini(tempArray, ","); safe_set_emojis(configs); eraseElements(tempArray); } if(ini.section_exist("rulesets")) ini.enter_section("rulesets"); else ini.enter_section("ruleset"); global.enableRuleGen = ini.get_bool("enabled"); if(global.enableRuleGen) { 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.get_all("ruleset", vArray); importItems(vArray, false); global.customRulesets = INIBinding::from<RulesetConfig>::from_ini(vArray); } else if(ini.item_prefix_exist("surge_ruleset")) { string_array vArray; ini.get_all("surge_ruleset", vArray); importItems(vArray, false); global.customRulesets = INIBinding::from<RulesetConfig>::from_ini(vArray); } } else { global.overwriteOriginalRules = false; global.updateRulesetOnRequest = false; } if(ini.section_exist("proxy_groups")) ini.enter_section("proxy_groups"); else ini.enter_section("clash_proxy_group"); if(ini.item_prefix_exist("custom_proxy_group")) { string_array vArray; ini.get_all("custom_proxy_group", vArray); importItems(vArray, false); global.customProxyGroups = INIBinding::from<ProxyGroupConfig>::from_ini(vArray); } ini.enter_section("template"); ini.get_if_exist("template_path", global.templatePath); string_multimap tempmap; ini.get_items(tempmap); eraseElements(global.templateVars); for(auto &x : tempmap) { if(x.first == "template_path") continue; global.templateVars[x.first] = x.second; } global.templateVars["managed_config_prefix"] = global.managedConfigPrefix; if(ini.section_exist("aliases")) { ini.enter_section("aliases"); ini.get_items(tempmap); webServer.reset_redirect(); for(auto &x : tempmap) webServer.append_redirect(x.first, x.second); } if(ini.section_exist("tasks")) { string_array vArray; ini.enter_section("tasks"); ini.get_all("task", vArray); importItems(vArray, false); global.enableCron = !vArray.empty(); global.cronTasks = INIBinding::from<CronTaskConfig>::from_ini(vArray); refresh_schedule(); } 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.enter_section("advanced"); std::string log_level; 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 { switch(hash_(log_level)) { case "warn"_hash: global.logLevel = LOG_LEVEL_WARNING; break; case "error"_hash: global.logLevel = LOG_LEVEL_ERROR; break; case "fatal"_hash: global.logLevel = LOG_LEVEL_FATAL; break; case "verbose"_hash: global.logLevel = LOG_LEVEL_VERBOSE; break; case "debug"_hash: global.logLevel = LOG_LEVEL_DEBUG; break; default: global.logLevel = LOG_LEVEL_INFO; } } 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.get_bool("enable_cache")) { 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 { global.cacheSubscription = global.cacheConfig = global.cacheRuleset = 0; //disable cache global.serveCacheOnFetchFail = false; } } 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); } int loadExternalYAML(YAML::Node &node, ExternalConfig &ext) { YAML::Node section = node["custom"], object; std::string name, type, url, interval; std::string group, strLine; section["clash_rule_base"] >> ext.clash_rule_base; section["surge_rule_base"] >> ext.surge_rule_base; section["surfboard_rule_base"] >> ext.surfboard_rule_base; section["mellow_rule_base"] >> ext.mellow_rule_base; section["quan_rule_base"] >> ext.quan_rule_base; section["quanx_rule_base"] >> ext.quanx_rule_base; section["loon_rule_base"] >> ext.loon_rule_base; section["sssub_rule_base"] >> ext.sssub_rule_base; section["singbox_rule_base"] >> ext.singbox_rule_base; section["enable_rule_generator"] >> ext.enable_rule_generator; section["overwrite_original_rules"] >> ext.overwrite_original_rules; const char *group_name = section["proxy_groups"].IsDefined() ? "proxy_groups" : "custom_proxy_group"; if(section[group_name].size()) { string_array vArray; readGroup(section[group_name], vArray, global.APIMode); ext.custom_proxy_group = INIBinding::from<ProxyGroupConfig>::from_ini(vArray); } const char *ruleset_name = section["rulesets"].IsDefined() ? "rulesets" : "surge_ruleset"; if(section[ruleset_name].size()) { string_array vArray; readRuleset(section[ruleset_name], vArray, global.APIMode); if(global.maxAllowedRulesets && vArray.size() > global.maxAllowedRulesets) { writeLog(0, "Ruleset count in external config has exceeded limit.", LOG_LEVEL_WARNING); return -1; } ext.surge_ruleset = INIBinding::from<RulesetConfig>::from_ini(vArray); } if(section["rename_node"].size()) { string_array vArray; readRegexMatch(section["rename_node"], "@", vArray, global.APIMode); ext.rename = INIBinding::from<RegexMatchConfig>::from_ini(vArray, "@"); } ext.add_emoji = safe_as<std::string>(section["add_emoji"]); ext.remove_old_emoji = safe_as<std::string>(section["remove_old_emoji"]); const char *emoji_name = section["emojis"].IsDefined() ? "emojis" : "emoji"; if(section[emoji_name].size()) { string_array vArray; readEmoji(section[emoji_name], vArray, global.APIMode); ext.emoji = INIBinding::from<RegexMatchConfig>::from_ini(vArray, ","); } section["include_remarks"] >> ext.include; section["exclude_remarks"] >> ext.exclude; if(node["template_args"].IsSequence() && ext.tpl_args != NULL) { std::string key, value; for(size_t i = 0; i < node["template_args"].size(); i++) { node["template_args"][i]["key"] >> key; node["template_args"][i]["value"] >> value; ext.tpl_args->local_vars[key] = value; } } return 0; } int loadExternalTOML(toml::value &root, ExternalConfig &ext) { auto section = toml::find(root, "custom"); find_if_exist(section, "enable_rule_generator", ext.enable_rule_generator, "overwrite_original_rules", ext.overwrite_original_rules, "clash_rule_base", ext.clash_rule_base, "surge_rule_base", ext.surge_rule_base, "surfboard_rule_base", ext.surfboard_rule_base, "mellow_rule_base", ext.mellow_rule_base, "quan_rule_base", ext.quan_rule_base, "quanx_rule_base", ext.quanx_rule_base, "loon_rule_base", ext.loon_rule_base, "sssub_rule_base", ext.sssub_rule_base, "singbox_rule_base", ext.singbox_rule_base, "add_emoji", ext.add_emoji, "remove_old_emoji", ext.remove_old_emoji, "include_remarks", ext.include, "exclude_remarks", ext.exclude ); if(ext.tpl_args != nullptr) operate_toml_kv_table(toml::find_or<std::vector<toml::table>>(root, "template_args", {}), "key", "value", [&](const toml::value &key, const toml::value &value) { std::string val = toml::format(value); ext.tpl_args->local_vars[key.as_string()] = val; }); auto groups = toml::find_or<std::vector<toml::value>>(root, "custom_groups", {}); importItems(groups, "custom_groups", false); ext.custom_proxy_group = toml::get<ProxyGroupConfigs>(toml::value(groups)); auto rulesets = toml::find_or<std::vector<toml::value>>(root, "rulesets", {}); importItems(rulesets, "rulesets", false); if(global.maxAllowedRulesets && rulesets.size() > global.maxAllowedRulesets) { writeLog(0, "Ruleset count in external config has exceeded limit. ", LOG_LEVEL_WARNING); return -1; } ext.surge_ruleset = toml::get<RulesetConfigs>(toml::value(rulesets)); auto emojiconfs = toml::find_or<std::vector<toml::value>>(root, "emoji", {}); importItems(emojiconfs, "emoji", false); ext.emoji = toml::get<RegexMatchConfigs>(toml::value(emojiconfs)); auto renameconfs = toml::find_or<std::vector<toml::value>>(root, "rename_node", {}); importItems(renameconfs, "rename_node", false); ext.rename = toml::get<RegexMatchConfigs>(toml::value(renameconfs)); return 0; } int loadExternalConfig(std::string &path, ExternalConfig &ext) { std::string base_content, proxy = parseProxy(global.proxyConfig), config = fetchFile(path, proxy, global.cacheConfig); if(render_template(config, *ext.tpl_args, base_content, global.templatePath) != 0) base_content = config; try { YAML::Node yaml = YAML::Load(base_content); if(yaml.size() && yaml["custom"].IsDefined()) return loadExternalYAML(yaml, ext); toml::value conf = parseToml(base_content, path); if(!conf.is_uninitialized() && toml::find_or<int>(conf, "version", 0)) return loadExternalTOML(conf, ext); } catch (YAML::Exception &e) { //ignore } catch (toml::exception &e) { //ignore } INIReader ini; ini.store_isolated_line = true; ini.set_isolated_items_section("custom"); if(ini.parse(base_content) != INIREADER_EXCEPTION_NONE) { //std::cerr<<"Load external configuration failed. Reason: "<<ini.get_last_error()<<"\n"; writeLog(0, "Load external configuration failed. Reason: " + ini.get_last_error(), LOG_LEVEL_ERROR); return -1; } ini.enter_section("custom"); if(ini.item_prefix_exist("custom_proxy_group")) { string_array vArray; ini.get_all("custom_proxy_group", vArray); importItems(vArray, global.APIMode); ext.custom_proxy_group = INIBinding::from<ProxyGroupConfig>::from_ini(vArray); } std::string ruleset_name = ini.item_prefix_exist("ruleset") ? "ruleset" : "surge_ruleset"; if(ini.item_prefix_exist(ruleset_name)) { string_array vArray; ini.get_all(ruleset_name, vArray); importItems(vArray, global.APIMode); if(global.maxAllowedRulesets && vArray.size() > global.maxAllowedRulesets) { writeLog(0, "Ruleset count in external config has exceeded limit. ", LOG_LEVEL_WARNING); return -1; } ext.surge_ruleset = INIBinding::from<RulesetConfig>::from_ini(vArray); } 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.get_if_exist("singbox_rule_base", ext.singbox_rule_base); 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.item_prefix_exist("rename")) { string_array vArray; ini.get_all("rename", vArray); importItems(vArray, global.APIMode); ext.rename = INIBinding::from<RegexMatchConfig>::from_ini(vArray, "@"); } 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.get_all("emoji", vArray); importItems(vArray, global.APIMode); ext.emoji = INIBinding::from<RegexMatchConfig>::from_ini(vArray, ","); } 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.section_exist("template") && ext.tpl_args != nullptr) { ini.enter_section("template"); string_multimap tempmap; ini.get_items(tempmap); for(auto &x : tempmap) ext.tpl_args->local_vars[x.first] = x.second; } return 0; }
50,401
C++
.cpp
1,189
33.585366
191
0.608306
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,479
multithread.cpp
tindy2013_subconverter/src/handler/multithread.cpp
#include <future> #include <thread> #include "handler/settings.h" #include "utils/network.h" #include "webget.h" #include "multithread.h" //#include "vfs.h" //safety lock for multi-thread std::mutex on_emoji, on_rename, on_stream, on_time; RegexMatchConfigs safe_get_emojis() { guarded_mutex guard(on_emoji); return global.emojis; } RegexMatchConfigs safe_get_renames() { guarded_mutex guard(on_rename); return global.renames; } RegexMatchConfigs safe_get_streams() { guarded_mutex guard(on_stream); return global.streamNodeRules; } RegexMatchConfigs safe_get_times() { guarded_mutex guard(on_time); return global.timeNodeRules; } void safe_set_emojis(RegexMatchConfigs data) { guarded_mutex guard(on_emoji); global.emojis.swap(data); } void safe_set_renames(RegexMatchConfigs data) { guarded_mutex guard(on_rename); global.renames.swap(data); } void safe_set_streams(RegexMatchConfigs data) { guarded_mutex guard(on_stream); global.streamNodeRules.swap(data); } void safe_set_times(RegexMatchConfigs data) { guarded_mutex guard(on_time); global.timeNodeRules.swap(data); } std::shared_future<std::string> fetchFileAsync(const std::string &path, const std::string &proxy, int cache_ttl, bool find_local, bool async) { std::shared_future<std::string> retVal; /*if(vfs::vfs_exist(path)) retVal = std::async(std::launch::async, [path](){return vfs::vfs_get(path);}); else */if(find_local && fileExist(path, true)) retVal = std::async(std::launch::async, [path](){return fileGet(path, true);}); else if(isLink(path)) retVal = std::async(std::launch::async, [path, proxy, cache_ttl](){return webGet(path, proxy, cache_ttl);}); else return std::async(std::launch::async, [](){return std::string();}); if(!async) retVal.wait(); return retVal; } std::string fetchFile(const std::string &path, const std::string &proxy, int cache_ttl, bool find_local) { return fetchFileAsync(path, proxy, cache_ttl, find_local, false).get(); }
2,067
C++
.cpp
68
27.220588
141
0.713639
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,480
upload.cpp
tindy2013_subconverter/src/handler/upload.cpp
#include <string> #include "utils/ini_reader/ini_reader.h" #include "utils/logger.h" #include "utils/rapidjson_extra.h" #include "utils/system.h" #include "webget.h" std::string buildGistData(std::string name, std::string content) { rapidjson::StringBuffer sb; rapidjson::Writer<rapidjson::StringBuffer> writer(sb); writer.StartObject(); writer.Key("description"); writer.String("subconverter"); writer.Key("public"); writer.Bool(false); writer.Key("files"); writer.StartObject(); writer.Key(name.data()); writer.StartObject(); writer.Key("content"); writer.String(content.data()); writer.EndObject(); writer.EndObject(); writer.EndObject(); return sb.GetString(); } int uploadGist(std::string name, std::string path, std::string content, bool writeManageURL) { INIReader ini; rapidjson::Document json; std::string token, id, username, retData, url; int retVal = 0; if(!fileExist("gistconf.ini")) { //std::cerr<<"gistconf.ini not found. Skipping...\n"; writeLog(0, "gistconf.ini not found. Skipping...", LOG_LEVEL_ERROR); return -1; } 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"); if(!token.size()) { //std::cerr<<"No token is provided. Skipping...\n"; writeLog(0, "No token is provided. Skipping...", LOG_LEVEL_ERROR); return -1; } id = ini.get("id"); username = ini.get("username"); if(!path.size()) { if(ini.item_exist("path")) path = ini.get(name, "path"); else path = name; } if(!id.size()) { //std::cerr<<"No gist id is provided. Creating new gist...\n"; writeLog(0, "No Gist id is provided. Creating new Gist...", LOG_LEVEL_ERROR); retVal = webPost("https://api.github.com/gists", buildGistData(path, content), getSystemProxy(), {{"Authorization", "token " + token}}, &retData); if(retVal != 201) { //std::cerr<<"Create new Gist failed! Return data:\n"<<retData<<"\n"; writeLog(0, "Create new Gist failed!\nReturn code: " + std::to_string(retVal) + "\nReturn data:\n" + retData, LOG_LEVEL_ERROR); return -1; } } else { url = "https://gist.githubusercontent.com/" + username + "/" + id + "/raw/" + path; //std::cerr<<"Gist id provided. Modifying Gist...\n"; writeLog(0, "Gist id provided. Modifying Gist...", LOG_LEVEL_INFO); if(writeManageURL) content = "#!MANAGED-CONFIG " + url + "\n" + content; retVal = webPatch("https://api.github.com/gists/" + id, buildGistData(path, content), getSystemProxy(), {{"Authorization", "token " + token}}, &retData); if(retVal != 200) { //std::cerr<<"Modify gist failed! Return data:\n"<<retData<<"\n"; writeLog(0, "Modify Gist failed!\nReturn code: " + std::to_string(retVal) + "\nReturn data:\n" + retData, LOG_LEVEL_ERROR); return -1; } } json.Parse(retData.data()); GetMember(json, "id", id); if(json.HasMember("owner")) GetMember(json["owner"], "login", username); url = "https://gist.githubusercontent.com/" + username + "/" + id + "/raw/" + path; //std::cerr<<"Writing to Gist success!\nGenerator: "<<name<<"\nPath: "<<path<<"\nRaw URL: "<<url<<"\nGist owner: "<<username<<"\n"; writeLog(0, "Writing to Gist success!\nGenerator: " + name + "\nPath: " + path + "\nRaw URL: " + url + "\nGist owner: " + username, LOG_LEVEL_INFO); ini.erase_section(); ini.set("token", token); ini.set("id", id); ini.set("username", username); ini.set_current_section(path); ini.erase_section(); ini.set("type", name); ini.set("url", url); ini.to_file("gistconf.ini"); return 0; }
4,082
C++
.cpp
106
32.198113
161
0.599748
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,481
webserver_httplib.cpp
tindy2013_subconverter/src/server/webserver_httplib.cpp
#include <string> #ifdef MALLOC_TRIM #include <malloc.h> #endif // MALLOC_TRIM #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 16384 #include "httplib.h" #include "utils/base64/base64.h" #include "utils/logger.h" #include "utils/string_hash.h" #include "utils/stl_extra.h" #include "utils/urlencode.h" #include "webserver.h" static const char *request_header_blacklist[] = {"host", "accept", "accept-encoding"}; static inline bool is_request_header_blacklisted(const std::string &header) { for (auto &x : request_header_blacklist) { if (strcasecmp(x, header.c_str()) == 0) { return true; } } return false; } void WebServer::stop_web_server() { SERVER_EXIT_FLAG = true; } static httplib::Server::Handler makeHandler(const responseRoute &rr) { return [rr](const httplib::Request &request, httplib::Response &response) { Request req; Response resp; req.method = request.method; req.url = request.path; for (auto &h: request.headers) { if (startsWith(h.first, "LOCAL_") || startsWith(h.first, "REMOTE_") || is_request_header_blacklisted(h.first)) { continue; } req.headers.emplace(h.first.data(), h.second.data()); } req.argument = request.params; if (request.method == "POST" || request.method == "PUT" || request.method == "PATCH") { if (request.is_multipart_form_data() && !request.files.empty()) { req.postdata = request.files.begin()->second.content; } else if (request.get_header_value("Content-Type") == "application/x-www-form-urlencoded") { req.postdata = urlDecode(request.body); } else { req.postdata = request.body; } } auto result = rr.rc(req, resp); response.status = resp.status_code; for (auto &h: resp.headers) { response.set_header(h.first, h.second); } auto content_type = resp.content_type; if (content_type.empty()) { content_type = rr.content_type; } response.set_content(result, content_type); }; } static std::string dump(const httplib::Headers &headers) { std::string s; for (auto &x: headers) { if (startsWith(x.first, "LOCAL_") || startsWith(x.first, "REMOTE_")) continue; s += x.first + ": " + x.second + "|"; } return s; } int WebServer::start_web_server_multi(listener_args *args) { httplib::Server server; for (auto &x : responses) { switch (hash_(x.method)) { case "GET"_hash: case "HEAD"_hash: server.Get(x.path, makeHandler(x)); break; case "POST"_hash: server.Post(x.path, makeHandler(x)); break; case "PUT"_hash: server.Put(x.path, makeHandler(x)); break; case "DELETE"_hash: server.Delete(x.path, makeHandler(x)); break; case "PATCH"_hash: server.Patch(x.path, makeHandler(x)); break; } } server.Options(R"(.*)", [&](const httplib::Request &req, httplib::Response &res) { auto path = req.path; std::string allowed; for (auto &rr : responses) { if (rr.path == path) { allowed += rr.method + ","; } } if (!allowed.empty()) { allowed.pop_back(); res.status = 200; res.set_header("Access-Control-Allow-Methods", allowed); res.set_header("Access-Control-Allow-Origin", "*"); res.set_header("Access-Control-Allow-Headers", "Content-Type,Authorization"); } else { res.status = 404; } }); server.set_pre_routing_handler([&](const httplib::Request &req, httplib::Response &res) { writeLog(0, "Accept connection from client " + req.remote_addr + ":" + std::to_string(req.remote_port), LOG_LEVEL_DEBUG); writeLog(0, "handle_cmd: " + req.method + " handle_uri: " + req.target, LOG_LEVEL_VERBOSE); writeLog(0, "handle_header: " + dump(req.headers), LOG_LEVEL_VERBOSE); if (req.has_header("SubConverter-Request")) { res.status = 500; res.set_content("Loop request detected!", "text/plain"); return httplib::Server::HandlerResponse::Handled; } res.set_header("Server", "subconverter/" VERSION " cURL/" LIBCURL_VERSION); if (require_auth) { static std::string auth_token = "Basic " + base64Encode(auth_user + ":" + auth_password); auto auth = req.get_header_value("Authorization"); if (auth != auth_token) { res.status = 401; res.set_header("WWW-Authenticate", "Basic realm=" + auth_realm + ", charset=\"UTF-8\""); res.set_content("Unauthorized", "text/plain"); return httplib::Server::HandlerResponse::Handled; } } res.set_header("X-Client-IP", req.remote_addr); if (req.has_header("Access-Control-Request-Headers")) { res.set_header("Access-Control-Allow-Headers", req.get_header_value("Access-Control-Request-Headers")); } return httplib::Server::HandlerResponse::Unhandled; }); for (auto &x : redirect_map) { server.Get(x.first, [x](const httplib::Request &req, httplib::Response &res) { auto arguments = req.params; auto query = x.second; auto pos = query.find('?'); query += pos == std::string::npos ? '?' : '&'; for (auto &p: arguments) { query += p.first + "=" + urlEncode(p.second) + "&"; } if (!query.empty()) { query.pop_back(); } res.set_redirect(query); }); } server.set_exception_handler([](const httplib::Request &req, httplib::Response &res, const std::exception_ptr &e) { try { if (e) std::rethrow_exception(e); } catch (const httplib::Error &err) { res.set_content(to_string(err), "text/plain"); } catch (const std::exception &ex) { std::string return_data = "Internal server error while processing request '" + req.target + "'!\n"; return_data += "\n exception: "; return_data += type(ex); return_data += "\n what(): "; return_data += ex.what(); res.status = 500; res.set_content(return_data, "text/plain"); } catch (...) { res.status = 500; } }); if (serve_file) { server.set_mount_point("/", serve_file_root); } server.new_task_queue = [args] { return new httplib::ThreadPool(args->max_workers); }; server.bind_to_port(args->listen_address, args->port, 0); std::thread thread([&]() { server.listen_after_bind(); }); while (!SERVER_EXIT_FLAG) { if (args->looper_callback) { args->looper_callback(); } std::this_thread::sleep_for(std::chrono::milliseconds(args->looper_interval)); } server.stop(); thread.join(); return 0; } int WebServer::start_web_server(listener_args *args) { return start_web_server_multi(args); }
7,761
C++
.cpp
237
23.71308
129
0.53754
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,488
version.h
tindy2013_subconverter/src/version.h
#ifndef VERSION_H_INCLUDED #define VERSION_H_INCLUDED #define VERSION "v0.9.0" #endif // VERSION_H_INCLUDED
110
C++
.h
4
26
28
0.788462
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,489
script_duktape.h
tindy2013_subconverter/src/script/script_duktape.h
#ifndef SCRIPT_DUKTAPE_H_INCLUDED #define SCRIPT_DUKTAPE_H_INCLUDED #include <string> #include <duktape.h> #include "nodeinfo.h" #include "misc.h" duk_context *duktape_init(); int duktape_push_nodeinfo(duk_context *ctx, const nodeInfo &node); int duktape_push_nodeinfo_arr(duk_context *ctx, const nodeInfo &node, duk_idx_t index = -1); int duktape_peval(duk_context *ctx, const std::string &script); int duktape_call_function(duk_context *ctx, const std::string &name, size_t nargs, ...); int duktape_get_res_int(duk_context *ctx); std::string duktape_get_res_str(duk_context *ctx); bool duktape_get_res_bool(duk_context *ctx); std::string duktape_get_err_stack(duk_context *ctx); #define SCRIPT_ENGINE_INIT(name) \ duk_context* name = duktape_init(); \ defer(duk_destroy_heap(name);) #endif // SCRIPT_DUKTAPE_H_INCLUDED
834
C++
.h
19
42.210526
92
0.751852
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,490
script.h
tindy2013_subconverter/src/script/script.h
#ifndef SCRIPT_H_INCLUDED #define SCRIPT_H_INCLUDED #include <string> #include <chaiscript/chaiscript.hpp> template <typename... input_type, typename return_type> int evalScript(const std::string &script, return_type &return_value, input_type&... input_value) { chaiscript::ChaiScript chai; try { auto fun = chai.eval<std::function<return_type (input_type...)>>(script); return_value = fun(input_value...); } catch (std::exception&) { return -1; } return 0; } #endif // SCRIPT_H_INCLUDED
547
C++
.h
19
24.684211
152
0.674286
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,491
cron.h
tindy2013_subconverter/src/script/cron.h
#ifndef CRON_H_INCLUDED #define CRON_H_INCLUDED void refresh_schedule(); size_t cron_tick(); #endif // CRON_H_INCLUDED
121
C++
.h
5
22.8
25
0.77193
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,492
script_quickjs.h
tindy2013_subconverter/src/script/script_quickjs.h
#ifndef SCRIPT_QUICKJS_H_INCLUDED #define SCRIPT_QUICKJS_H_INCLUDED #include "parser/config/proxy.h" #include "utils/defer.h" #ifndef NO_JS_RUNTIME #include <quickjspp.hpp> void script_runtime_init(qjs::Runtime &runtime); int script_context_init(qjs::Context &context); int script_cleanup(qjs::Context &context); void script_print_stack(qjs::Context &context); inline JSValue JS_NewString(JSContext *ctx, const std::string& str) { return JS_NewStringLen(ctx, str.c_str(), str.size()); } inline std::string JS_GetPropertyIndexToString(JSContext *ctx, JSValueConst obj, uint32_t index) { JSValue val = JS_GetPropertyUint32(ctx, obj, index); size_t len; const char *str = JS_ToCStringLen(ctx, &len, val); std::string result(str, len); JS_FreeCString(ctx, str); JS_FreeValue(ctx, val); return result; } namespace qjs { template<typename T> static T unwrap_free(JSContext *ctx, JSValue v, const char* key) noexcept { auto obj = JS_GetPropertyStr(ctx, v, key); T t = js_traits<T>::unwrap(ctx, obj); JS_FreeValue(ctx, obj); return t; } template<> struct js_traits<tribool> { static JSValue wrap(JSContext *ctx, const tribool &t) noexcept { auto obj = JS_NewObject(ctx); JS_SetPropertyStr(ctx, obj, "value", JS_NewBool(ctx, t.get())); JS_SetPropertyStr(ctx, obj, "isDefined", JS_NewBool(ctx, !t.is_undef())); return obj; } static tribool unwrap(JSContext *ctx, JSValueConst v) { tribool t; bool defined = unwrap_free<bool>(ctx, v, "isDefined"); if(defined) { bool value = unwrap_free<bool>(ctx, v, "value"); t.set(value); } return t; } }; template<> struct js_traits<StringArray> { static StringArray unwrap(JSContext *ctx, JSValueConst v) { StringArray arr; auto length = unwrap_free<uint32_t>(ctx, v, "length"); for (uint32_t i = 0; i < length; i++) { arr.push_back(JS_GetPropertyIndexToString(ctx, v, i)); } return arr; } static JSValue wrap(JSContext *ctx, const StringArray& arr) { JSValue jsArray = JS_NewArray(ctx); for (std::size_t i = 0; i < arr.size(); i++) { JS_SetPropertyUint32(ctx, jsArray, i, JS_NewString(ctx, arr[i])); } return jsArray; } }; template<> struct js_traits<Proxy> { static JSValue wrap(JSContext *ctx, const Proxy &n) noexcept { JSValue obj = JS_NewObjectProto(ctx, JS_NULL); if (JS_IsException(obj)) { return obj; } JS_DefinePropertyValueStr(ctx, obj, "Type", js_traits<ProxyType>::wrap(ctx, n.Type), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Id", JS_NewUint32(ctx, n.Id), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "GroupId", JS_NewUint32(ctx, n.GroupId), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Group", JS_NewString(ctx, n.Group), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Remark", JS_NewString(ctx, n.Remark), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Server", JS_NewString(ctx, n.Hostname), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Port", JS_NewInt32(ctx, n.Port), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Username", JS_NewString(ctx, n.Username), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Password", JS_NewString(ctx, n.Password), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "EncryptMethod", JS_NewString(ctx, n.EncryptMethod), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Plugin", JS_NewString(ctx, n.Plugin), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "PluginOption", JS_NewString(ctx, n.PluginOption), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Protocol", JS_NewString(ctx, n.Protocol), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ProtocolParam", JS_NewString(ctx, n.ProtocolParam), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "OBFS", JS_NewString(ctx, n.OBFS), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "OBFSParam", JS_NewString(ctx, n.OBFSParam), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "UserId", JS_NewString(ctx, n.UserId), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "AlterId", JS_NewInt32(ctx, n.AlterId), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "TransferProtocol", JS_NewString(ctx, n.TransferProtocol), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "FakeType", JS_NewString(ctx, n.FakeType), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "TLSSecure", JS_NewBool(ctx, n.TLSSecure), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Host", JS_NewString(ctx, n.Host), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Path", JS_NewString(ctx, n.Path), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Edge", JS_NewString(ctx, n.Edge), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "QUICSecure", JS_NewString(ctx, n.QUICSecure), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "QUICSecret", JS_NewString(ctx, n.QUICSecret), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "UDP", js_traits<tribool>::wrap(ctx, n.UDP), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "TCPFastOpen", js_traits<tribool>::wrap(ctx, n.TCPFastOpen), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "AllowInsecure", js_traits<tribool>::wrap(ctx, n.AllowInsecure), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "TLS13", js_traits<tribool>::wrap(ctx, n.TLS13), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "SnellVersion", JS_NewInt32(ctx, n.SnellVersion), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ServerName", JS_NewString(ctx, n.ServerName), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "SelfIP", JS_NewString(ctx, n.SelfIP), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "SelfIPv6", JS_NewString(ctx, n.SelfIPv6), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "PublicKey", JS_NewString(ctx, n.PublicKey), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "PrivateKey", JS_NewString(ctx, n.PrivateKey), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "PreSharedKey", JS_NewString(ctx, n.PreSharedKey), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "DnsServers", js_traits<StringArray>::wrap(ctx, n.DnsServers), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "Mtu", JS_NewUint32(ctx, n.Mtu), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "AllowedIPs", JS_NewString(ctx, n.AllowedIPs), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "KeepAlive", JS_NewUint32(ctx, n.KeepAlive), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "TestUrl", JS_NewString(ctx, n.TestUrl), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ClientId", JS_NewString(ctx, n.ClientId), JS_PROP_C_W_E); return obj; } static Proxy unwrap(JSContext *ctx, JSValueConst v) { Proxy node; node.Type = unwrap_free<ProxyType>(ctx, v, "Type"); node.Id = unwrap_free<int32_t>(ctx, v, "Id"); node.GroupId = unwrap_free<int32_t>(ctx, v, "GroupId"); node.Group = unwrap_free<std::string>(ctx, v, "Group"); node.Remark = unwrap_free<std::string>(ctx, v, "Remark"); node.Hostname = unwrap_free<std::string>(ctx, v, "Server"); node.Port = unwrap_free<uint32_t>(ctx, v, "Port"); node.Username = unwrap_free<std::string>(ctx, v, "Username"); node.Password = unwrap_free<std::string>(ctx, v, "Password"); node.EncryptMethod = unwrap_free<std::string>(ctx, v, "EncryptMethod"); node.Plugin = unwrap_free<std::string>(ctx, v, "Plugin"); node.PluginOption = unwrap_free<std::string>(ctx, v, "PluginOption"); node.Protocol = unwrap_free<std::string>(ctx, v, "Protocol"); node.ProtocolParam = unwrap_free<std::string>(ctx, v, "ProtocolParam"); node.OBFS = unwrap_free<std::string>(ctx, v, "OBFS"); node.OBFSParam = unwrap_free<std::string>(ctx, v, "OBFSParam"); node.UserId = unwrap_free<std::string>(ctx, v, "UserId"); node.AlterId = unwrap_free<uint32_t>(ctx, v, "AlterId"); node.TransferProtocol = unwrap_free<std::string>(ctx, v, "TransferProtocol"); node.FakeType = unwrap_free<std::string>(ctx, v, "FakeType"); node.TLSSecure = unwrap_free<bool>(ctx, v, "TLSSecure"); node.Host = unwrap_free<std::string>(ctx, v, "Host"); node.Path = unwrap_free<std::string>(ctx, v, "Path"); node.Edge = unwrap_free<std::string>(ctx, v, "Edge"); node.QUICSecure = unwrap_free<std::string>(ctx, v, "QUICSecure"); node.QUICSecret = unwrap_free<std::string>(ctx, v, "QUICSecret"); node.UDP = unwrap_free<tribool>(ctx, v, "UDP"); node.TCPFastOpen = unwrap_free<tribool>(ctx, v, "TCPFastOpen"); node.AllowInsecure = unwrap_free<tribool>(ctx, v, "AllowInsecure"); node.TLS13 = unwrap_free<tribool>(ctx, v, "TLS13"); node.SnellVersion = unwrap_free<int32_t>(ctx, v, "SnellVersion"); node.ServerName = unwrap_free<std::string>(ctx, v, "ServerName"); node.SelfIP = unwrap_free<std::string>(ctx, v, "SelfIP"); node.SelfIPv6 = unwrap_free<std::string>(ctx, v, "SelfIPv6"); node.PublicKey = unwrap_free<std::string>(ctx, v, "PublicKey"); node.PrivateKey = unwrap_free<std::string>(ctx, v, "PrivateKey"); node.PreSharedKey = unwrap_free<std::string>(ctx, v, "PreSharedKey"); node.DnsServers = unwrap_free<StringArray>(ctx, v, "DnsServers"); node.Mtu = unwrap_free<uint32_t>(ctx, v, "Mtu"); node.AllowedIPs = unwrap_free<std::string>(ctx, v, "AllowedIPs"); node.KeepAlive = unwrap_free<uint32_t>(ctx, v, "KeepAlive"); node.TestUrl = unwrap_free<std::string>(ctx, v, "TestUrl"); node.ClientId = unwrap_free<std::string>(ctx, v, "ClientId"); return node; } }; } template <typename Fn> void script_safe_runner(qjs::Runtime *runtime, qjs::Context *context, Fn runnable, bool clean_context = false) { qjs::Runtime *internal_runtime = runtime; qjs::Context *internal_context = context; defer(if(clean_context) {delete internal_context; delete internal_runtime;} ) if(clean_context) { internal_runtime = new qjs::Runtime(); script_runtime_init(*internal_runtime); internal_context = new qjs::Context(*internal_runtime); script_context_init(*internal_context); } if(internal_runtime && internal_context) runnable(*internal_context); } #else template <typename... Args> void script_safe_runner(Args... args) { } #endif // NO_JS_RUNTIME #endif // SCRIPT_QUICKJS_H_INCLUDED
11,580
C++
.h
199
48.251256
128
0.62392
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,493
templates.h
tindy2013_subconverter/src/generator/template/templates.h
#ifndef TEMPLATES_H_INCLUDED #define TEMPLATES_H_INCLUDED #include <string> #include <map> #include "generator/config/subexport.h" #include "utils/string.h" struct template_args { string_map global_vars; string_map request_params; string_map local_vars; string_map node_list; }; int render_template(const std::string &content, const template_args &vars, std::string &output, const std::string &include_scope = "templates"); int renderClashScript(YAML::Node &base_rule, std::vector<RulesetContent> &ruleset_content_array, const std::string &remote_path_prefix, bool script, bool overwrite_original_rules, bool clash_classic_ruleset); #endif // TEMPLATES_H_INCLUDED
685
C++
.h
16
40.5
208
0.775602
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,494
ruleconvert.h
tindy2013_subconverter/src/generator/config/ruleconvert.h
#ifndef RULECONVERT_H_INCLUDED #define RULECONVERT_H_INCLUDED #include <string> #include <vector> #include <future> #include <yaml-cpp/yaml.h> #include <rapidjson/document.h> #include "utils/ini_reader/ini_reader.h" enum ruleset_type { RULESET_SURGE, RULESET_QUANX, RULESET_CLASH_DOMAIN, RULESET_CLASH_IPCIDR, RULESET_CLASH_CLASSICAL }; struct RulesetContent { std::string rule_group; std::string rule_path; std::string rule_path_typed; int rule_type = RULESET_SURGE; std::shared_future<std::string> rule_content; int update_interval = 0; }; std::string convertRuleset(const std::string &content, int type); void rulesetToClash(YAML::Node &base_rule, std::vector<RulesetContent> &ruleset_content_array, bool overwrite_original_rules, bool new_field_name); std::string rulesetToClashStr(YAML::Node &base_rule, std::vector<RulesetContent> &ruleset_content_array, bool overwrite_original_rules, bool new_field_name); void rulesetToSurge(INIReader &base_rule, std::vector<RulesetContent> &ruleset_content_array, int surge_ver, bool overwrite_original_rules, const std::string& remote_path_prefix); void rulesetToSingBox(rapidjson::Document &base_rule, std::vector<RulesetContent> &ruleset_content_array, bool overwrite_original_rules); #endif // RULECONVERT_H_INCLUDED
1,316
C++
.h
31
39.806452
179
0.776213
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,495
subexport.h
tindy2013_subconverter/src/generator/config/subexport.h
#ifndef SUBEXPORT_H_INCLUDED #define SUBEXPORT_H_INCLUDED #include <string> #ifndef NO_JS_RUNTIME #include <quickjspp.hpp> #endif // NO_JS_RUNTIME #include "config/proxygroup.h" #include "config/regmatch.h" #include "parser/config/proxy.h" #include "utils/ini_reader/ini_reader.h" #include "utils/string.h" #include "utils/yamlcpp_extra.h" #include "ruleconvert.h" struct extra_settings { bool enable_rule_generator = true; bool overwrite_original_rules = true; RegexMatchConfigs rename_array; RegexMatchConfigs emoji_array; bool add_emoji = false; bool remove_emoji = false; bool append_proxy_type = false; bool nodelist = false; bool sort_flag = false; bool filter_deprecated = false; bool clash_new_field_name = false; bool clash_script = false; std::string surge_ssr_path; std::string managed_config_prefix; std::string quanx_dev_id; tribool udp = tribool(); tribool tfo = tribool(); tribool skip_cert_verify = tribool(); tribool tls13 = tribool(); bool clash_classical_ruleset = false; std::string sort_script; std::string clash_proxies_style = "flow"; std::string clash_proxy_groups_style = "flow"; bool authorized = false; extra_settings() = default; extra_settings(const extra_settings&) = delete; extra_settings(extra_settings&&) = delete; #ifndef NO_JS_RUNTIME qjs::Runtime *js_runtime = nullptr; qjs::Context *js_context = nullptr; ~extra_settings() { delete js_context; delete js_runtime; } #endif // NO_JS_RUNTIME }; std::string proxyToClash(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, bool clashR, extra_settings &ext); void proxyToClash(std::vector<Proxy> &nodes, YAML::Node &yamlnode, const ProxyGroupConfigs &extra_proxy_group, bool clashR, extra_settings &ext); std::string proxyToSurge(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, int surge_ver, extra_settings &ext); std::string proxyToMellow(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext); void proxyToMellow(std::vector<Proxy> &nodes, INIReader &ini, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext); std::string proxyToLoon(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext); std::string proxyToSSSub(std::string base_conf, std::vector<Proxy> &nodes, extra_settings &ext); std::string proxyToSingle(std::vector<Proxy> &nodes, int types, extra_settings &ext); std::string proxyToQuanX(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext); void proxyToQuanX(std::vector<Proxy> &nodes, INIReader &ini, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext); std::string proxyToQuan(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext); void proxyToQuan(std::vector<Proxy> &nodes, INIReader &ini, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext); std::string proxyToSSD(std::vector<Proxy> &nodes, std::string &group, std::string &userinfo, extra_settings &ext); std::string proxyToSingBox(std::vector<Proxy> &nodes, const std::string &base_conf, std::vector<RulesetContent> &ruleset_content_array, const ProxyGroupConfigs &extra_proxy_group, extra_settings &ext); #endif // SUBEXPORT_H_INCLUDED
4,024
C++
.h
67
56.776119
214
0.754813
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,496
nodemanip.h
tindy2013_subconverter/src/generator/config/nodemanip.h
#ifndef NODEMANIP_H_INCLUDED #define NODEMANIP_H_INCLUDED #include <string> #include <vector> #include <limits.h> #ifndef NO_JS_RUNTIME #include <quickjspp.hpp> #endif // NO_JS_RUNTIME #include "config/regmatch.h" #include "parser/config/proxy.h" #include "utils/map_extra.h" #include "utils/string.h" struct parse_settings { std::string *proxy = nullptr; string_array *exclude_remarks = nullptr; string_array *include_remarks = nullptr; RegexMatchConfigs *stream_rules = nullptr; RegexMatchConfigs *time_rules = nullptr; std::string *sub_info = nullptr; bool authorized = false; string_icase_map *request_header = nullptr; #ifndef NO_JS_RUNTIME qjs::Runtime *js_runtime = nullptr; qjs::Context *js_context = nullptr; #endif // NO_JS_RUNTIME }; int addNodes(std::string link, std::vector<Proxy> &allNodes, int groupID, parse_settings &parse_set); void filterNodes(std::vector<Proxy> &nodes, string_array &exclude_remarks, string_array &include_remarks, int groupID); bool applyMatcher(const std::string &rule, std::string &real_rule, const Proxy &node); void preprocessNodes(std::vector<Proxy> &nodes, extra_settings &ext); #endif // NODEMANIP_H_INCLUDED
1,201
C++
.h
32
35.09375
119
0.750645
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,497
infoparser.h
tindy2013_subconverter/src/parser/infoparser.h
#ifndef INFOPARSER_H_INCLUDED #define INFOPARSER_H_INCLUDED #include <string> #include "utils/string.h" #include "config/proxy.h" #include "config/regmatch.h" bool getSubInfoFromHeader(const std::string &header, std::string &result); bool getSubInfoFromNodes(const std::vector<Proxy> &nodes, const RegexMatchConfigs &stream_rules, const RegexMatchConfigs &time_rules, std::string &result); bool getSubInfoFromSSD(const std::string &sub, std::string &result); unsigned long long streamToInt(const std::string &stream); #endif // INFOPARSER_H_INCLUDED
555
C++
.h
11
49
155
0.801484
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,498
subparser.h
tindy2013_subconverter/src/parser/subparser.h
#ifndef SUBPARSER_H_INCLUDED #define SUBPARSER_H_INCLUDED #include <string> #include "config/proxy.h" enum class ConfType { Unknow, SS, SSR, V2Ray, SSConf, SSTap, Netch, SOCKS, HTTP, SUB, Local }; void vmessConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &add, const std::string &port, const std::string &type, const std::string &id, const std::string &aid, const std::string &net, const std::string &cipher, const std::string &path, const std::string &host, const std::string &edge, const std::string &tls, const std::string &sni, tribool udp = tribool(), tribool tfo = tribool(), tribool scv = tribool(), tribool tls13 = tribool(), const std::string &underlying_proxy = ""); void ssrConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &protocol, const std::string &method, const std::string &obfs, const std::string &password, const std::string &obfsparam, const std::string &protoparam, tribool udp = tribool(), tribool tfo = tribool(), tribool scv = tribool(), const std::string &underlying_proxy = ""); void ssConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &password, const std::string &method, const std::string &plugin, const std::string &pluginopts, tribool udp = tribool(), tribool tfo = tribool(), tribool scv = tribool(), tribool tls13 = tribool(), const std::string &underlying_proxy = ""); void socksConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &username, const std::string &password, tribool udp = tribool(), tribool tfo = tribool(), tribool scv = tribool(), const std::string &underlying_proxy = ""); void httpConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &username, const std::string &password, bool tls, tribool tfo = tribool(), tribool scv = tribool(), tribool tls13 = tribool(), const std::string &underlying_proxy = ""); void trojanConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &password, const std::string &network, const std::string &host, const std::string &path, bool tlssecure, tribool udp = tribool(), tribool tfo = tribool(), tribool scv = tribool(), tribool tls13 = tribool(), const std::string &underlying_proxy = ""); void snellConstruct(Proxy &node, const std::string &group, const std::string &remarks, const std::string &server, const std::string &port, const std::string &password, const std::string &obfs, const std::string &host, uint16_t version = 0, tribool udp = tribool(), tribool tfo = tribool(), tribool scv = tribool(), const std::string &underlying_proxy = ""); void explodeVmess(std::string vmess, Proxy &node); void explodeSSR(std::string ssr, Proxy &node); void explodeSS(std::string ss, Proxy &node); void explodeTrojan(std::string trojan, Proxy &node); void explodeQuan(const std::string &quan, Proxy &node); void explodeStdVMess(std::string vmess, Proxy &node); void explodeShadowrocket(std::string kit, Proxy &node); void explodeKitsunebi(std::string kit, Proxy &node); /// Parse a link void explode(const std::string &link, Proxy &node); void explodeSSD(std::string link, std::vector<Proxy> &nodes); void explodeSub(std::string sub, std::vector<Proxy> &nodes); int explodeConf(const std::string &filepath, std::vector<Proxy> &nodes); int explodeConfContent(const std::string &content, std::vector<Proxy> &nodes); #endif // SUBPARSER_H_INCLUDED
3,791
C++
.h
40
92.55
526
0.730913
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,499
proxy.h
tindy2013_subconverter/src/parser/config/proxy.h
#ifndef PROXY_H_INCLUDED #define PROXY_H_INCLUDED #include <string> #include <vector> #include "utils/tribool.h" using String = std::string; using StringArray = std::vector<String>; enum class ProxyType { Unknown, Shadowsocks, ShadowsocksR, VMess, Trojan, Snell, HTTP, HTTPS, SOCKS5, WireGuard }; inline String getProxyTypeName(ProxyType type) { switch(type) { case ProxyType::Shadowsocks: return "SS"; case ProxyType::ShadowsocksR: return "SSR"; case ProxyType::VMess: return "VMess"; case ProxyType::Trojan: return "Trojan"; case ProxyType::Snell: return "Snell"; case ProxyType::HTTP: return "HTTP"; case ProxyType::HTTPS: return "HTTPS"; case ProxyType::SOCKS5: return "SOCKS5"; default: return "Unknown"; } } struct Proxy { ProxyType Type = ProxyType::Unknown; uint32_t Id = 0; uint32_t GroupId = 0; String Group; String Remark; String Hostname; uint16_t Port = 0; String Username; String Password; String EncryptMethod; String Plugin; String PluginOption; String Protocol; String ProtocolParam; String OBFS; String OBFSParam; String UserId; uint16_t AlterId = 0; String TransferProtocol; String FakeType; bool TLSSecure = false; String Host; String Path; String Edge; String QUICSecure; String QUICSecret; tribool UDP; tribool TCPFastOpen; tribool AllowInsecure; tribool TLS13; String UnderlyingProxy; uint16_t SnellVersion = 0; String ServerName; String SelfIP; String SelfIPv6; String PublicKey; String PrivateKey; String PreSharedKey; StringArray DnsServers; uint16_t Mtu = 0; String AllowedIPs = "0.0.0.0/0, ::/0"; uint16_t KeepAlive = 0; String TestUrl; String ClientId; }; #define SS_DEFAULT_GROUP "SSProvider" #define SSR_DEFAULT_GROUP "SSRProvider" #define V2RAY_DEFAULT_GROUP "V2RayProvider" #define SOCKS_DEFAULT_GROUP "SocksProvider" #define HTTP_DEFAULT_GROUP "HTTPProvider" #define TROJAN_DEFAULT_GROUP "TrojanProvider" #define SNELL_DEFAULT_GROUP "SnellProvider" #define WG_DEFAULT_GROUP "WireGuardProvider" #endif // PROXY_H_INCLUDED
2,306
C++
.h
100
18.55
46
0.692834
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,500
regexp.h
tindy2013_subconverter/src/utils/regexp.h
#ifndef REGEXP_H_INCLUDED #define REGEXP_H_INCLUDED #include <string> bool regValid(const std::string &reg); bool regFind(const std::string &src, const std::string &match); std::string regReplace(const std::string &src, const std::string &match, const std::string &rep, bool global = true, bool multiline = true); bool regMatch(const std::string &src, const std::string &match); int regGetMatch(const std::string &src, const std::string &match, size_t group_count, ...); std::vector<std::string> regGetAllMatch(const std::string &src, const std::string &match, bool group_only = false); std::string regTrim(const std::string &src); #endif // REGEXP_H_INCLUDED
663
C++
.h
11
59
140
0.748844
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,501
tribool.h
tindy2013_subconverter/src/utils/tribool.h
#ifndef TRIBOOL_H_INCLUDED #define TRIBOOL_H_INCLUDED #include <string> #include "string.h" #include "string_hash.h" class tribool { public: tribool() : value_(indeterminate) {} tribool(bool value) : value_(value ? true_value : false_value) {} tribool(const std::string& str) { set(str); } tribool(const tribool& other) = default; tribool& operator=(const tribool& other) = default; tribool& operator=(bool value) { value_ = value ? true_value : false_value; return *this; } bool operator==(const tribool& other) const { return value_ == other.value_; } operator bool() const { return value_ == true_value; } bool is_undef() const { return value_ == indeterminate; } template <typename T> tribool& define(const T& value) { if (is_undef()) *this = value; return *this; } template <typename T> tribool& parse(const T& value) { return define(value); } tribool reverse() { if (value_ == false_value) value_ = true_value; else if (value_ == true_value) value_ = false_value; return *this; } bool get(const bool& def_value = false) const { if (is_undef()) return def_value; return value_ == true_value; } std::string get_str() const { switch (value_) { case indeterminate: return "undef"; case false_value: return "false"; case true_value: return "true"; default: return ""; } } template <typename T> bool set(const T& value) { value_ = (bool)value ? true_value : false_value; return value_; } bool set(const std::string& str) { switch (hash_(str)) { case "true"_hash: case "1"_hash: value_ = true_value; break; case "false"_hash: case "0"_hash: value_ = false_value; break; default: if (to_int(str, 0) > 1) value_ = true_value; else value_ = indeterminate; break; } return !is_undef(); } void clear() { value_ = indeterminate; } private: enum value_type : char { indeterminate = 0, false_value = 1, true_value = 2 }; value_type value_; }; #endif // TRIBOOL_H_INCLUDED
2,545
C++
.h
91
19.472527
82
0.52422
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,502
lock.h
tindy2013_subconverter/src/utils/lock.h
#ifndef LOCK_H_INCLUDED #define LOCK_H_INCLUDED #include <atomic> #include <thread> class RWLock { static constexpr int WRITE_LOCK_STATUS = -1; static constexpr int FREE_STATUS = 0; private: const std::thread::id NULL_THREAD; const bool WRITE_FIRST; std::thread::id m_write_thread_id; std::atomic_int m_lockCount; std::atomic_uint m_writeWaitCount; public: RWLock(const RWLock&) = delete; RWLock& operator=(const RWLock&) = delete; explicit RWLock(bool writeFirst = true): WRITE_FIRST(writeFirst), m_write_thread_id(), m_lockCount(0), m_writeWaitCount(0) {} virtual ~RWLock() = default; int readLock() { if (std::this_thread::get_id() != m_write_thread_id) { int count; if (WRITE_FIRST) { do { while ((count = m_lockCount) == WRITE_LOCK_STATUS || m_writeWaitCount > 0); } while (!m_lockCount.compare_exchange_weak(count, count + 1)); } else { do { while ((count = m_lockCount) == WRITE_LOCK_STATUS); } while (!m_lockCount.compare_exchange_weak(count, count + 1)); } } return m_lockCount; } int readUnlock() { if (std::this_thread::get_id() != m_write_thread_id) --m_lockCount; return m_lockCount; } int writeLock() { if (std::this_thread::get_id() != m_write_thread_id) { ++m_writeWaitCount; for (int zero = FREE_STATUS; !m_lockCount.compare_exchange_weak(zero, WRITE_LOCK_STATUS); zero = FREE_STATUS); --m_writeWaitCount; m_write_thread_id = std::this_thread::get_id(); } return m_lockCount; } int writeUnlock() { if (std::this_thread::get_id() != m_write_thread_id) { throw std::runtime_error("writeLock/Unlock mismatch"); } if (WRITE_LOCK_STATUS != m_lockCount) { throw std::runtime_error("RWLock internal error"); } m_write_thread_id = NULL_THREAD; m_lockCount.store(FREE_STATUS); return m_lockCount; } }; #endif //LOCK_H_INCLUDED
2,318
C++
.h
76
21.828947
129
0.545779
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,503
checkpoint.h
tindy2013_subconverter/src/utils/checkpoint.h
#ifndef CHECKPOINT_H_INCLUDED #define CHECKPOINT_H_INCLUDED #include <chrono> #include <iostream> inline std::chrono::time_point<std::chrono::steady_clock, std::chrono::nanoseconds> start_time; inline void checkpoint() { if(start_time == std::chrono::time_point<std::chrono::steady_clock, std::chrono::nanoseconds>()) start_time = std::chrono::steady_clock::now(); else { auto end_time = std::chrono::steady_clock::now(); std::chrono::duration duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time); std::cerr<<duration.count()<<"\n"; start_time = end_time; } } #endif // CHECKPOINT_H_INCLUDED
687
C++
.h
18
33.833333
118
0.682707
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,504
system.h
tindy2013_subconverter/src/utils/system.h
#ifndef SYSTEM_H_INCLUDED #define SYSTEM_H_INCLUDED #include <string> void sleepMs(int interval); std::string getEnv(const std::string &name); std::string getSystemProxy(); #endif // SYSTEM_H_INCLUDED
204
C++
.h
7
27.714286
44
0.78866
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,505
file.h
tindy2013_subconverter/src/utils/file.h
#ifndef FILE_H_INCLUDED #define FILE_H_INCLUDED #include <string> #include <string.h> #ifdef _WIN32 #include <unistd.h> #define PATH_SLASH "\\" #else #include <sys/types.h> #include <sys/stat.h> #define PATH_SLASH "//" #endif // _WIN32 #include <sys/types.h> #include <dirent.h> std::string fileGet(const std::string &path, bool scope_limit = false); bool fileExist(const std::string &path, bool scope_limit = false); bool fileCopy(const std::string &source, const std::string &dest); int fileWrite(const std::string &path, const std::string &content, bool overwrite); template<typename F> int operateFiles(const std::string &path, F &&op) { DIR* dir = opendir(path.data()); if(!dir) return -1; struct dirent* dp; while((dp = readdir(dir)) != NULL) { if(strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0) { if(op(dp->d_name)) break; } } closedir(dir); return 0; } inline int md(const char *path) { #ifdef _WIN32 return mkdir(path); #else return mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); #endif // _WIN32 } #endif // FILE_H_INCLUDED
1,161
C++
.h
45
22.422222
83
0.645627
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,506
yamlcpp_extra.h
tindy2013_subconverter/src/utils/yamlcpp_extra.h
#ifndef YAMLCPP_EXTRA_H_INCLUDED #define YAMLCPP_EXTRA_H_INCLUDED #include <yaml-cpp/yaml.h> #include <string> #include <vector> template <typename T> void operator >> (const YAML::Node& node, T& i) { if(node.IsDefined() && !node.IsNull()) //fail-safe i = node.as<T>(); }; template <typename T> T safe_as (const YAML::Node& node) { if(node.IsDefined() && !node.IsNull()) return node.as<T>(); return T(); }; template <typename T> void operator >>= (const YAML::Node& node, T& i) { i = safe_as<T>(node); }; using string_array = std::vector<std::string>; inline std::string dump_to_pairs (const YAML::Node &node, const string_array &exclude = string_array()) { std::string result; for(auto iter = node.begin(); iter != node.end(); iter++) { if(iter->second.Type() != YAML::NodeType::Scalar) continue; std::string key = iter->first.as<std::string>(); if(std::find(exclude.cbegin(), exclude.cend(), key) != exclude.cend()) continue; std::string value = iter->second.as<std::string>(); result += key + "=" + value + ","; } return result.erase(result.size() - 1); } #endif // YAMLCPP_EXTRA_H_INCLUDED
1,217
C++
.h
37
28.567568
103
0.619778
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,507
bitwise.h
tindy2013_subconverter/src/utils/bitwise.h
#ifndef BITWISE_H_INCLUDED #define BITWISE_H_INCLUDED #define GETBIT(x,n) (((int)x < 1) ? 0 : ((x >> (n - 1)) & 1)) #define SETBIT(x,n,v) x ^= (-v ^ x) & (1UL << (n - 1)) #endif // BITWISE_H_INCLUDED
202
C++
.h
5
39
61
0.574359
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,509
defer.h
tindy2013_subconverter/src/utils/defer.h
#ifndef DEFER_H_INCLUDED #define DEFER_H_INCLUDED #define CONCAT(a,b) a ## b #define DO_CONCAT(a,b) CONCAT(a,b) template <typename T> class __defer_struct final {private: T fn; bool __cancelled = false; public: explicit __defer_struct(T func) : fn(std::move(func)) {} ~__defer_struct() {if(!__cancelled) fn();} void cancel() {__cancelled = true;} }; //#define defer(x) std::unique_ptr<void> DO_CONCAT(__defer_deleter_,__LINE__) (nullptr, [&](...){x}); #define defer(x) __defer_struct DO_CONCAT(__defer_deleter,__LINE__) ([&](...){x;}); #endif // DEFER_H_INCLUDED
565
C++
.h
8
69.375
237
0.654054
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,510
urlencode.h
tindy2013_subconverter/src/utils/urlencode.h
#ifndef URLENCODE_H_INCLUDED #define URLENCODE_H_INCLUDED #include <string> #include "utils/string.h" std::string urlEncode(const std::string& str); std::string urlDecode(const std::string& str); std::string joinArguments(const string_multimap &args); #endif // URLENCODE_H_INCLUDED
287
C++
.h
8
34.375
55
0.792727
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,512
file_extra.h
tindy2013_subconverter/src/utils/file_extra.h
#ifndef FILE_EXTRA_H_INCLUDED #define FILE_EXTRA_H_INCLUDED #include "base64/base64.h" #include "file.h" #include "md5/md5_interface.h" inline std::string fileToBase64(const std::string &filepath) { return base64Encode(fileGet(filepath)); } inline std::string fileGetMD5(const std::string &filepath) { return getMD5(fileGet(filepath)); } #endif // FILE_EXTRA_H_INCLUDED
382
C++
.h
14
25.428571
60
0.774725
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,513
rapidjson_extra.h
tindy2013_subconverter/src/utils/rapidjson_extra.h
#ifndef RAPIDJSON_EXTRA_H_INCLUDED #define RAPIDJSON_EXTRA_H_INCLUDED #include <stdexcept> template <typename T> void exception_thrower(T e, const std::string &cond, const std::string &file, int line) { if(!e) throw std::runtime_error("rapidjson assertion failed: " + cond + " (" + file + ":" + std::to_string(line) + ")"); } #ifdef RAPIDJSON_ASSERT #undef RAPIDJSON_ASSERT #endif // RAPIDJSON_ASSERT #define VALUE(x) #x #define RAPIDJSON_ASSERT(x) exception_thrower(x, VALUE(x), __FILE__, __LINE__) #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/error/en.h> #include <string> inline void operator >> (const rapidjson::Value &value, std::string &i) { if(value.IsNull()) i = ""; else if(value.IsString()) i = std::string(value.GetString()); else if(value.IsInt64()) i = std::to_string(value.GetInt64()); else if(value.IsBool()) i = value.GetBool() ? "true" : "false"; else if(value.IsDouble()) i = std::to_string(value.GetDouble()); else i = ""; } inline void operator >> (const rapidjson::Value &value, int &i) { if(value.IsNull()) i = 0; else if(value.IsInt()) i = value.GetInt(); else if(value.IsString()) i = std::stoi(value.GetString()); else if(value.IsBool()) i = value.GetBool() ? 1 : 0; else i = 0; } inline std::string GetMember(const rapidjson::Value &value, const std::string &member) { std::string retStr; if(value.IsObject() && value.HasMember(member.data())) value[member.data()] >> retStr; return retStr; } inline void GetMember(const rapidjson::Value &value, const std::string &member, std::string &target) { std::string retStr = GetMember(value, member); if(!retStr.empty()) target.assign(retStr); } template <typename ...Args> inline rapidjson::Value buildObject(rapidjson::MemoryPoolAllocator<> &allocator, Args... kvs) { static_assert(sizeof...(kvs) % 2 == 0, "buildObject requires an even number of arguments"); static_assert((std::is_same<Args, const char*>::value && ...), "buildObject requires all arguments to be const char*"); rapidjson::Value ret(rapidjson::kObjectType); auto args = {kvs...}; auto it = args.begin(); while (it != args.end()) { const char *key = *it++, *value = *it++; ret.AddMember(rapidjson::StringRef(key), rapidjson::StringRef(value), allocator); } return ret; } inline rapidjson::Value buildBooleanValue(bool value) { return value ? rapidjson::Value(rapidjson::kTrueType) : rapidjson::Value(rapidjson::kFalseType); } namespace rapidjson_ext { template <typename ReturnType> struct ExtensionFunction { virtual ReturnType operator() (rapidjson::Value &root) const = 0; virtual ReturnType operator() (rapidjson::Value &&root) const { return (*this)(root); }; friend ReturnType operator| (rapidjson::Value &root, const ExtensionFunction<ReturnType> &func) { return func(root); } friend ReturnType operator| (rapidjson::Value &&root, const ExtensionFunction<ReturnType> &func) { return func(root); } }; struct AddMemberOrReplace : public ExtensionFunction<rapidjson::Value &> { rapidjson::Value &value; const rapidjson::Value::Ch *name; rapidjson::MemoryPoolAllocator<> &allocator; AddMemberOrReplace(const rapidjson::Value::Ch *name, rapidjson::Value &value, rapidjson::MemoryPoolAllocator<> &allocator) : value(value), name(name), allocator(allocator) {} AddMemberOrReplace(const rapidjson::Value::Ch *name, rapidjson::Value &&value, rapidjson::MemoryPoolAllocator<> &allocator) : value(value), name(name), allocator(allocator) {} inline rapidjson::Value & operator() (rapidjson::Value &root) const override { if (root.HasMember(name)) root[name] = value; else root.AddMember(rapidjson::Value(name, allocator), value, allocator); return root; } }; struct AppendToArray : public ExtensionFunction<rapidjson::Value &> { rapidjson::Value &value; rapidjson::GenericValue<rapidjson::UTF8<>> name; rapidjson::MemoryPoolAllocator<> &allocator; AppendToArray(const rapidjson::Value::Ch *name, rapidjson::Value &value, rapidjson::MemoryPoolAllocator<> &allocator): value(value), name(rapidjson::Value(name, allocator)), allocator(allocator) {} AppendToArray(const rapidjson::Value::Ch *name, rapidjson::Value &&value, rapidjson::MemoryPoolAllocator<> &allocator): value(value), name(rapidjson::Value(name, allocator)), allocator(allocator) {} AppendToArray(const rapidjson::Value::Ch *name, std::size_t length, rapidjson::Value &value, rapidjson::MemoryPoolAllocator<> &allocator): value(value), name(rapidjson::Value(name, length, allocator)), allocator(allocator) {} AppendToArray(const rapidjson::Value::Ch *name, std::size_t length, rapidjson::Value &&value, rapidjson::MemoryPoolAllocator<> &allocator): value(value), name(rapidjson::Value(name, length, allocator)), allocator(allocator) {} AppendToArray(rapidjson::Value &&name, rapidjson::Value &value, rapidjson::MemoryPoolAllocator<> &allocator): value(value), allocator(allocator) { this->name.Swap(name); } inline rapidjson::Value &operator()(rapidjson::Value &root) const override { if (root.HasMember(name)) { if (root[name].IsArray()) { root[name].PushBack(value, allocator); } else { root[name] = rapidjson::Value(rapidjson::kArrayType).PushBack(value, allocator); } } else { root.AddMember(rapidjson::Value(name, allocator), rapidjson::Value(rapidjson::kArrayType).PushBack(value, allocator), allocator); } return root; } }; struct SerializeObject : public ExtensionFunction<std::string> { inline std::string operator() (rapidjson::Value &root) const override { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); root.Accept(writer); return buffer.GetString(); } }; } #endif // RAPIDJSON_EXTRA_H_INCLUDED
6,691
C++
.h
157
34.56051
154
0.631029
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,514
stl_extra.h
tindy2013_subconverter/src/utils/stl_extra.h
#ifndef STL_EXTRA_H_INCLUDED #define STL_EXTRA_H_INCLUDED #include <vector> template <typename T> inline void eraseElements(std::vector<T> &target) { target.clear(); target.shrink_to_fit(); } template <typename T> inline void eraseElements(T &target) { T().swap(target); } #if __cpp_concepts >= 201907L // C++20 concepts supported (g++-10 or clang++-10) template <typename Container> concept ConstIterable = requires(Container a) { { a.cbegin() } -> std::same_as<typename Container::const_iterator>; { a.cend() } -> std::same_as<typename Container::const_iterator>; typename Container::const_reference; }; template <typename Container> concept Iterable = requires(Container a) { { a.begin() } -> std::same_as<typename Container::iterator>; { a.end() } -> std::same_as<typename Container::iterator>; typename Container::reference; }; template <typename ConstIterableContainer> requires ConstIterable<ConstIterableContainer> inline bool none_of(const ConstIterableContainer &container, std::function<bool(typename ConstIterableContainer::const_reference)> func) { return std::none_of(container.cbegin(), container.cend(), func); } #else // __cpp_concepts >= 201907L template <typename Container> inline bool none_of(const Container &container, std::function<bool(typename Container::const_reference)> func) { return std::none_of(container.cbegin(), container.cend(), func); } #endif // __cpp_concepts >= 201907L #endif // STL_EXTRA_H_INCLUDED
1,497
C++
.h
39
35.974359
136
0.739461
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,515
string.h
tindy2013_subconverter/src/utils/string.h
#ifndef STRING_H_INCLUDED #define STRING_H_INCLUDED #include <numeric> #include <string> #include <sstream> #include <vector> #include <map> using string = std::string; using string_size = std::string::size_type; using string_array = std::vector<std::string>; using string_view_array = std::vector<std::string_view>; using string_map = std::map<std::string, std::string>; using string_multimap = std::multimap<std::string, std::string>; using string_pair_array = std::vector<std::pair<std::string, std::string>>; std::vector<std::string> split(const std::string &s, const std::string &separator); std::vector<std::string_view> split(std::string_view s, char separator); void split(std::vector<std::string_view> &result, std::string_view s, char separator); std::string join(const string_array &arr, const std::string &delimiter); template <typename InputIt> std::string join(InputIt first, InputIt last, const std::string &delimiter) { if(first == last) return ""; if(std::next(first) == last) return *first; return std::accumulate(std::next(first), last, *first, [&](const std::string &a, const std::string &b) {return a + delimiter + b; }); } std::string getUrlArg(const std::string &url, const std::string &request); std::string getUrlArg(const string_multimap &args, const std::string &request); std::string replaceAllDistinct(std::string str, const std::string &old_value, const std::string &new_value); std::string trimOf(const std::string& str, char target, bool before = true, bool after = true); std::string trim(const std::string& str, bool before = true, bool after = true); std::string trimQuote(const std::string &str, bool before = true, bool after = true); void trimSelfOf(std::string &str, char target, bool before = true, bool after = true); std::string trimWhitespace(const std::string &str, bool before = false, bool after = true); std::string randomStr(int len); bool isStrUTF8(const std::string &data); void removeUTF8BOM(std::string &data); std::string UTF8ToCodePoint(const std::string &data); std::string toLower(const std::string &str); std::string toUpper(const std::string &str); void processEscapeChar(std::string &str); void processEscapeCharReverse(std::string &str); int parseCommaKeyValue(const std::string &input, const std::string &separator, string_pair_array &result); inline bool strFind(const std::string &str, const std::string &target) { return str.find(target) != std::string::npos; } #if __cpp_lib_starts_ends_with >= 201711L inline bool startsWith(const std::string &hay, const std::string &needle) { return hay.starts_with(needle); } inline bool endsWith(const std::string &hay, const std::string &needle) { return hay.ends_with(needle); } #else inline bool startsWith(const std::string &hay, const std::string &needle) { return hay.find(needle) == 0; } inline bool endsWith(const std::string &hay, const std::string &needle) { auto hay_size = hay.size(), needle_size = needle.size(); return hay_size >= needle_size && hay.rfind(needle) == hay_size - needle_size; } #endif inline bool count_least(const std::string &hay, const char needle, size_t cnt) { string_size pos = hay.find(needle); while(pos != std::string::npos) { cnt--; if(!cnt) return true; pos = hay.find(needle, pos + 1); } return false; } inline char getLineBreak(const std::string &str) { return count_least(str, '\n', 1) ? '\n' : '\r'; } template <typename T> concept Arithmetic = std::is_arithmetic_v<T>; template <typename OutType, typename InType> requires Arithmetic<OutType> inline OutType to_number(const InType &value, OutType def_value = 0) { OutType retval = 0; char c; std::stringstream ss; ss << value; if(!(ss >> retval) || ss >> c) return def_value; else return retval; } int to_int(const std::string &str, int def_value = 0); template <typename Type> concept StringConstructible = requires(Type a) { { std::string(a) } -> std::same_as<std::string>; }; template <typename Container, typename Element> concept Insertable = requires(Container a, Element b) { { a.insert(b) } -> std::same_as<typename Container::iterator>; }; template<typename Container, typename KeyType, typename ValueType> requires Insertable<Container, std::pair<std::string, ValueType>> void fillMap(Container& map, KeyType&& key, ValueType&& value) { map.insert({std::string(std::forward<KeyType>(key)), std::forward<ValueType>(value)}); } template<typename Container, typename KeyType, typename ValueType, typename... Args> requires Insertable<Container, std::pair<std::string, ValueType>> void fillMap(Container& map, KeyType&& key, ValueType&& value, Args&&... args) { map.insert({std::string(std::forward<KeyType>(key)), std::forward<ValueType>(value)}); fillMap(map, std::forward<Args>(args)...); } template<typename KeyType, typename ValueType, typename... Args> std::multimap<std::string, ValueType> multiMapOf(KeyType&& key, ValueType&& value, Args&&... args) { std::multimap<std::string, ValueType> result; fillMap(result, std::forward<KeyType>(key), std::forward<ValueType>(value), std::forward<Args>(args)...); return result; } #ifndef HAVE_TO_STRING namespace std { template <typename T> std::string to_string(const T& n) { std::ostringstream ss; ss << n; return ss.str(); } } #endif // HAVE_TO_STRING #endif // STRING_H_INCLUDED
5,458
C++
.h
137
37.218978
137
0.715581
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,516
map_extra.h
tindy2013_subconverter/src/utils/map_extra.h
#ifndef MAP_EXTRA_H_INCLUDED #define MAP_EXTRA_H_INCLUDED #include <string> #include <map> #include <algorithm> struct strICaseComp { bool operator() (const std::string &lhs, const std::string &rhs) const { return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(), [](unsigned char c1, unsigned char c2) { return ::tolower(c1) < ::tolower(c2); }); } }; using string_icase_map = std::map<std::string, std::string, strICaseComp>; #endif // MAP_EXTRA_H_INCLUDED
733
C++
.h
19
24.526316
85
0.48169
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,517
codepage.h
tindy2013_subconverter/src/utils/codepage.h
#ifndef CODEPAGE_H_INCLUDED #define CODEPAGE_H_INCLUDED #include <string> std::string utf8ToACP(const std::string &str_src); std::string acpToUTF8(const std::string &str_src); #endif // CODEPAGE_H_INCLUDED
209
C++
.h
6
33.333333
50
0.785
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,518
network.h
tindy2013_subconverter/src/utils/network.h
#ifndef NETWORK_H_INCLUDED #define NETWORK_H_INCLUDED #include <string> #include "string.h" std::string getFormData(const std::string &raw_data); std::string getUrlArg(const std::string &url, const std::string &request); bool isIPv4(const std::string &address); bool isIPv6(const std::string &address); void urlParse(std::string &url, std::string &host, std::string &path, int &port, bool &isTLS); std::string hostnameToIPAddr(const std::string &host); inline bool isLink(const std::string &url) { return startsWith(url, "https://") || startsWith(url, "http://") || startsWith(url, "data:"); } #endif // NETWORK_H_INCLUDED
632
C++
.h
15
40.533333
97
0.736928
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,520
base64.h
tindy2013_subconverter/src/utils/base64/base64.h
#ifndef BASE64_H_INCLUDED #define BASE64_H_INCLUDED #include <string> std::string base64Decode(const std::string &encoded_string, bool accept_urlsafe = false); std::string base64Encode(const std::string &string_to_encode); std::string urlSafeBase64Apply(const std::string &encoded_string); std::string urlSafeBase64Reverse(const std::string &encoded_string); std::string urlSafeBase64Decode(const std::string &encoded_string); std::string urlSafeBase64Encode(const std::string &string_to_encode); #endif // BASE64_H_INCLUDED
529
C++
.h
10
51.5
89
0.805825
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,522
md5_interface.h
tindy2013_subconverter/src/utils/md5/md5_interface.h
#ifndef MD5_INTERFACE_H_INCLUDED #define MD5_INTERFACE_H_INCLUDED #include <string> #include "md5.h" inline std::string getMD5(const std::string &data) { std::string result; /* unsigned int i = 0; unsigned char digest[16] = {}; #ifdef USE_MBEDTLS mbedtls_md5_context ctx; mbedtls_md5_init(&ctx); mbedtls_md5_starts_ret(&ctx); mbedtls_md5_update_ret(&ctx, reinterpret_cast<const unsigned char*>(data.data()), data.size()); mbedtls_md5_finish_ret(&ctx, reinterpret_cast<unsigned char*>(&digest)); mbedtls_md5_free(&ctx); #else MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, data.data(), data.size()); MD5_Final((unsigned char *)&digest, &ctx); #endif // USE_MBEDTLS char tmp[3] = {}; for(i = 0; i < 16; i++) { snprintf(tmp, 3, "%02x", digest[i]); result += tmp; } */ char result_str[MD5_STRING_SIZE]; md5::md5_t md5; md5.process(data.data(), data.size()); md5.finish(); md5.get_string(result_str); result.assign(result_str); return result; } #endif // MD5_INTERFACE_H_INCLUDED
1,105
C++
.h
39
23.974359
99
0.63981
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,524
webget.h
tindy2013_subconverter/src/handler/webget.h
#ifndef WEBGET_H_INCLUDED #define WEBGET_H_INCLUDED #include <string> #include <map> #include "utils/map_extra.h" #include "utils/string.h" enum http_method { HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PATCH }; struct FetchArgument { const http_method method; const std::string url; const std::string proxy; const std::string *post_data = nullptr; const string_icase_map *request_headers = nullptr; std::string *cookies = nullptr; const unsigned int cache_ttl = 0; const bool keep_resp_on_fail = false; }; struct FetchResult { int *status_code; std::string *content = nullptr; std::string *response_headers = nullptr; std::string *cookies = nullptr; }; int webGet(const FetchArgument& argument, FetchResult &result); std::string webGet(const std::string &url, const std::string &proxy = "", unsigned int cache_ttl = 0, std::string *response_headers = nullptr, string_icase_map *request_headers = nullptr); void flushCache(); int webPost(const std::string &url, const std::string &data, const std::string &proxy, const string_icase_map &request_headers, std::string *retData); int webPatch(const std::string &url, const std::string &data, const std::string &proxy, const string_icase_map &request_headers, std::string *retData); std::string buildSocks5ProxyString(const std::string &addr, int port, const std::string &username, const std::string &password); // Unimplemented: (CURLOPT_HTTPHEADER: Host:) std::string httpGet(const std::string &host, const std::string &addr, const std::string &uri); std::string httpsGet(const std::string &host, const std::string &addr, const std::string &uri); #endif // WEBGET_H_INCLUDED
1,688
C++
.h
41
38.414634
188
0.733374
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,525
multithread.h
tindy2013_subconverter/src/handler/multithread.h
#ifndef MULTITHREAD_H_INCLUDED #define MULTITHREAD_H_INCLUDED #include <mutex> #include <future> #include <yaml-cpp/yaml.h> #include "config/regmatch.h" #include "utils/ini_reader/ini_reader.h" #include "utils/string.h" using guarded_mutex = std::lock_guard<std::mutex>; RegexMatchConfigs safe_get_emojis(); RegexMatchConfigs safe_get_renames(); RegexMatchConfigs safe_get_streams(); RegexMatchConfigs safe_get_times(); YAML::Node safe_get_clash_base(); INIReader safe_get_mellow_base(); void safe_set_emojis(RegexMatchConfigs data); void safe_set_renames(RegexMatchConfigs data); void safe_set_streams(RegexMatchConfigs data); void safe_set_times(RegexMatchConfigs data); std::shared_future<std::string> fetchFileAsync(const std::string &path, const std::string &proxy, int cache_ttl, bool find_local = true, bool async = false); std::string fetchFile(const std::string &path, const std::string &proxy, int cache_ttl, bool find_local = true); #endif // MULTITHREAD_H_INCLUDED
983
C++
.h
22
43.409091
157
0.789529
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,526
interfaces.h
tindy2013_subconverter/src/handler/interfaces.h
#ifndef INTERFACES_H_INCLUDED #define INTERFACES_H_INCLUDED #include <string> #include <map> #include <inja.hpp> #include "config/ruleset.h" #include "generator/config/subexport.h" #include "server/webserver.h" std::string parseProxy(const std::string &source); void refreshRulesets(RulesetConfigs &ruleset_list, std::vector<RulesetContent> &rca); void readConf(); int simpleGenerator(); std::string convertRuleset(const std::string &content, int type); std::string getProfile(RESPONSE_CALLBACK_ARGS); std::string getRuleset(RESPONSE_CALLBACK_ARGS); std::string subconverter(RESPONSE_CALLBACK_ARGS); std::string simpleToClashR(RESPONSE_CALLBACK_ARGS); std::string surgeConfToClash(RESPONSE_CALLBACK_ARGS); std::string renderTemplate(RESPONSE_CALLBACK_ARGS); std::string template_webGet(inja::Arguments &args); std::string jinja2_webGet(const std::string &url); std::string parseHostname(inja::Arguments &args); #endif // INTERFACES_H_INCLUDED
952
C++
.h
23
40
85
0.808696
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,527
settings.h
tindy2013_subconverter/src/handler/settings.h
#ifndef SETTINGS_H_INCLUDED #define SETTINGS_H_INCLUDED #include <string> #include "config/crontask.h" #include "config/regmatch.h" #include "config/proxygroup.h" #include "config/ruleset.h" #include "generator/config/ruleconvert.h" #include "generator/template/templates.h" #include "utils/logger.h" #include "utils/string.h" #include "utils/stl_extra.h" #include "utils/tribool.h" struct Settings { //common settings std::string prefPath = "pref.ini", defaultExtConfig; string_array excludeRemarks, includeRemarks; RulesetConfigs customRulesets; RegexMatchConfigs streamNodeRules, timeNodeRules; std::vector<RulesetContent> rulesetsContent; std::string listenAddress = "127.0.0.1", defaultUrls, insertUrls, managedConfigPrefix; int listenPort = 25500, maxPendingConns = 10, maxConcurThreads = 4; bool prependInsert = true, skipFailedLinks = false; bool APIMode = true, writeManagedConfig = false, enableRuleGen = true, updateRulesetOnRequest = false, overwriteOriginalRules = true; bool printDbgInfo = false, CFWChildProcess = false, appendUserinfo = true, asyncFetchRuleset = false, surgeResolveHostname = true; std::string accessToken, basePath = "base"; std::string custom_group; int logLevel = LOG_LEVEL_VERBOSE; long maxAllowedDownloadSize = 1048576L; string_map aliases; //global variables for template std::string templatePath = "templates"; string_map templateVars; //generator settings bool generatorMode = false; std::string generateProfiles; //preferences bool reloadConfOnRequest = false; RegexMatchConfigs renames, emojis; bool addEmoji = false, removeEmoji = false, appendType = false, filterDeprecated = true; tribool UDPFlag, TFOFlag, skipCertVerify, TLS13Flag, enableInsert; bool enableSort = false, updateStrict = false; bool clashUseNewField = false, singBoxAddClashModes = true; std::string clashProxiesStyle = "flow", clashProxyGroupsStyle = "block"; std::string proxyConfig, proxyRuleset, proxySubscription; int updateInterval = 0; std::string sortScript, filterScript; std::string clashBase; ProxyGroupConfigs customProxyGroups; std::string surgeBase, surfboardBase, mellowBase, quanBase, quanXBase, loonBase, SSSubBase, singBoxBase; std::string surgeSSRPath, quanXDevID; //cache system bool serveCacheOnFetchFail = false; int cacheSubscription = 60, cacheConfig = 300, cacheRuleset = 21600; //limits size_t maxAllowedRulesets = 64, maxAllowedRules = 32768; bool scriptCleanContext = false; //cron system bool enableCron = false; CronTaskConfigs cronTasks; }; struct ExternalConfig { ProxyGroupConfigs custom_proxy_group; RulesetConfigs surge_ruleset; std::string clash_rule_base; std::string surge_rule_base; std::string surfboard_rule_base; std::string mellow_rule_base; std::string quan_rule_base; std::string quanx_rule_base; std::string loon_rule_base; std::string sssub_rule_base; std::string singbox_rule_base; RegexMatchConfigs rename; RegexMatchConfigs emoji; string_array include; string_array exclude; template_args *tpl_args = nullptr; bool overwrite_original_rules = false; bool enable_rule_generator = true; tribool add_emoji; tribool remove_old_emoji; }; extern Settings global; int importItems(string_array &target, bool scope_limit = true); int loadExternalConfig(std::string &path, ExternalConfig &ext); template <class... Args> void parseGroupTimes(const std::string &src, Args... args) { std::array<int*, sizeof...(args)> ptrs {args...}; string_size bpos = 0, epos = src.find(","); for(int *x : ptrs) { if(x != nullptr) *x = to_int(src.substr(bpos, epos - bpos), 0); if(epos != src.npos) { bpos = epos + 1; epos = src.find(",", bpos); } else return; } return; } #endif // SETTINGS_H_INCLUDED
4,029
C++
.h
108
32.675926
137
0.723431
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,528
upload.h
tindy2013_subconverter/src/handler/upload.h
#ifndef UPLOAD_H_INCLUDED #define UPLOAD_H_INCLUDED #include <string> std::string buildGistData(std::string name, std::string content); int uploadGist(std::string name, std::string path, std::string content, bool writeManageURL); #endif // UPLOAD_H_INCLUDED
261
C++
.h
6
42
93
0.789683
tindy2013/subconverter
12,883
2,744
197
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false