build_router_package.sh 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. #!/usr/bin/env sh
  2. set -eu
  3. SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
  4. APP_DIR="$SCRIPT_DIR"
  5. PKG_ROOT_NAME=${PKG_ROOT_NAME:-vmess}
  6. OUT_TAR=${OUT_TAR:-"$APP_DIR/vmess.tar.gz"}
  7. TMP_DIR=${TMP_DIR:-"/tmp/vmess_pkg.$$"}
  8. ROUTER_CONF=${ROUTER_CONF:-"$APP_DIR/config_router.conf"}
  9. HTTP_SCRIPT=${HTTP_SCRIPT:-"$APP_DIR/scripts/router_local_http.sh"}
  10. UPDATE_SCRIPT=${UPDATE_SCRIPT:-"$APP_DIR/scripts/router_local_update.sh"}
  11. # Defaults aligned with current repo layout.
  12. BUSYBOX_SRC=${BUSYBOX_SRC:-"$APP_DIR/busybox/busybox-armv7l"}
  13. CFST_SRC_DIR=${CFST_SRC_DIR:-"$APP_DIR/cfst_linux_armv5"}
  14. VERBOSE=${VERBOSE:-1}
  15. SYNC_FROM_CONFIG=${SYNC_FROM_CONFIG:-}
  16. WRITE_BACK=${WRITE_BACK:-0}
  17. while [ $# -gt 0 ]; do
  18. case "$1" in
  19. --sync-from=*|--sync-from-config=*|--sync-from-json=*)
  20. SYNC_FROM_CONFIG="${1#*=}"
  21. shift
  22. ;;
  23. --sync-from|--sync-from-config|--sync-from-json)
  24. [ $# -ge 2 ] || { printf '[error] %s requires a file path argument\n' "$1" >&2; exit 1; }
  25. SYNC_FROM_CONFIG="$2"
  26. shift 2
  27. ;;
  28. --write-back)
  29. WRITE_BACK=1
  30. shift
  31. ;;
  32. *)
  33. shift
  34. ;;
  35. esac
  36. done
  37. log() {
  38. if [ "${VERBOSE}" = "1" ]; then
  39. printf '%s\n' "$*"
  40. fi
  41. }
  42. warn() {
  43. printf '[warn] %s\n' "$*" >&2
  44. }
  45. err() {
  46. printf '[error] %s\n' "$*" >&2
  47. exit 1
  48. }
  49. require_file() {
  50. p="$1"
  51. [ -f "$p" ] || err "required file missing: $p"
  52. }
  53. require_dir() {
  54. p="$1"
  55. [ -d "$p" ] || err "required directory missing: $p"
  56. }
  57. parse_conf_var() {
  58. conf="$1"
  59. key="$2"
  60. if [ ! -r "$conf" ]; then
  61. return 1
  62. fi
  63. sed -n "s|^${key}=\"\\(.*\\)\"$|\\1|p" "$conf" | head -n 1
  64. }
  65. resolve_from_conf_dir() {
  66. conf="$1"
  67. val="$2"
  68. conf_dir=$(CDPATH= cd -- "$(dirname -- "$conf")" && pwd)
  69. case "$val" in
  70. "") printf '%s\n' "" ;;
  71. /*) printf '%s\n' "$val" ;;
  72. *) printf '%s/%s\n' "$conf_dir" "$val" ;;
  73. esac
  74. }
  75. check_busybox_httpd() {
  76. bb="$1"
  77. if [ ! -f "$bb" ]; then
  78. warn "BusyBox binary missing: $bb"
  79. return 1
  80. fi
  81. if [ -x "$bb" ] && "$bb" --list 2>/dev/null | grep '^httpd$' >/dev/null 2>&1; then
  82. return 0
  83. fi
  84. # 跨平台构建(例如在 macOS 上打包 Linux ARM ELF 二进制),回退到静态字符串检查
  85. if strings "$bb" 2>/dev/null | grep -q 'httpd'; then
  86. return 0
  87. fi
  88. warn "BusyBox has no httpd applet: $bb"
  89. return 1
  90. }
  91. log "[pkg] app dir: $APP_DIR"
  92. log "[pkg] output: $OUT_TAR"
  93. require_file "$ROUTER_CONF"
  94. require_file "$HTTP_SCRIPT"
  95. require_file "$UPDATE_SCRIPT"
  96. require_dir "$CFST_SRC_DIR"
  97. require_file "$BUSYBOX_SRC"
  98. # 基础文件校验通过后再安全初始化临时目录与 trap
  99. case "$TMP_DIR" in
  100. ""|"/"|"/tmp"|"/var"|"$APP_DIR"|"$HOME") err "Unsafe TMP_DIR: '$TMP_DIR'" ;;
  101. esac
  102. cleanup() {
  103. rm -rf "$TMP_DIR"
  104. }
  105. trap cleanup EXIT INT TERM
  106. bb_from_conf_raw=$(parse_conf_var "$ROUTER_CONF" "BUSYBOX_BIN" || true)
  107. if [ -n "${bb_from_conf_raw:-}" ]; then
  108. bb_from_conf=$(resolve_from_conf_dir "$ROUTER_CONF" "$bb_from_conf_raw")
  109. if [ "$bb_from_conf" != "$BUSYBOX_SRC" ]; then
  110. warn "BUSYBOX_BIN in conf points to: $bb_from_conf_raw -> $bb_from_conf"
  111. warn "packaging source busybox is: $BUSYBOX_SRC"
  112. warn "if needed, set BUSYBOX_SRC to keep packaging and runtime consistent"
  113. fi
  114. fi
  115. sync_conf_from_json() {
  116. src_conf="$1"
  117. json_file="$2"
  118. dst_conf="$3"
  119. if ! command -v python3 >/dev/null 2>&1; then
  120. warn "python3 not found, skip syncing router config from JSON"
  121. cp "$src_conf" "$dst_conf"
  122. return 0
  123. fi
  124. python3 - "$src_conf" "$json_file" "$dst_conf" <<'EOF'
  125. import json
  126. import re
  127. import sys
  128. src_conf_path, json_path, dst_conf_path = sys.argv[1], sys.argv[2], sys.argv[3]
  129. with open(json_path, "r", encoding="utf-8") as f:
  130. cfg = json.load(f)
  131. updates = {}
  132. out_cfg = cfg.get("output", {})
  133. if "selected_value_file" in out_cfg:
  134. updates["VALUE_TEXT_FILE"] = str(out_cfg["selected_value_file"])
  135. if "selected_value_json" in out_cfg:
  136. updates["VALUE_JSON_FILE"] = str(out_cfg["selected_value_json"])
  137. if "selected_value_json_key" in out_cfg:
  138. updates["VALUE_JSON_KEY"] = str(out_cfg["selected_value_json_key"])
  139. if "state_last_good_key" in out_cfg:
  140. updates["STATE_LAST_GOOD_KEY"] = str(out_cfg["state_last_good_key"])
  141. if "export_vars_file" in out_cfg:
  142. updates["EXPORT_VARS_FILE"] = str(out_cfg["export_vars_file"])
  143. if "substore_value_key" in out_cfg:
  144. updates["EXPORT_VALUE_KEY"] = str(out_cfg["substore_value_key"])
  145. sel_cfg = cfg.get("selection", {})
  146. if "top_n" in sel_cfg:
  147. updates["TOP_N"] = str(sel_cfg["top_n"])
  148. cfst_cfg = cfg.get("cfst_local", {})
  149. run_args = cfst_cfg.get("run_args", [])
  150. if isinstance(run_args, list):
  151. arg_map = {
  152. "-p": "CFST_DISPLAY_COUNT",
  153. "-f": "CFST_IP_FILE",
  154. "-n": "CFST_THREADS",
  155. "-t": "CFST_TEST_COUNT",
  156. "-dn": "CFST_DOWNLOAD_COUNT",
  157. "-dt": "CFST_DOWNLOAD_TIME",
  158. "-tp": "CFST_PORT",
  159. "-url": "CFST_URL",
  160. "-cfcolo": "CFST_CFCOLO",
  161. "-tl": "CFST_LATENCY_LIMIT",
  162. "-tll": "CFST_LATENCY_LOWER",
  163. "-sl": "CFST_LOSS_LIMIT",
  164. "-speedlimit": "CFST_SPEED_LIMIT",
  165. }
  166. i = 0
  167. while i < len(run_args):
  168. flag = str(run_args[i]).strip()
  169. if flag in arg_map and i + 1 < len(run_args):
  170. updates[arg_map[flag]] = str(run_args[i + 1]).strip()
  171. i += 2
  172. elif flag == "-httping":
  173. updates["CFST_HTTPING"] = "1"
  174. i += 1
  175. elif flag == "-dd":
  176. updates["CFST_DISABLE_DOWNLOAD"] = "1"
  177. i += 1
  178. elif flag == "-allip":
  179. updates["CFST_ALL_IP"] = "1"
  180. i += 1
  181. else:
  182. i += 1
  183. with open(src_conf_path, "r", encoding="utf-8") as f:
  184. conf_lines = f.readlines()
  185. new_lines = []
  186. modified_keys = set()
  187. for line in conf_lines:
  188. m = re.match(r'^([A-Za-z0-9_]+)="(.*)"', line.strip())
  189. if m:
  190. key = m.group(1)
  191. if key in updates:
  192. new_lines.append(f'{key}="{updates[key]}"\n')
  193. modified_keys.add(key)
  194. continue
  195. new_lines.append(line)
  196. for key, val in updates.items():
  197. if key not in modified_keys:
  198. new_lines.append(f'{key}="{val}"\n')
  199. with open(dst_conf_path, "w", encoding="utf-8") as f:
  200. f.writelines(new_lines)
  201. EOF
  202. }
  203. if ! check_busybox_httpd "$BUSYBOX_SRC"; then
  204. warn "continuing packaging, but router HTTP may fail later"
  205. fi
  206. mkdir -p "$TMP_DIR/$PKG_ROOT_NAME/scripts" "$TMP_DIR/$PKG_ROOT_NAME/cfst"
  207. if [ -n "$SYNC_FROM_CONFIG" ]; then
  208. require_file "$SYNC_FROM_CONFIG"
  209. log "[pkg] syncing router config from $SYNC_FROM_CONFIG"
  210. sync_conf_from_json "$ROUTER_CONF" "$SYNC_FROM_CONFIG" "$TMP_DIR/$PKG_ROOT_NAME/config_router.conf"
  211. if [ "$WRITE_BACK" = "1" ]; then
  212. cp "$TMP_DIR/$PKG_ROOT_NAME/config_router.conf" "$ROUTER_CONF"
  213. log "[pkg] written synced config back to $ROUTER_CONF"
  214. fi
  215. else
  216. cp "$ROUTER_CONF" "$TMP_DIR/$PKG_ROOT_NAME/config_router.conf"
  217. fi
  218. cp "$HTTP_SCRIPT" "$TMP_DIR/$PKG_ROOT_NAME/scripts/router_local_http.sh"
  219. cp "$UPDATE_SCRIPT" "$TMP_DIR/$PKG_ROOT_NAME/scripts/router_local_update.sh"
  220. cp "$BUSYBOX_SRC" "$TMP_DIR/$PKG_ROOT_NAME/busybox_armv7l"
  221. cp -R "$CFST_SRC_DIR"/. "$TMP_DIR/$PKG_ROOT_NAME/cfst/"
  222. chmod +x \
  223. "$TMP_DIR/$PKG_ROOT_NAME/busybox_armv7l" \
  224. "$TMP_DIR/$PKG_ROOT_NAME/scripts/router_local_http.sh" \
  225. "$TMP_DIR/$PKG_ROOT_NAME/scripts/router_local_update.sh" || true
  226. rm -f "$OUT_TAR"
  227. COPYFILE_DISABLE=1 tar --exclude='.DS_Store' --exclude='._*' -czf "$OUT_TAR" -C "$TMP_DIR" "$PKG_ROOT_NAME"
  228. log "[pkg] tar created: $OUT_TAR"
  229. log "[pkg] tar size: $(ls -lh "$OUT_TAR" | awk '{print $5}')"
  230. log "[pkg] tar content preview:"
  231. tar -tzf "$OUT_TAR" | sed -n '1,120p'
  232. if ! tar -tzf "$OUT_TAR" | grep "^$PKG_ROOT_NAME/busybox_armv7l$" >/dev/null; then
  233. err "package validation failed: busybox_armv7l missing"
  234. fi
  235. if ! tar -tzf "$OUT_TAR" | grep "^$PKG_ROOT_NAME/scripts/router_local_http.sh$" >/dev/null; then
  236. err "package validation failed: router_local_http.sh missing"
  237. fi
  238. if ! tar -tzf "$OUT_TAR" | grep "^$PKG_ROOT_NAME/cfst/cfst$" >/dev/null; then
  239. err "package validation failed: cfst binary missing"
  240. fi
  241. log "[pkg] validation passed"