├── .github ├── dependabot.yml └── workflows │ └── docker-image.yml ├── .gitignore ├── .idea ├── .gitignore ├── deployment.xml ├── dictionaries ├── inspectionProfiles │ ├── Project_Default.xml │ └── profiles_settings.xml ├── jsLibraryMappings.xml ├── misc.xml ├── modules.xml ├── nexttracewebapi.iml └── vcs.xml ├── Dockerfile ├── LICENSE ├── README.md ├── app.py ├── assets ├── css │ └── m.css ├── favicon.ico ├── font │ └── roboto-mono-latin.woff2 └── js │ ├── main.js │ ├── settingsmenu.js │ ├── socket.io.js │ └── socket.io.js.map ├── entrypoint.sh ├── nginx.conf ├── requirements.txt └── templates └── index.html /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "pip" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/docker-image.yml: -------------------------------------------------------------------------------- 1 | name: 'docker image build' 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: 7 | - master 8 | paths: 9 | - "**/*.py" 10 | - "**/*.html" 11 | - "**/*.css" 12 | - "**/nginx.conf" 13 | - "**/Dockerfile" 14 | - "**/entrypoint.sh" 15 | - "**/requirements.txt" 16 | 17 | jobs: 18 | docker: 19 | runs-on: ubuntu-latest 20 | steps: 21 | - name: Checkout 22 | uses: actions/checkout@v3 23 | - name: Checkout submodules 24 | run: git submodule update --init --recursive 25 | - name: Set up QEMU 26 | uses: docker/setup-qemu-action@v2 27 | - name: Set up Docker Buildx 28 | uses: docker/setup-buildx-action@v2 29 | - name: Login to DockerHub 30 | uses: docker/login-action@v2 31 | with: 32 | username: ${{ secrets.DOCKERHUB_USERNAME }} 33 | password: ${{ secrets.DOCKERHUB_TOKEN }} 34 | - name: Build and push 35 | uses: docker/build-push-action@v3 36 | with: 37 | context: . 38 | platforms: linux/amd64,linux/arm64/v8 39 | push: true 40 | tags: tsosc/nexttraceweb:latest 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### Python template 2 | # Byte-compiled / optimized / DLL files 3 | __pycache__/ 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | cover/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | .pybuilder/ 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | # For a library or package, you might want to ignore these files since the code is 88 | # intended to run in multiple environments; otherwise, check them in: 89 | # .python-version 90 | 91 | # pipenv 92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 95 | # install all needed dependencies. 96 | #Pipfile.lock 97 | 98 | # poetry 99 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 100 | # This is especially recommended for binary packages to ensure reproducibility, and is more 101 | # commonly ignored for libraries. 102 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 103 | #poetry.lock 104 | 105 | # pdm 106 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 107 | #pdm.lock 108 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 109 | # in version control. 110 | # https://pdm.fming.dev/#use-with-ide 111 | .pdm.toml 112 | 113 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 114 | __pypackages__/ 115 | 116 | # Celery stuff 117 | celerybeat-schedule 118 | celerybeat.pid 119 | 120 | # SageMath parsed files 121 | *.sage.py 122 | 123 | # Environments 124 | .env 125 | .venv 126 | env/ 127 | venv/ 128 | ENV/ 129 | env.bak/ 130 | venv.bak/ 131 | 132 | # Spyder project settings 133 | .spyderproject 134 | .spyproject 135 | 136 | # Rope project settings 137 | .ropeproject 138 | 139 | # mkdocs documentation 140 | /site 141 | 142 | # mypy 143 | .mypy_cache/ 144 | .dmypy.json 145 | dmypy.json 146 | 147 | # Pyre type checker 148 | .pyre/ 149 | 150 | # pytype static type analyzer 151 | .pytype/ 152 | 153 | # Cython debug symbols 154 | cython_debug/ 155 | 156 | # PyCharm 157 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 158 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 159 | # and can be added to the global gitignore or merged into this file. For a more nuclear 160 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 161 | #.idea/ 162 | 163 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # 默认忽略的文件 2 | /shelf/ 3 | /workspace.xml 4 | # 基于编辑器的 HTTP 客户端请求 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /.idea/deployment.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 15 | -------------------------------------------------------------------------------- /.idea/dictionaries: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 95 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/jsLibraryMappings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/nexttracewebapi.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 17 | 18 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.23.4-alpine3.21 AS builder 2 | 3 | # 安装所需的软件包 4 | RUN apk update && apk add --no-cache git 5 | 6 | # 克隆NEXTTRACE源代码并编译 7 | WORKDIR /build 8 | RUN git clone https://github.com/nxtrace/Ntrace-core.git . && \ 9 | go clean -modcache && \ 10 | go mod download && \ 11 | go build -trimpath -ldflags '-w -s -checklinkname=0' -o nexttrace . 12 | 13 | FROM ubuntu:22.04 14 | 15 | # 安装所需的软件包 16 | RUN apt-get update && \ 17 | apt-get upgrade -y && \ 18 | apt-get install -y python3-pip nginx && \ 19 | apt-get clean && \ 20 | rm -rf /var/lib/apt/lists/* 21 | 22 | # 安装Python依赖包 23 | COPY requirements.txt /tmp/requirements.txt 24 | RUN pip3 install --no-cache-dir -r /tmp/requirements.txt 25 | 26 | # 从构建阶段复制NEXTTRACE二进制文件到最终镜像 27 | COPY --from=builder /build/nexttrace /usr/local/bin/nexttrace 28 | RUN chmod +x /usr/local/bin/nexttrace 29 | 30 | # 复制应用程序文件 31 | COPY app.py /app/app.py 32 | 33 | # 复制templates和assets文件夹 34 | COPY templates /app/templates 35 | COPY assets /app/assets 36 | 37 | # 配置Nginx 38 | COPY nginx.conf /etc/nginx/nginx.conf 39 | 40 | # 设置工作目录 41 | WORKDIR /app 42 | 43 | # Copy start.sh to the container 44 | COPY entrypoint.sh /app/entrypoint.sh 45 | 46 | EXPOSE 30080 47 | 48 | # 设置脚本作为入口点 49 | ENTRYPOINT ["/app/entrypoint.sh"] 50 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | NextTrace Logo 4 | 5 |
6 | 7 | # NEXTTRACE WEB API 8 | 9 | NEXTTRACE项目派生的仓库,用于实现简易的NEXTTRACE WEB API服务端 10 | 11 | 截屏2023-06-12 00 24 06 12 |

13 | 截屏2023-06-12 00 12 57 14 | 截屏2023-06-12 00 26 22 15 |

16 | 17 | 18 | 19 | 20 | 请注意,本项目使用了websocket作为通信协议,因此请在配置反代时参考仓库内的代码(本仓库提供的Docker Image 已内置 Nginx 反代)。 21 | 22 | Inspired by PING.PE 23 | 24 | 感谢PING.PE这么多年来的坚持,让我们能够在这个时候有一个这么好的项目可以参考 25 | 26 | ## How To Use 27 | 28 | 推荐使用Docker安装 29 | ```bash 30 | docker pull tsosc/nexttraceweb 31 | docker run --network host -d --privileged --name ntwa tsosc/nexttraceweb 32 | # 使用 http://your_ip:30080 访问 33 | ``` 34 | 若要使用其他地址和端口,请在docker run时加入参数 35 | ```bash 36 | docker run --network host -d --privileged --name ntwa tsosc/nexttraceweb 127.0.0.1:30080 37 | # 监听127.0.0.1:30080 38 | docker run --network host -d --privileged --name ntwa tsosc/nexttraceweb 80 39 | # 监听所有IP的80端口 40 | docker run --network host -d --privileged --name ntwa tsosc/nexttraceweb [::1]:30080 41 | # 监听[::1]:30080 42 | ``` 43 | 44 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import os 4 | import re 5 | import subprocess 6 | import threading 7 | import time 8 | from threading import Thread 9 | 10 | from flask import Flask, render_template, request 11 | from flask_socketio import SocketIO 12 | import eventlet 13 | 14 | eventlet.monkey_patch() 15 | 16 | # 从环境变量中读取日志级别 17 | log_level = os.environ.get('NTWA_LOG_LEVEL', 'INFO').upper() 18 | 19 | # 验证获取的日志级别是否有效 20 | valid_log_levels = ['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET'] 21 | if log_level not in valid_log_levels: 22 | log_level = 'INFO' # 设置默认值为 INFO 如果环境变量中的值无效 23 | 24 | # 使用获取到的日志级别配置日志 25 | logging.basicConfig(level=log_level, format='%(asctime)s %(levelname)s %(message)s') 26 | 27 | app = Flask(__name__, static_folder='assets') 28 | app.config['SECRET_KEY'] = 'secret' 29 | socketio = SocketIO(app) 30 | nexttrace_path = '/usr/local/bin/nexttrace' 31 | time_limit = 10 32 | 33 | # 存储每个客户端的进程 34 | clients = {} 35 | client_last_active = {} 36 | 37 | 38 | def check_timeouts(): 39 | while True: 40 | for sid, last_active in list(client_last_active.items()): 41 | if time.time() - last_active > time_limit: 42 | logging.debug(f"Client {sid} timed out") 43 | stop_nexttrace_for_sid(sid) 44 | del client_last_active[sid] 45 | time.sleep(1) 46 | 47 | 48 | def stop_nexttrace_for_sid(sid): 49 | task = clients.get(sid) 50 | if task and task.process: 51 | logging.info(f"Attempting to terminate process for client {sid}") 52 | task.process.terminate() 53 | try: 54 | task.process.wait(timeout=1) 55 | logging.info(f"Process terminated successfully for client {sid}") 56 | except subprocess.TimeoutExpired: 57 | logging.warning(f"Process termination timeout for client {sid}, forcing kill") 58 | task.process.kill() 59 | logging.info(f"Process killed forcefully for client {sid}") 60 | socketio.emit('nexttrace_complete', room=sid) 61 | if sid in clients: 62 | del clients[sid] 63 | logging.info(f"Client {sid} removed from clients dictionary after process termination") 64 | 65 | 66 | Thread(target=check_timeouts, daemon=True).start() 67 | 68 | 69 | class OutputMonitor: 70 | def __init__(self, process, socketio, sid, options): 71 | self.process = process 72 | self.last_output_time = time.time() 73 | self.lock = threading.Lock() 74 | self.socketio = socketio 75 | self.sid = sid 76 | self.options = options 77 | 78 | def monitor(self, line): 79 | with self.lock: 80 | self.last_output_time = time.time() 81 | 82 | def start_newline_inserter(self, timeout): 83 | def insert_newline(): 84 | while True: 85 | time.sleep(1) 86 | with self.lock: 87 | if time.time() - self.last_output_time > timeout: 88 | if len(self.options) > 0: 89 | logging.debug(f"in start_newline_inserter: {self.options}") 90 | self.socketio.emit('nexttrace_options', self.options, room=self.sid) 91 | self.options = [] 92 | break 93 | 94 | t = Thread(target=insert_newline, daemon=True) 95 | t.start() 96 | 97 | 98 | class NextTraceTask: 99 | def __init__(self, sid, _socketio, params, _nexttrace_path): 100 | self.sid = sid 101 | self.socketio = _socketio 102 | self.params = params 103 | self.nexttrace_path = _nexttrace_path 104 | self.process = None 105 | 106 | def run(self): 107 | fixParam = '--map --raw -q 1 --send-time 1' # -d disable-geoip 108 | process_env = os.environ.copy() 109 | process_env['NEXTTRACE_UNINTERRUPTED'] = '1' 110 | 111 | # DNS options 112 | options = [] 113 | 114 | pattern = re.compile(r'[&;<>\"\'()|\[\]{}$#!%*+=]') 115 | if pattern.search(self.params): 116 | self.socketio.emit('nexttrace_output', 'Invalid params', room=self.sid) 117 | self.socketio.emit('nexttrace_complete', room=self.sid) 118 | raise ValueError('Invalid params') 119 | logging.debug(f"cmd: {[self.nexttrace_path] + self.params.split() + fixParam.split()}") 120 | self.process = subprocess.Popen( 121 | [self.nexttrace_path] + self.params.split() + fixParam.split(), 122 | stdout=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True, env=process_env, bufsize=1 123 | ) 124 | output_monitor = OutputMonitor(self.process, self.socketio, self.sid, options) 125 | output_monitor_flag = True 126 | 127 | for line in iter(self.process.stdout.readline, ''): 128 | logging.debug(f"line: {line}") 129 | if re.match(r'^\d+\..*$', line): 130 | options.append(line.split()[1]) 131 | if output_monitor_flag: 132 | output_monitor.start_newline_inserter(timeout=0.1) # 0.1 seconds 133 | output_monitor_flag = False 134 | elif re.match(r'^\d+\|', line): 135 | line_split = line.split('|') 136 | res = line_split[0:5] + [''.join(line_split[5:9])] + line_split[9:10] 137 | if '||||||' in line: 138 | res = line_split[0:1] + ['', '', '', '', '', ''] 139 | logging.debug(f"{res}") 140 | res_str = json.dumps(obj=res, ensure_ascii=False) 141 | logging.debug(f"nexttrace_output: {res_str}") 142 | self.socketio.emit('nexttrace_output', res_str, room=self.sid) 143 | client_last_active[self.sid] = time.time() # 更新客户端的最后活跃时间 144 | 145 | if self.process.poll() is not None: 146 | self.socketio.emit('nexttrace_complete', room=self.sid) 147 | break 148 | 149 | def process_input(self, data): 150 | if self.process: 151 | self.process.stdin.write(data) 152 | self.process.stdin.flush() 153 | else: 154 | logging.warning('want to input but Process not started') 155 | 156 | 157 | @socketio.on('connect') 158 | def handle_connect(): 159 | logging.info(f'Client {request.sid} connected') 160 | client_last_active[request.sid] = time.time() 161 | 162 | 163 | @socketio.on('disconnect') 164 | def handle_disconnect(): 165 | logging.info(f'Client {request.sid} disconnected') 166 | stop_nexttrace_for_sid(request.sid) 167 | 168 | 169 | @socketio.on('start_nexttrace') 170 | def start_nexttrace(data): 171 | try: 172 | # 尝试将数据解析为JSON 173 | if isinstance(data, str): 174 | data = json.loads(data) 175 | 176 | # 确保数据是一个字典且包含 'ip' 键 177 | if isinstance(data, dict) and 'ip' in data: 178 | logging.info(f"Client {request.sid} start nexttrace, params: {data}") 179 | params = data['ip'] 180 | if params: 181 | dst = params.strip() 182 | pattern0 = re.compile(r'^[a-fA-F0-9:]+$') 183 | pattern1 = re.compile(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$') 184 | pattern2 = re.compile( 185 | r'^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$') 186 | if not (pattern0.match(dst) or pattern1.match(dst) or pattern2.match(dst)) or len(dst) > 127: 187 | logging.warning(f"Invalid dst: {params}") 188 | return 189 | data = data.get('extra') 190 | if isinstance(data, str): 191 | data = json.loads(data) 192 | # 从 JSON 中提取其他参数 193 | ipVersion = data.get('ipVersion') 194 | if ipVersion == 'ipv4': 195 | params += ' --ipv4' 196 | elif ipVersion == 'ipv6': 197 | params += ' --ipv6' 198 | protocol = data.get('protocol') 199 | if protocol == 'tcp': 200 | params += ' --tcp' 201 | elif protocol == 'udp': 202 | params += ' --udp' 203 | language = data.get('language') 204 | if language == 'en': 205 | params += ' --language en' 206 | intervalSeconds = data.get('intervalSeconds') 207 | if intervalSeconds: 208 | params += f' --ttl-time {int(float(intervalSeconds) * 1000)}' 209 | packetSize = data.get('packetSize') 210 | if packetSize: 211 | params += f' --psize {int(packetSize)}' 212 | maxHop = data.get('maxHop') 213 | if maxHop: 214 | params += f' --max-hops {int(maxHop)}' 215 | minHop = data.get('minHop') 216 | if minHop: 217 | params += f' --first {int(minHop)}' 218 | port = data.get('port') 219 | if port: 220 | params += f' --port {int(port)}' 221 | device = data.get('device') 222 | if device: 223 | device = device.strip() 224 | pattern = re.compile(r'^[a-zA-Z]*\d*$') 225 | if pattern.match(device) and len(device) < 128: 226 | params += f' --dev {device}' 227 | dataProvider = data.get('dataProvider') 228 | if dataProvider and len(dataProvider) < 16: 229 | dataProvider = dataProvider.strip() 230 | allowedList = [ 231 | "Ip2region", "ip2region", "IP.SB", "ip.sb", "IPInfo", "ipinfo", 232 | "IPInsight", "ipinsight", "IPAPI.com", "ip-api.com", "IPInfoLocal", 233 | "ipinfolocal", "chunzhen", "LeoMoeAPI", "leomoeapi", "disable-geoip" 234 | ] 235 | if dataProvider in allowedList: 236 | params += f' --data-provider {dataProvider}' 237 | 238 | # 创建任务 239 | task = NextTraceTask(request.sid, socketio, params, nexttrace_path) 240 | clients[request.sid] = task 241 | # 更新客户端的最后活跃时间 242 | client_last_active[request.sid] = time.time() 243 | # 启动线程 244 | thread = Thread(target=task.run) 245 | try: 246 | thread.start() 247 | except ValueError: 248 | logging.warning(f"Invalid params: {params}") 249 | else: 250 | logging.warning(f"Invalid data format received: {data}") 251 | 252 | except json.JSONDecodeError: 253 | logging.warning(f"Received data is not valid JSON: {data}") 254 | 255 | 256 | @socketio.on('stop_nexttrace') 257 | def stop_nexttrace(): 258 | logging.info(f"Client {request.sid} stop nexttrace") 259 | stop_nexttrace_for_sid(request.sid) 260 | 261 | 262 | @socketio.on('nexttrace_options_choice') 263 | def nexttrace_options_choice(data): 264 | try: 265 | if isinstance(data, str): 266 | data = json.loads(data) 267 | if isinstance(data, dict) and 'choice' in data: 268 | choice = data['choice'] 269 | if isinstance(choice, int): 270 | logging.info(f"Client {request.sid} choose option {choice}") 271 | choice_str = f"{choice}\n" # Convert choice to string and append newline character 272 | task = clients.get(request.sid) 273 | if task: 274 | logging.debug(f"Client {request.sid} send choice {choice_str}") 275 | task.process_input(choice_str) 276 | else: 277 | logging.debug(f"Client want to send choice {choice_str}, but {request.sid} not found") 278 | else: 279 | logging.warning(f"Invalid choice format: {choice}") 280 | else: 281 | logging.warning(f"Invalid data format received: {data}") 282 | except json.JSONDecodeError: 283 | logging.warning(f"Received data is not valid JSON: {data}") 284 | 285 | 286 | @app.route('/') 287 | def index(): 288 | return render_template('index.html'), 200 289 | 290 | 291 | if __name__ == '__main__': 292 | # 从环境变量中读取主机和端口,如果环境变量不存在,使用默认值'127.0.0.1'和35000 293 | host = os.environ.get('TEST_HOST', '127.0.0.1') 294 | _port = int(os.environ.get('TEST_PORT', 35000)) 295 | 296 | # 使用从环境变量中读取的主机和端口运行应用 297 | socketio.run(app, host, _port) 298 | -------------------------------------------------------------------------------- /assets/css/m.css: -------------------------------------------------------------------------------- 1 | /* 默认样式 */ 2 | .floating-menu { 3 | display: none; 4 | position: fixed; 5 | top: 50%; 6 | left: 50%; 7 | transform: translate(-50%, -50%); 8 | background-color: darkblue; 9 | padding: 2vw; 10 | border: 1px solid #ccc; 11 | box-shadow: 0 2px 4px; 12 | } 13 | 14 | /* 移动设备样式 */ 15 | @media screen and (max-width: 767px) { 16 | .floating-menu { 17 | top: 50%; 18 | left: 50%; 19 | transform: translate(-50%, -50%); 20 | padding: 4vw; 21 | background-color: darkblue; 22 | border: 1px solid #ccc; 23 | box-shadow: 0 2px 4px; 24 | } 25 | } 26 | 27 | .block-container { 28 | display: flex; 29 | box-shadow: 0 2px 3px mediumpurple; 30 | align-items: center; 31 | justify-content: center; 32 | background-color: midnightblue; 33 | } 34 | 35 | .floating-menu input { 36 | margin-bottom: 5px; 37 | background-color: midnightblue; 38 | color: white; 39 | } 40 | 41 | /*IP选择框开始*/ 42 | .modal { 43 | display: none; 44 | } 45 | 46 | .modal-content { 47 | display: none; 48 | position: absolute; 49 | top: 50%; 50 | left: 50%; 51 | transform: translate(-50%, -50%); 52 | padding: 20px; 53 | background-color: midnightblue; 54 | box-shadow: 0 2px 3px mediumpurple; 55 | } 56 | 57 | .close { 58 | float: right; 59 | font-size: 20px; 60 | cursor: pointer; 61 | } 62 | 63 | /*END*/ 64 | 65 | @font-face { 66 | font-family: 'Roboto Mono'; 67 | font-style: normal; 68 | font-weight: 400; 69 | src: url(/assets/font/roboto-mono-latin.woff2) format('woff2'); 70 | unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; 71 | } 72 | 73 | :root { 74 | color-scheme: dark; 75 | } 76 | 77 | input, button { 78 | padding: 7px; 79 | } 80 | 81 | @media only screen and (max-width: 700px) { 82 | input, button { 83 | font-size: 2em; 84 | } 85 | } 86 | 87 | .input_settings { 88 | background-color: #002000; 89 | border: 1px solid #155015; 90 | color: #e0e0e0; 91 | } 92 | 93 | .button_settings { 94 | background-color: #002000; 95 | border: 1px solid #155015; 96 | color: #e0e0e0; 97 | } 98 | 99 | p { 100 | /*prevent font scaling on mobile*/ 101 | max-height: 999999px; 102 | -webkit-text-size-adjust: none; 103 | text-size-adjust: none; 104 | } 105 | 106 | div { 107 | max-height: 999999px; 108 | -webkit-text-size-adjust: none; 109 | text-size-adjust: none; 110 | } 111 | 112 | body { 113 | background-color: #000000; 114 | color: white; 115 | font-family: Roboto Mono, Consolas, "Courier New", Courier, monospace; 116 | font-size: 14px; 117 | color: #f0f0f0; 118 | line-height: 1.5em; 119 | -webkit-text-size-adjust: none; 120 | text-size-adjust: none; 121 | } 122 | 123 | a { 124 | color: #f0f0f0; 125 | } 126 | 127 | td { 128 | padding-top: 3px; 129 | padding-bottom: 3px; 130 | vertical-align: top; 131 | } 132 | 133 | @media only screen and (max-width: 700px) { 134 | input, button { 135 | font-size: 200%; 136 | } 137 | } 138 | 139 | table { 140 | padding-left: 0px; 141 | padding-right: 0px; 142 | } 143 | 144 | .span_usage_command { 145 | color: #ffffff; 146 | } 147 | 148 | .div_error { 149 | background-color: #600000; 150 | padding: 10px; 151 | margin-top: 10px; 152 | margin-bottom: 10px; 153 | color: #f0e0e0; 154 | border-radius: 5px; 155 | border: 1px solid #703030; 156 | } 157 | 158 | 159 | .switch { 160 | position: relative; 161 | display: inline-block; 162 | width: 60px; 163 | height: 34px; 164 | } 165 | 166 | .switch input { 167 | opacity: 0; 168 | width: 0; 169 | height: 0; 170 | } 171 | 172 | .slider { 173 | position: absolute; 174 | cursor: pointer; 175 | top: 0; 176 | left: 0; 177 | right: 0; 178 | bottom: 0; 179 | background-color: #ccc; 180 | -webkit-transition: .2s; 181 | transition: .2s; 182 | } 183 | 184 | .slider:before { 185 | position: absolute; 186 | content: ""; 187 | height: 26px; 188 | width: 26px; 189 | left: 4px; 190 | bottom: 4px; 191 | background-color: white; 192 | -webkit-transition: .2s; 193 | transition: .2s; 194 | } 195 | 196 | input:checked + .slider { 197 | background-color: #2196F3; 198 | } 199 | 200 | input:focus + .slider { 201 | box-shadow: 0 0 1px #2196F3; 202 | } 203 | 204 | input:checked + .slider:before { 205 | -webkit-transform: translateX(26px); 206 | -ms-transform: translateX(26px); 207 | transform: translateX(26px); 208 | } 209 | 210 | /* Rounded sliders */ 211 | .slider.round { 212 | border-radius: 34px; 213 | } 214 | 215 | .slider.round:before { 216 | border-radius: 50%; 217 | } 218 | 219 | #page-div { 220 | /* for html2canvas */ 221 | background-color: #000000; 222 | } 223 | 224 | .pingtable table { 225 | line-height: 0.8em; /*for html2canvas */ 226 | border-spacing: 0px 0px; 227 | font-family: Consolas, "Courier New", Courier, monospace; 228 | } 229 | 230 | table.pingtable td { 231 | width: 66px; 232 | cursor: default; 233 | text-align: left; 234 | padding-top: 0px; 235 | padding-bottom: 1px; 236 | padding-right: 7px; 237 | padding-left: 3px; 238 | margin: 0px; 239 | white-space: nowrap; 240 | font-size: 13px; 241 | 242 | } 243 | 244 | table.pingtable td:first-child { 245 | width: 140px; 246 | } 247 | 248 | table.pingtable td:nth-child(2) { 249 | width: 150px; 250 | } 251 | 252 | table.pingtable th { 253 | padding-top: 2px; 254 | padding-bottom: 1px; 255 | padding-right: 7px; 256 | padding-left: 3px; 257 | margin: 0px; 258 | text-align: left; 259 | color: yellow; 260 | color: black; 261 | background-color: #009000; 262 | } 263 | 264 | table.pingtable th:first-child { 265 | border-top-left-radius: 3px; 266 | border-bottom-left-radius: 3px; 267 | } 268 | 269 | table.pingtable th:last-child { 270 | border-top-right-radius: 3px; 271 | border-bottom-right-radius: 3px; 272 | } 273 | 274 | table.pingtable tr { 275 | margin: 0px; 276 | padding: 0px; 277 | } 278 | 279 | .mtr_report { 280 | color: #30e050; 281 | font-size: 14px; 282 | line-height: 130%; 283 | font-family: Roboto Mono, Consolas, "Courier New", Courier, monospace; 284 | } 285 | 286 | pre.mtr_report a { 287 | color: #104718; 288 | text-decoration: underline; 289 | -webkit-text-size-adjust: none; 290 | text-size-adjust: none; 291 | } 292 | 293 | pre.mtr_report a span { 294 | /*dirty trick to change color of underline */ 295 | color: #30e050; 296 | text-decoration: none; 297 | -webkit-text-size-adjust: none; 298 | text-size-adjust: none; 299 | } 300 | -------------------------------------------------------------------------------- /assets/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nxtrace/nexttracewebapi/00682062f7dc58299076ac042fcf4aa6d8d16a44/assets/favicon.ico -------------------------------------------------------------------------------- /assets/font/roboto-mono-latin.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nxtrace/nexttracewebapi/00682062f7dc58299076ac042fcf4aa6d8d16a44/assets/font/roboto-mono-latin.woff2 -------------------------------------------------------------------------------- /assets/js/main.js: -------------------------------------------------------------------------------- 1 | var socket = io.connect(location.origin); 2 | var dataMap = {}; // 存储已合并的数据 3 | 4 | socket.on('connect', function () { 5 | console.log('Connected'); 6 | }); 7 | 8 | socket.on('disconnect', function () { 9 | console.log('Disconnected'); 10 | }); 11 | 12 | socket.on('nexttrace_output', function (data) { 13 | var outputTable = document.getElementById('output'); 14 | mergeDataAndAddOrUpdateRow(outputTable, data); 15 | }); 16 | 17 | socket.on('nexttrace_complete', function () { 18 | console.log('Nexttrace complete'); 19 | }); 20 | 21 | socket.on('nexttrace_options', function (data) { 22 | console.log('Nexttrace options', data); 23 | 24 | // Show modal and let user choose IP address 25 | var modal = document.getElementById("ipSelector"); 26 | var span = document.getElementsByClassName("close")[0]; 27 | 28 | // Populate IP list 29 | var ipListDiv = document.getElementById("ip-list"); 30 | ipListDiv.innerHTML = ''; 31 | data.forEach((ipAddress, index) => { 32 | var ipElement = document.createElement("div"); 33 | ipElement.innerHTML = ipAddress; 34 | ipElement.onclick = function () { 35 | var option = index + 1; // store the index in option variable, +1 to make it 1-based 36 | socket.emit('nexttrace_options_choice', {"choice": option}); // emit the choice 37 | modal.style.display = "none"; 38 | }; 39 | ipListDiv.appendChild(ipElement); 40 | }); 41 | 42 | // Show modal 43 | modal.style.display = "block"; 44 | 45 | // When user clicks on close, hide the modal 46 | span.onclick = function () { 47 | modal.style.display = "none"; 48 | }; 49 | 50 | // When user clicks outside of the modal, close it 51 | modal.onclick = function (event) { 52 | if (event.target === modal) { 53 | modal.style.display = "none"; 54 | } 55 | }; 56 | }); 57 | 58 | async function startNexttrace() { 59 | var params = document.getElementById("params").value; 60 | stopNexttrace() 61 | // 重置表格 62 | initTable(); 63 | localStorage.setItem("ipVersion", document.getElementById("ipVersion").value); 64 | localStorage.setItem("protocol", document.getElementById("protocol").value); 65 | var extraSettings = getFormattedSettings(); 66 | 67 | // 使用 await 来等待 parseDomain 函数的结果 68 | var ip = await parseDomain(params) 69 | console.log('要trace的ip/domain:', ip) 70 | 71 | if (ip == null) { 72 | document.getElementById("params").placeholder = "Invalid input or unresolvable domain"; 73 | console.log('Invalid input or unresolvable domain'); 74 | alert('Invalid input or unresolvable domain') 75 | } else { 76 | console.log('begin -> ', 'dst:', ip, 'settingsString:', extraSettings); 77 | socket.emit('start_nexttrace', {ip: ip, extra: extraSettings}); 78 | } 79 | } 80 | 81 | function stopNexttrace() { 82 | dataMap = {} 83 | socket.emit('stop_nexttrace'); 84 | } 85 | 86 | function mergeDataAndAddOrUpdateRow(table, cells) { 87 | var parsedData = JSON.parse(cells); // 解析接收到的JSON列表 88 | var hop = parsedData[0]; 89 | var latency = parseFloat(parsedData[3]); 90 | var latencyLast = latency; // 初始化最新一次的 latency 值 91 | 92 | if (hop in dataMap) { 93 | // 如果存在相同 hop 的数据,则更新已有行的数据 94 | var rowToUpdate = dataMap[hop].row; 95 | // console.log("rowToUpdate:", rowToUpdate); 96 | var latencyLastCell = rowToUpdate.querySelector('.latency_last'); 97 | var latencyAvgCell = rowToUpdate.querySelector('.latency_avg'); 98 | var sentCell = rowToUpdate.querySelector('.sent'); 99 | var lossPktRateCell = rowToUpdate.querySelector('.lossPktRate'); 100 | 101 | var ipCell = rowToUpdate.querySelector('.ip'); 102 | var ipList = ipCell.textContent.split('\n'); 103 | if (/\S/.test(parsedData[1]) && !ipList.includes(parsedData[1])) { 104 | if (ipCell.textContent !== '') { 105 | ipCell.textContent += '\n' + parsedData[1]; 106 | } else { 107 | ipCell.textContent = parsedData[1]; 108 | } 109 | } 110 | 111 | if (/\S/.test(parsedData[4])) { 112 | rowToUpdate.querySelector('.asn').textContent = parsedData[4]; 113 | } 114 | if (/\S/.test(parsedData[5])) { 115 | rowToUpdate.querySelector('.location').textContent = parsedData[5]; 116 | } 117 | if (/\S/.test(parsedData[6])) { 118 | rowToUpdate.querySelector('.domain').textContent = parsedData[6]; 119 | } 120 | var latencyBestCell = rowToUpdate.querySelector('.latency_best'); 121 | var latencyWorstCell = rowToUpdate.querySelector('.latency_worst'); 122 | var latencyStdCell = rowToUpdate.querySelector('.latency_std'); 123 | 124 | var data = dataMap[hop].data; 125 | if (latency !== 0 && !isNaN(latency)) { 126 | data.latencyList.push(latency); 127 | // 更新数据 128 | data.count++; 129 | data.latencySum += latency; 130 | latencyAvg = data.latencySum / data.count; 131 | latencyLast = latency; // 更新最新一次的 latency 值 132 | // 更新单元格内容 133 | latencyLastCell.textContent = latencyLast.toFixed(2); 134 | latencyAvgCell.textContent = latencyAvg.toFixed(2); 135 | sentCell.textContent = data.count + data.lossPktSum; 136 | latencyBestCell.textContent = Math.min.apply(null, data.latencyList).toFixed(2); 137 | latencyWorstCell.textContent = Math.max.apply(null, data.latencyList).toFixed(2); 138 | 139 | // 添加这些行来设置背景颜色 140 | var colorForLast = getRGB(latencyLast); 141 | latencyLastCell.style.backgroundColor = 'rgb(' + colorForLast['r'] + ',' + colorForLast['g'] + ',' + colorForLast['b'] + ')'; 142 | var colorForAvg = getRGB(latencyAvg); 143 | latencyAvgCell.style.backgroundColor = 'rgb(' + colorForAvg['r'] + ',' + colorForAvg['g'] + ',' + colorForAvg['b'] + ')'; 144 | var colorForBest = getRGB(Math.min.apply(null, data.latencyList)); 145 | latencyBestCell.style.backgroundColor = 'rgb(' + colorForBest['r'] + ',' + colorForBest['g'] + ',' + colorForBest['b'] + ')'; 146 | var colorForWorst = getRGB(Math.max.apply(null, data.latencyList)); 147 | latencyWorstCell.style.backgroundColor = 'rgb(' + colorForWorst['r'] + ',' + colorForWorst['g'] + ',' + colorForWorst['b'] + ')'; 148 | 149 | var latencyStd = 0; 150 | data.latencyList.forEach(function (latency) { 151 | latencyStd += Math.pow(latency - latencyAvg, 2); 152 | }); 153 | latencyStd = Math.sqrt(latencyStd / data.count); 154 | latencyStdCell.textContent = latencyStd.toFixed(2); 155 | var colorForStd = getRGBstdev(latencyStd); 156 | latencyStdCell.style.backgroundColor = 'rgb(' + colorForStd['r'] + ',' + colorForStd['g'] + ',' + colorForStd['b'] + ')'; 157 | 158 | } else { 159 | latencyLastCell.textContent = '-' 160 | data.lossPktSum++; 161 | lossPktRateCell.textContent = String(Math.round((100 * data.lossPktSum / (data.lossPktSum + data.count)) * 10) / 10); 162 | lossPktRateCell.style.backgroundColor = getLossColor(100 * data.lossPktSum / (data.lossPktSum + data.count)); 163 | sentCell.textContent = data.count + data.lossPktSum; 164 | } 165 | 166 | var rdnsCell = rowToUpdate.querySelector('.rdns'); 167 | var rdnsList = rdnsCell.textContent.split('\n'); 168 | if (/\S/.test(parsedData[2]) && !rdnsList.includes(parsedData[2])) { 169 | if (rdnsCell.textContent !== '') { 170 | rdnsCell.textContent += '\n' + parsedData[2]; 171 | } else { 172 | rdnsCell.textContent = parsedData[2]; 173 | } 174 | } 175 | 176 | 177 | } else { 178 | if (latency !== 0 && !isNaN(latency)) { 179 | var data = { 180 | count: 1, 181 | latencySum: latency, 182 | lossPktSum: 0, 183 | latencyList: [latency] 184 | }; 185 | var latencyAvg = latency; 186 | dataMap[hop] = { 187 | data: data, 188 | row: addDataRow(table, parsedData, latencyLast.toFixed(2), latencyAvg.toFixed(2), 1, 0) 189 | }; 190 | } else { 191 | var data = { 192 | count: 0, 193 | latencySum: 0, 194 | lossPktSum: 1, 195 | latencyList: [] 196 | }; 197 | dataMap[hop] = { 198 | data: data, 199 | row: addDataRow(table, parsedData, '-', '-', 0, 1) 200 | }; 201 | } 202 | 203 | } 204 | sortTableRows(table); 205 | } 206 | 207 | function sortTableRows(table) { 208 | var tbody = table.getElementsByTagName('tbody')[0]; 209 | var rows = Array.prototype.slice.call(tbody.getElementsByTagName('tr'), 0); 210 | 211 | // 按照第一列(索引为0)的数字大小排序 212 | rows.sort(function (a, b) { 213 | var aValue = parseInt(a.cells[0].textContent, 10); 214 | var bValue = parseInt(b.cells[0].textContent, 10); 215 | return aValue - bValue; 216 | }); 217 | 218 | // 将排序后的行重新添加到tbody 219 | rows.forEach(function (row) { 220 | tbody.appendChild(row); 221 | }); 222 | hideEmptyRowsAfterLastWithData(tbody) 223 | } 224 | 225 | function hideEmptyRowsAfterLastWithData(tbody) { 226 | var rows = tbody.getElementsByTagName('tr'); 227 | var lastRowWithDataIndex = null; 228 | 229 | // 查找最后一个具有第二列数据的行的索引 230 | for (var i = 0; i < rows.length; i++) { 231 | if (rows[i].cells[1].textContent.trim() !== "") { 232 | lastRowWithDataIndex = i; 233 | } 234 | } 235 | for (var i = lastRowWithDataIndex + 1; i < rows.length; i++) { 236 | rows[i].style.display = 'none'; 237 | } 238 | } 239 | 240 | function addDataRow(table, cells, latencyLast, latencyAvg, count, lossPktSum) { 241 | // console.log("cells array:", cells); 242 | var tbody = table.getElementsByTagName('tbody')[0]; 243 | 244 | // 创建新行 245 | var row = document.createElement('tr'); 246 | 247 | var classNames = ['hops', 'ip', 'rdns', 'latency', 'asn', 'location', 'domain']; 248 | 249 | cells.forEach(function (cellContent, index) { 250 | if (index !== 3 && index !== 2) { 251 | var cell = document.createElement('td'); 252 | cell.textContent = cellContent; 253 | if (index <= classNames.length) { 254 | cell.className = classNames[index]; 255 | } 256 | row.appendChild(cell); 257 | } 258 | }); 259 | 260 | var lossPktRateCell = document.createElement('td'); 261 | lossPktRateCell.textContent = String(Math.round((100 * lossPktSum / (lossPktSum + count)) * 10) / 10); 262 | lossPktRateCell.className = 'lossPktRate'; 263 | row.appendChild(lossPktRateCell); 264 | 265 | var sentCell = document.createElement('td'); 266 | sentCell.textContent = count + lossPktSum; 267 | sentCell.className = 'sent'; 268 | row.appendChild(sentCell); 269 | 270 | var latencyLastCell = document.createElement('td'); 271 | latencyLastCell.textContent = latencyLast; 272 | latencyLastCell.className = 'latency_last'; 273 | row.appendChild(latencyLastCell); 274 | 275 | var latencyAvgCell = document.createElement('td'); 276 | latencyAvgCell.textContent = latencyAvg; 277 | latencyAvgCell.className = 'latency_avg'; 278 | row.appendChild(latencyAvgCell); 279 | 280 | var latencyBestCell = document.createElement('td'); 281 | latencyBestCell.textContent = latencyLast; 282 | latencyBestCell.className = 'latency_best'; 283 | row.appendChild(latencyBestCell); 284 | 285 | var latencyWorstCell = document.createElement('td'); 286 | latencyWorstCell.textContent = latencyLast; 287 | latencyWorstCell.className = 'latency_worst'; 288 | row.appendChild(latencyWorstCell); 289 | 290 | var latencyStdCell = document.createElement('td'); 291 | latencyStdCell.textContent = '0'; 292 | latencyStdCell.className = 'latency_std'; 293 | row.appendChild(latencyStdCell); 294 | 295 | var rdnsCell = document.createElement('td'); 296 | rdnsCell.textContent = cells[2]; 297 | rdnsCell.className = 'rdns'; 298 | row.appendChild(rdnsCell); 299 | 300 | // 将新行插入到表格最后 301 | tbody.appendChild(row); 302 | return row; 303 | } 304 | 305 | function handleKeyPress(event) { 306 | if (event.keyCode === 13) { // 按下回车键的键码是 13 307 | event.preventDefault(); // 阻止默认的回车键行为 308 | startNexttrace(); // 调用 startNexttrace() 函数 309 | } 310 | } 311 | 312 | function getRGB(latency) { 313 | var result = []; 314 | result ['r'] = 0; 315 | result ['g'] = 0; 316 | result ['b'] = 0; 317 | if (isNaN(latency) || latency === 0) { 318 | return result; 319 | } 320 | var color_r = Math.round((latency - 180) / 2); 321 | //var color_r = Math.round ( 0.000001 * Math.pow ( latency - 150, 3.3 ) ); 322 | if (color_r < 0) color_r = 0; 323 | if (color_r > 100) color_r = 100; 324 | 325 | //var color_g = Math.round ( ( 200 - latency / 1.2 ) ); 326 | // https://www.desmos.com/calculator 327 | // y = 55 - 0.0000075 * x^3 328 | var color_g = Math.round(40 - 0.000005 * Math.pow(latency, 3)); 329 | if (color_g < 0) color_g = 0; 330 | if (color_g > 40) color_g = 40; 331 | var color_b = 0; 332 | result ['r'] = color_r; 333 | result ['g'] = color_g; 334 | result ['b'] = color_b; 335 | return result; 336 | } 337 | 338 | function getRGBstdev(stdev) { 339 | var result = []; 340 | result ['r'] = 0; 341 | result ['g'] = 0; 342 | result ['b'] = 0; 343 | if (isNaN(stdev) || stdev === 0) { 344 | return result; 345 | } 346 | var color_r = Math.round((stdev - 5) * 4); 347 | if (color_r < 0) color_r = 0; 348 | if (color_r > 100) color_r = 100; 349 | var color_g = 0; 350 | var color_b = 0; 351 | result ['r'] = color_r; 352 | result ['g'] = color_g; 353 | result ['b'] = color_b; 354 | return result; 355 | } 356 | 357 | function getLossColor(loss) { 358 | var colorLossR = Math.round(Math.pow(loss, 1.6) + 10); 359 | if (colorLossR < 11) colorLossR = 0; 360 | if (colorLossR > 160) colorLossR = 160; 361 | return 'rgba(' + colorLossR + ',0,0,1)'; 362 | } 363 | 364 | function resetForm() { 365 | stopNexttrace() 366 | // 重置输入框 367 | document.getElementById("params").value = ""; 368 | // 重置表格 369 | initTable(); 370 | } 371 | 372 | function initTable() { 373 | // 清空动态添加的表格行 374 | var tableBody = document.querySelector("#output tbody"); 375 | tableBody.innerHTML = ` 376 | HOP 377 | IP 378 | ASN 379 | LOCATION 380 | DOMAIN 381 | LOSS% 382 | SENT 383 | LAST 384 | AVG 385 | BEST 386 | WORST 387 | STDEV 388 | PTR 389 | 390 | `; 391 | } 392 | 393 | function getValueFromLocalStorage(key) { 394 | var _value = localStorage.getItem(key); 395 | return _value ? _value : null; 396 | } 397 | 398 | function getFormattedSettings() { 399 | var settings = { 400 | ipVersion: getValueFromLocalStorage("ipVersion"), 401 | protocol: getValueFromLocalStorage("protocol"), 402 | language: getValueFromLocalStorage("language"), 403 | intervalSeconds: getValueFromLocalStorage("intervalSeconds"), 404 | packetSize: getValueFromLocalStorage("packetSize"), 405 | maxHop: getValueFromLocalStorage("maxHop"), 406 | minHop: getValueFromLocalStorage("minHop"), 407 | port: getValueFromLocalStorage("port"), 408 | dataProvider: getValueFromLocalStorage("dataProvider"), 409 | device: getValueFromLocalStorage("device") 410 | }; 411 | 412 | // 将设置对象转换为JSON字符串 413 | return JSON.stringify(settings); 414 | } 415 | 416 | function fetchWithTimeout(url, options, timeout = 3000) { 417 | return Promise.race([ 418 | fetch(url, options), 419 | new Promise((_, reject) => 420 | setTimeout(() => reject(new Error('请求超时')), timeout) 421 | ) 422 | ]); 423 | } 424 | 425 | function resolveDomain(domain) { 426 | return new Promise((resolve, reject) => { 427 | var ipVersion = getValueFromLocalStorage("ipVersion"); 428 | var types = []; 429 | // 根据ipVersion决定查询类型 430 | if (ipVersion === 'ipv6') { 431 | types = ['AAAA']; // 只查询IPv6 432 | } else if (ipVersion === 'all') { 433 | types = ['AAAA', 'A']; // 查询IPv4和IPv6 434 | } else { 435 | types = ['A']; // 默认只查询IPv4 436 | } 437 | var resolvedAddresses = []; 438 | 439 | function doResolve(dnsUrl) { 440 | var promises = types.map(function (type) { 441 | return fetchWithTimeout(dnsUrl + '?name=' + domain + '&type=' + type, { 442 | headers: {'accept': 'application/dns-json'} 443 | }, 3000) // 设置超时时间为 3 秒 444 | .then(function (response) { 445 | return response.json(); 446 | }) 447 | .then(function (data) { 448 | if (data && data.Answer && data.Answer.length > 0) { 449 | for (var i = 0; i < data.Answer.length; i++) { 450 | var ipAddress = data.Answer[i].data; 451 | console.log('IP地址:', ipAddress, '类型:', type); 452 | resolvedAddresses.push(ipAddress); 453 | } 454 | } else { 455 | console.log('未能解析域名,', 'type:', type, 'domain:', domain); 456 | } 457 | }); 458 | }); 459 | 460 | return Promise.all(promises); 461 | } 462 | 463 | // 尝试使用 Cloudflare 464 | doResolve('https://cloudflare-dns.com/dns-query').catch(() => { 465 | console.log('使用 Cloudflare 失败,尝试使用 doh.sb'); 466 | return doResolve('https://doh.sb/dns-query'); 467 | }).then(() => { 468 | if (resolvedAddresses.length > 1) { 469 | // Show modal and let user choose IP address 470 | var modal = document.getElementById("ipSelector"); 471 | var span = document.getElementsByClassName("close")[0]; 472 | 473 | // Populate IP list 474 | var ipListDiv = document.getElementById("ip-list"); 475 | ipListDiv.innerHTML = ''; 476 | resolvedAddresses.forEach(ipAddress => { 477 | var ipElement = document.createElement("div"); 478 | ipElement.innerHTML = ipAddress; 479 | ipElement.onclick = function () { 480 | resolve(ipAddress); 481 | modal.style.display = "none"; 482 | }; 483 | ipListDiv.appendChild(ipElement); 484 | }); 485 | 486 | // Show modal 487 | modal.style.display = "block"; 488 | 489 | // When user clicks on close, hide the modal 490 | span.onclick = function () { 491 | modal.style.display = "none"; 492 | resolve(null); 493 | }; 494 | 495 | // When user clicks outside of the modal, close it 496 | window.onclick = function (event) { 497 | if (event.target === modal) { 498 | modal.style.display = "none"; 499 | resolve(null); 500 | } 501 | }; 502 | } else { 503 | // If there is only one IP or none, resolve immediately 504 | resolve(resolvedAddresses[0] || null); 505 | } 506 | }).catch(() => { 507 | // 在此处显示一个错误消息 508 | alert('无法解析域名,请检查你与DOH服务器的连接或尝试使用使用SERVER RESOLVE模式.'); 509 | // 弹出确认对话框 510 | var userChoice = confirm("是否切换为 SERVER RESOLVE 模式?"); 511 | // 根据用户选择执行操作 512 | if (userChoice) { 513 | // 用户点击了 “是” 514 | localStorage.setItem("localResolve", "false"); 515 | document.getElementById("localResolveCheckbox").checked = JSON.parse(localStorage.getItem("localResolve")); 516 | } else { 517 | alert('RESOLVE模式您稍后可以在Settings中更改.'); 518 | } 519 | }); 520 | }); 521 | } 522 | 523 | function parseDomain(domain) { 524 | //判断domian 是不是IPv4 525 | if ((domain.match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/)) || (domain.match(/^[a-fA-F0-9:]+$/))) { 526 | return domain; 527 | } 528 | return new Promise((resolve, reject) => { 529 | if (!domain || domain === "") { 530 | console.error("Usage: Please provide a domain/ip/url."); 531 | resolve(null); 532 | } 533 | 534 | if (domain.includes("/")) { 535 | domain = domain.split("/")[2]; 536 | } 537 | 538 | if (domain.includes("]")) { 539 | domain = domain.split("]")[0].split("[")[1]; 540 | } else if (domain.includes(":")) { 541 | if ((domain.match(/:/g) || []).length === 1) { 542 | domain = domain.split(":")[0]; 543 | } 544 | } 545 | 546 | var localResolve = getValueFromLocalStorage("localResolve"); 547 | if (localResolve === "true") { 548 | console.log("使用本地DNS解析域名:", domain); 549 | resolveDomain(domain).then(ipAddress => { 550 | if (ipAddress) { 551 | resolve(ipAddress); 552 | } else { 553 | resolve(null); 554 | } 555 | }); 556 | } else { 557 | console.log("使用服务器解析域名:", domain); 558 | resolve(domain); 559 | } 560 | }); 561 | } 562 | 563 | function deviceValidateInput() { 564 | var allowedPattern = '^[a-zA-Z]*\\d*$'; 565 | 566 | var inputElement = document.getElementById("devInput"); 567 | var errorMessageElement = document.getElementById("dev-error-message"); 568 | 569 | if (inputElement.value === "") { 570 | errorMessageElement.style.display = "none"; 571 | return true; 572 | } 573 | 574 | if (!inputElement.value.match(allowedPattern)) { 575 | // Input value is not in the allowed list 576 | errorMessageElement.style.display = "inline"; 577 | inputElement.value = ""; // Optionally clear the input 578 | return false; 579 | } else { 580 | // Input is valid, hide the error message if it's showing 581 | errorMessageElement.style.display = "none"; 582 | return true; 583 | } 584 | } 585 | 586 | function dataProviderValidateInput() { 587 | var allowedValues = [ 588 | "Ip2region", "ip2region", "IP.SB", "ip.sb", "IPInfo", "ipinfo", 589 | "IPInsight", "ipinsight", "IPAPI.com", "ip-api.com", "IPInfoLocal", 590 | "ipinfolocal", "chunzhen", "LeoMoeAPI", "leomoeapi", "disable-geoip" 591 | ]; 592 | 593 | var inputElement = document.getElementById("dataProvider"); 594 | var errorMessageElement = document.getElementById("dp-error-message"); 595 | 596 | if (inputElement.value === "") { 597 | errorMessageElement.style.display = "none"; 598 | return true; 599 | } 600 | 601 | if (allowedValues.indexOf(inputElement.value) === -1) { 602 | // Input value is not in the allowed list 603 | errorMessageElement.style.display = "inline"; 604 | inputElement.value = ""; // Optionally clear the input 605 | return false; 606 | } else { 607 | // Input is valid, hide the error message if it's showing 608 | errorMessageElement.style.display = "none"; 609 | return true; 610 | } 611 | } 612 | 613 | -------------------------------------------------------------------------------- /assets/js/settingsmenu.js: -------------------------------------------------------------------------------- 1 | var settingBtn = document.getElementById("settingBtn"); 2 | var settingMenu = document.getElementById("settingMenu"); 3 | var saveBtn = document.getElementById("saveBtn"); 4 | 5 | settingBtn.addEventListener("click", function (event) { 6 | event.preventDefault(); // 阻止按钮默认的提交行为 7 | settingMenu.style.display = "block"; 8 | }); 9 | 10 | document.addEventListener("click", function (event) { 11 | var target = event.target; 12 | if (!settingMenu.contains(target) && target !== settingBtn) { 13 | settingMenu.style.display = "none"; 14 | } 15 | }); 16 | var intervalTimeRange = document.getElementById("intervalTimeRange"); 17 | var intervalTimeInput = document.getElementById("intervalTimeInput"); 18 | // 拖动滑块时更新输入框的值 19 | intervalTimeRange.addEventListener("input", function () { 20 | intervalTimeInput.value = intervalTimeRange.value; 21 | }); 22 | // 输入框值变化时更新拖动滑块的值 23 | intervalTimeInput.addEventListener("input", function () { 24 | intervalTimeRange.value = intervalTimeInput.value; 25 | }); 26 | var packetSizeRange = document.getElementById("packetSizeRange"); 27 | var packetSizeInput = document.getElementById("packetSizeInput"); 28 | // 拖动滑块时更新输入框的值 29 | packetSizeRange.addEventListener("input", function () { 30 | packetSizeInput.value = packetSizeRange.value; 31 | }); 32 | // 输入框值变化时更新拖动滑块的值 33 | packetSizeInput.addEventListener("input", function () { 34 | packetSizeRange.value = packetSizeInput.value; 35 | }); 36 | 37 | saveBtn.addEventListener("click", function (event) { 38 | event.preventDefault(); // 阻止按钮默认的提交行为 39 | var stat0 = deviceValidateInput(); 40 | var stat1 = dataProviderValidateInput(); 41 | if (!(stat0 && stat1)) { 42 | return; 43 | } 44 | // Save settings to localStorage 45 | localStorage.setItem("language", document.getElementById("language").value); 46 | localStorage.setItem("intervalSeconds", document.getElementById("intervalTimeInput").value); 47 | localStorage.setItem("packetSize", document.getElementById("packetSizeInput").value); 48 | localStorage.setItem("maxHop", document.getElementById("maxHopInput").value); 49 | localStorage.setItem("minHop", document.getElementById("minHopInput").value); 50 | localStorage.setItem("port", document.getElementById("portInput").value); 51 | localStorage.setItem("device", document.getElementById("devInput").value); 52 | localStorage.setItem("dataProvider", document.getElementById("dataProvider").value); 53 | localStorage.setItem("localResolve", document.getElementById("localResolveCheckbox").checked); 54 | 55 | settingMenu.style.display = "none"; 56 | }); 57 | document.addEventListener("DOMContentLoaded", async function (event) { 58 | // Check if localResolve is in localStorage 59 | if (localStorage.getItem("localResolve") === null) { 60 | // If not, set the default value to true 61 | localStorage.setItem("localResolve", true); 62 | } 63 | // Set the checkbox state based on the localStorage value 64 | document.getElementById("localResolveCheckbox").checked = JSON.parse(localStorage.getItem("localResolve")); 65 | 66 | // Load settings from localStorage 67 | if (localStorage.getItem("protocol")) { 68 | document.getElementById("protocol").value = localStorage.getItem("protocol"); 69 | } 70 | if (localStorage.getItem("language")) { 71 | document.getElementById("language").value = localStorage.getItem("language"); 72 | } 73 | if (localStorage.getItem("intervalSeconds")) { 74 | var intervalSeconds = localStorage.getItem("intervalSeconds"); 75 | document.getElementById("intervalTimeInput").value = intervalSeconds; 76 | document.getElementById("intervalTimeRange").value = intervalSeconds; 77 | } 78 | if (localStorage.getItem("packetSize")) { 79 | var packetSize = localStorage.getItem("packetSize"); 80 | document.getElementById("packetSizeInput").value = packetSize; 81 | document.getElementById("packetSizeRange").value = packetSize; 82 | } 83 | if (localStorage.getItem("maxHop")) { 84 | document.getElementById("maxHopInput").value = localStorage.getItem("maxHop"); 85 | } 86 | if (localStorage.getItem("minHop")) { 87 | document.getElementById("minHopInput").value = localStorage.getItem("minHop"); 88 | } 89 | if (localStorage.getItem("port")) { 90 | document.getElementById("portInput").value = localStorage.getItem("port"); 91 | } 92 | if (localStorage.getItem("device")) { 93 | document.getElementById("devInput").value = localStorage.getItem("device"); 94 | } 95 | if (localStorage.getItem("dataProvider")) { 96 | document.getElementById("dataProvider").value = localStorage.getItem("dataProvider"); 97 | } 98 | if (localStorage.getItem("localResolve")) { 99 | document.getElementById("localResolveCheckbox").checked = JSON.parse(localStorage.getItem("localResolve")); 100 | } 101 | const urlParams = new URLSearchParams(window.location.search); 102 | const trace = urlParams.get('trace'); 103 | if (trace) { 104 | document.getElementById('params').value = trace; 105 | try { 106 | await startNexttrace(); 107 | console.log('startNexttrace function has completed'); 108 | } catch (error) { 109 | console.error('An error occurred:', error); 110 | } 111 | } 112 | }); 113 | -------------------------------------------------------------------------------- /entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | python3 -u app.py & 4 | 5 | # 设置默认值 6 | HOSTPORT="${1:-30080}" 7 | 8 | # 检查HOSTPORT是否只包含端口号 9 | LISTEN_DIRECTIVE="listen ${HOSTPORT}" 10 | 11 | # 修改nginx.conf文件 12 | sed -i "s/listen 30080;/${LISTEN_DIRECTIVE};/" /etc/nginx/nginx.conf 13 | if [ -n "$1" ]; then 14 | sed -i "/listen \[::\]:30080/d" /etc/nginx/nginx.conf 15 | fi 16 | # 启动nginx 17 | exec nginx -g 'daemon off;' 18 | -------------------------------------------------------------------------------- /nginx.conf: -------------------------------------------------------------------------------- 1 | worker_processes 1; 2 | 3 | events { 4 | worker_connections 1024; 5 | multi_accept on; 6 | } 7 | 8 | http { 9 | map $http_upgrade $connection_upgrade { 10 | default upgrade; 11 | '' close; 12 | } 13 | 14 | upstream app { 15 | server 127.0.0.1:35000; 16 | } 17 | 18 | server { 19 | listen 30080; 20 | listen [::]:30080; 21 | location / { 22 | proxy_set_header Host $http_host; 23 | proxy_set_header X-Real-IP $remote_addr; 24 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 25 | proxy_set_header X-Forwarded-Proto $scheme; 26 | 27 | proxy_pass http://app; 28 | } 29 | location /socket.io { 30 | proxy_set_header Host $http_host; 31 | proxy_set_header X-Real-IP $remote_addr; 32 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 33 | proxy_set_header X-Forwarded-Proto $scheme; 34 | 35 | proxy_http_version 1.1; 36 | proxy_buffering off; 37 | proxy_set_header Upgrade $http_upgrade; 38 | proxy_set_header Connection "Upgrade"; 39 | proxy_redirect off; 40 | 41 | proxy_pass http://app/socket.io; 42 | } 43 | location /favicon.ico { 44 | proxy_pass http://app/assets/favicon.ico; 45 | } 46 | access_log /dev/stdout; 47 | error_log /dev/stderr; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Flask-SocketIO==5.5.1 2 | Flask==3.1.0 3 | eventlet~=0.33.3 4 | -------------------------------------------------------------------------------- /templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | NextTrace Web 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |

NextTrace Web

13 |
14 | 17 | 18 | 23 | 24 | 29 | 30 | 31 | 32 | 33 |
34 | 35 | 39 |
40 | 41 |
42 | 43 | 44 |
45 |
46 | 47 |
48 | 49 | 50 |
51 |
52 | 53 | 54 |
55 | 56 | 57 |
58 | 59 | 60 |
61 | 62 | 63 | 64 |
65 | 66 | 67 | 68 | 78 | 79 |
80 | 84 |
85 | 86 |
87 | 92 |
93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 |
HOPIPASNLOCATIONDOMAINLOSS%SENTLASTAVGBESTWORSTSTDEVPTR
114 | 115 | 116 | --------------------------------------------------------------------------------