mirror of
https://github.com/cesanta/mongoose.git
synced 2026-11-08 16:11:18 +00:00
Compare commits
96
Commits
7.23
..
c2d95cc19b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2d95cc19b | ||
|
|
4aa0a243f9 | ||
|
|
65a7996ef9 | ||
|
|
5879c3cbf2 | ||
|
|
cf9d56be79 | ||
|
|
da82df2041 | ||
|
|
954eb07b6d | ||
|
|
d7e708b9bc | ||
|
|
ce35cbf586 | ||
|
|
3aa5f2a1fd | ||
|
|
1b0906510b | ||
|
|
8a116d9289 | ||
|
|
71e0176944 | ||
|
|
bba5a0ca3a | ||
|
|
9c388b5f19 | ||
|
|
8afa940acf | ||
|
|
df1a409b21 | ||
|
|
7ec403341c | ||
|
|
8e0c765c2c | ||
|
|
883e0a981f | ||
|
|
ff1fb5c745 | ||
|
|
795f16d5fb | ||
|
|
51773ecea3 | ||
|
|
2834aa57ee | ||
|
|
e2b5d7175f | ||
|
|
a419e16f26 | ||
|
|
789372c5b3 | ||
|
|
81f6acbce7 | ||
|
|
7fa96f3a38 | ||
|
|
876cf5605f | ||
|
|
8df146b1b8 | ||
|
|
f62f3545b4 | ||
|
|
4d6fa4b91c | ||
|
|
1be11a66e3 | ||
|
|
d1060d247b | ||
|
|
002c9df3de | ||
|
|
fa34b7439a | ||
|
|
60c75a22b8 | ||
|
|
bbee8ae61f | ||
|
|
9173c8dfda | ||
|
|
b93cbbeb13 | ||
|
|
aa1dfe8000 | ||
|
|
e8a82d1821 | ||
|
|
201a81a315 | ||
|
|
aae31aba9c | ||
|
|
29aa53cebd | ||
|
|
5d4fffbb14 | ||
|
|
ed5ef09d1c | ||
|
|
1e99974b83 | ||
|
|
6814b44b03 | ||
|
|
7e9ddc2d09 | ||
|
|
c13d5d7a56 | ||
|
|
555c5a76be | ||
|
|
863aea34c4 | ||
|
|
830f6c589b | ||
|
|
cc64c41737 | ||
|
|
4660f2ca0f | ||
|
|
ffcad7ee47 | ||
|
|
09a97b915a | ||
|
|
35a9242b67 | ||
|
|
5c34018899 | ||
|
|
c857ddae57 | ||
|
|
830acc19ee | ||
|
|
f87d439710 | ||
|
|
86adf12a77 | ||
|
|
a561f3e096 | ||
|
|
2b0a5e9701 | ||
|
|
8346a60971 | ||
|
|
140fa6cebf | ||
|
|
cd05b162a8 | ||
|
|
3fde04137c | ||
|
|
5591b7d131 | ||
|
|
9ddac8faa7 | ||
|
|
9123330f72 | ||
|
|
b938728c2a | ||
|
|
fab922230c | ||
|
|
90418ffb1b | ||
|
|
5a317e81d9 | ||
|
|
7e8c3a59e2 | ||
|
|
6093ac12a0 | ||
|
|
e7cfaa70c7 | ||
|
|
897d26edfb | ||
|
|
6b5d358ede | ||
|
|
0d97280af4 | ||
|
|
afc84b7c92 | ||
|
|
66bf5952a4 | ||
|
|
f002c30cbb | ||
|
|
53d2356472 | ||
|
|
e312219e80 | ||
|
|
2aff813795 | ||
|
|
9c4506763b | ||
|
|
ec3b9e7c4f | ||
|
|
ddd9651f91 | ||
|
|
304ea2a649 | ||
|
|
83bac34094 | ||
|
|
9c6b4edd37 |
No files matched your search
@@ -1,16 +1,42 @@
|
||||
name: Claude Full Codebase Security Scan
|
||||
name: Claude Codebase Security Scan
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
prompt_path:
|
||||
description: "Path to the repo prompt file Claude should read"
|
||||
required: true
|
||||
default: "resources/specs/claude-security-scan.md"
|
||||
target_ref:
|
||||
description: "Branch, tag, or SHA to scan"
|
||||
required: false
|
||||
default: ""
|
||||
common_misc:
|
||||
description: "Run common/misc security scan"
|
||||
required: false
|
||||
type: boolean
|
||||
default: true
|
||||
mongoose_core:
|
||||
description: "Run Mongoose core security scan"
|
||||
required: false
|
||||
type: boolean
|
||||
default: true
|
||||
web_http_auth:
|
||||
description: "Run web/HTTP/auth security scan"
|
||||
required: false
|
||||
type: boolean
|
||||
default: true
|
||||
tls:
|
||||
description: "Run TLS security scan"
|
||||
required: false
|
||||
type: boolean
|
||||
default: true
|
||||
net_builtin:
|
||||
description: "Run built-in network security scan"
|
||||
required: false
|
||||
type: boolean
|
||||
default: true
|
||||
protocols:
|
||||
description: "Run protocol security scan"
|
||||
required: false
|
||||
type: boolean
|
||||
default: true
|
||||
#schedule:
|
||||
# Weekly scan: Sunday 02:00 UTC
|
||||
# - cron: "0 2 * * 0"
|
||||
@@ -20,53 +46,140 @@ permissions:
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: claude-full-codebase-security-scan-${{ github.ref }}
|
||||
group: claude-security-scans
|
||||
cancel-in-progress: false
|
||||
queue: max
|
||||
|
||||
jobs:
|
||||
scan:
|
||||
name: Full codebase security scan
|
||||
prepare:
|
||||
name: Prepare selected scan matrix
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
|
||||
env:
|
||||
DEFAULT_PROMPT_PATH: "resources/specs/claude-security-scan.md"
|
||||
outputs:
|
||||
target_ref: ${{ steps.plan.outputs.target_ref }}
|
||||
matrix: ${{ steps.plan.outputs.matrix }}
|
||||
has_scans: ${{ steps.plan.outputs.has_scans }}
|
||||
|
||||
steps:
|
||||
- name: Resolve scan inputs
|
||||
id: vars
|
||||
- name: Resolve scan inputs and build matrix
|
||||
id: plan
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
PROMPT_PATH="${{ inputs.prompt_path }}"
|
||||
TARGET_REF="${{ inputs.target_ref }}"
|
||||
RUN_COMMON_MISC="${{ inputs.common_misc }}"
|
||||
RUN_MONGOOSE_CORE="${{ inputs.mongoose_core }}"
|
||||
RUN_WEB_HTTP_AUTH="${{ inputs.web_http_auth }}"
|
||||
RUN_TLS="${{ inputs.tls }}"
|
||||
RUN_NET_BUILTIN="${{ inputs.net_builtin }}"
|
||||
RUN_PROTOCOLS="${{ inputs.protocols }}"
|
||||
else
|
||||
PROMPT_PATH="${DEFAULT_PROMPT_PATH}"
|
||||
TARGET_REF=""
|
||||
RUN_COMMON_MISC="true"
|
||||
RUN_MONGOOSE_CORE="true"
|
||||
RUN_WEB_HTTP_AUTH="true"
|
||||
RUN_TLS="true"
|
||||
RUN_NET_BUILTIN="true"
|
||||
RUN_PROTOCOLS="true"
|
||||
fi
|
||||
|
||||
if [ -z "$TARGET_REF" ]; then
|
||||
TARGET_REF="${{ github.ref }}"
|
||||
fi
|
||||
|
||||
echo "prompt_path=$PROMPT_PATH" >> "$GITHUB_OUTPUT"
|
||||
echo "target_ref=$TARGET_REF" >> "$GITHUB_OUTPUT"
|
||||
MATRIX="$(jq -cn \
|
||||
--arg common_misc "$RUN_COMMON_MISC" \
|
||||
--arg mongoose_core "$RUN_MONGOOSE_CORE" \
|
||||
--arg web_http_auth "$RUN_WEB_HTTP_AUTH" \
|
||||
--arg tls "$RUN_TLS" \
|
||||
--arg net_builtin "$RUN_NET_BUILTIN" \
|
||||
--arg protocols "$RUN_PROTOCOLS" \
|
||||
'{
|
||||
include: ([
|
||||
{
|
||||
enabled: ($common_misc == "true"),
|
||||
area: "common_misc",
|
||||
display_name: "Common / Misc",
|
||||
area_prompt: "resources/specs/areas/common_misc.md"
|
||||
},
|
||||
{
|
||||
enabled: ($mongoose_core == "true"),
|
||||
area: "mongoose_core",
|
||||
display_name: "Mongoose Core",
|
||||
area_prompt: "resources/specs/areas/mongoose_core.md"
|
||||
},
|
||||
{
|
||||
enabled: ($web_http_auth == "true"),
|
||||
area: "web_http_auth",
|
||||
display_name: "Web / HTTP / Auth",
|
||||
area_prompt: "resources/specs/areas/web_http_auth.md"
|
||||
},
|
||||
{
|
||||
enabled: ($tls == "true"),
|
||||
area: "tls",
|
||||
display_name: "TLS",
|
||||
area_prompt: "resources/specs/areas/tls.md"
|
||||
},
|
||||
{
|
||||
enabled: ($net_builtin == "true"),
|
||||
area: "net_builtin",
|
||||
display_name: "Built-In Network",
|
||||
area_prompt: "resources/specs/areas/net_builtin.md"
|
||||
},
|
||||
{
|
||||
enabled: ($protocols == "true"),
|
||||
area: "protocols",
|
||||
display_name: "Protocols",
|
||||
area_prompt: "resources/specs/areas/protocols.md"
|
||||
}
|
||||
] | map(select(.enabled)) | map(del(.enabled)))
|
||||
}'
|
||||
)"
|
||||
|
||||
HAS_SCANS="$(jq -r '.include | length > 0' <<< "$MATRIX")"
|
||||
|
||||
echo "target_ref=$TARGET_REF" >> "$GITHUB_OUTPUT"
|
||||
echo "matrix=$MATRIX" >> "$GITHUB_OUTPUT"
|
||||
echo "has_scans=$HAS_SCANS" >> "$GITHUB_OUTPUT"
|
||||
|
||||
scan:
|
||||
name: ${{ matrix.display_name }} security scan
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.has_scans == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
max-parallel: 1
|
||||
matrix: ${{ fromJSON(needs.prepare.outputs.matrix) }}
|
||||
|
||||
env:
|
||||
MASTER_PROMPT_PATH: "resources/specs/claude-security-scan.md"
|
||||
FILTERING_PROMPT_PATH: "resources/specs/claude-false-positive-filtering.md"
|
||||
SCAN_AREA: ${{ matrix.area }}
|
||||
AREA_PROMPT_PATH: ${{ matrix.area_prompt }}
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ steps.vars.outputs.target_ref }}
|
||||
ref: ${{ needs.prepare.outputs.target_ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Verify prompt file exists
|
||||
- name: Verify required prompt files exist
|
||||
shell: bash
|
||||
run: |
|
||||
test -f "${{ steps.vars.outputs.prompt_path }}" || {
|
||||
echo "Prompt file not found: ${{ steps.vars.outputs.prompt_path }}"
|
||||
exit 1
|
||||
}
|
||||
for prompt_file in "$MASTER_PROMPT_PATH" "$AREA_PROMPT_PATH" "$FILTERING_PROMPT_PATH"; do
|
||||
test -f "$prompt_file" || {
|
||||
echo "Required prompt file not found: $prompt_file"
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
|
||||
- name: Run Claude full codebase security scan
|
||||
- name: Run Claude ${{ matrix.display_name }} security scan
|
||||
id: claude_scan
|
||||
uses: anthropics/claude-code-action@v1
|
||||
timeout-minutes: 30
|
||||
@@ -75,19 +188,21 @@ jobs:
|
||||
|
||||
prompt: |
|
||||
REPO: ${{ github.repository }}
|
||||
REF: ${{ steps.vars.outputs.target_ref }}
|
||||
PROMPT_FILE: ${{ steps.vars.outputs.prompt_path }}
|
||||
REF: ${{ needs.prepare.outputs.target_ref }}
|
||||
MASTER_PROMPT_FILE: ${{ env.MASTER_PROMPT_PATH }}
|
||||
SCAN_AREA: ${{ matrix.area }}
|
||||
AREA_PROMPT_FILE: ${{ matrix.area_prompt }}
|
||||
FILTERING_PROMPT_FILE: ${{ env.FILTERING_PROMPT_PATH }}
|
||||
|
||||
You are running a full-codebase security scan in GitHub Actions.
|
||||
You are running a focused security scan for the assigned area in GitHub Actions.
|
||||
|
||||
First, read the main prompt file at:
|
||||
${{ steps.vars.outputs.prompt_path }}
|
||||
First, read the master prompt at ${{ env.MASTER_PROMPT_PATH }}.
|
||||
Then read the assigned area prompt at ${{ matrix.area_prompt }}.
|
||||
Read the false-positive filtering prompt at ${{ env.FILTERING_PROMPT_PATH }} as required by the master prompt.
|
||||
|
||||
Treat that file as the authoritative security-review instruction set. You will also
|
||||
read and analyze additional prompt files mentioned in the main prompt file by their absolute paths in the repo,
|
||||
as per the instructions found in it.
|
||||
Perform the security review for the ${{ matrix.area }} area. Follow relevant supporting code when necessary, but do not independently scan unrelated areas.
|
||||
Return only the JSON required by the master prompt.
|
||||
|
||||
Scan the checked-out repository as a whole codebase.
|
||||
Do not modify files.
|
||||
Do not create commits.
|
||||
Do not open pull requests.
|
||||
@@ -106,8 +221,8 @@ jobs:
|
||||
set -u
|
||||
mkdir -p private-scan-results
|
||||
TODAY="$(date -u +%Y%m%d)"
|
||||
EXECUTION_OUTPUT_FILE="claude-execution-output_${TODAY}.json"
|
||||
FINDINGS_FILE="security-findings_${TODAY}.json"
|
||||
EXECUTION_OUTPUT_FILE="claude-execution-output_${SCAN_AREA}_${TODAY}.json"
|
||||
FINDINGS_FILE="security-findings_${SCAN_AREA}_${TODAY}.json"
|
||||
|
||||
HAS_EXECUTION_OUTPUT="false"
|
||||
HAS_JSON_FINDINGS="false"
|
||||
@@ -177,5 +292,5 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git commit -m "Add security scan results ${{ steps.prepare_outputs.outputs.date_suffix }}"
|
||||
git commit -m "Add ${SCAN_AREA} security scan results ${{ steps.prepare_outputs.outputs.date_suffix }}"
|
||||
git push
|
||||
@@ -1,9 +1,6 @@
|
||||
name: Claude PR Security Review
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened]
|
||||
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
pr_number:
|
||||
@@ -22,7 +19,7 @@ permissions:
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: claude-pr-security-review-${{ github.event.pull_request.number || inputs.pr_number }}
|
||||
group: claude-pr-security-review-${{ inputs.pr_number }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
@@ -33,7 +30,7 @@ jobs:
|
||||
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number || inputs.pr_number }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
|
||||
steps:
|
||||
- name: Resolve workflow variables
|
||||
|
||||
@@ -116,6 +116,26 @@ jobs:
|
||||
cat log
|
||||
test/health.awk < log > json
|
||||
scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/${{ matrix.target }}_${{ matrix.cc }}_${{ matrix.ssl }}_$(date +"%Y%m%d").json"
|
||||
|
||||
miprtx:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
ssl: ["", BUILTIN]
|
||||
name: MIP RTX TAP SSL=${{ matrix.ssl }}
|
||||
env:
|
||||
IPV6: 0
|
||||
RTX: 1
|
||||
SSL: ${{ matrix.ssl }}
|
||||
TFLAGS: -DMQTT_HOST -DIPV6_NOROUTING -DNO_ABORT
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with: { fetch-depth: 2 }
|
||||
- run: |
|
||||
source ./test/setup_ga_network.sh ; sed -i -e "s/127.0.0.1//" test/mosquitto.conf ; ./test/setup_mqtt_server.sh
|
||||
make -C test mip_tap_test
|
||||
|
||||
mip89:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
@@ -147,6 +167,21 @@ jobs:
|
||||
if [[ "${{ matrix.target }}" == *port* ]]; then source ./test/setup_ga_network.sh ; export ENV="-e Tmp=. -e WINEDEBUG=-all -e HOST_IP -e HOST_IPV6 -e HOST_IFC" ; sed -i -e "s/127.0.0.1//" test/mosquitto.conf; cat test/mosquitto.conf; ./test/setup_mqtt_server.sh ; make -C test port_tap_bridge ; test/port_tap_bridge & sleep 2 ; fi
|
||||
make -C test ${{ matrix.target }} IPV6=${{ matrix.ipv6 }} SSL=${{ matrix.ssl }} MULTIREC=NO
|
||||
|
||||
miprtxbe:
|
||||
runs-on: ubuntu-latest
|
||||
name: MIP RTX be s390 port
|
||||
env:
|
||||
IPV6: 0
|
||||
RTX: 1
|
||||
TFLAGS: -DMQTT_HOST -DIPV6_NOROUTING -DNO_ABORT
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with: { fetch-depth: 2 }
|
||||
- run: |
|
||||
sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
|
||||
source ./test/setup_ga_network.sh ; export ENV="-e Tmp=. -e WINEDEBUG=-all -e HOST_IP -e HOST_IPV6 -e HOST_IFC -e RTX" ; sed -i -e "s/127.0.0.1//" test/mosquitto.conf ; ./test/setup_mqtt_server.sh ; make -C test port_tap_bridge ; test/port_tap_bridge & sleep 2
|
||||
make -C test mip_port_s390 MULTIREC=NO
|
||||
|
||||
l2:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
@@ -534,11 +569,12 @@ jobs:
|
||||
infineon/xmc47_relax-make-baremetal-builtin
|
||||
infineon/xmc_plt2go_4400-make-baremetal-builtin
|
||||
infineon/xmc72_evk-make-baremetal-builtin
|
||||
nxp/frdm-mcxn947-make-baremetal-builtin
|
||||
nxp/frdm-mcxn947-make-freertos-builtin
|
||||
nxp/rt1020-evk-make-baremetal-builtin
|
||||
nxp/rt1060-evk-make-baremetal-builtin
|
||||
nxp/rt1170-evk-make-baremetal-builtin
|
||||
nxp/frdm-imxrt1186/minimal
|
||||
nxp/frdm-mcxe247/minimal
|
||||
nxp/frdm-mcxn947/minimal
|
||||
nxp/frdm-rw612/minimal
|
||||
nxp/rt1060-evkb/minimal
|
||||
nxp/rt1170-evkb/minimal
|
||||
- group: rp-ti
|
||||
examples: |
|
||||
rp/pico-w
|
||||
@@ -614,28 +650,6 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- group: nxp-1
|
||||
examples: |
|
||||
nxp/nxp-frdmk66f-freertos
|
||||
nxp/nxp-lpcxpresso54s018m-freertos
|
||||
nxp/nxp-mimxrt1020-freertos
|
||||
nxp/nxp-evkbimxrt1050-lwip-freertos
|
||||
nxp/nxp-evkmimxrt1020-lwip-freertos
|
||||
nxp/nxp-evkmimxrt1024-lwip-freertos
|
||||
nxp/nxp-evkmimxrt1060-lwip-freertos
|
||||
nxp/nxp-evkmimxrt1064-lwip-freertos
|
||||
nxp/nxp-evkmimxrt1160-cm7-lwip-freertos
|
||||
- group: nxp-2
|
||||
examples: |
|
||||
nxp/nxp-evkmimxrt1170-cm7-lwip-freertos
|
||||
nxp/nxp-frdmk64f-lwip-freertos
|
||||
nxp/nxp-frdmk66f-lwip-freertos
|
||||
nxp/nxp-lpcxpresso54018-lwip-freertos
|
||||
nxp/nxp-lpcxpresso54608-lwip-freertos
|
||||
nxp/nxp-lpcxpresso54618-lwip-freertos
|
||||
nxp/nxp-lpcxpresso54628-lwip-freertos
|
||||
nxp/nxp-twrk65f180m-lwip-freertos
|
||||
nxp/nxp-twrkv58f220m-lwip-freertos
|
||||
- group: other
|
||||
examples: |
|
||||
mqtt/mqtt-client/microchip/same54-xpro
|
||||
@@ -696,17 +710,11 @@ jobs:
|
||||
cflags: ""
|
||||
examples: |
|
||||
http/device-dashboard/microchip/same54-xpro
|
||||
nxp/rt1020-evk-make-freertos-builtin
|
||||
nxp/rt1060-evk-make-freertos-builtin
|
||||
nxp/rt1170-evk-make-freertos-builtin
|
||||
renesas/ek-ra6m4-make-baremetal-builtin
|
||||
- group: builtin
|
||||
cflags: -DMG_TLS=MG_TLS_BUILTIN
|
||||
examples: |
|
||||
http/device-dashboard/microchip/same54-xpro
|
||||
nxp/rt1020-evk-make-freertos-builtin
|
||||
nxp/rt1060-evk-make-freertos-builtin
|
||||
nxp/rt1170-evk-make-freertos-builtin
|
||||
renesas/ek-ra6m4-make-baremetal-builtin
|
||||
name: device dashboard ARM ${{ matrix.group }}
|
||||
steps:
|
||||
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
run: |
|
||||
min=$(date -u -d '5 hours ago' +%s)
|
||||
max=$(date -u -d '2 hours ago' +%s)
|
||||
gh api --paginate "/repos/$GITHUB_REPOSITORY/actions/workflows/nightly.yml/runs?status=failure&per_page=100" --jq '.workflow_runs[] | select(.run_attempt == 1) | [.id, .updated_at] | @tsv' |
|
||||
gh api --paginate "/repos/$GITHUB_REPOSITORY/actions/workflows/nightly.yml/runs?status=failure&per_page=100" --jq '.workflow_runs[] | select(.run_attempt == 1) | [.id, .created_at] | @tsv' |
|
||||
while IFS=$'\t' read -r id updated; do
|
||||
when=$(date -u -d "$updated" +%s)
|
||||
if [ "$when" -ge "$min" ] && [ "$when" -le "$max" ]; then
|
||||
|
||||
@@ -53,16 +53,6 @@ jobs:
|
||||
run: sudo apt -y update && sudo apt -y install gcc-arm-none-eabi
|
||||
- run: make -C tutorials/stm32/nucleo-h563zi/minimal test VCON_API_KEY=${{secrets.VCON_API_KEY}}
|
||||
|
||||
test_rt1020:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with: { fetch-depth: 3 }
|
||||
- name: baremetal
|
||||
run: sudo apt -y update && sudo apt -y install gcc-arm-none-eabi
|
||||
- run: make -C tutorials/nxp/rt1020-evk-make-baremetal-builtin test VCON_API_KEY=${{secrets.VCON_API_KEY}}
|
||||
- run: make -C tutorials/nxp/rt1020-evk-make-freertos-builtin test VCON_API_KEY=${{secrets.VCON_API_KEY}}
|
||||
|
||||
test_rt1060:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -70,8 +60,7 @@ jobs:
|
||||
with: { fetch-depth: 3 }
|
||||
- name: baremetal
|
||||
run: sudo apt -y update && sudo apt -y install gcc-arm-none-eabi
|
||||
- run: make -C tutorials/nxp/rt1060-evk-make-baremetal-builtin test VCON_API_KEY=${{secrets.VCON_API_KEY}}
|
||||
- run: make -C tutorials/nxp/rt1060-evk-make-freertos-builtin test VCON_API_KEY=${{secrets.VCON_API_KEY}}
|
||||
- run: make -C tutorials/nxp/rt1060-evkb/minimal build
|
||||
|
||||
test_rt1170:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -80,8 +69,7 @@ jobs:
|
||||
with: { fetch-depth: 3 }
|
||||
- name: baremetal
|
||||
run: sudo apt -y update && sudo apt -y install gcc-arm-none-eabi
|
||||
- run: make -C tutorials/nxp/rt1170-evk-make-baremetal-builtin test VCON_API_KEY=${{secrets.VCON_API_KEY}}
|
||||
- run: make -C tutorials/nxp/rt1170-evk-make-freertos-builtin test VCON_API_KEY=${{secrets.VCON_API_KEY}}
|
||||
- run: make -C tutorials/nxp/rt1170-evkb/minimal build
|
||||
|
||||
test_ra6m4:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -148,11 +148,12 @@ jobs:
|
||||
- path: infineon/xmc47_relax-make-baremetal-builtin
|
||||
- path: infineon/xmc_plt2go_4400-make-baremetal-builtin
|
||||
- path: infineon/xmc72_evk-make-baremetal-builtin
|
||||
- path: nxp/frdm-mcxn947-make-baremetal-builtin
|
||||
- path: nxp/frdm-mcxn947-make-freertos-builtin
|
||||
- path: nxp/rt1020-evk-make-baremetal-builtin
|
||||
- path: nxp/rt1060-evk-make-baremetal-builtin
|
||||
- path: nxp/rt1170-evk-make-baremetal-builtin
|
||||
- path: nxp/frdm-imxrt1186/minimal
|
||||
- path: nxp/frdm-mcxe247/minimal
|
||||
- path: nxp/frdm-mcxn947/minimal
|
||||
- path: nxp/frdm-rw612/minimal
|
||||
- path: nxp/rt1060-evkb/minimal
|
||||
- path: nxp/rt1170-evkb/minimal
|
||||
- path: stm32/nucleo-f429zi/minimal
|
||||
- path: stm32/nucleo-f746zg/minimal
|
||||
- path: stm32/nucleo-h563zi/minimal
|
||||
@@ -169,7 +170,7 @@ jobs:
|
||||
- uses: actions/checkout@v5
|
||||
with: { fetch-depth: 2 }
|
||||
- run: |
|
||||
if ./test/match_changed_files.sh '^src'; then
|
||||
if ./test/match_changed_files.sh '^src|^tutorials/${{ matrix.example.path }}'; then
|
||||
echo GO=1 >> $GITHUB_ENV
|
||||
sudo apt -y update && sudo apt -y install gcc-arm-none-eabi
|
||||
fi
|
||||
@@ -248,9 +249,6 @@ jobs:
|
||||
matrix:
|
||||
example:
|
||||
- path: http/device-dashboard/microchip/same54-xpro
|
||||
- path: nxp/rt1020-evk-make-freertos-builtin
|
||||
- path: nxp/rt1060-evk-make-freertos-builtin
|
||||
- path: nxp/rt1170-evk-make-freertos-builtin
|
||||
- path: renesas/ek-ra6m4-make-baremetal-builtin
|
||||
- path: rp/pico-rndis
|
||||
- path: rp/pico-w
|
||||
|
||||
@@ -486,7 +486,7 @@ embedded devices and needs only a few lines added to `mongoose_config.h`:
|
||||
|
||||
```c
|
||||
#define MG_OTA_URL "https://mongoose.ws/ota/u/PREFIX/ota.json" // Copy from instructions panel
|
||||
#define MG_OTA_FIRMWARE_VERSION "MY_PRODUCT_1.4.2" // Change this
|
||||
#define MG_FIRMWARE_VERSION "MY_PRODUCT_1.4.2" // Change this
|
||||
```
|
||||
|
||||
No backend programming required. The device registers itself and checks in at
|
||||
|
||||
@@ -220,6 +220,8 @@ Technical guides and deep dives into embedded web servers, WebUI integration and
|
||||
- [STM32 Ethernet and caches](https://mongoose.ws/articles/stm32-ethernet-and-cache/)
|
||||
- [NXP RW612 OTA Firmware Update](https://mongoose.ws/articles/rw612-ota-firmware-update/)
|
||||
- [lwIP vs Mongoose - TCP/IP Stack Integration Benchmark](https://mongoose.ws/articles/lwip-vs-mongoose-tcpip-stack-integration/)
|
||||
- [Embedded TCP/IP Stacks Comparison](https://mongoose.ws/embedded-tcpip-stack-comparison/)
|
||||
- [STM32H5 File System on Internal Flash: LittleFS + Mongoose](https://mongoose.ws/articles/stm32h5-file-system-on-internal-flash/)
|
||||
|
||||
|
||||
## Contributions
|
||||
|
||||
+1636
-668
File diff suppressed because it is too large.
Load diff
+341
-101
@@ -103,8 +103,9 @@ extern "C" {
|
||||
#include <sys/types.h>
|
||||
#include <time.h>
|
||||
|
||||
#ifndef MG_PATH_MAX
|
||||
#define MG_PATH_MAX 100
|
||||
#define MG_ENABLE_DIRLIST 0
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
@@ -127,8 +128,9 @@ extern "C" {
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifndef MG_PATH_MAX
|
||||
#define MG_PATH_MAX 100
|
||||
#define MG_ENABLE_DIRLIST 0
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
@@ -158,10 +160,6 @@ extern "C" {
|
||||
#define MG_PATH_MAX 100
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 0
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef MG_ENABLE_TCPIP
|
||||
#define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack
|
||||
@@ -327,10 +325,6 @@ extern "C" {
|
||||
#define MG_ENABLE_POSIX_FS 1
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 1
|
||||
#endif
|
||||
|
||||
#ifndef MG_OTA_ESP32_WDT_TIMEOUT_MS
|
||||
#define MG_OTA_ESP32_WDT_TIMEOUT_MS 10000U
|
||||
#endif
|
||||
@@ -438,16 +432,12 @@ static inline uint32_t mg_ota_esp32_state_set(uint32_t state) {
|
||||
#define MG_PATH_MAX 100
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 0
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_TCPIP
|
||||
#define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack
|
||||
#endif
|
||||
|
||||
#if MG_ENABLE_TCPIP && !defined(MG_ENABLE_DRIVER_IMXRT10) && \
|
||||
!defined(MG_ENABLE_DRIVER_IMXRT11)
|
||||
!defined(MG_ENABLE_DRIVER_IMXRT11) && !defined(MG_ENABLE_DRIVER_NETC)
|
||||
#if defined(CPU_MIMXRT1021DAG5A) || defined(CPU_MIMXRT1024DAG5A) || \
|
||||
defined(CPU_MIMXRT1042XJM5B) || defined(CPU_MIMXRT1052DVL6B) || \
|
||||
defined(CPU_MIMXRT1062DVL6B) || defined(CPU_MIMXRT1064DVL6B) || \
|
||||
@@ -462,6 +452,8 @@ static inline uint32_t mg_ota_esp32_state_set(uint32_t state) {
|
||||
defined(_MIMXRT1176_cm7_H_) || defined(_MIMXRT1176_cm4_H_) || \
|
||||
defined(_MIMXRT1176_H_)
|
||||
#define MG_ENABLE_DRIVER_IMXRT11 1
|
||||
#elif defined(CPU_MIMXRT1186CVJ8C_cm33) || defined(MIMXRT1186_cm33_H_)
|
||||
#define MG_ENABLE_DRIVER_NETC 1
|
||||
#else
|
||||
#error Select an Ethernet driver in mongoose_config.h
|
||||
#endif
|
||||
@@ -493,13 +485,31 @@ static inline uint32_t mg_ota_esp32_state_set(uint32_t state) {
|
||||
defined(_MIMXRT1176_cm7_H_) || defined(_MIMXRT1176_cm4_H_) || \
|
||||
defined(_MIMXRT1176_H_))
|
||||
#define MG_OTA MG_OTA_RT1170
|
||||
#elif !defined(MG_OTA) && \
|
||||
(defined(CPU_MIMXRT1186CVJ8C_cm33) || defined(MIMXRT1186_cm33_H_))
|
||||
#define MG_OTA MG_OTA_RT1180
|
||||
#endif
|
||||
|
||||
#ifndef MG_IRAM
|
||||
#if defined(CPU_MIMXRT1186CVJ8C_cm33) || defined(MIMXRT1186_cm33_H_)
|
||||
#define MG_IRAM \
|
||||
__attribute__((noinline, section(".ramfunc.$SRAM_ITC_cm33")))
|
||||
#else
|
||||
#define MG_IRAM __attribute__((noinline, section(".data_RAM2")))
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef MG_ETH_RAM
|
||||
#if defined(CPU_MIMXRT1186CVJ8C_cm33) || defined(MIMXRT1186_cm33_H_)
|
||||
#define MG_ETH_RAM __attribute__((section(".bss.$ETH_RAM")))
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef MG_SET_MAC_ADDRESS
|
||||
#if defined(MG_ENABLE_DRIVER_NETC) && MG_ENABLE_DRIVER_NETC
|
||||
// No OCOTP_FUSES present on RT1186 to generate the UUID
|
||||
#define MG_SET_MAC_ADDRESS(mac) (void) (mac)
|
||||
#else
|
||||
#if defined(MG_ENABLE_DRIVER_IMXRT11) && MG_ENABLE_DRIVER_IMXRT11
|
||||
#define MG_OCOTP_FUSES ((volatile uint32_t *) 0x40cac900)
|
||||
#else
|
||||
@@ -515,11 +525,70 @@ static inline uint32_t mg_ota_esp32_state_set(uint32_t state) {
|
||||
mac[5] = (MG_OCOTP_FUSES[4] >> 0) & 255; \
|
||||
} while (0)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef MG_IMXRT_WDOG1_TIMEOUT_MS
|
||||
#define MG_IMXRT_WDOG1_TIMEOUT_MS 10000
|
||||
#define MG_IMXRT_WDOG1_TIMEOUT_MS 10000U
|
||||
#endif
|
||||
|
||||
#if defined(CPU_MIMXRT1186CVJ8C_cm33) || defined(MIMXRT1186_cm33_H_)
|
||||
|
||||
#define MG_IMXRT_RTWDOG1_UNLOCK() \
|
||||
do { \
|
||||
if ((RTWDOG1->CS & RTWDOG_CS_CMD32EN_MASK) != 0U) { \
|
||||
RTWDOG1->CNT = RTWDOG_UPDATE_KEY; \
|
||||
} else { \
|
||||
RTWDOG1->CNT = RTWDOG_UPDATE_KEY & 0xffffU; \
|
||||
RTWDOG1->CNT = RTWDOG_UPDATE_KEY >> 16; \
|
||||
} \
|
||||
while ((RTWDOG1->CS & RTWDOG_CS_ULK_MASK) == 0U) (void) 0; \
|
||||
} while (0)
|
||||
|
||||
#define MG_IMXRT_RTWDOG1_FEED() \
|
||||
do { \
|
||||
uint32_t primask_ = __get_PRIMASK(); \
|
||||
__disable_irq(); \
|
||||
if ((RTWDOG1->CS & RTWDOG_CS_CMD32EN_MASK) != 0U) { \
|
||||
RTWDOG1->CNT = RTWDOG_REFRESH_KEY; \
|
||||
} else { \
|
||||
RTWDOG1->CNT = RTWDOG_REFRESH_KEY & 0xffffU; \
|
||||
RTWDOG1->CNT = RTWDOG_REFRESH_KEY >> 16; \
|
||||
} \
|
||||
if (primask_ == 0U) __enable_irq(); \
|
||||
} while (0)
|
||||
|
||||
#ifndef MG_OTA_ROLLBACK_TIMER_START
|
||||
#define MG_OTA_ROLLBACK_TIMER_START() \
|
||||
do { \
|
||||
uint32_t primask_ = __get_PRIMASK(); \
|
||||
SRC_GENERAL_REG->SRMASK &= ~SRC_GENERAL_SRMASK_WDOG1_MASK_MASK; \
|
||||
__disable_irq(); \
|
||||
MG_IMXRT_RTWDOG1_UNLOCK(); \
|
||||
RTWDOG1->WIN = 0U; \
|
||||
RTWDOG1->TOVAL = (MG_IMXRT_WDOG1_TIMEOUT_MS + 7U) / 8U; \
|
||||
RTWDOG1->CS = RTWDOG_CS_EN_MASK | RTWDOG_CS_UPDATE_MASK | \
|
||||
RTWDOG_CS_CLK(1U) | RTWDOG_CS_PRES_MASK | \
|
||||
RTWDOG_CS_CMD32EN_MASK; \
|
||||
while ((RTWDOG1->CS & RTWDOG_CS_RCS_MASK) == 0U) (void) 0; \
|
||||
if (primask_ == 0U) __enable_irq(); \
|
||||
} while (0)
|
||||
#endif
|
||||
|
||||
#ifndef MG_OTA_ROLLBACK_TIMER_FEED
|
||||
#define MG_OTA_ROLLBACK_TIMER_FEED() MG_IMXRT_RTWDOG1_FEED()
|
||||
#endif
|
||||
|
||||
// GPR5 survives RTWDOG global resets and is not reserved by the boot ROM.
|
||||
#ifndef MG_OTA_STATE_GET
|
||||
#define MG_OTA_STATE_GET() SRC_GENERAL_REG->GPR[5]
|
||||
#endif
|
||||
|
||||
#ifndef MG_OTA_STATE_SET
|
||||
#define MG_OTA_STATE_SET(v) (SRC_GENERAL_REG->GPR[5] = (uint32_t) (v))
|
||||
#endif
|
||||
|
||||
#else
|
||||
|
||||
#define MG_IMXRT_WDOG1_FEED() \
|
||||
do { \
|
||||
WDOG1->WSR = 0x5555; \
|
||||
@@ -562,6 +631,8 @@ static inline uint32_t mg_ota_esp32_state_set(uint32_t state) {
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#if MG_ARCH == MG_ARCH_PICOSDK
|
||||
#if !defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP
|
||||
@@ -809,10 +880,6 @@ static inline int mg_mkdir(const char *path, mode_t mode) {
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 1
|
||||
#endif
|
||||
|
||||
#ifndef MG_PATH_MAX
|
||||
#define MG_PATH_MAX FILENAME_MAX
|
||||
#endif
|
||||
@@ -994,10 +1061,6 @@ typedef int socklen_t;
|
||||
#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR)
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 1
|
||||
#endif
|
||||
|
||||
#ifndef SIGPIPE
|
||||
#define SIGPIPE 0
|
||||
#endif
|
||||
@@ -1282,10 +1345,6 @@ struct timeval {
|
||||
#define MG_ENABLE_WINSOCK 1
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 0
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_CUSTOM_RANDOM
|
||||
#define MG_ENABLE_CUSTOM_RANDOM 0
|
||||
#endif
|
||||
@@ -1335,7 +1394,7 @@ struct timeval {
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_POSIX_FS
|
||||
#define MG_ENABLE_POSIX_FS 0
|
||||
#define MG_ENABLE_POSIX_FS MG_ENABLE_LFS
|
||||
#endif
|
||||
|
||||
#ifndef MG_INVALID_SOCKET
|
||||
@@ -1375,6 +1434,14 @@ struct timeval {
|
||||
#define MG_ENABLE_TCPIP_DRIVER_INIT 1 // enabled built-in driver for
|
||||
#endif // Mongoose built-in network stack
|
||||
|
||||
#ifndef MG_ENABLE_TCPIP_TCPRTX
|
||||
#define MG_ENABLE_TCPIP_TCPRTX 0 // TCP retransmission queue
|
||||
#endif
|
||||
|
||||
#ifndef MG_TCPIP_DHCPNAME_SIZE
|
||||
#define MG_TCPIP_DHCPNAME_SIZE 18 // struct mg_tcpip_if :: dhcp_name size
|
||||
#endif
|
||||
|
||||
#ifndef MG_TCPIP_IP // e.g. MG_IPV4(192, 168, 0, 223)
|
||||
#define MG_TCPIP_IP MG_IPV4(0, 0, 0, 0) // Default is 0.0.0.0 (DHCP)
|
||||
#endif
|
||||
@@ -1411,10 +1478,6 @@ struct timeval {
|
||||
#define MG_SET_MAC_ADDRESS(mac)
|
||||
#endif
|
||||
|
||||
#ifndef MG_TCPIP_DHCPNAME_SIZE
|
||||
#define MG_TCPIP_DHCPNAME_SIZE 18 // struct mg_tcpip_if :: dhcp_name size
|
||||
#endif
|
||||
|
||||
#ifndef MG_SET_WIFI_CONFIG
|
||||
#define MG_SET_WIFI_CONFIG(ifp, driver_data)
|
||||
#endif
|
||||
@@ -1427,6 +1490,10 @@ struct timeval {
|
||||
#define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_HEALTH
|
||||
#define MG_ENABLE_HEALTH 0
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1671,8 +1738,8 @@ typedef size_t (*mg_pm_t)(mg_pfn_t fn, void *arg, va_list *);
|
||||
// - mg_print_base64 - prints a buffer as a base64-encoded string
|
||||
// - mg_print_esc - prints a JSON-escaped string
|
||||
// - mg_print_hex - prints a buffer as a hex string
|
||||
// - mg_print_ip - prints an IP address in a struct mg_str
|
||||
// - mg_print_ip_port - prints IP address and port in a struct mg_str
|
||||
// - mg_print_ip - prints an IP address in a struct mg_addr
|
||||
// - mg_print_ip_port - prints IP address and port in a struct mg_addr
|
||||
// - mg_print_ip4 - prints an IPv4 address
|
||||
// - mg_print_ip6 - prints an IPv6 address
|
||||
// - mg_print_mac - prints a MAC address
|
||||
@@ -1730,15 +1797,15 @@ char *mg_mprintf(const char *fmt, ...);
|
||||
size_t mg_queue_printf(struct mg_queue *, const char *fmt, ...);
|
||||
|
||||
// Built-in %M/%m printer functions. Each reads its argument(s) from ap.
|
||||
size_t mg_print_base64(mg_pfn_t, void *arg, va_list *ap); // expects: const void *buf, size_t len
|
||||
size_t mg_print_base64(mg_pfn_t, void *arg, va_list *ap); // expects: int len, uint8_t *buf
|
||||
size_t mg_print_esc(mg_pfn_t, void *arg, va_list *ap); // expects: int len, const char *str -- use MG_ESC()
|
||||
size_t mg_print_hex(mg_pfn_t, void *arg, va_list *ap); // expects: const void *buf, size_t len
|
||||
size_t mg_print_hex(mg_pfn_t, void *arg, va_list *ap); // expects: int len, uint8_t *buf
|
||||
size_t mg_print_ip(mg_pfn_t, void *arg, va_list *ap); // expects: const struct mg_addr *
|
||||
size_t mg_print_ip_port(mg_pfn_t, void *arg, va_list *ap); // expects: const struct mg_addr *
|
||||
size_t mg_print_ip4(mg_pfn_t, void *arg, va_list *ap); // expects: uint32_t *ipv4
|
||||
size_t mg_print_ip6(mg_pfn_t, void *arg, va_list *ap); // expects: uint8_t[16] ipv6
|
||||
size_t mg_print_mac(mg_pfn_t, void *arg, va_list *ap); // expects: uint8_t[6] mac
|
||||
size_t mg_print_ieee64(mg_pfn_t, void *arg, va_list *ap); // expects: uint64_t
|
||||
size_t mg_print_ieee64(mg_pfn_t, void *arg, va_list *ap); // expects: uint8_t[8] ieee64
|
||||
size_t mg_print_l2addr(mg_pfn_t, void *arg, va_list *ap); // expects: uint8_t l2, uint8_t[n] n-byte l2-dependent address
|
||||
size_t mg_print_html_esc(mg_pfn_t, void *arg, va_list *ap); // expects: int len, const char *str -- use MG_ESC()
|
||||
|
||||
@@ -1844,6 +1911,7 @@ void mg_timer_poll(struct mg_timer **head, uint64_t new_ms);
|
||||
|
||||
|
||||
|
||||
|
||||
// Flags returned by mg_fs.st() and passed to mg_fs.open().
|
||||
enum { MG_FS_READ = 1, MG_FS_WRITE = 2, MG_FS_DIR = 4, MG_FS_EXCL = 8 };
|
||||
|
||||
@@ -1881,6 +1949,7 @@ void mg_fs_close(struct mg_fd *fd);
|
||||
|
||||
// Sequential directory iterator. Call repeatedly with the same buf/len;
|
||||
// each call fills buf with the next entry name. Returns false when done.
|
||||
// Note: make sure buf[0] == 0 before the first call
|
||||
bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len);
|
||||
|
||||
// Reads the entire file into a heap-allocated buffer. The returned mg_str is
|
||||
@@ -1920,6 +1989,26 @@ struct mg_str mg_unpacked(const char *path);
|
||||
extern const struct mg_mem_file mg_packed_files[];
|
||||
|
||||
|
||||
#if MG_ENABLE_LFS
|
||||
#include <fcntl.h>
|
||||
#include <lfs.h>
|
||||
|
||||
#ifndef DT_DIR
|
||||
#define DT_DIR 4
|
||||
#endif
|
||||
#ifndef DT_REG
|
||||
#define DT_REG 8
|
||||
#endif
|
||||
|
||||
struct dirent {
|
||||
char d_name[LFS_NAME_MAX + 1];
|
||||
unsigned char d_type;
|
||||
};
|
||||
|
||||
typedef struct mg_lfs_fd DIR;
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2358,6 +2447,7 @@ struct mg_mgr {
|
||||
struct mg_tcpip_if *ifp; // Builtin TCP/IP stack: network interface pointer
|
||||
size_t extraconnsize; // Builtin TCP/IP stack: extra bytes allocated per connection
|
||||
union mg_pipe pipe; // Socketpair write-end / queue, used by mg_wakeup()
|
||||
struct mg_rpc *rpcs; // Linked list of registered RPC handlers
|
||||
#if MG_ENABLE_FREERTOS_TCP
|
||||
SocketSet_t ss; // FreeRTOS-TCP socket set
|
||||
#endif
|
||||
@@ -2402,7 +2492,6 @@ struct mg_connection {
|
||||
unsigned is_closing : 1; // Close and free immediately on next poll
|
||||
unsigned is_full : 1; // Pause incoming reads until cleared
|
||||
unsigned is_tls_throttled : 1; // TLS write was throttled; retry pending
|
||||
unsigned is_resp : 1; // HTTP: response is still being generated
|
||||
unsigned is_readable : 1; // Socket is ready to read (epoll/select)
|
||||
unsigned is_writable : 1; // Socket is ready to write (epoll/select)
|
||||
};
|
||||
@@ -2579,6 +2668,9 @@ struct mg_http_serve_opts {
|
||||
const char *mime_types; // Additional MIME types: "ext1=type1,ext2=type2". NULL for defaults only
|
||||
const char *page404; // Path to a custom 404 page, e.g. "/404.html". NULL for built-in
|
||||
struct mg_fs *fs; // Filesystem to use. NULL defaults to POSIX
|
||||
bool enable_delete; // Allow to DELETE files
|
||||
bool enable_upload; // Allow to POST/PUT files
|
||||
bool enable_dir_listing; // Enable directory listing
|
||||
};
|
||||
|
||||
// A single part of a multipart/form-data body, filled by mg_http_next_multipart().
|
||||
@@ -2652,8 +2744,11 @@ struct mg_connection *mg_http_connect(struct mg_mgr *, const char *url,
|
||||
// mg_http_listen(), mg_http_serve_file(), mg_http_reply(), mg_match()
|
||||
// Notes:
|
||||
// Call from an MG_EV_HTTP_MSG handler. The uri in hm is mapped under
|
||||
// opts->root_dir. Directory listing depends on MG_ENABLE_DIRLIST; SSI uses
|
||||
// opts->ssi_pattern when configured.
|
||||
// opts->root_dir. opts->enable_dir_listing enables directory listing; SSI
|
||||
// uses opts->ssi_pattern when configured. opts->enable_delete enables
|
||||
// DELETE; opts->enable_upload enables POST/PUT, writing the whole body to
|
||||
// a file - see mg_http_serve_upload() to also stream big uploads without
|
||||
// buffering.
|
||||
void mg_http_serve_dir(struct mg_connection *, struct mg_http_message *hm,
|
||||
const struct mg_http_serve_opts *);
|
||||
|
||||
@@ -2661,6 +2756,15 @@ void mg_http_serve_dir(struct mg_connection *, struct mg_http_message *hm,
|
||||
void mg_http_serve_file(struct mg_connection *, struct mg_http_message *hm,
|
||||
const char *path, const struct mg_http_serve_opts *);
|
||||
|
||||
// Streams a big POST/PUT upload straight to a file, instead of buffering the
|
||||
// whole body. Optional companion to mg_http_serve_dir(): call this from
|
||||
// MG_EV_HTTP_HDRS with the same opts, and keep calling mg_http_serve_dir()
|
||||
// from MG_EV_HTTP_MSG as usual - it still handles uploads this function skips.
|
||||
// Does nothing unless opts->enable_upload is set, the method is POST or PUT,
|
||||
// and Content-Length is known and big enough.
|
||||
void mg_http_serve_upload(struct mg_connection *, struct mg_http_message *hm,
|
||||
const struct mg_http_serve_opts *);
|
||||
|
||||
// Sends a complete HTTP response with Content-Length.
|
||||
//
|
||||
// Example:
|
||||
@@ -2707,20 +2811,6 @@ void mg_http_creds(struct mg_http_message *, char *, size_t, char *, size_t);
|
||||
long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
|
||||
struct mg_fs *fs, const char *dir, size_t max_size);
|
||||
|
||||
// Streams the raw request body into dir/name via fs. Non-blocking: installs an
|
||||
// internal handler and returns immediately. fn is called with NULL on success
|
||||
// or an error string on failure.
|
||||
void mg_http_start_upload(struct mg_connection *c, struct mg_http_message *hm,
|
||||
struct mg_str name, struct mg_str dir,
|
||||
struct mg_fs *fs,
|
||||
void (*fn)(struct mg_connection *, const char *));
|
||||
|
||||
// Starts an OTA firmware update from an HTTP POST upload.
|
||||
// Calls mg_ota_begin/write/end internally; fn is called with NULL on success,
|
||||
// or an error string on failure.
|
||||
void mg_http_start_ota(struct mg_connection *c, struct mg_http_message *hm,
|
||||
void (*fn)(struct mg_connection *, const char *));
|
||||
|
||||
// Sends a 401 Unauthorized response with a Basic Auth WWW-Authenticate challenge.
|
||||
void mg_http_bauth(struct mg_connection *, const char *user, const char *pass);
|
||||
|
||||
@@ -2739,7 +2829,7 @@ struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v);
|
||||
// Full examples:
|
||||
// tutorials/http/file-upload-html-form, tutorials/http/http-server
|
||||
// Related APIs:
|
||||
// mg_http_listen(), mg_http_start_upload()
|
||||
// mg_http_listen(), mg_http_stream_body()
|
||||
// Notes:
|
||||
// Call from an MG_EV_HTTP_MSG handler after the full request body is
|
||||
// received. part.name, part.filename, and part.body are zero-copy slices into
|
||||
@@ -2749,6 +2839,35 @@ size_t mg_http_next_multipart(struct mg_str, size_t, struct mg_http_part *);
|
||||
// Returns the HTTP status code from a parsed response message (e.g. 200, 404).
|
||||
int mg_http_status(const struct mg_http_message *hm);
|
||||
|
||||
// Streams a POST/PUT body to a callback as it arrives, without buffering it.
|
||||
// Call it from an MG_EV_HTTP_HDRS handler, after matching the request, e.g.
|
||||
// with mg_match(). Returns true if it took over the connection, false if the
|
||||
// request is not POST/PUT, is chunked, or has no Content-Length.
|
||||
//
|
||||
// Callback upload_fn(hm, data, user_data) is called:
|
||||
// - at start: hm is set. Open the file, set *user_data.
|
||||
// - per chunk: data is set, 512 byte aligned except the last. Not called
|
||||
// again after a failure.
|
||||
// - at end: both NULL. Always called once, also when the connection drops
|
||||
// early, so release resources here. A truncated body looks like a complete
|
||||
// one: validate before committing.
|
||||
// Return true on success, false on error.
|
||||
// Example:
|
||||
// if (ev == MG_EV_HTTP_HDRS && mg_match(hm->uri, mg_str("/fs/*"), NULL) {
|
||||
// mg_http_stream_body(c, hm, upload, NULL));
|
||||
// }
|
||||
// Full example:
|
||||
// tutorials/http/file-upload-single-post
|
||||
// Related APIs:
|
||||
// mg_http_listen(), mg_http_next_multipart()
|
||||
// Notes:
|
||||
// After it returns true, this function hijacks the connection. Existing event
|
||||
// handler not called, hm is invalid, c->data and c->fn_data are modified
|
||||
bool mg_http_stream_body(struct mg_connection *c, struct mg_http_message *hm,
|
||||
bool (*upload_fn)(struct mg_http_message *,
|
||||
struct mg_str *, void **user_data),
|
||||
void *user_data);
|
||||
|
||||
|
||||
void mg_http_serve_ssi(struct mg_connection *c, const char *root,
|
||||
const char *fullpath);
|
||||
@@ -2835,7 +2954,7 @@ void mg_tls_free(struct mg_connection *);
|
||||
long mg_tls_send(struct mg_connection *, const void *buf, size_t len);
|
||||
long mg_tls_recv(struct mg_connection *, void *buf, size_t len);
|
||||
size_t mg_tls_pending(struct mg_connection *);
|
||||
void mg_tls_flush(struct mg_connection *);
|
||||
long mg_tls_flush(struct mg_connection *);
|
||||
void mg_tls_handshake(struct mg_connection *);
|
||||
void mg_tls_ctx_init(struct mg_mgr *);
|
||||
void mg_tls_ctx_free(struct mg_mgr *);
|
||||
@@ -4533,9 +4652,7 @@ struct mg_field_set {
|
||||
// fn sets *index = -1 to signal end of iteration.
|
||||
// Size query: framework sets *index = -1 before fn(READ); fn
|
||||
// sets *index = total size
|
||||
bool (*get_dir)(const struct mg_dash_user *u, char *buf,
|
||||
size_t len); // Non-NULL: file array
|
||||
struct mg_field_set *next; // Next set in the list
|
||||
struct mg_field_set *next; // Next set in the list
|
||||
};
|
||||
|
||||
// Custom URI handler, registered with MG_DASH_REGISTER_CUSTOM_HANDLER()
|
||||
@@ -4556,6 +4673,9 @@ struct mg_dash {
|
||||
int session_auto_expiration_seconds; // Session lifetime, 0: 1 hour default
|
||||
struct mg_dash_user *guest; // Used when authenticate == NULL
|
||||
struct mg_fs *upload_fs; // FS for uploads/listing, default &mg_fs_posix
|
||||
// Resolves the built-in file manager's root dir for user u, e.g. per-user
|
||||
// upload directories. NULL: file manager disabled
|
||||
bool (*files_dir)(const struct mg_dash_user *u, char *buf, size_t len);
|
||||
};
|
||||
|
||||
#define MG_DASH_ADD_FIELD_SET(dash_, set_) \
|
||||
@@ -4581,43 +4701,6 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data);
|
||||
// array size if *set->index < 0, or a single element update otherwise
|
||||
void mg_dash_send_change(struct mg_mgr *mgr, struct mg_field_set *);
|
||||
|
||||
// Default reader for file-backed array sets (set->get_dir != NULL)
|
||||
// Usage example - this is a complete implemenation of the file manager:
|
||||
// ```c
|
||||
// static struct file {
|
||||
// int index;
|
||||
// char name[64];
|
||||
// size_t size;
|
||||
// uint64_t checksum;
|
||||
// } s_file;
|
||||
// static struct mg_field_set set_files;
|
||||
//
|
||||
// static bool get_dir(const struct mg_dash_user *u, char *buf, size_t len) {
|
||||
// (void) u;
|
||||
// mkdir("/tmp/dashboard", 0755);
|
||||
// mg_snprintf(buf, len, "%s", "/tmp/dashboard");
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// static struct mg_field fields_files[] = {
|
||||
// {"name", MG_VAL_STR, s_file.name, sizeof(s_file.name)},
|
||||
// {"size", MG_VAL_UINT64, &s_file.size, 0},
|
||||
// {"checksum", MG_VAL_UINT64, &s_file.checksum, sizeof(s_file.checksum)},
|
||||
// {NULL, MG_VAL_INT, NULL, 0},
|
||||
// };
|
||||
//
|
||||
// static bool files_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
// if (op == MG_DASH_WRITE) return s_uploads_enabled && u->level >= 7;
|
||||
// if (op != MG_DASH_READ) return false;
|
||||
// if (!mg_dash_dir_read(&set_files, u)) return false;
|
||||
// s_file.checksum = 0; // Mock to show how to set custom fields
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// static struct mg_field_set set_files = {"files", fields_files, files_fn, &s_file.index, get_dir, NULL};
|
||||
// ```
|
||||
bool mg_dash_dir_read(struct mg_field_set *set, struct mg_dash_user *u);
|
||||
|
||||
// Helper forward declarations for Mongoose CMSIS pack modules
|
||||
extern struct mg_mgr g_mgr;
|
||||
extern void mg_dash_init(struct mg_mgr *);
|
||||
@@ -4629,7 +4712,7 @@ extern void mg_mqtt_poll(struct mg_mgr *);
|
||||
// This is a low-level OTA API, not intended to be called directly by users.
|
||||
// Users are provided with a higher-level API:
|
||||
// - defining MG_OTA_URL enables HTTP or HTTPS pull-based updates
|
||||
// - mg_http_start_ota() enables push-based updates
|
||||
// - mg_http_stream_body() enables push-based updates
|
||||
//
|
||||
// However, it is possible to use the mg_ota_* API directly. Below is the
|
||||
// example code of a function that is called repeatedly. It expects the
|
||||
@@ -4667,6 +4750,7 @@ extern void mg_mqtt_poll(struct mg_mgr *);
|
||||
#define MG_OTA_RT1060 302 // IMXRT1060
|
||||
#define MG_OTA_RT1064 303 // IMXRT1064
|
||||
#define MG_OTA_RT1170 304 // IMXRT1170
|
||||
#define MG_OTA_RT1180 305 // IMXRT1180
|
||||
#define MG_OTA_MCXN 310 // MCXN947
|
||||
#define MG_OTA_RW612 320 // FRDM-RW612
|
||||
#define MG_OTA_FLASH 900 // OTA via internal flash
|
||||
@@ -4779,7 +4863,7 @@ enum {
|
||||
// needs to be defined. Fetches metadata_url, which must
|
||||
// return a JSON object like:
|
||||
// { "version": "1.2.3", "url": "FIRMWARE_URL", "size": 324645 }
|
||||
// If the server version differs from MG_OTA_FIRMWARE_VERSION, downloads
|
||||
// If the server version differs from MG_FIRMWARE_VERSION, downloads
|
||||
// FIRMWARE_URL and performs the OTA update. fn is called on every outcome:
|
||||
// NULL on successful flash, "Same version" when already up to date, or an
|
||||
// error string on failure. Pass NULL to use the default handler which logs
|
||||
@@ -4806,8 +4890,8 @@ void mg_ota_url_check(struct mg_mgr *mgr, const char *metadata_url,
|
||||
#endif
|
||||
|
||||
// Firmware version for mg_ota_poll(). Settable in mongoose_config.h
|
||||
#ifndef MG_OTA_FIRMWARE_VERSION
|
||||
#define MG_OTA_FIRMWARE_VERSION "1.0.0"
|
||||
#ifndef MG_FIRMWARE_VERSION
|
||||
#define MG_FIRMWARE_VERSION "1.0.0"
|
||||
#endif
|
||||
|
||||
// Maximum version string length
|
||||
@@ -4833,6 +4917,111 @@ void mg_ota_device_id(char *buf, size_t len);
|
||||
// mg_mgr_poll() when MG_OTA_URL is set in mongoose_config.h. Do not call
|
||||
// directly.
|
||||
void mg_ota_poll(struct mg_mgr *);
|
||||
// Device health monitoring
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#ifndef MG_HEALTH_MAGIC
|
||||
#define MG_HEALTH_MAGIC {'M', 'G', 'H', '3'} // '3' is the layout version
|
||||
#endif
|
||||
|
||||
// Places the record in RAM that survives a reset. Define in mongoose_config.h
|
||||
// to match the linker script, e.g. __attribute__((section(".mg_health")))
|
||||
#ifndef MG_HEALTH_RAM
|
||||
#define MG_HEALTH_RAM
|
||||
#endif
|
||||
|
||||
// Why the device restarted. Hardware usually reports several flags at once,
|
||||
// so these are ordered by how much they tell you: the most specific cause a
|
||||
// device reports wins
|
||||
enum mg_health_reason {
|
||||
MG_HEALTH_RESET_UNKNOWN = 0, // Nothing reported, or no masks configured
|
||||
MG_HEALTH_RESET_POWER, // Power-on reset, RAM contents are lost
|
||||
MG_HEALTH_RESET_BROWNOUT, // Supply dipped below the brown-out level
|
||||
MG_HEALTH_RESET_PIN, // External reset pin, e.g. the reset button
|
||||
MG_HEALTH_RESET_SOFTWARE, // Firmware asked for it, e.g. NVIC_SystemReset
|
||||
MG_HEALTH_RESET_LOWPOWER, // Illegal or failed low-power transition
|
||||
MG_HEALTH_RESET_WATCHDOG, // Watchdog fired: the application stopped
|
||||
MG_HEALTH_RESET_FAULT // Fault handler ran, see regs[] and saved_stack
|
||||
};
|
||||
|
||||
#ifndef MG_HEALTH_DATA_SIZE
|
||||
#define MG_HEALTH_DATA_SIZE 20
|
||||
#endif
|
||||
|
||||
struct mg_health {
|
||||
char magic[4]; // MG_HEALTH_MAGIC when the record holds valid data
|
||||
uint32_t reset_reason; // enum mg_health_reason that started this boot
|
||||
uint32_t cpuid; // ARM CPU ID
|
||||
uint32_t data[MG_HEALTH_DATA_SIZE];
|
||||
};
|
||||
|
||||
extern struct mg_health mg_health_record; // Defined in health.c
|
||||
|
||||
// Return true if the record holds valid data, i.e. it survived the reset and
|
||||
// was written by this firmware layout
|
||||
static inline bool mg_health_valid(void) {
|
||||
static const char magic[] = MG_HEALTH_MAGIC;
|
||||
return memcmp(mg_health_record.magic, magic,
|
||||
sizeof(mg_health_record.magic)) == 0;
|
||||
}
|
||||
|
||||
static inline int mg_health_reason(void) {
|
||||
return mg_health_valid() ? (int) mg_health_record.reset_reason
|
||||
: MG_HEALTH_RESET_UNKNOWN;
|
||||
}
|
||||
|
||||
static inline const char *mg_health_reason_str(int reason) {
|
||||
switch (reason) {
|
||||
case MG_HEALTH_RESET_POWER: return "power";
|
||||
case MG_HEALTH_RESET_BROWNOUT: return "brownout";
|
||||
case MG_HEALTH_RESET_PIN: return "pin";
|
||||
case MG_HEALTH_RESET_SOFTWARE: return "software";
|
||||
case MG_HEALTH_RESET_LOWPOWER: return "lowpower";
|
||||
case MG_HEALTH_RESET_WATCHDOG: return "watchdog";
|
||||
case MG_HEALTH_RESET_FAULT: return "fault";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
// Start a new boot: validate the record, count the boot, store the reset
|
||||
// reason. The current boot moves to prev_* slots first, so the previous
|
||||
// boot's uptime and reason stay readable. Called by MG_HEALTH_INIT()
|
||||
static inline void mg_health_init(void) {
|
||||
char magic[] = MG_HEALTH_MAGIC;
|
||||
// struct mg_health *h = mg_health_get();
|
||||
if (!mg_health_valid()) { // First boot, or RAM lost its contents
|
||||
memset(&mg_health_record, 0, sizeof(mg_health_record));
|
||||
memcpy(mg_health_record.magic, magic, sizeof(mg_health_record.magic));
|
||||
}
|
||||
}
|
||||
|
||||
#define MG_HEALTH_INIT() mg_health_init()
|
||||
extern size_t mg_print_crash_record(mg_pfn_t, void *, va_list *);
|
||||
// Cloud connector API to https://mdash.net - device management cloud
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#ifndef MG_MDASH_URL
|
||||
#define MG_MDASH_URL "wss://mdash.net/api/v2/rpc"
|
||||
#endif
|
||||
|
||||
#ifndef MG_MDASH_KEY
|
||||
#define MG_MDASH_KEY ""
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_MDASH
|
||||
#define MG_ENABLE_MDASH 0
|
||||
#endif
|
||||
|
||||
void mg_mdash_init(struct mg_mgr *);
|
||||
void mg_mdash_poll(struct mg_mgr *);
|
||||
void mg_mdash_free(struct mg_mgr *);
|
||||
|
||||
|
||||
|
||||
@@ -5018,6 +5207,7 @@ struct mg_tcpip_if {
|
||||
bool enable_req_sntp; // DHCP client requests an SNTP server address
|
||||
bool enable_fcs_check; // Verify and strip FCS from received frames
|
||||
bool enable_mac_check; // Drop frames not addressed to this MAC
|
||||
bool enable_tcp_retransmit; // Enable optional TCP retransmission queue
|
||||
bool update_mac_hash_table; // Signal driver to refresh MAC multicast hash table
|
||||
bool is_ip_changed; // Set by stack when IP changes; triggers connection restart
|
||||
struct mg_tcpip_driver *driver; // Hardware driver; must be set before mg_tcpip_init()
|
||||
@@ -5111,6 +5301,7 @@ extern struct mg_tcpip_driver mg_tcpip_driver_cyw;
|
||||
extern struct mg_tcpip_driver mg_tcpip_driver_nxp_wifi;
|
||||
extern struct mg_tcpip_driver mg_tcpip_driver_st67w6;
|
||||
extern struct mg_tcpip_driver mg_tcpip_driver_atcmd;
|
||||
extern struct mg_tcpip_driver mg_tcpip_driver_netc;
|
||||
|
||||
// SPI bus abstraction for SPI-attached network chips (e.g. W5500).
|
||||
// Populate and assign to the driver's driver_data field.
|
||||
@@ -5455,6 +5646,55 @@ struct mg_tcpip_driver_imxrt_data {
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP && \
|
||||
defined(MG_ENABLE_DRIVER_NETC) && MG_ENABLE_DRIVER_NETC
|
||||
|
||||
struct mg_tcpip_driver_netc_data {
|
||||
int mdc_cr;
|
||||
uint8_t phy_addr;
|
||||
|
||||
// Selects the physical Ethernet link (ETH0 through ETH3)
|
||||
// Its switch port is bridged to pseudo-port 4,
|
||||
// which connects internally to ENETC1
|
||||
// IMXRT1180 RM 53.4.1.1 NETC Block diagram
|
||||
uint8_t link;
|
||||
};
|
||||
|
||||
#ifndef MG_TCPIP_PHY_ADDR
|
||||
#define MG_TCPIP_PHY_ADDR 5
|
||||
#endif
|
||||
|
||||
#ifndef MG_DRIVER_MDC_CR
|
||||
#define MG_DRIVER_MDC_CR 48
|
||||
#endif
|
||||
|
||||
#ifndef MG_TCPIP_NETC_LINK
|
||||
#define MG_TCPIP_NETC_LINK 0
|
||||
#endif
|
||||
|
||||
struct mg_tcpip_driver;
|
||||
extern struct mg_tcpip_driver mg_tcpip_driver_netc;
|
||||
|
||||
#define MG_TCPIP_DRIVER_INIT(mgr) \
|
||||
do { \
|
||||
static struct mg_tcpip_driver_netc_data driver_data_; \
|
||||
static struct mg_tcpip_if mif_; \
|
||||
driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \
|
||||
driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \
|
||||
driver_data_.link = MG_TCPIP_NETC_LINK; \
|
||||
mif_.ip = MG_TCPIP_IP; \
|
||||
mif_.mask = MG_TCPIP_MASK; \
|
||||
mif_.gw = MG_TCPIP_GW; \
|
||||
mif_.driver = &mg_tcpip_driver_netc; \
|
||||
mif_.driver_data = &driver_data_; \
|
||||
MG_SET_MAC_ADDRESS(mif_.mac); \
|
||||
mg_tcpip_init(mgr, &mif_); \
|
||||
MG_INFO(("Driver: netc, MAC: %M", mg_print_mac, mif_.mac)); \
|
||||
} while (0)
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#if MG_ENABLE_TCPIP && \
|
||||
defined(MG_ENABLE_DRIVER_NXP_WIFI) && MG_ENABLE_DRIVER_NXP_WIFI
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
<license>License.txt</license>
|
||||
<supportContact>https://mongoose.ws/contact/</supportContact>
|
||||
<releases>
|
||||
<release date="2026-09-28" version="7.23.1">See https://github.com/cesanta/mongoose/releases/tag/7.23</release>
|
||||
<release date="2026-05-11" version="7.21.7">See https://github.com/cesanta/mongoose/releases/tag/7.21</release>
|
||||
<release date="2026-05-05" version="7.21.5">See https://github.com/cesanta/mongoose/releases/tag/7.21</release>
|
||||
<release date="2026-04-24" version="7.21.4">See https://github.com/cesanta/mongoose/releases/tag/7.21</release>
|
||||
@@ -19,7 +20,7 @@
|
||||
<keyword>IMPLEMENTED_WITH_STM32CUBEMX</keyword>
|
||||
</keywords>
|
||||
<components>
|
||||
<component Cclass="Mongoose" Cgroup="Networking Core" Cversion="7.21.7" maxInstances="1">
|
||||
<component Cclass="Mongoose" Cgroup="Networking Core" Cversion="7.23.1" maxInstances="1">
|
||||
<description>Networking Core</description>
|
||||
<files>
|
||||
<file category="doc" name="README.md"/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
VERSION = 7.21.7
|
||||
VERSION = 7.23.1
|
||||
REPO_ROOT = ../..
|
||||
MX ?= /Applications/STMicroelectronics/STM32CubeMX.app/Contents/MacOs/STM32CubeMX
|
||||
FILES = Cesanta.I-CUBE-Mongoose.pdsc Release_Notes.html mongoose_config.h README.md
|
||||
@@ -44,23 +44,5 @@ mongoose.h: Mongoose
|
||||
mongoose.c: Mongoose
|
||||
cp $(REPO_ROOT)/mongoose.c $@
|
||||
|
||||
pk: $(PACK)
|
||||
rm -f gen.mx
|
||||
echo swmgr remove Cesanta.I-CUBE-Mongoose.$(VERSION) >> gen.mx
|
||||
echo swmgr install `pwd`/Cesanta.I-CUBE-Mongoose.$(VERSION).pack ask >> gen.mx
|
||||
echo exit >> gen.mx
|
||||
$(MX) -q `pwd`/gen.mx
|
||||
|
||||
|
||||
mx: $(PACK)
|
||||
mkdir -p $@
|
||||
cp ../downloads/nucleo_h563zi.ioc $@
|
||||
V=`grep 'Mcu.ThirdParty0' $@/nucleo_h563zi.ioc | sed 's,^.*se.,,'`; sed -i '' "s,$$V,$(VERSION),g" $@/nucleo_h563zi.ioc
|
||||
rm -f gen.mx
|
||||
echo config load `pwd`/$@/nucleo_h563zi.ioc >> gen.mx
|
||||
echo project generate >> gen.mx
|
||||
echo exit >> gen.mx
|
||||
$(MX) -q `pwd`/gen.mx
|
||||
|
||||
clean:
|
||||
rm -rf *.pack STM32CubeMX/*.$(VERSION)_*.xml $(GENERATED) gen.mx mx
|
||||
rm -rf *.pack STM32CubeMX/*.$(VERSION)_*.xml $(GENERATED)
|
||||
@@ -39,8 +39,7 @@ patch_linker_script() {
|
||||
HUART=`perl -nle 'print \$1 if /^UART_HandleTypeDef (.+);/' $MAIN_C`
|
||||
grep -q mongoose.h $MAIN_C || perl -i -ne 'print; print "#include \"mongoose.h\"\n" if /BEGIN Includes/' $MAIN_C
|
||||
grep -q '^static void log_fn' $MAIN_C || perl -i -ne "print; print \"static void log_fn(char ch, void *param) {\n HAL_UART_Transmit(param, (unsigned char *) &ch, 1, HAL_MAX_DELAY);\n}\n\" if /USER CODE BEGIN 0/" $MAIN_C
|
||||
grep -q 'mg_mgr_init' $MAIN_C || perl -i -ne 'print; print " struct mg_mgr mgr;\n mg_mgr_init(&mgr);\n mg_log_set_fn(log_fn, &'"${HUART}"');\n\n" if /USER CODE BEGIN WHILE/' $MAIN_C
|
||||
grep -q 'mg_mgr_init' $MAIN_C && grep -q 'mg_log_set_fn' $MAIN_C || perl -i -ne 'print; print " mg_log_set_fn(log_fn, &'"${HUART}"');\n" if /mg_mgr_init/' $MAIN_C
|
||||
grep -q 'mg_mgr_init' $MAIN_C || perl -i -ne 'print; print " struct mg_mgr mgr;\n mg_log_set_fn(log_fn, &'"${HUART}"');\n mg_mgr_init(&mgr);\n mg_log_set_fn(log_fn, &'"${HUART}"');\n\n" if /USER CODE BEGIN WHILE/' $MAIN_C
|
||||
grep -q 'mg_mgr_poll' $MAIN_C || perl -i -ne 'print " mg_mgr_poll(&mgr, 0);\n" if /USER CODE END WHILE/; print;' $MAIN_C
|
||||
patch_linker_script $DIR/STM32H723XG_FLASH.ld
|
||||
patch_linker_script $DIR/STM32H743XX_FLASH.ld
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# Security Scan Area: common_misc
|
||||
|
||||
## Target
|
||||
|
||||
Area: common_misc
|
||||
|
||||
This area covers common utility code, parsing/string/formatting helpers, URL handling, hash/base64 helpers, filesystem backends, little filesystem integration, and flash support.
|
||||
|
||||
Primary files:
|
||||
- `src/base64.c`
|
||||
- `src/fmt.c`
|
||||
- `src/json.c`
|
||||
- `src/log.c`
|
||||
- `src/md5.c`
|
||||
- `src/printf.c`
|
||||
- `src/sha1.c`
|
||||
- `src/sha256.c`
|
||||
- `src/str.c`
|
||||
- `src/url.c`
|
||||
- `src/util.c`
|
||||
- `src/fs*.c`
|
||||
- `src/lfs.c`
|
||||
- `src/flash.c`
|
||||
|
||||
Perform a focused security review centered on these files and this security surface.
|
||||
|
||||
Supporting code elsewhere under `src/` may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not inspect or report code outside `src/` or independently review unrelated areas.
|
||||
|
||||
## Area-Specific Security Guidance
|
||||
|
||||
**Filesystem Backends:**
|
||||
- Review packed filesystem code and filesystem backends for traversal, unauthorized file read/write, overwrite, or truncation.
|
||||
- Check path canonicalization across POSIX, Windows, embedded filesystems, packed filesystems, and custom `mg_fs` implementations.
|
||||
- Look for trailing slash confusion, NUL byte truncation, and case sensitivity differences in backend path handling.
|
||||
|
||||
**URL Parsing:**
|
||||
- Review URL parsing for scheme, host, port, IPv6 literal, userinfo, percent-encoding, embedded NUL, empty host, default port, and path/query boundary confusion.
|
||||
- Check for SSRF-relevant behavior only when attacker input can control the destination host, protocol, or network boundary. Path-only control is not sufficient.
|
||||
@@ -0,0 +1,30 @@
|
||||
# Security Scan Area: mongoose_core
|
||||
|
||||
## Target
|
||||
|
||||
Area: mongoose_core
|
||||
|
||||
This area covers the core event/network/connection machinery, iobuf handling, queues, socket transport, timers, and BSD abstraction.
|
||||
|
||||
Primary files:
|
||||
- `src/event.c`
|
||||
- `src/iobuf.c`
|
||||
- `src/net.c`
|
||||
- `src/queue.c`
|
||||
- `src/sock.c`
|
||||
- `src/timer.c`
|
||||
- `src/bsd.c`
|
||||
|
||||
Perform a focused security review centered on these files and this security surface.
|
||||
|
||||
Supporting code elsewhere under `src/` may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not inspect or report code outside `src/` or independently review unrelated areas.
|
||||
|
||||
## Area-Specific Security Guidance
|
||||
|
||||
**Protocol State Machine and Event-Driven Lifecycle Bugs:**
|
||||
- Review transitions between listening, accepted, connecting, resolving, TLS handshaking, HTTP, WebSocket, MQTT, draining, closing, and closed states.
|
||||
- Check whether malformed input can cause protocol handlers to process data in the wrong state, process stale data after close, or invoke callbacks with invalid event data.
|
||||
- Look for use-after-free or stale pointer use when callbacks call `mg_close_conn`, mark a connection closing, mutate iobufs, change protocol handlers, or initiate TLS/WebSocket/MQTT transitions.
|
||||
- Verify that partial reads/writes, backpressure, `is_full`, draining, TLS pending states, and send-buffer mutations cannot cause duplicated sends, skipped validation, or parser confusion.
|
||||
- Review timer and wakeup handling for stale user data pointers, cross-thread queue misuse, and callbacks firing after associated connections/state have been freed.
|
||||
- Only report concurrency or race issues when a concrete event ordering can trigger memory corruption, unauthorized action, or reliable device/process crash.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Security Scan Area: net_builtin
|
||||
|
||||
## Target
|
||||
|
||||
Area: net_builtin
|
||||
|
||||
This area covers the built-in TCP/IP stack and its selected L2 implementations.
|
||||
|
||||
Primary files:
|
||||
- `src/l2_*.c`
|
||||
- `src/net_builtin.c`
|
||||
|
||||
Perform a focused security review centered on these files and this security surface.
|
||||
|
||||
Supporting code elsewhere under `src/` may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not inspect or report code outside `src/` or independently review unrelated areas.
|
||||
|
||||
## Area-Specific Security Guidance
|
||||
|
||||
**Built-In TCP/IP Stack, Packet Parsing, and Embedded Network Drivers:**
|
||||
- Review Ethernet, ARP, IP, IPv6, ICMP, UDP, TCP, DHCP, SNTP, and driver receive/transmit paths for packet-length validation before reading protocol headers.
|
||||
- Check IP/TCP/UDP header length fields, options length, fragmentation/reassembly behavior, checksum handling, and payload offset calculations for underflow, overflow, or out-of-bounds access.
|
||||
- Look for malformed packets that can corrupt descriptor rings, RX/TX buffers, queue state, ARP tables, connection state, or timers.
|
||||
- Review interrupt handlers and bare-metal driver code for bounded processing loops. Flag IRQ paths where attacker-controlled traffic can cause livelock, starvation, descriptor ownership loss, or repeated processing of the same malformed frame.
|
||||
- Check DMA descriptor ownership transitions, memory barriers, cache coherency handling, and buffer length fields for race-like bugs that can cause memory corruption or stale packet reuse.
|
||||
- Review platform-specific drivers such as STM32, NXP, TI, Microchip, Renesas, Infineon, Wiznet, Cypress WiFi, cellular, and other built-in stack integrations for inconsistent bounds checks or endian conversions.
|
||||
- Treat a remotely reachable malformed Ethernet/IP/TCP/UDP packet that crashes, wedges, or corrupts an embedded target as reportable.
|
||||
@@ -0,0 +1,38 @@
|
||||
# Security Scan Area: protocols
|
||||
|
||||
## Target
|
||||
|
||||
Area: protocols
|
||||
|
||||
This area covers the smaller externally controlled protocol parsers and state machines other than HTTP, WebSocket, and TLS.
|
||||
|
||||
Primary files:
|
||||
- `src/modbus.c`
|
||||
- `src/rpc.c`
|
||||
- `src/sntp.c`
|
||||
- `src/mqtt.c`
|
||||
- `src/dns.c`
|
||||
|
||||
Perform a focused security review centered on these files and this security surface.
|
||||
|
||||
Supporting code elsewhere under `src/` may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not inspect or report code outside `src/` or independently review unrelated areas.
|
||||
|
||||
## Area-Specific Security Guidance
|
||||
|
||||
**MQTT Parser and Broker/Client State Machine Vulnerabilities:**
|
||||
- Review MQTT fixed header parsing, remaining-length decoding, variable-length integer loops, packet identifier handling, QoS transitions, topic extraction, property parsing, and MQTT 3.x vs MQTT 5 differences.
|
||||
- Look for malformed MQTT packets that can trigger out-of-bounds reads/writes, stack buffer overflow, heap corruption, assertion/crash, or parser desynchronization.
|
||||
- Specifically check SUBSCRIBE and UNSUBSCRIBE handling for unbounded numbers of topics, malformed topic length fields, missing QoS bytes, invalid QoS values, and writes to fixed-size response arrays.
|
||||
- Verify that PUBLISH handling enforces topic length, packet length, QoS rules, retained flag handling, packet identifier requirements, and message bounds before accessing fields.
|
||||
- Check protocol handlers for authorization bypass, cross-topic data exposure, wildcard topic mishandling, `$SYS` or reserved topic confusion, and unintended publish/subscribe access.
|
||||
- Review MQTT reconnect/resubscribe logic for stale connection state, packet identifier reuse bugs, and memory lifetime problems after close/reconnect.
|
||||
- Treat unauthenticated single-packet broker crash, client crash from malicious broker response, or memory corruption during MQTT parsing as reportable.
|
||||
|
||||
**DNS and mDNS Parsing and Name Resolution:**
|
||||
- Review DNS and mDNS message parsing for label length validation, compression pointer loops, pointer bounds, recursive expansion limits, integer overflow, malformed resource records, and out-of-bounds reads.
|
||||
- Check that DNS answers are matched to outstanding requests by transaction ID, question name/type/class, and source expectations where applicable.
|
||||
- Look for cache poisoning, response spoofing, or name confusion if DNS response validation is weak in client or resolver code.
|
||||
- Verify that DNS failures, timeouts, and retries cannot leave dangling active request state or corrupt connection state.
|
||||
|
||||
**Modbus, RPC, and SNTP:**
|
||||
- Review externally controlled lengths, framing, message parsing, and protocol state for malformed peer input that can cause parser desynchronization, state corruption, or a remotely triggerable crash or wedge.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Security Scan Area: tls
|
||||
|
||||
## Target
|
||||
|
||||
Area: tls
|
||||
|
||||
This area covers the complete Mongoose TLS implementation represented by the primary files.
|
||||
|
||||
Primary files:
|
||||
- `src/tls_aes128.c`
|
||||
- `src/tls_builtin.c`
|
||||
- `src/tls_chacha20.c`
|
||||
- `src/tls_dummy.c`
|
||||
- `src/tls_mbed.c`
|
||||
- `src/tls_openssl.c`
|
||||
- `src/tls_rsa.c`
|
||||
- `src/tls_uecc.c`
|
||||
- `src/tls_x25519.c`
|
||||
|
||||
Perform a focused security review centered on these files and this security surface.
|
||||
|
||||
Supporting code elsewhere under `src/` may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not inspect or report code outside `src/` or independently review unrelated areas.
|
||||
|
||||
Connection, core, network, and helper code under `src/` may be inspected when needed to understand the complete TLS execution path.
|
||||
|
||||
## Area-Specific Security Guidance
|
||||
|
||||
### Mandatory High-Risk Coverage: Built-In TLS
|
||||
|
||||
The built-in TLS implementation (`MG_TLS_BUILTIN`) is a mandatory high-risk review target. Perform a substantial security analysis of all security-relevant built-in TLS code, including parsing, cryptographic processing, authentication and certificate validation, length and buffer handling, protocol state, cross-call behavior, and failure paths.
|
||||
|
||||
Trace attacker-controlled TLS peer input through normal client and server execution, including traffic received before peer authentication is complete. Report any credible memory-safety, authentication, confidentiality, integrity, state-corruption, or remotely triggerable availability vulnerability.
|
||||
|
||||
**TLS, Certificate, Hostname Verification, and Cryptographic Validation:**
|
||||
- Review all TLS backends, including built-in TLS, mbedTLS, OpenSSL, WolfSSL, and custom TLS integration, for equivalent security behavior where possible.
|
||||
- Flag certificate verification bypasses, accidental `skip_verification` use in security-sensitive defaults, missing hostname verification when `name`/SNI is available, or inconsistent validation across TLS backends.
|
||||
- For hostname verification, check wildcard handling carefully. A wildcard certificate identity must not match multiple DNS labels. For example, `*.example.com` must not match `a.b.example.com`.
|
||||
- Verify that wildcard matching is applied only to certificate presented identifiers, not to arbitrary reference identifiers or general DNS glob matching.
|
||||
- Review `mg_match` or other glob/matching helpers if used for certificate identity checks, authorization checks, filesystem paths, routing, or topic matching. Flag cases where glob semantics are broader than the security policy requires.
|
||||
- Check certificate parsing for DER/PEM boundary errors, length overflows, malformed ASN.1, extension parsing mistakes, name constraints, SAN vs CN precedence, embedded NUL, and invalid string type handling.
|
||||
- Review TLS record parsing, handshake transcript handling, key schedule, random generation, ECC/X25519 operations, AES-GCM nonce/tag handling, and error handling for memory safety and authentication failures.
|
||||
- Flag any behavior that silently falls back from verified TLS to unverified TLS or plaintext.
|
||||
- Check that TLS receive/send error paths cannot corrupt connection state, reuse freed buffers, or continue processing unauthenticated plaintext as encrypted data.
|
||||
@@ -0,0 +1,61 @@
|
||||
# Security Scan Area: web_http_auth
|
||||
|
||||
## Target
|
||||
|
||||
Area: web_http_auth
|
||||
|
||||
This area covers HTTP parsing and framing, HTTP-facing filesystem behavior, SSI, WebSocket, authentication/token/dashboard code, and HTTP-based OTA behavior.
|
||||
|
||||
Primary files:
|
||||
- `src/http.c`
|
||||
- `src/ssi.c`
|
||||
- `src/ws.c`
|
||||
- `src/jwt.c`
|
||||
- `src/dash.c`
|
||||
- `src/ota.c`
|
||||
|
||||
Perform a focused security review centered on these files and this security surface.
|
||||
|
||||
Supporting code elsewhere under `src/` may be inspected when necessary to establish reachability, data flow, state, validation, mitigation, or impact, but do not inspect or report code outside `src/` or independently review unrelated areas.
|
||||
|
||||
For OTA behavior, follow operations under `src/` into TLS, flash, filesystem, JSON, URL, or other support code when necessary, while keeping the review centered on the `web_http_auth` surface.
|
||||
|
||||
## Area-Specific Security Guidance
|
||||
|
||||
**HTTP Parser, Request Smuggling, and Message Framing:**
|
||||
- Verify that HTTP requests or responses containing both `Content-Length` and `Transfer-Encoding` are rejected or handled in a way that cannot cause front-end/back-end desynchronization. Treat CL+TE coexistence as security-relevant request smuggling risk.
|
||||
- Verify that duplicate `Content-Length`, duplicate `Transfer-Encoding`, conflicting transfer codings, malformed chunk sizes, chunk extensions, premature EOF, and body length mismatches cannot cause inconsistent body parsing.
|
||||
- Check whether HTTP/1.0, HTTP/1.1, and malformed protocol versions alter CL/TE handling unsafely. A message with both `Content-Length` and `Transfer-Encoding` should not be accepted merely because of version differences.
|
||||
- Look for parsing paths where headers are normalized differently from later lookup paths, including case folding, whitespace around colon, obs-fold/line folding, embedded NUL, duplicate headers, or partial header names.
|
||||
- Review URL decoding, query parsing, multipart parsing, upload handling, range handling, and chunked responses for bounds mistakes, truncation, or inconsistent decoded-vs-raw path decisions.
|
||||
- Check static file serving and SSI handling for path traversal through percent-encoding, double decoding, backslashes on Windows, mixed separators, dot-dot segments, absolute paths, drive letters, symlinks, embedded NUL, or alias/root_dir confusion.
|
||||
- Review HTTP authentication helper paths for parsing ambiguities in Basic auth, header extraction, credential truncation, empty username/password acceptance, or incorrect comparison behavior.
|
||||
- Check that HTTP upgrade to WebSocket validates method, headers, key, version, and connection semantics consistently before switching protocol state.
|
||||
|
||||
**WebSocket Framing and Upgrade Vulnerabilities:**
|
||||
- Review WebSocket frame parsing for extended payload length handling, 16-bit/64-bit length conversion, masking rules, fragmentation, continuation frames, control-frame length limits, close/ping/pong handling, and compression-related assumptions if present.
|
||||
- Check that client-to-server frames require masking and that malformed mask/payload boundaries cannot read or write out of bounds.
|
||||
- Look for state-machine confusion after HTTP upgrade, especially where partial frames, fragmented messages, or mixed HTTP/WebSocket bytes can cause parser desynchronization.
|
||||
- Check whether large or malformed frame lengths can cause integer overflow, memory corruption, uncontrolled allocation, connection lockup, or single-connection/device crash.
|
||||
- Verify that WebSocket message APIs preserve attacker-controlled binary data length correctly and do not pass non-null-terminated payloads to C-string functions.
|
||||
|
||||
**HTTP-Facing Filesystem Serving, Uploads, and SSI:**
|
||||
- Review `mg_http_serve_dir`, `mg_http_serve_file`, upload APIs, and SSI expansion for traversal, unauthorized file read/write, overwrite, truncation, or unexpected executable/include behavior.
|
||||
- Look for inconsistent handling of decoded and undecoded paths, double decoding, query string leakage into path, trailing slash confusion, NUL byte truncation, and case sensitivity differences.
|
||||
- Review multipart upload parsing for boundary confusion, filename traversal, field length overflow, partial-write behavior, and max-size enforcement.
|
||||
- Check SSI include handling for directory escape, recursive include loops, unintended disclosure of local files, and parsing of attacker-controlled SSI directives.
|
||||
- Verify that range requests and static response headers cannot cause out-of-bounds reads or disclose memory.
|
||||
|
||||
**OTA/Firmware Update and Device Dashboard Security:**
|
||||
- Review firmware update endpoints and code paths for missing authentication, authorization bypass, path confusion, arbitrary write, unsafe flash offset/length handling, and failure to verify firmware authenticity where the code claims secure update behavior.
|
||||
- Check update chunk parsing for integer overflow, flash boundary crossing, rollback/downgrade exposure, incomplete image bootability, and crash/power-loss unsafe state transitions.
|
||||
- Flag any code path where unauthenticated network input can write firmware, configuration, filesystem contents, flash pages, bootloader state, or device identity material.
|
||||
- Review device dashboard code for security-sensitive default routes, credentials, upload handlers, debug endpoints, config mutation endpoints, and CORS/header behavior.
|
||||
|
||||
**Authentication, Authorization, and Access-Control Patterns in Mongoose Integrations:**
|
||||
- Review helper APIs and code paths that implement HTTP auth, cookies, sessions, tokens, device dashboards, REST APIs, upload endpoints, and firmware update endpoints.
|
||||
- Flag authentication bypasses caused by prefix route matching, glob matching, decoded-vs-raw URI confusion, case normalization mistakes, missing boundary checks, or default-open sensitive endpoints.
|
||||
- Check for authorization decisions made in client-side JavaScript only. Client-side checks are not security boundaries.
|
||||
- Review CORS and origin checks only when they protect credentialed sensitive operations and the exploit path is concrete.
|
||||
- Look for credential comparison bugs, truncation of usernames/passwords, accepting empty credentials, parsing only part of an Authorization header, or treating malformed credentials as anonymous-but-authorized.
|
||||
- Flag sensitive data exposure when secrets, credentials, tokens, private keys, firmware signing material, PII, or device identity values can be read by unauthorized remote clients or logged from attacker-triggered paths.
|
||||
@@ -5,7 +5,7 @@
|
||||
3. The exploit depends on NULL, dangling, fake, or corrupted pointers/objects supplied by a local caller, including invalid `mg_connection`, `mg_mgr`, `mg_str`, iobufs, or callback data.
|
||||
4. The exploit requires manually mutating internal structs, flags, parser offsets, descriptor indexes, connection state, TLS state, MQTT/WebSocket state, or filesystem state into impossible combinations.
|
||||
5. The bug exists only in tests, fuzz harnesses, benchmarks, synthetic unit tests, or debug-only code, with no shared production logic.
|
||||
6. The issue is only in a tutorial/demo/example with no realistic production relevance or sensitive operation.
|
||||
6. The affected file is outside `src/`.
|
||||
7. The attacker must edit source code, build flags, compile-time macros, TLS backend choices, filesystem roots, or local device configuration.
|
||||
8. The attacker must directly write hardware registers, MMIO, DMA descriptors, descriptor ownership bits, IRQ state, cache registers, or peripheral configuration.
|
||||
9. Generic DoS from high traffic volume, many valid connections, slow clients, missing quotas, missing rate limits, or ordinary resource saturation.
|
||||
@@ -14,6 +14,8 @@
|
||||
12. Generic crypto advice with no concrete impact on authentication, confidentiality, integrity, downgrade resistance, hostname verification, certificate validation, key handling, nonces/tags, or plaintext fallback.
|
||||
13. Speculative protocol claims without a specific malformed input shape, reachable parser path, and concrete security impact.
|
||||
14. Pure application policy gaps: no default auth, no CSRF, no user access model, no account lockout, no audit logs, or no password policy.
|
||||
15. OTA findings based only on allowing plain HTTP, lacking firmware hash/signature verification, or permitting update URLs to change scheme/host when this is documented/configurable behavior and no existing security check is bypassed.
|
||||
16. Filter TCP findings that rely primarily on predictability or insufficient entropy in protocol sequence-state generation, including attacks based on guessing or reconstructing connection state without observing the traffic.
|
||||
|
||||
# SIGNAL QUALITY CRITERIA
|
||||
**For remaining findings, assess:**
|
||||
@@ -25,7 +27,7 @@
|
||||
6. Does the report provide exact files, functions, line numbers, data flow, bounds reasoning, state reasoning, or a minimal malformed input?
|
||||
7. Is the malformed input shape clear, such as CL+TE HTTP, oversized MQTT SUBSCRIBE, malformed WebSocket length, DNS compression loop, wildcard TLS certificate, invalid packet header length, or encoded path traversal?
|
||||
8. Is the severity justified by reachability and impact?
|
||||
9. Is this a library/helper/default/example-pattern vulnerability rather than only arbitrary application misuse?
|
||||
9. Is this a library/helper/default vulnerability rather than only arbitrary application misuse?
|
||||
10. Is the fix specific enough to act on: reject CL+TE, bound arrays, validate DNS pointers, enforce one-label wildcard matching, check packet lengths, canonicalize paths, or bound RX loops?
|
||||
11. Is a DoS finding caused by a concrete implementation flaw rather than volume, slow clients, missing quotas, or capacity limits?
|
||||
12. In embedded context, can a small malformed input reliably crash, wedge, corrupt, or permanently disrupt a device/process?
|
||||
@@ -42,26 +44,26 @@
|
||||
8. Keep unsafe `mg_match` or glob use at security boundaries: certificate identity, route authorization, filesystem policy, MQTT topic authorization, or access control.
|
||||
9. Keep DNS/mDNS label, compression pointer, pointer loop, RR length, transaction matching, spoofing, OOB, or infinite-loop issues with external reachability.
|
||||
10. Keep filesystem traversal through exposed serving/upload/SSI paths, including encoding, double decoding, backslashes, dot-dot, absolute paths, drive letters, symlinks, NULs, alias/root confusion, and upload filename traversal.
|
||||
11. Keep OTA/update issues allowing unauthenticated or improperly validated writes to firmware, flash, config, filesystem, boot state, device identity, or update metadata.
|
||||
12. Keep embedded packet parser bugs in Ethernet, ARP, IP, IPv6, ICMP, UDP, TCP, DHCP, SNTP, or drivers when malformed traffic causes OOB, overflow, descriptor corruption, queue corruption, state corruption, or crash.
|
||||
13. Keep IRQ, polling, RX descriptor, and packet-loop livelock/starvation/wedge bugs caused by received traffic.
|
||||
14. Keep event-lifecycle bugs reachable from external input: UAF, stale pointer, double close, callback lifetime error, iobuf mutation after close, protocol transition confusion, timer/wakeup after free.
|
||||
15. Keep externally reachable `mg_str` null-termination mistakes causing OOB read, data leak, auth bypass, parser confusion, or crash.
|
||||
16. Keep integer conversion bugs where external lengths affect allocation, copying, parsing, or bounds checks.
|
||||
17. Filter parser/helper reports based only on a local caller passing invalid pointers, fake lengths, fake structs, or corrupted objects.
|
||||
18. Filter reports requiring direct mutation of connection internals such as protocol flags, closing flags, handler pointers, iobuf fields, callback pointers, or user data.
|
||||
19. Filter reports requiring attacker control of `MG_ENABLE_*`, TLS backend macros, filesystem backend macros, compiler flags, debug flags, sanitizer settings, or platform defines.
|
||||
20. Filter direct hardware-access reports requiring writes to registers, DMA descriptors, MMIO, IRQ state, cache controls, or peripheral configuration.
|
||||
21. Filter generic “Mongoose lacks authentication” reports unless a helper, example, route pattern, auth parser, MQTT broker behavior, dashboard, upload handler, or OTA endpoint creates a concrete issue.
|
||||
22. Filter generic rate-limit/quota/connection-cap/upload-cap findings unless a specific bug lets a small malformed input trigger crash, corruption, infinite loop, or disproportionate exhaustion.
|
||||
23. Filter purely theoretical UB, portability, unaligned-access, or signed-overflow reports with no supported-platform impact and no realistic external trigger.
|
||||
24. Filter RFC non-compliance without concrete smuggling, bypass, memory corruption, data exposure, state corruption, or crash.
|
||||
25. Keep security-relevant production-like examples: dashboards, upload servers, MQTT brokers, firmware update flows, auth examples, TLS examples, and filesystem-serving examples.
|
||||
26. Keep client-side findings caused by malicious servers, brokers, DNS responders, TLS peers, WebSocket peers, or HTTP peers.
|
||||
27. Keep callback-related findings only when Mongoose invokes the callback normally and then unsafely continues using freed or mutated state.
|
||||
28. Keep availability findings when one malformed packet, request, certificate, DNS response, MQTT message, WebSocket frame, or small sequence can reliably crash, wedge, corrupt, or disrupt a Mongoose target.
|
||||
29. Keep custom backend findings only when the issue is in Mongoose’s backend interface, default backend, documented backend contract, or common backend implementation.
|
||||
30. When uncertain, keep findings with clear external input, reachable code path, and concrete impact in Mongoose library/protocol/driver code; filter internal-access, impossible-state, local-misuse, generic-hardening, and speculative reports.
|
||||
31. For dashboard reports, do not infer unauthenticated access from a route-specific check alone; account for the broader authentication flow. Keep concrete reachable bugs such as path traversal, unsafe decoded paths, or file read/write/delete issues.
|
||||
32. Filter reports regarding DNS transaction ID predictability or lack of strict question-name matching in DNS response processing, as these are acknowledged design limitations of the current implementation.
|
||||
33. Filter reports that unauthenticated SNTP time affects TLS certificate validity when Mongoose only performs the SNTP sync if mg_boot_timestamp_ms has not already been initialized.
|
||||
11. Keep embedded packet parser bugs in Ethernet, ARP, IP, IPv6, ICMP, UDP, TCP, DHCP, SNTP, or drivers when malformed traffic causes OOB, overflow, descriptor corruption, queue corruption, state corruption, or crash.
|
||||
12. Keep IRQ, polling, RX descriptor, and packet-loop livelock/starvation/wedge bugs caused by received traffic.
|
||||
13. Keep event-lifecycle bugs reachable from external input: UAF, stale pointer, double close, callback lifetime error, iobuf mutation after close, protocol transition confusion, timer/wakeup after free.
|
||||
14. Keep externally reachable `mg_str` null-termination mistakes causing OOB read, data leak, auth bypass, parser confusion, or crash.
|
||||
15. Keep integer conversion bugs where external lengths affect allocation, copying, parsing, or bounds checks.
|
||||
16. Filter parser/helper reports based only on a local caller passing invalid pointers, fake lengths, fake structs, or corrupted objects.
|
||||
17. Filter reports requiring direct mutation of connection internals such as protocol flags, closing flags, handler pointers, iobuf fields, callback pointers, or user data.
|
||||
18. Filter reports requiring attacker control of `MG_ENABLE_*`, TLS backend macros, filesystem backend macros, compiler flags, debug flags, sanitizer settings, or platform defines.
|
||||
19. Filter direct hardware-access reports requiring writes to registers, DMA descriptors, MMIO, IRQ state, cache controls, or peripheral configuration.
|
||||
20. Filter generic “Mongoose lacks authentication” reports unless a helper, route pattern, auth parser, MQTT broker behavior, dashboard, upload handler, or OTA endpoint creates a concrete issue.
|
||||
21. Filter generic rate-limit/quota/connection-cap/upload-cap findings unless a specific bug lets a small malformed input trigger crash, corruption, infinite loop, or disproportionate exhaustion.
|
||||
22. Filter purely theoretical UB, portability, unaligned-access, or signed-overflow reports with no supported-platform impact and no realistic external trigger.
|
||||
23. Filter RFC non-compliance without concrete smuggling, bypass, memory corruption, data exposure, state corruption, or crash.
|
||||
24. Keep security-relevant production library code under `src/` for dashboards, uploads, MQTT, firmware updates, authentication, TLS, and filesystem serving.
|
||||
25. Keep client-side findings caused by malicious servers, brokers, DNS responders, TLS peers, WebSocket peers, or HTTP peers.
|
||||
26. Keep callback-related findings only when Mongoose invokes the callback normally and then unsafely continues using freed or mutated state.
|
||||
27. Keep availability findings when one malformed packet, request, certificate, DNS response, MQTT message, WebSocket frame, or small sequence can reliably crash, wedge, corrupt, or disrupt a Mongoose target.
|
||||
28. Keep custom backend findings only when the issue is in Mongoose’s backend interface, default backend, documented backend contract, or common backend implementation.
|
||||
29. When uncertain, keep findings with clear external input, reachable code path, and concrete impact in Mongoose library/protocol/driver code; filter internal-access, impossible-state, local-misuse, generic-hardening, and speculative reports.
|
||||
30. For dashboard reports, do not infer unauthenticated access from a route-specific check alone; account for the broader authentication flow. Keep concrete reachable bugs such as path traversal, unsafe decoded paths, or file read/write/delete issues.
|
||||
31. Filter reports regarding DNS transaction ID predictability or lack of strict question-name matching in DNS response processing, as these are acknowledged design limitations of the current implementation.
|
||||
32. Filter reports that unauthenticated SNTP time affects TLS certificate validity when Mongoose only performs the SNTP sync if mg_boot_timestamp_ms has not already been initialized.
|
||||
33. Filter TCP ISN predictability, weak sequence-number generation, RFC 6528 non-compliance, blind/off-path handshake spoofing, forged RST, and sequence-number-guessing reports in the built-in TCP/IP stack.
|
||||
@@ -1,24 +1,35 @@
|
||||
Review the complete PR diff. This contains all code changes in the PR.
|
||||
Review only changes under `src/` in the complete PR diff. Ignore all other changes in the PR.
|
||||
|
||||
# OBJECTIVE
|
||||
|
||||
Perform a security-focused code review to identify HIGH-CONFIDENCE security vulnerabilities that could have real exploitation potential.
|
||||
|
||||
This is not a general code review - focus ONLY on security implications newly added by this PR. Do not comment on existing security concerns.
|
||||
This is not a general code review - focus ONLY on security implications newly added by this PR under `src/`. Do not analyze, count, or report changes outside `src/`. Do not comment on existing security concerns.
|
||||
|
||||
For this task, you will rely on two additional files, `resources/specs/claude-security-scan-instructions.md` detailing security scan instructions specific to the repository and `resources/specs/claude-false-positive-filtering.md` detailing patterns, precedents, exclusion rules based on which some of the identified vulnerabilities will be excluded from the final reporting. The instructions, rules and criterias found in those two files are MANDATORY TO BE HONOURED and your security audit will have to take all of them into account.
|
||||
For this task, you will rely on the specified shared security-review sections in `resources/specs/claude-security-scan.md`, the specified security-guidance sections in the six `resources/specs/areas/*.md` prompts listed below, and `resources/specs/claude-false-positive-filtering.md` detailing patterns, precedents, exclusion rules based on which some of the identified vulnerabilities will be excluded from the final reporting. The instructions, rules and criterias found in those referenced sections and the filtering file are MANDATORY TO BE HONOURED and your security audit will have to take all of them into account.
|
||||
|
||||
YOU MUST READ AND ANALYZE BOTH OF THESE FILES BEFORE COMMENCING THE SECURITY AUDIT. THESE FILES, ALONG WITH SECTIONS FROM THEM, WILL BE MENTIONED IN THE FOLLOWING PARTS OF THIS PROMPT, PROVIDING FULL CONTEXT FOR ACCOMPLISHING THE GIVEN TASK.
|
||||
YOU MUST READ AND ANALYZE THE SPECIFIED SECTIONS AND THE FILTERING FILE BEFORE COMMENCING THE SECURITY AUDIT. THESE SOURCES WILL BE MENTIONED IN THE FOLLOWING PARTS OF THIS PROMPT, PROVIDING FULL CONTEXT FOR ACCOMPLISHING THE GIVEN TASK.
|
||||
|
||||
# CRITICAL INSTRUCTIONS
|
||||
1. MINIMIZE FALSE POSITIVES: Only flag issues where you're >80% confident of actual exploitability
|
||||
2. AVOID NOISE: Skip theoretical issues, style concerns, or low-impact findings
|
||||
3. UNDERSTANDING CONTEXT AND SCOPE OF REVIEW: In the security scan instructions file `resources/specs/claude-security-scan-instructions.md`, read the `External Attacker Threat Model` and `Mongoose-Specific Security Review Scope` subsections found in the `SECURITY SCAN CONTEXT` main section for a full understanding of the scanning model, code review context and the perspective from which the scanning is going to take place.
|
||||
3. UNDERSTANDING CONTEXT AND SCOPE OF REVIEW: In `resources/specs/claude-security-scan.md`, read only the `External Attacker Threat Model` and `Mongoose-Specific Security Review Scope` subsections found in the `SECURITY SCAN CONTEXT` main section for a full understanding of the scanning model, code review context and the perspective from which the scanning is going to take place. Do not apply unrelated full-scan instructions from that file. In particular, do not inherit assigned-area scan scope, full-scan JSON output requirements, full-scan `review_completed` semantics, instructions to scan long-standing code independently of the PR, or area-selection workflow behavior. This PR prompt's scope, methodology, validation, and output rules remain authoritative.
|
||||
4. TREAT EXCLUSIONS AS MANDATORY. The exclusions section below is mandatory. If a potential finding falls under an exclusion, do not report it. If a finding partially overlaps an exclusion, only report it if there is a concrete, non-excluded security impact.
|
||||
|
||||
# SECURITY CATEGORIES TO EXAMINE
|
||||
|
||||
In the security scan instructions file `resources/specs/claude-security-scan-instructions.md`, read all the security categories found in the `SECURITY CATEGORIES TO EXAMINE` main section. THESE ARE THE SECURITY CATEGORIES WHICH NEED TO BE EXAMINED.
|
||||
Read the general/common security categories in the `GENERAL SECURITY CATEGORIES TO EXAMINE` section of `resources/specs/claude-security-scan.md`.
|
||||
|
||||
Also read the `Area-Specific Security Guidance` section from every area prompt:
|
||||
|
||||
* `resources/specs/areas/common_misc.md`
|
||||
* `resources/specs/areas/mongoose_core.md`
|
||||
* `resources/specs/areas/web_http_auth.md`
|
||||
* `resources/specs/areas/tls.md`
|
||||
* `resources/specs/areas/net_builtin.md`
|
||||
* `resources/specs/areas/protocols.md`
|
||||
|
||||
Use only the security guidance from the area prompts and ignore their full-scan-specific `Target` sections. Consider the complete set of common and area-specific security categories for every file the PR modifies under `src/`. Do not choose one area or make this PR review area-scoped. Ignore all other changed paths and report only security vulnerabilities introduced by the PR under `src/`.
|
||||
|
||||
Use these categories to guide prioritization, not as a checklist requiring equal coverage of every item.
|
||||
|
||||
@@ -37,7 +48,7 @@ Phase 2 - Comparative Analysis:
|
||||
- Flag code that introduces new attack surfaces
|
||||
|
||||
Phase 3 - Vulnerability Assessment:
|
||||
- Examine each modified file for security implications
|
||||
- Examine each modified file under `src/` for security implications
|
||||
- Trace data flow from user inputs to sensitive operations
|
||||
- Look for privilege boundaries being crossed unsafely
|
||||
- Identify injection points and unsafe deserialization
|
||||
@@ -110,6 +121,6 @@ Better to miss some theoretical issues than flood the report with false positive
|
||||
|
||||
Read the `HARD EXCLUSIONS` section found in the `resources/specs/claude-false-positive-filtering.md` filtering file, for each possbile vulnerability found, check if it matches any items from the patterns listed in that section and if that is the case, exclude that vulnerability from the report. DO NOT REPORT IT if a match is found. Also, take into account the project-specific filtering and reporting precedents found in the `PRECEDENTS` section of the filtering file.
|
||||
|
||||
Begin your analysis now. Use the repository exploration tools to understand the codebase context, then analyze the PR changes for security implications.
|
||||
Begin your analysis now. Use the repository exploration tools to understand the `src/` codebase context, then analyze only the PR changes under `src/` for security implications.
|
||||
|
||||
Your final action must be posting the PR comment. You should not reply again after posting the PR comment.
|
||||
Your final action must be posting the PR comment. You should not reply again after posting the PR comment.
|
||||
@@ -1,130 +0,0 @@
|
||||
# SECURITY SCAN CONTEXT
|
||||
|
||||
**External Attacker Threat Model:**
|
||||
- Analyze vulnerabilities from the perspective of an external attacker, not from the perspective of a developer, local user, debugger, test harness, or code running inside the process.
|
||||
- The attacker can provide bytes through real external interfaces exposed by Mongoose or a Mongoose-based application: TCP, UDP, HTTP, WebSocket, MQTT, DNS, mDNS, TLS handshakes/certificates, Ethernet/IP/TCP/UDP packets, uploaded files, request paths, query strings, headers, message bodies, malicious server responses, and other protocol inputs.
|
||||
- The attacker cannot directly call internal C functions, pass arbitrary invalid pointers, mutate internal structs, invoke callbacks manually, edit compile-time macros, alter build flags, write to hardware registers, control DMA descriptors directly, attach a debugger, or run code inside the target process.
|
||||
- For a finding to be valid, show how attacker-controlled external input reaches the vulnerable code path through normal library/application execution.
|
||||
- Do not report findings that require impossible internal states unless the finding also explains how an external input can cause that state.
|
||||
- Do not report “API misuse” as a library vulnerability unless the API contract makes the insecure use likely, undocumented, or unavoidable.
|
||||
- For embedded networking and driver code, assume the attacker can send malformed network traffic to the device, but cannot directly manipulate hardware registers, memory-mapped I/O, DMA rings, or interrupt state except as a consequence of packets processed by the driver.
|
||||
|
||||
**Mongoose-Specific Security Review Scope:**
|
||||
- Treat this repository as a security-sensitive embedded C/C++ networking stack. Mongoose processes attacker-controlled bytes from TCP, UDP, HTTP, WebSocket, MQTT, DNS, mDNS, TLS, filesystem upload/download paths, and built-in TCP/IP drivers.
|
||||
- In this repository, remotely triggerable denial of service is security-relevant when it is caused by a concrete implementation flaw such as memory corruption, parser abort, assertion failure, stack exhaustion, infinite loop, unbounded recursion, IRQ livelock, connection state corruption, descriptor-ring corruption, or a single unauthenticated packet causing process/device crash.
|
||||
- Prioritize HIGH and MEDIUM severity findings. Include LOW only when unusually concrete, externally relevant, and useful. Do not report vague robustness concerns. Every finding must identify the attacker-controlled input, affected parser/state machine/buffer, concrete impact, and the exact code path.
|
||||
- Prefer findings with a plausible packet/request/message shape. For network protocol issues, describe the relevant malformed HTTP request, MQTT packet, WebSocket frame, DNS message, TLS handshake/certificate input, Ethernet/IP/TCP/UDP packet, or filesystem request.
|
||||
- Because this is C/C++, memory safety vulnerabilities are in scope. Buffer overflows, stack overflows, heap overflows, out-of-bounds reads/writes, use-after-free, double free, integer overflow leading to memory corruption, invalid pointer lifetime, and unsafe length conversions must be reviewed carefully.
|
||||
- Do not dismiss issues merely because they are “only DoS” if the issue is remotely triggerable against an embedded server, broker, device dashboard, firmware-update endpoint, or network-facing parser.
|
||||
|
||||
# SECURITY CATEGORIES TO EXAMINE
|
||||
|
||||
## Mandatory High-Risk Coverage: Built-In TLS
|
||||
|
||||
The built-in TLS implementation (`MG_TLS_BUILTIN`) is a mandatory high-risk review target. Perform a substantial security analysis of all security-relevant built-in TLS code, including parsing, cryptographic processing, authentication and certificate validation, length and buffer handling, protocol state, cross-call behavior, and failure paths.
|
||||
|
||||
Trace attacker-controlled TLS peer input through normal client and server execution, including traffic received before peer authentication is complete. Report any credible memory-safety, authentication, confidentiality, integrity, state-corruption, or remotely triggerable availability vulnerability.
|
||||
|
||||
Do not set `review_completed` to `true` unless the built-in TLS implementation has been meaningfully inspected as a whole.
|
||||
|
||||
|
||||
**C Memory Safety and Length-Handling Vulnerabilities:**
|
||||
- Look for writes to fixed-size stack or heap buffers where the loop bound is derived from attacker-controlled protocol fields, including topic counts, header counts, chunk counts, multipart parts, DNS labels, WebSocket fragments, TCP/IP options, or filesystem path components.
|
||||
- Check all conversions between `size_t`, `int`, `long`, `uint16_t`, `uint32_t`, and signed protocol lengths. Flag integer truncation, wraparound, negative-to-large conversion, or off-by-one behavior that can affect allocation, parsing, copying, or bounds checks.
|
||||
- Review any `memcpy`, `memmove`, `memcmp`, `snprintf`, `mg_snprintf`, `mg_xprintf`, iobuf append/delete/resize operation, and manual pointer increment where source length can originate from network input.
|
||||
- Treat `struct mg_str` values as non-null-terminated unless the code proves otherwise. Flag use of `strlen`, `%s`, `strcmp`, `strstr`, or C-string APIs on attacker-controlled `mg_str.buf` unless length and termination are guaranteed.
|
||||
- Check for parser code that advances pointers without proving that enough bytes remain. Flag any read of fixed-size fields, variable-length integers, DNS labels, TLS vectors, MQTT remaining length, WebSocket extended lengths, or HTTP chunks before bounds are validated.
|
||||
- Look for inconsistent ownership and lifetime of buffers referenced by `mg_str`, connection receive/send iobufs, TLS buffers, filesystem buffers, and event callback data.
|
||||
- Check for reentrancy hazards in event callbacks where user handlers may close a connection, mutate iobufs, start TLS, change protocol handlers, or free state while protocol code continues using stale pointers.
|
||||
|
||||
**HTTP Parser, Request Smuggling, and Message Framing:**
|
||||
- Verify that HTTP requests or responses containing both `Content-Length` and `Transfer-Encoding` are rejected or handled in a way that cannot cause front-end/back-end desynchronization. Treat CL+TE coexistence as security-relevant request smuggling risk.
|
||||
- Verify that duplicate `Content-Length`, duplicate `Transfer-Encoding`, conflicting transfer codings, malformed chunk sizes, chunk extensions, premature EOF, and body length mismatches cannot cause inconsistent body parsing.
|
||||
- Check whether HTTP/1.0, HTTP/1.1, and malformed protocol versions alter CL/TE handling unsafely. A message with both `Content-Length` and `Transfer-Encoding` should not be accepted merely because of version differences.
|
||||
- Look for parsing paths where headers are normalized differently from later lookup paths, including case folding, whitespace around colon, obs-fold/line folding, embedded NUL, duplicate headers, or partial header names.
|
||||
- Review URL decoding, query parsing, multipart parsing, upload handling, range handling, and chunked responses for bounds mistakes, truncation, or inconsistent decoded-vs-raw path decisions.
|
||||
- Check static file serving and SSI handling for path traversal through percent-encoding, double decoding, backslashes on Windows, mixed separators, dot-dot segments, absolute paths, drive letters, symlinks, embedded NUL, or alias/root_dir confusion.
|
||||
- Review HTTP authentication helper paths for parsing ambiguities in Basic auth, header extraction, credential truncation, empty username/password acceptance, or incorrect comparison behavior.
|
||||
- Check that HTTP upgrade to WebSocket validates method, headers, key, version, and connection semantics consistently before switching protocol state.
|
||||
|
||||
**MQTT Parser and Broker/Client State Machine Vulnerabilities:**
|
||||
- Review MQTT fixed header parsing, remaining-length decoding, variable-length integer loops, packet identifier handling, QoS transitions, topic extraction, property parsing, and MQTT 3.x vs MQTT 5 differences.
|
||||
- Look for malformed MQTT packets that can trigger out-of-bounds reads/writes, stack buffer overflow, heap corruption, assertion/crash, or parser desynchronization.
|
||||
- Specifically check SUBSCRIBE and UNSUBSCRIBE handling for unbounded numbers of topics, malformed topic length fields, missing QoS bytes, invalid QoS values, and writes to fixed-size response arrays.
|
||||
- Verify that PUBLISH handling enforces topic length, packet length, QoS rules, retained flag handling, packet identifier requirements, and message bounds before accessing fields.
|
||||
- Check broker examples and protocol handlers for authorization bypass, cross-topic data exposure, wildcard topic mishandling, `$SYS` or reserved topic confusion, and unintended publish/subscribe access.
|
||||
- Review MQTT reconnect/resubscribe logic for stale connection state, packet identifier reuse bugs, and memory lifetime problems after close/reconnect.
|
||||
- Treat unauthenticated single-packet broker crash, client crash from malicious broker response, or memory corruption during MQTT parsing as reportable.
|
||||
|
||||
**WebSocket Framing and Upgrade Vulnerabilities:**
|
||||
- Review WebSocket frame parsing for extended payload length handling, 16-bit/64-bit length conversion, masking rules, fragmentation, continuation frames, control-frame length limits, close/ping/pong handling, and compression-related assumptions if present.
|
||||
- Check that client-to-server frames require masking and that malformed mask/payload boundaries cannot read or write out of bounds.
|
||||
- Look for state-machine confusion after HTTP upgrade, especially where partial frames, fragmented messages, or mixed HTTP/WebSocket bytes can cause parser desynchronization.
|
||||
- Check whether large or malformed frame lengths can cause integer overflow, memory corruption, uncontrolled allocation, connection lockup, or single-connection/device crash.
|
||||
- Verify that WebSocket message APIs preserve attacker-controlled binary data length correctly and do not pass non-null-terminated payloads to C-string functions.
|
||||
|
||||
**TLS, Certificate, Hostname Verification, and Cryptographic Validation:**
|
||||
- Review all TLS backends, including built-in TLS, mbedTLS, OpenSSL, WolfSSL, and custom TLS integration, for equivalent security behavior where possible.
|
||||
- Flag certificate verification bypasses, accidental `skip_verification` use in security-sensitive examples or defaults, missing hostname verification when `name`/SNI is available, or inconsistent validation across TLS backends.
|
||||
- For hostname verification, check wildcard handling carefully. A wildcard certificate identity must not match multiple DNS labels. For example, `*.example.com` must not match `a.b.example.com`.
|
||||
- Verify that wildcard matching is applied only to certificate presented identifiers, not to arbitrary reference identifiers or general DNS glob matching.
|
||||
- Review `mg_match` or other glob/matching helpers if used for certificate identity checks, authorization checks, filesystem paths, routing, or topic matching. Flag cases where glob semantics are broader than the security policy requires.
|
||||
- Check certificate parsing for DER/PEM boundary errors, length overflows, malformed ASN.1, extension parsing mistakes, name constraints, SAN vs CN precedence, embedded NUL, and invalid string type handling.
|
||||
- Review TLS record parsing, handshake transcript handling, key schedule, random generation, ECC/X25519 operations, AES-GCM nonce/tag handling, and error handling for memory safety and authentication failures.
|
||||
- Flag any behavior that silently falls back from verified TLS to unverified TLS or plaintext.
|
||||
- Check that TLS receive/send error paths cannot corrupt connection state, reuse freed buffers, or continue processing unauthenticated plaintext as encrypted data.
|
||||
|
||||
**DNS, mDNS, URL Parsing, and Name Resolution:**
|
||||
- Review DNS and mDNS message parsing for label length validation, compression pointer loops, pointer bounds, recursive expansion limits, integer overflow, malformed resource records, and out-of-bounds reads.
|
||||
- Check that DNS answers are matched to outstanding requests by transaction ID, question name/type/class, and source expectations where applicable.
|
||||
- Look for cache poisoning, response spoofing, or name confusion if DNS response validation is weak in client or resolver code.
|
||||
- Review URL parsing for scheme, host, port, IPv6 literal, userinfo, percent-encoding, embedded NUL, empty host, default port, and path/query boundary confusion.
|
||||
- Check for SSRF-relevant behavior only when attacker input can control the destination host, protocol, or network boundary. Path-only control is not sufficient.
|
||||
- Verify that DNS failures, timeouts, and retries cannot leave dangling active request state or corrupt connection state.
|
||||
|
||||
**Built-In TCP/IP Stack, Packet Parsing, and Embedded Network Drivers:**
|
||||
- Review Ethernet, ARP, IP, IPv6, ICMP, UDP, TCP, DHCP, SNTP, and driver receive/transmit paths for packet-length validation before reading protocol headers.
|
||||
- Check IP/TCP/UDP header length fields, options length, fragmentation/reassembly behavior, checksum handling, and payload offset calculations for underflow, overflow, or out-of-bounds access.
|
||||
- Look for malformed packets that can corrupt descriptor rings, RX/TX buffers, queue state, ARP tables, connection state, or timers.
|
||||
- Review interrupt handlers and bare-metal driver code for bounded processing loops. Flag IRQ paths where attacker-controlled traffic can cause livelock, starvation, descriptor ownership loss, or repeated processing of the same malformed frame.
|
||||
- Check DMA descriptor ownership transitions, memory barriers, cache coherency handling, and buffer length fields for race-like bugs that can cause memory corruption or stale packet reuse.
|
||||
- Review platform-specific drivers such as STM32, NXP, TI, Microchip, Renesas, Infineon, Wiznet, Cypress WiFi, cellular, and other built-in stack integrations for inconsistent bounds checks or endian conversions.
|
||||
- Treat a remotely reachable malformed Ethernet/IP/TCP/UDP packet that crashes, wedges, or corrupts an embedded target as reportable.
|
||||
|
||||
**Filesystem Serving, Uploads, Packed Filesystems, and SSI:**
|
||||
- Review `mg_http_serve_dir`, `mg_http_serve_file`, upload APIs, packed filesystem code, and SSI expansion for traversal, unauthorized file read/write, overwrite, truncation, or unexpected executable/include behavior.
|
||||
- Check path canonicalization across POSIX, Windows, embedded filesystems, packed filesystems, and custom `mg_fs` implementations.
|
||||
- Look for inconsistent handling of decoded and undecoded paths, double decoding, query string leakage into path, trailing slash confusion, NUL byte truncation, and case sensitivity differences.
|
||||
- Review multipart upload parsing for boundary confusion, filename traversal, field length overflow, partial-write behavior, and max-size enforcement.
|
||||
- Check SSI include handling for directory escape, recursive include loops, unintended disclosure of local files, and parsing of attacker-controlled SSI directives.
|
||||
- Verify that range requests and static response headers cannot cause out-of-bounds reads or disclose memory.
|
||||
|
||||
**OTA/Firmware Update and Device Dashboard Security:**
|
||||
- Review firmware update endpoints and examples for missing authentication, authorization bypass, path confusion, arbitrary write, unsafe flash offset/length handling, and failure to verify firmware authenticity where the code claims secure update behavior.
|
||||
- Check update chunk parsing for integer overflow, flash boundary crossing, rollback/downgrade exposure, incomplete image bootability, and crash/power-loss unsafe state transitions.
|
||||
- Flag any code path where unauthenticated network input can write firmware, configuration, filesystem contents, flash pages, bootloader state, or device identity material.
|
||||
- Review device dashboard examples for security-sensitive default routes, credentials, upload handlers, debug endpoints, config mutation endpoints, and CORS/header behavior when they are likely to be copied into production.
|
||||
- Do not report ordinary insecure demo behavior unless it creates a realistic copy-paste production vulnerability or affects library code.
|
||||
|
||||
**Protocol State Machine and Event-Driven Lifecycle Bugs:**
|
||||
- Review transitions between listening, accepted, connecting, resolving, TLS handshaking, HTTP, WebSocket, MQTT, draining, closing, and closed states.
|
||||
- Check whether malformed input can cause protocol handlers to process data in the wrong state, process stale data after close, or invoke callbacks with invalid event data.
|
||||
- Look for use-after-free or stale pointer use when callbacks call `mg_close_conn`, mark a connection closing, mutate iobufs, change protocol handlers, or initiate TLS/WebSocket/MQTT transitions.
|
||||
- Verify that partial reads/writes, backpressure, `is_full`, draining, TLS pending states, and send-buffer mutations cannot cause duplicated sends, skipped validation, or parser confusion.
|
||||
- Review timer and wakeup handling for stale user data pointers, cross-thread queue misuse, and callbacks firing after associated connections/state have been freed.
|
||||
- Only report concurrency or race issues when a concrete event ordering can trigger memory corruption, unauthorized action, or reliable device/process crash.
|
||||
|
||||
**Cross-Platform C Portability With Security Impact:**
|
||||
- Review code paths whose security depends on struct packing, alignment, endianness, pointer size, signedness of `char`, integer width, or platform-specific filesystem/network behavior.
|
||||
- Check for unaligned memory access on embedded targets when parsing attacker-controlled network packets.
|
||||
- Verify endian conversions for Ethernet/IP/TCP/UDP/DNS/MQTT/TLS fields before bounds checks and allocations.
|
||||
- Look for platform branches where one backend performs validation and another does not, especially across UNIX, Windows, lwIP, Zephyr, FreeRTOS-like systems, bare-metal, and built-in TCP/IP stack modes.
|
||||
- Flag portability bugs only when they create a realistic vulnerability on a supported platform, not merely theoretical undefined behavior.
|
||||
|
||||
**Authentication, Authorization, and Access-Control Patterns in Mongoose Integrations:**
|
||||
- Review examples and helper APIs that implement HTTP auth, cookies, sessions, tokens, device dashboards, REST APIs, MQTT topic access, upload endpoints, and firmware update endpoints.
|
||||
- Flag authentication bypasses caused by prefix route matching, glob matching, decoded-vs-raw URI confusion, case normalization mistakes, missing boundary checks, or default-open sensitive endpoints.
|
||||
- Check for authorization decisions made in client-side JavaScript only. Client-side checks are not security boundaries.
|
||||
- Review CORS and origin checks only when they protect credentialed sensitive operations and the exploit path is concrete.
|
||||
- Look for credential comparison bugs, truncation of usernames/passwords, accepting empty credentials, parsing only part of an Authorization header, or treating malformed credentials as anonymous-but-authorized.
|
||||
- Flag sensitive data exposure when secrets, credentials, tokens, private keys, firmware signing material, PII, or device identity values can be read by unauthorized remote clients or logged from attacker-triggered paths.
|
||||
@@ -1,24 +1,34 @@
|
||||
# Full Codebase Security Scan Prompt
|
||||
# Security Scan Master Prompt
|
||||
|
||||
You are an expert security reviewer performing a full-codebase security audit of the checked-out repository.
|
||||
You are an expert security reviewer performing a focused security audit centered on one assigned scan area in the checked-out repository.
|
||||
|
||||
You must analyze the repository as a whole and identify credible, externally reachable security vulnerabilities in the current implementation.
|
||||
You must analyze the assigned target and security surface and identify credible, externally reachable security vulnerabilities in the current implementation.
|
||||
|
||||
For this task, you will rely on two additional files, `resources/specs/claude-security-scan-instructions.md` detailing security scan instructions specific to the repository and `resources/specs/claude-false-positive-filtering.md` detailing patterns, precedents, exclusion rules based on which some of the identified vulnerabilities will be excluded from the final reporting. The instructions, rules and criterias found in those two files are MANDATORY TO BE HONOURED and your security audit will have to take all of them into account.
|
||||
Every full security scan uses:
|
||||
|
||||
YOU MUST READ AND ANALYZE BOTH OF THESE FILES BEFORE COMMENCING THE SECURITY AUDIT. THESE FILES, ALONG WITH SECTIONS FROM THEM, WILL BE MENTIONED IN THE FOLLOWING PARTS OF THIS PROMPT, PROVIDING FULL CONTEXT FOR ACCOMPLISHING THE GIVEN TASK.
|
||||
1. the shared master prompt: `resources/specs/claude-security-scan.md`;
|
||||
2. one area prompt selected by the workflow: `resources/specs/areas/<area>.md`;
|
||||
3. the common filtering prompt: `resources/specs/claude-false-positive-filtering.md`.
|
||||
|
||||
The area prompt defines what is being scanned. This master prompt defines how security analysis and reporting are performed. The filtering prompt defines what must not be reported and which historical precedents must be honored.
|
||||
|
||||
YOU MUST READ AND ANALYZE THE ASSIGNED AREA PROMPT AND THE COMMON FILTERING PROMPT BEFORE COMMENCING THE SECURITY AUDIT. THE INSTRUCTIONS, RULES, AND CRITERIA IN ALL THREE PROMPTS ARE MANDATORY TO BE HONORED.
|
||||
|
||||
## OBJECTIVE
|
||||
|
||||
You are reviewing a full source repository for security vulnerabilities.
|
||||
You are reviewing one assigned security area in a source repository for security vulnerabilities.
|
||||
|
||||
The repository may contain application code, protocol parsers, networking code, embedded code, library code, examples, tests, build scripts, documentation, generated files, and third-party/vendor code.
|
||||
The `src/` directory contains the protocol parsers, networking code, embedded code, library code, generated code, and platform-specific code in scope for this review.
|
||||
|
||||
Your task is to determine which parts of the repository are security-relevant, identify externally reachable attack surfaces, and report only findings with a concrete vulnerability pattern, credible attacker influence, and meaningful security impact.
|
||||
The area-specific prompt defines the primary files and security surface for this invocation. Your task is to identify externally reachable attack surfaces within that assigned area and report only findings with a concrete vulnerability pattern, credible attacker influence, and meaningful security impact.
|
||||
|
||||
The security review target is limited to code under `src/`. Do not analyze, count, or report code outside `src/` as part of the security review.
|
||||
|
||||
You may inspect code outside the listed target files only when it is also under `src/` and is necessary to understand data flow, reachability, call chains, state transitions, memory ownership, mitigations, authentication or authorization, protocol interaction, exploitability, or impact. Inspecting supporting code must not turn into an independent security review of unrelated areas. Findings must remain tied to the assigned target and security surface and must identify an affected file under `src/`.
|
||||
|
||||
DO NOT modify files, create commits, open PRs, create issues or post comments! You must only produce the final JSON report requested below.
|
||||
|
||||
Identify high-confidence security vulnerabilities in the full codebase. For this prompt, high-confidence means confidence >= 0.7 under the scoring rules below. Focus on vulnerabilities that are reachable through normal execution paths and attacker-controlled inputs. Report only findings that have a concrete security impact.
|
||||
Identify high-confidence security vulnerabilities in the assigned scan area. For this prompt, high-confidence means confidence >= 0.7 under the scoring rules below. Focus on vulnerabilities that are reachable through normal execution paths and attacker-controlled inputs. Report only findings that have a concrete security impact.
|
||||
|
||||
Do not report vague best-practice concerns, speculative hardening suggestions, style issues, maintainability concerns, generic bug risks, or findings without a clear attacker-controlled path.
|
||||
|
||||
@@ -26,9 +36,26 @@ Existing vulnerabilities in the current codebase are in scope.
|
||||
|
||||
Previously introduced vulnerabilities are in scope.
|
||||
|
||||
Any security-relevant issue present in the checked-out repository is in scope unless explicitly excluded below.
|
||||
Any security-relevant issue tied to the assigned target or security surface is in scope unless explicitly excluded below.
|
||||
|
||||
In the security scan instructions file `resources/specs/claude-security-scan-instructions.md`, read the `External Attacker Threat Model` and `Mongoose-Specific Security Review Scope` subsections found in the `SECURITY SCAN CONTEXT` main section for a full understanding of the scanning model and the code review context.
|
||||
## SECURITY SCAN CONTEXT
|
||||
|
||||
**External Attacker Threat Model:**
|
||||
- Analyze vulnerabilities from the perspective of an external attacker, not from the perspective of a developer, local user, debugger, test harness, or code running inside the process.
|
||||
- The attacker can provide bytes through real external interfaces exposed by Mongoose or a Mongoose-based application: TCP, UDP, HTTP, WebSocket, MQTT, DNS, mDNS, TLS handshakes/certificates, Ethernet/IP/TCP/UDP packets, uploaded files, request paths, query strings, headers, message bodies, malicious server responses, and other protocol inputs.
|
||||
- The attacker cannot directly call internal C functions, pass arbitrary invalid pointers, mutate internal structs, invoke callbacks manually, edit compile-time macros, alter build flags, write to hardware registers, control DMA descriptors directly, attach a debugger, or run code inside the target process.
|
||||
- For a finding to be valid, show how attacker-controlled external input reaches the vulnerable code path through normal library/application execution.
|
||||
- Do not report findings that require impossible internal states unless the finding also explains how an external input can cause that state.
|
||||
- Do not report “API misuse” as a library vulnerability unless the API contract makes the insecure use likely, undocumented, or unavoidable.
|
||||
- For embedded networking and driver code, assume the attacker can send malformed network traffic to the device, but cannot directly manipulate hardware registers, memory-mapped I/O, DMA rings, or interrupt state except as a consequence of packets processed by the driver.
|
||||
|
||||
**Mongoose-Specific Security Review Scope:**
|
||||
- Treat this repository as a security-sensitive embedded C/C++ networking stack. Mongoose processes attacker-controlled bytes from TCP, UDP, HTTP, WebSocket, MQTT, DNS, mDNS, TLS, filesystem upload/download paths, and built-in TCP/IP drivers.
|
||||
- In this repository, remotely triggerable denial of service is security-relevant when it is caused by a concrete implementation flaw such as memory corruption, parser abort, assertion failure, stack exhaustion, infinite loop, unbounded recursion, IRQ livelock, connection state corruption, descriptor-ring corruption, or a single unauthenticated packet causing process/device crash.
|
||||
- Prioritize HIGH and MEDIUM severity findings. Include LOW only when unusually concrete, externally relevant, and useful. Do not report vague robustness concerns. Every finding must identify the attacker-controlled input, affected parser/state machine/buffer, concrete impact, and the exact code path.
|
||||
- Prefer findings with a plausible packet/request/message shape. For network protocol issues, describe the relevant malformed HTTP request, MQTT packet, WebSocket frame, DNS message, TLS handshake/certificate input, Ethernet/IP/TCP/UDP packet, or filesystem request.
|
||||
- Because this is C/C++, memory safety vulnerabilities are in scope. Buffer overflows, stack overflows, heap overflows, out-of-bounds reads/writes, use-after-free, double free, integer overflow leading to memory corruption, invalid pointer lifetime, and unsafe length conversions must be reviewed carefully.
|
||||
- Do not dismiss issues merely because they are “only DoS” if the issue is remotely triggerable against an embedded server, broker, device dashboard, firmware-update endpoint, or network-facing parser.
|
||||
|
||||
## CRITICAL INSTRUCTIONS
|
||||
|
||||
@@ -56,12 +83,14 @@ Do not report:
|
||||
* Purely defensive hardening suggestions.
|
||||
* Issues that only matter under unrealistic assumptions.
|
||||
|
||||
### 3. Analyze the repository as a whole
|
||||
### 3. Analyze the assigned scan area
|
||||
|
||||
This is a full-codebase scan. You should inspect the repository structure, identify major components, and prioritize security-sensitive code paths.
|
||||
This is a targeted scan centered on the primary files and security surface defined by the assigned area prompt. Follow relevant supporting code under `src/` when necessary to establish reachability, data flow, state, validation, mitigation, exploitability, or impact, but do not inspect code outside `src/` as part of the security review or independently review unrelated areas.
|
||||
|
||||
Do not restrict analysis to a diff. Do not assume only changed files matter. Do not assume an issue is irrelevant because it appears in old or long-standing code.
|
||||
|
||||
Findings must remain tied to the assigned target and security surface.
|
||||
|
||||
### 4. Prioritize externally reachable attack surfaces
|
||||
|
||||
Prioritize code reachable from attacker-controlled or peer-controlled inputs. Relevant inputs may include, but are not limited to:
|
||||
@@ -94,25 +123,40 @@ The exclusions section below is mandatory. If a potential finding falls under an
|
||||
|
||||
If a finding partially overlaps an exclusion, only report it if there is a concrete, non-excluded security impact.
|
||||
|
||||
## SECURITY CATEGORIES TO EXAMINE
|
||||
## GENERAL SECURITY CATEGORIES TO EXAMINE
|
||||
|
||||
In the security scan instructions file `resources/specs/claude-security-scan-instructions.md`, read all the security categories found in the `SECURITY CATEGORIES TO EXAMINE` main section. THESE ARE THE SECURITY CATEGORIES WHICH NEED TO BE EXAMINED.
|
||||
The following common security categories apply to every assigned scan area. The assigned area prompt provides additional area-specific security guidance.
|
||||
|
||||
Use these categories to guide prioritization, not as a checklist requiring equal coverage of every item.
|
||||
|
||||
**C Memory Safety and Length-Handling Vulnerabilities:**
|
||||
- Look for writes to fixed-size stack or heap buffers where the loop bound is derived from attacker-controlled protocol fields, including topic counts, header counts, chunk counts, multipart parts, DNS labels, WebSocket fragments, TCP/IP options, or filesystem path components.
|
||||
- Check all conversions between `size_t`, `int`, `long`, `uint16_t`, `uint32_t`, and signed protocol lengths. Flag integer truncation, wraparound, negative-to-large conversion, or off-by-one behavior that can affect allocation, parsing, copying, or bounds checks.
|
||||
- Review any `memcpy`, `memmove`, `memcmp`, `snprintf`, `mg_snprintf`, `mg_xprintf`, iobuf append/delete/resize operation, and manual pointer increment where source length can originate from network input.
|
||||
- Treat `struct mg_str` values as non-null-terminated unless the code proves otherwise. Flag use of `strlen`, `%s`, `strcmp`, `strstr`, or C-string APIs on attacker-controlled `mg_str.buf` unless length and termination are guaranteed.
|
||||
- Check for parser code that advances pointers without proving that enough bytes remain. Flag any read of fixed-size fields, variable-length integers, DNS labels, TLS vectors, MQTT remaining length, WebSocket extended lengths, or HTTP chunks before bounds are validated.
|
||||
- Look for inconsistent ownership and lifetime of buffers referenced by `mg_str`, connection receive/send iobufs, TLS buffers, filesystem buffers, and event callback data.
|
||||
- Check for reentrancy hazards in event callbacks where user handlers may close a connection, mutate iobufs, start TLS, change protocol handlers, or free state while protocol code continues using stale pointers.
|
||||
|
||||
**Cross-Platform C Portability With Security Impact:**
|
||||
- Review code paths whose security depends on struct packing, alignment, endianness, pointer size, signedness of `char`, integer width, or platform-specific filesystem/network behavior.
|
||||
- Check for unaligned memory access on embedded targets when parsing attacker-controlled network packets.
|
||||
- Verify endian conversions for Ethernet/IP/TCP/UDP/DNS/MQTT/TLS fields before bounds checks and allocations.
|
||||
- Look for platform branches where one backend performs validation and another does not, especially across UNIX, Windows, lwIP, Zephyr, FreeRTOS-like systems, bare-metal, and built-in TCP/IP stack modes.
|
||||
- Flag portability bugs only when they create a realistic vulnerability on a supported platform, not merely theoretical undefined behavior.
|
||||
|
||||
## ANALYSIS METHODOLOGY
|
||||
|
||||
Follow this methodology before producing the final JSON.
|
||||
|
||||
### Phase 1: Repository context research
|
||||
|
||||
First, understand the repository.
|
||||
First, understand the assigned area within `src/`.
|
||||
|
||||
Identify:
|
||||
|
||||
* Main source directories.
|
||||
* Build systems.
|
||||
* Public APIs.
|
||||
* Relevant directories under `src/`.
|
||||
* Public APIs declared under `src/`.
|
||||
* Protocol implementations.
|
||||
* Network-facing components.
|
||||
* File parsing components.
|
||||
@@ -120,14 +164,13 @@ Identify:
|
||||
* TLS, crypto, or certificate validation logic.
|
||||
* Memory management patterns.
|
||||
* Platform-specific code.
|
||||
* Example, test, fuzz, generated, and vendor directories.
|
||||
* Components most likely to process attacker-controlled input.
|
||||
* Components in the assigned area most likely to process attacker-controlled input.
|
||||
|
||||
Use repository files to infer the actual architecture instead of assuming a generic web application model.
|
||||
Use files under `src/` to infer the actual architecture instead of assuming a generic web application model.
|
||||
|
||||
### Phase 2: Attack surface mapping
|
||||
|
||||
Map the externally reachable attack surfaces.
|
||||
Map the externally reachable attack surfaces within the assigned area.
|
||||
|
||||
For each important surface, determine:
|
||||
|
||||
@@ -166,6 +209,7 @@ Before including any finding in the final output, confirm:
|
||||
* The severity matches the impact.
|
||||
* The finding is not a duplicate of another finding.
|
||||
* The finding is not excluded.
|
||||
* The finding is tied to the assigned target or security surface.
|
||||
|
||||
If you cannot provide this level of specificity, do not report the finding.
|
||||
|
||||
@@ -218,6 +262,8 @@ The value of `files_reviewed` should reflect the number of files substantially i
|
||||
|
||||
Do not inflate this number by counting files that were only listed or briefly skimmed.
|
||||
|
||||
The value `review_completed: true` means the assigned scan area was meaningfully reviewed, not that the entire repository was reviewed.
|
||||
|
||||
## SEVERITY GUIDELINES
|
||||
|
||||
Use these severity definitions.
|
||||
@@ -313,10 +359,9 @@ Take into account the project-specific filtering and reporting precedents found
|
||||
|
||||
## DIRECTORY AND FILE EXCLUSIONS
|
||||
|
||||
Do not analyze or report findings from the following paths unless they are directly used by production/library code:
|
||||
- .github/
|
||||
- resources/
|
||||
- test/
|
||||
Only analyze and report findings from files under `src/`.
|
||||
|
||||
Do not analyze or count code outside `src/` as part of the security review.
|
||||
|
||||
## OUTPUT REQUIREMENTS
|
||||
|
||||
@@ -336,4 +381,4 @@ Do not include commentary.
|
||||
|
||||
Do not reply again after outputting the JSON.
|
||||
|
||||
Begin the full-codebase security analysis now.
|
||||
Begin the assigned-area security analysis now.
|
||||
+2
-1
@@ -12,7 +12,8 @@
|
||||
#include <sys/types.h>
|
||||
#include <time.h>
|
||||
|
||||
#ifndef MG_PATH_MAX
|
||||
#define MG_PATH_MAX 100
|
||||
#define MG_ENABLE_DIRLIST 0
|
||||
#endif
|
||||
|
||||
#endif
|
||||
+2
-1
@@ -18,7 +18,8 @@
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifndef MG_PATH_MAX
|
||||
#define MG_PATH_MAX 100
|
||||
#define MG_ENABLE_DIRLIST 0
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -25,10 +25,6 @@
|
||||
#define MG_PATH_MAX 100
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 0
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef MG_ENABLE_TCPIP
|
||||
#define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack
|
||||
|
||||
@@ -33,10 +33,6 @@
|
||||
#define MG_ENABLE_POSIX_FS 1
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 1
|
||||
#endif
|
||||
|
||||
#ifndef MG_OTA_ESP32_WDT_TIMEOUT_MS
|
||||
#define MG_OTA_ESP32_WDT_TIMEOUT_MS 10000U
|
||||
#endif
|
||||
|
||||
+83
-6
@@ -27,16 +27,12 @@
|
||||
#define MG_PATH_MAX 100
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 0
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_TCPIP
|
||||
#define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack
|
||||
#endif
|
||||
|
||||
#if MG_ENABLE_TCPIP && !defined(MG_ENABLE_DRIVER_IMXRT10) && \
|
||||
!defined(MG_ENABLE_DRIVER_IMXRT11)
|
||||
!defined(MG_ENABLE_DRIVER_IMXRT11) && !defined(MG_ENABLE_DRIVER_NETC)
|
||||
#if defined(CPU_MIMXRT1021DAG5A) || defined(CPU_MIMXRT1024DAG5A) || \
|
||||
defined(CPU_MIMXRT1042XJM5B) || defined(CPU_MIMXRT1052DVL6B) || \
|
||||
defined(CPU_MIMXRT1062DVL6B) || defined(CPU_MIMXRT1064DVL6B) || \
|
||||
@@ -51,6 +47,8 @@
|
||||
defined(_MIMXRT1176_cm7_H_) || defined(_MIMXRT1176_cm4_H_) || \
|
||||
defined(_MIMXRT1176_H_)
|
||||
#define MG_ENABLE_DRIVER_IMXRT11 1
|
||||
#elif defined(CPU_MIMXRT1186CVJ8C_cm33) || defined(MIMXRT1186_cm33_H_)
|
||||
#define MG_ENABLE_DRIVER_NETC 1
|
||||
#else
|
||||
#error Select an Ethernet driver in mongoose_config.h
|
||||
#endif
|
||||
@@ -82,13 +80,31 @@
|
||||
defined(_MIMXRT1176_cm7_H_) || defined(_MIMXRT1176_cm4_H_) || \
|
||||
defined(_MIMXRT1176_H_))
|
||||
#define MG_OTA MG_OTA_RT1170
|
||||
#elif !defined(MG_OTA) && \
|
||||
(defined(CPU_MIMXRT1186CVJ8C_cm33) || defined(MIMXRT1186_cm33_H_))
|
||||
#define MG_OTA MG_OTA_RT1180
|
||||
#endif
|
||||
|
||||
#ifndef MG_IRAM
|
||||
#if defined(CPU_MIMXRT1186CVJ8C_cm33) || defined(MIMXRT1186_cm33_H_)
|
||||
#define MG_IRAM \
|
||||
__attribute__((noinline, section(".ramfunc.$SRAM_ITC_cm33")))
|
||||
#else
|
||||
#define MG_IRAM __attribute__((noinline, section(".data_RAM2")))
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef MG_ETH_RAM
|
||||
#if defined(CPU_MIMXRT1186CVJ8C_cm33) || defined(MIMXRT1186_cm33_H_)
|
||||
#define MG_ETH_RAM __attribute__((section(".bss.$ETH_RAM")))
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef MG_SET_MAC_ADDRESS
|
||||
#if defined(MG_ENABLE_DRIVER_NETC) && MG_ENABLE_DRIVER_NETC
|
||||
// No OCOTP_FUSES present on RT1186 to generate the UUID
|
||||
#define MG_SET_MAC_ADDRESS(mac) (void) (mac)
|
||||
#else
|
||||
#if defined(MG_ENABLE_DRIVER_IMXRT11) && MG_ENABLE_DRIVER_IMXRT11
|
||||
#define MG_OCOTP_FUSES ((volatile uint32_t *) 0x40cac900)
|
||||
#else
|
||||
@@ -104,11 +120,70 @@
|
||||
mac[5] = (MG_OCOTP_FUSES[4] >> 0) & 255; \
|
||||
} while (0)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef MG_IMXRT_WDOG1_TIMEOUT_MS
|
||||
#define MG_IMXRT_WDOG1_TIMEOUT_MS 10000
|
||||
#define MG_IMXRT_WDOG1_TIMEOUT_MS 10000U
|
||||
#endif
|
||||
|
||||
#if defined(CPU_MIMXRT1186CVJ8C_cm33) || defined(MIMXRT1186_cm33_H_)
|
||||
|
||||
#define MG_IMXRT_RTWDOG1_UNLOCK() \
|
||||
do { \
|
||||
if ((RTWDOG1->CS & RTWDOG_CS_CMD32EN_MASK) != 0U) { \
|
||||
RTWDOG1->CNT = RTWDOG_UPDATE_KEY; \
|
||||
} else { \
|
||||
RTWDOG1->CNT = RTWDOG_UPDATE_KEY & 0xffffU; \
|
||||
RTWDOG1->CNT = RTWDOG_UPDATE_KEY >> 16; \
|
||||
} \
|
||||
while ((RTWDOG1->CS & RTWDOG_CS_ULK_MASK) == 0U) (void) 0; \
|
||||
} while (0)
|
||||
|
||||
#define MG_IMXRT_RTWDOG1_FEED() \
|
||||
do { \
|
||||
uint32_t primask_ = __get_PRIMASK(); \
|
||||
__disable_irq(); \
|
||||
if ((RTWDOG1->CS & RTWDOG_CS_CMD32EN_MASK) != 0U) { \
|
||||
RTWDOG1->CNT = RTWDOG_REFRESH_KEY; \
|
||||
} else { \
|
||||
RTWDOG1->CNT = RTWDOG_REFRESH_KEY & 0xffffU; \
|
||||
RTWDOG1->CNT = RTWDOG_REFRESH_KEY >> 16; \
|
||||
} \
|
||||
if (primask_ == 0U) __enable_irq(); \
|
||||
} while (0)
|
||||
|
||||
#ifndef MG_OTA_ROLLBACK_TIMER_START
|
||||
#define MG_OTA_ROLLBACK_TIMER_START() \
|
||||
do { \
|
||||
uint32_t primask_ = __get_PRIMASK(); \
|
||||
SRC_GENERAL_REG->SRMASK &= ~SRC_GENERAL_SRMASK_WDOG1_MASK_MASK; \
|
||||
__disable_irq(); \
|
||||
MG_IMXRT_RTWDOG1_UNLOCK(); \
|
||||
RTWDOG1->WIN = 0U; \
|
||||
RTWDOG1->TOVAL = (MG_IMXRT_WDOG1_TIMEOUT_MS + 7U) / 8U; \
|
||||
RTWDOG1->CS = RTWDOG_CS_EN_MASK | RTWDOG_CS_UPDATE_MASK | \
|
||||
RTWDOG_CS_CLK(1U) | RTWDOG_CS_PRES_MASK | \
|
||||
RTWDOG_CS_CMD32EN_MASK; \
|
||||
while ((RTWDOG1->CS & RTWDOG_CS_RCS_MASK) == 0U) (void) 0; \
|
||||
if (primask_ == 0U) __enable_irq(); \
|
||||
} while (0)
|
||||
#endif
|
||||
|
||||
#ifndef MG_OTA_ROLLBACK_TIMER_FEED
|
||||
#define MG_OTA_ROLLBACK_TIMER_FEED() MG_IMXRT_RTWDOG1_FEED()
|
||||
#endif
|
||||
|
||||
// GPR5 survives RTWDOG global resets and is not reserved by the boot ROM.
|
||||
#ifndef MG_OTA_STATE_GET
|
||||
#define MG_OTA_STATE_GET() SRC_GENERAL_REG->GPR[5]
|
||||
#endif
|
||||
|
||||
#ifndef MG_OTA_STATE_SET
|
||||
#define MG_OTA_STATE_SET(v) (SRC_GENERAL_REG->GPR[5] = (uint32_t) (v))
|
||||
#endif
|
||||
|
||||
#else
|
||||
|
||||
#define MG_IMXRT_WDOG1_FEED() \
|
||||
do { \
|
||||
WDOG1->WSR = 0x5555; \
|
||||
@@ -150,3 +225,5 @@
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -50,10 +50,6 @@
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 1
|
||||
#endif
|
||||
|
||||
#ifndef MG_PATH_MAX
|
||||
#define MG_PATH_MAX FILENAME_MAX
|
||||
#endif
|
||||
|
||||
@@ -166,10 +166,6 @@ typedef int socklen_t;
|
||||
#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR)
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 1
|
||||
#endif
|
||||
|
||||
#ifndef SIGPIPE
|
||||
#define SIGPIPE 0
|
||||
#endif
|
||||
|
||||
+13
-9
@@ -82,10 +82,6 @@
|
||||
#define MG_ENABLE_WINSOCK 1
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_DIRLIST
|
||||
#define MG_ENABLE_DIRLIST 0
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_CUSTOM_RANDOM
|
||||
#define MG_ENABLE_CUSTOM_RANDOM 0
|
||||
#endif
|
||||
@@ -135,7 +131,7 @@
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_POSIX_FS
|
||||
#define MG_ENABLE_POSIX_FS 0
|
||||
#define MG_ENABLE_POSIX_FS MG_ENABLE_LFS
|
||||
#endif
|
||||
|
||||
#ifndef MG_INVALID_SOCKET
|
||||
@@ -175,6 +171,14 @@
|
||||
#define MG_ENABLE_TCPIP_DRIVER_INIT 1 // enabled built-in driver for
|
||||
#endif // Mongoose built-in network stack
|
||||
|
||||
#ifndef MG_ENABLE_TCPIP_TCPRTX
|
||||
#define MG_ENABLE_TCPIP_TCPRTX 0 // TCP retransmission queue
|
||||
#endif
|
||||
|
||||
#ifndef MG_TCPIP_DHCPNAME_SIZE
|
||||
#define MG_TCPIP_DHCPNAME_SIZE 18 // struct mg_tcpip_if :: dhcp_name size
|
||||
#endif
|
||||
|
||||
#ifndef MG_TCPIP_IP // e.g. MG_IPV4(192, 168, 0, 223)
|
||||
#define MG_TCPIP_IP MG_IPV4(0, 0, 0, 0) // Default is 0.0.0.0 (DHCP)
|
||||
#endif
|
||||
@@ -211,10 +215,6 @@
|
||||
#define MG_SET_MAC_ADDRESS(mac)
|
||||
#endif
|
||||
|
||||
#ifndef MG_TCPIP_DHCPNAME_SIZE
|
||||
#define MG_TCPIP_DHCPNAME_SIZE 18 // struct mg_tcpip_if :: dhcp_name size
|
||||
#endif
|
||||
|
||||
#ifndef MG_SET_WIFI_CONFIG
|
||||
#define MG_SET_WIFI_CONFIG(ifp, driver_data)
|
||||
#endif
|
||||
@@ -226,3 +226,7 @@
|
||||
#ifndef MG_ENABLE_CHACHA20
|
||||
#define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_HEALTH
|
||||
#define MG_ENABLE_HEALTH 0
|
||||
#endif
|
||||
+56
-179
@@ -1,5 +1,6 @@
|
||||
#include "dash.h"
|
||||
#include "http.h"
|
||||
#include "ota.h"
|
||||
#include "util.h"
|
||||
|
||||
#define MG_NO_CACHE_HEADERS "Cache-Control: no-cache\r\n"
|
||||
@@ -77,12 +78,7 @@ static int mg_dash_array_size(struct mg_field_set *set,
|
||||
struct mg_dash_user *u) {
|
||||
int saved = *set->index, sz = -1;
|
||||
*set->index = -1;
|
||||
if (set->fn) {
|
||||
if (set->fn(MG_DASH_READ, u)) sz = *set->index;
|
||||
} else if (set->get_dir) {
|
||||
mg_dash_dir_read(set, u);
|
||||
sz = *set->index;
|
||||
}
|
||||
if (set->fn && set->fn(MG_DASH_READ, u)) sz = *set->index;
|
||||
*set->index = saved;
|
||||
return sz;
|
||||
}
|
||||
@@ -100,10 +96,7 @@ static size_t mg_dash_print_array(mg_pfn_t fn, void *arg, va_list *ap) {
|
||||
for (;;) {
|
||||
bool done = to >= 0 && *set->index > to;
|
||||
if (!done) {
|
||||
if (set->fn)
|
||||
set->fn(MG_DASH_READ, u);
|
||||
else if (set->get_dir)
|
||||
mg_dash_dir_read(set, u);
|
||||
if (set->fn) set->fn(MG_DASH_READ, u);
|
||||
done = *set->index < 0;
|
||||
}
|
||||
if (done) break;
|
||||
@@ -170,6 +163,11 @@ void mg_dash_send_change(struct mg_mgr *mgr, struct mg_field_set *set) {
|
||||
struct mg_dash_cdata *d;
|
||||
struct mg_dash_user *u;
|
||||
if (!c->is_websocket) continue;
|
||||
if (c->send.len > MG_DASH_MAX_SEND_BUF_SIZE) { // Skip slow consumers
|
||||
MG_ERROR(("skipping, send buf %lu > %d", (unsigned long) c->send.len,
|
||||
MG_DASH_MAX_SEND_BUF_SIZE));
|
||||
continue;
|
||||
}
|
||||
d = (struct mg_dash_cdata *) c->data;
|
||||
u = d->u;
|
||||
if (u == NULL) continue;
|
||||
@@ -180,8 +178,7 @@ void mg_dash_send_change(struct mg_mgr *mgr, struct mg_field_set *set) {
|
||||
MG_ESC("change"), MG_ESC("params"), MG_ESC(set->name), sz);
|
||||
} else {
|
||||
int saved_idx = set->index != NULL ? *set->index : 0;
|
||||
bool ok = set->fn ? set->fn(MG_DASH_READ, u)
|
||||
: (set->get_dir ? mg_dash_dir_read(set, u) : true);
|
||||
bool ok = set->fn ? set->fn(MG_DASH_READ, u) : true;
|
||||
if (!ok) {
|
||||
if (set->index != NULL) *set->index = saved_idx;
|
||||
continue;
|
||||
@@ -228,8 +225,7 @@ static int mg_dash_parse_field(struct mg_str json, struct mg_field *f) {
|
||||
mg_json_get_num(json, json_path, (double *) f->value);
|
||||
} else if (f->type == MG_VAL_STR && f->value_size > 0) {
|
||||
struct mg_str tok = mg_json_get_tok(json, json_path);
|
||||
ok = tok.len >= 2 && tok.buf[0] == '"' &&
|
||||
tok.buf[tok.len - 1] == '"';
|
||||
ok = tok.len >= 2 && tok.buf[0] == '"' && tok.buf[tok.len - 1] == '"';
|
||||
if (ok) mg_json_unescape(json, json_path, (char *) f->value, f->value_size);
|
||||
} else if (f->type == MG_VAL_RAW && f->value_size > 0) {
|
||||
ok = mg_snprintf((char *) f->value, f->value_size, "%.*s", json.len,
|
||||
@@ -266,68 +262,6 @@ static int mg_dash_apply(struct mg_connection *c, struct mg_dash *dash,
|
||||
return total_count;
|
||||
}
|
||||
|
||||
bool mg_dash_dir_read(struct mg_field_set *set, struct mg_dash_user *u) {
|
||||
char dir[256], fname[128] = "";
|
||||
struct mg_fs *fs = u->dash->upload_fs ? u->dash->upload_fs : &mg_fs_posix;
|
||||
struct mg_field *name_field = NULL, *size_field = NULL;
|
||||
size_t i;
|
||||
|
||||
if (!set->get_dir(u, dir, sizeof(dir))) return false;
|
||||
|
||||
for (i = 0; set->fields[i].name != NULL; i++) {
|
||||
if (name_field == NULL && set->fields[i].type == MG_VAL_STR &&
|
||||
strcmp(set->fields[i].name, "name") == 0)
|
||||
name_field = &set->fields[i];
|
||||
if (size_field == NULL && strcmp(set->fields[i].name, "size") == 0)
|
||||
size_field = &set->fields[i];
|
||||
}
|
||||
if (name_field == NULL) return false;
|
||||
|
||||
if (*set->index == -1) { // Size query: count all files
|
||||
int count = 0;
|
||||
while (mg_fs_ls(fs, dir, fname, sizeof(fname))) count++;
|
||||
*set->index = count;
|
||||
return true;
|
||||
}
|
||||
|
||||
{ // Regular read: scan to *set->index
|
||||
int target = *set->index, cur = 0;
|
||||
while (mg_fs_ls(fs, dir, fname, sizeof(fname))) {
|
||||
if (cur++ == target) {
|
||||
mg_snprintf((char *) name_field->value, name_field->value_size, "%s",
|
||||
fname);
|
||||
if (size_field != NULL) {
|
||||
char path[512];
|
||||
size_t sz = 0;
|
||||
mg_snprintf(path, sizeof(path), "%s/%s", dir, fname);
|
||||
fs->st(path, &sz, NULL);
|
||||
if (size_field->type == MG_VAL_UINT64)
|
||||
*(uint64_t *) size_field->value = (uint64_t) sz;
|
||||
else if (size_field->type == MG_VAL_INT)
|
||||
*(int *) size_field->value = (int) sz;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
*set->index = -1; // No more entries
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
static bool mg_dash_set_file_name(struct mg_field_set *set,
|
||||
struct mg_str name) {
|
||||
size_t i;
|
||||
for (i = 0; set->fields[i].name != NULL; i++) {
|
||||
struct mg_field *f = &set->fields[i];
|
||||
if (f->type == MG_VAL_STR && strcmp(f->name, "name") == 0) {
|
||||
mg_snprintf((char *) f->value, f->value_size, "%.*s", (int) name.len,
|
||||
name.buf);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static inline void mg_log_http_req(struct mg_connection *c,
|
||||
struct mg_http_message *hm) {
|
||||
int len = 0;
|
||||
@@ -360,33 +294,6 @@ static inline void mg_log_http_req(struct mg_connection *c,
|
||||
c->send.buf + n));
|
||||
}
|
||||
|
||||
static void mg_dash_ota_cb(struct mg_connection *c, const char *errmsg) {
|
||||
mg_http_reply(c, errmsg ? 500 : 200, NULL, errmsg ? errmsg : "ok\n");
|
||||
c->is_draining = 1;
|
||||
}
|
||||
|
||||
static void mg_dash_upload_cb(struct mg_connection *c, const char *errmsg) {
|
||||
if (errmsg) {
|
||||
mg_http_reply(c, 500, NULL, "%s\n", errmsg);
|
||||
} else {
|
||||
// mg_http_start_upload() repurposes c->data for its own bookkeeping,
|
||||
// so the field set can't be cached there. Re-derive the dashboard from
|
||||
// c->fn_data instead, and notify every file-backed array: the upload
|
||||
// could belong to any of them, and re-querying get_dir() per recipient
|
||||
// is what mg_dash_send_change() does anyway (directories can be
|
||||
// user-specific)
|
||||
struct mg_dash *dash = (struct mg_dash *) c->fn_data;
|
||||
struct mg_field_set *fs;
|
||||
mg_http_reply(c, 200, NULL, "ok\n");
|
||||
for (fs = dash->sets; fs != NULL; fs = fs->next) {
|
||||
if (fs->get_dir == NULL) continue;
|
||||
*fs->index = -1; // Signal mg_dash_send_change() to broadcast new size
|
||||
mg_dash_send_change(c->mgr, fs);
|
||||
}
|
||||
}
|
||||
c->is_draining = 1;
|
||||
}
|
||||
|
||||
static uint64_t mg_dash_make_expiration_time(struct mg_dash *dash) {
|
||||
unsigned t = (unsigned) dash->session_auto_expiration_seconds;
|
||||
if (t == 0) t = 3600; // Default expiration time in seconds
|
||||
@@ -626,6 +533,40 @@ static void mg_dash_handle_add(struct mg_connection *c, struct mg_dash *dash,
|
||||
}
|
||||
}
|
||||
|
||||
// Firmware upload callback for mg_http_stream_body(). Uses *p as a flag:
|
||||
// non-NULL means an OTA session is open and must be closed by mg_ota_end()
|
||||
static bool otacb(struct mg_http_message *hm, struct mg_str *data, void **p) {
|
||||
if (hm != NULL) { // Start
|
||||
if (!mg_ota_begin(hm->body.len)) return false;
|
||||
*p = (void *) (ptrdiff_t) 1;
|
||||
return true;
|
||||
} else if (data != NULL) { // Next chunk
|
||||
return mg_ota_write(data->buf, data->len);
|
||||
}
|
||||
if (*p == NULL) return false; // End. Begin failed, nothing to finish
|
||||
*p = NULL;
|
||||
return mg_ota_end();
|
||||
}
|
||||
|
||||
static void mg_serve_fs(struct mg_connection *c, struct mg_http_message *hm,
|
||||
struct mg_dash_user *u, bool stream) {
|
||||
struct mg_dash *dash = (struct mg_dash *) c->fn_data;
|
||||
char root[128] = "/fs/=";
|
||||
if (u == NULL) {
|
||||
mg_http_reply(c, 403, MG_JSON_HEADERS, "Not Authorised\n");
|
||||
} else if (dash->files_dir(u, root + 5, sizeof(root) - 5) == false) {
|
||||
mg_http_reply(c, 500, MG_JSON_HEADERS, "Upload dir error\n");
|
||||
} else {
|
||||
struct mg_http_serve_opts o;
|
||||
memset(&o, 0, sizeof(o));
|
||||
o.root_dir = root;
|
||||
o.fs = dash->upload_fs ? dash->upload_fs : &mg_fs_posix;
|
||||
o.enable_delete = o.enable_upload = o.enable_dir_listing = true;
|
||||
if (stream) mg_http_serve_upload(c, hm, &o);
|
||||
else mg_http_serve_dir(c, hm, &o);
|
||||
}
|
||||
}
|
||||
|
||||
void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
|
||||
struct mg_dash *dash = (struct mg_dash *) c->fn_data;
|
||||
struct mg_dash_cdata *d = (struct mg_dash_cdata *) c->data;
|
||||
@@ -639,9 +580,6 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
|
||||
// Received headers - check authentication and possibly start uploads/ota
|
||||
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
||||
struct mg_dash_user *u = mg_dash_authenticate(c, hm, dash);
|
||||
struct mg_str parts[3];
|
||||
memset(parts, 0, sizeof(parts));
|
||||
|
||||
if (mg_match(hm->uri, mg_str("/api/hi"), NULL) ||
|
||||
mg_match(hm->uri, mg_str("/api/logout"), NULL)) {
|
||||
// Do nothing, handle them MG_EV_HTTP_MSG. We bypass auth for those
|
||||
@@ -651,49 +589,21 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
|
||||
} else if (mg_match(hm->uri, mg_str("/api/login"), NULL) && u != NULL) {
|
||||
mg_handle_login(c, u);
|
||||
d->marker = CONN_HANDLED;
|
||||
} else if (u != NULL && dash->files_dir != NULL &&
|
||||
mg_match(hm->uri, mg_str("/fs/#"), NULL)) {
|
||||
mg_serve_fs(c, hm, u, true);
|
||||
return; // Important - the serve_fs() call can invalidate hm
|
||||
} else if (mg_match(hm->uri, mg_str("/api/ota"), NULL)) {
|
||||
mg_http_start_ota(c, hm, mg_dash_ota_cb);
|
||||
} else if (mg_match(hm->uri, mg_str("/fs/*/*"), parts) &&
|
||||
(mg_strcasecmp(hm->method, mg_str("POST")) == 0 ||
|
||||
mg_strcasecmp(hm->method, mg_str("PUT")) == 0)) {
|
||||
struct mg_field_set *set = mg_dash_find_field_set(dash, parts[0]);
|
||||
struct mg_str name = parts[1];
|
||||
int len =
|
||||
mg_url_decode(name.buf, name.len, (char *) name.buf, name.len + 1, 0);
|
||||
if (len > 0 && (size_t) len <= name.len) name.len = (size_t) len;
|
||||
if (set == NULL || set->get_dir == NULL) {
|
||||
mg_http_reply(c, 404, MG_JSON_HEADERS, "Not Found\n");
|
||||
d->marker = CONN_HANDLED;
|
||||
} else if (u == NULL) {
|
||||
mg_http_reply(c, 403, MG_JSON_HEADERS, "Not Authorised\n");
|
||||
d->marker = CONN_HANDLED;
|
||||
} else if (!mg_path_is_sane(name)) {
|
||||
mg_http_reply(c, 400, MG_JSON_HEADERS, "Bad file name\n");
|
||||
d->marker = CONN_HANDLED;
|
||||
} else {
|
||||
mg_dash_set_file_name(set, name);
|
||||
if (set->fn != NULL && !set->fn(MG_DASH_WRITE, u)) {
|
||||
mg_http_reply(c, 403, MG_JSON_HEADERS, "Not Authorised\n");
|
||||
d->marker = CONN_HANDLED;
|
||||
} else {
|
||||
char dir[256];
|
||||
struct mg_fs *fs = dash->upload_fs ? dash->upload_fs : &mg_fs_posix;
|
||||
if (!set->get_dir(u, dir, sizeof(dir))) {
|
||||
mg_http_reply(c, 500, MG_JSON_HEADERS, "Upload dir error\n");
|
||||
d->marker = CONN_HANDLED;
|
||||
} else {
|
||||
mg_http_start_upload(c, hm, name, mg_str(dir), fs,
|
||||
mg_dash_upload_cb);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Authenticated above. If streaming started, the stream handler owns
|
||||
// the connection and c->data, so skip the marker check below
|
||||
if (mg_http_stream_body(c, hm, otacb, NULL)) return;
|
||||
}
|
||||
if (d->marker != '\0') mg_log_http_req(c, hm);
|
||||
} else if (ev == MG_EV_HTTP_MSG && d->marker != '\0') {
|
||||
// The response has been send in EV_HDRS path, so we're not reponding
|
||||
// anything but clearing the marker for the next request.
|
||||
d->marker = 0;
|
||||
c->is_resp = 0;
|
||||
c->pfn_data = NULL; // Response done
|
||||
} else if (ev == MG_EV_HTTP_MSG && d->marker == '\0') {
|
||||
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
||||
struct mg_dash_user *u = mg_dash_authenticate(c, hm, dash);
|
||||
@@ -709,42 +619,9 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
|
||||
} else if (mg_match(hm->uri, mg_str("/api/websocket"), NULL)) {
|
||||
d->u = u;
|
||||
mg_ws_upgrade(c, hm, NULL);
|
||||
} else if (mg_match(hm->uri, mg_str("/fs/*/*"), parts)) {
|
||||
struct mg_field_set *set = mg_dash_find_field_set(dash, parts[0]);
|
||||
if (set == NULL || set->get_dir == NULL) {
|
||||
mg_http_reply(c, 404, MG_JSON_HEADERS, "Not Found");
|
||||
} else if (u == NULL) {
|
||||
mg_http_reply(c, 403, MG_JSON_HEADERS, "Not Authorised\n");
|
||||
} else {
|
||||
char dir[256], path[512];
|
||||
struct mg_fs *fs = dash->upload_fs ? dash->upload_fs : &mg_fs_posix;
|
||||
struct mg_str name = parts[1];
|
||||
int len = mg_url_decode(name.buf, name.len, (char *) name.buf,
|
||||
name.len + 1, 0);
|
||||
if (len > 0 && (size_t) len <= name.len) name.len = (size_t) len;
|
||||
if (!mg_path_is_sane(name)) {
|
||||
mg_http_reply(c, 400, MG_JSON_HEADERS, "Bad file name\n");
|
||||
return;
|
||||
}
|
||||
if (!set->get_dir(u, dir, sizeof(dir))) {
|
||||
mg_http_reply(c, 500, MG_JSON_HEADERS, "Upload dir error\n");
|
||||
return;
|
||||
}
|
||||
mg_snprintf(path, sizeof(path), "%s/%.*s", dir, name.len, name.buf);
|
||||
if (mg_strcasecmp(hm->method, mg_str("DELETE")) == 0) {
|
||||
mg_dash_set_file_name(set, name);
|
||||
if (set->fn != NULL && !set->fn(MG_DASH_DELETE, u)) {
|
||||
mg_http_reply(c, 403, MG_JSON_HEADERS, "Not Authorised\n");
|
||||
} else {
|
||||
fs->rm(path);
|
||||
*set->index = -1; // Signal mg_dash_send_change() to send new size
|
||||
mg_dash_send_change(c->mgr, set);
|
||||
mg_http_reply(c, 200, NULL, "true");
|
||||
}
|
||||
} else {
|
||||
mg_http_serve_file(c, hm, path, NULL);
|
||||
}
|
||||
}
|
||||
} else if (dash->files_dir != NULL &&
|
||||
mg_match(hm->uri, mg_str("/fs/#"), NULL)) {
|
||||
mg_serve_fs(c, hm, u, false);
|
||||
} else if (mg_match(hm->uri, mg_str("/api/del/*/*/*"), parts) ||
|
||||
mg_match(hm->uri, mg_str("/api/del/*/*"), parts)) {
|
||||
mg_dash_handle_del(c, dash, u, parts);
|
||||
@@ -775,7 +652,7 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ch == NULL) mg_http_reply(c, 404, MG_JSON_HEADERS, "Not Found");
|
||||
if (ch == NULL) mg_http_reply(c, 404, MG_JSON_HEADERS, "Not Found\n");
|
||||
mg_log_http_req(c, hm);
|
||||
}
|
||||
}
|
||||
|
||||
+4
-40
@@ -73,9 +73,7 @@ struct mg_field_set {
|
||||
// fn sets *index = -1 to signal end of iteration.
|
||||
// Size query: framework sets *index = -1 before fn(READ); fn
|
||||
// sets *index = total size
|
||||
bool (*get_dir)(const struct mg_dash_user *u, char *buf,
|
||||
size_t len); // Non-NULL: file array
|
||||
struct mg_field_set *next; // Next set in the list
|
||||
struct mg_field_set *next; // Next set in the list
|
||||
};
|
||||
|
||||
// Custom URI handler, registered with MG_DASH_REGISTER_CUSTOM_HANDLER()
|
||||
@@ -96,6 +94,9 @@ struct mg_dash {
|
||||
int session_auto_expiration_seconds; // Session lifetime, 0: 1 hour default
|
||||
struct mg_dash_user *guest; // Used when authenticate == NULL
|
||||
struct mg_fs *upload_fs; // FS for uploads/listing, default &mg_fs_posix
|
||||
// Resolves the built-in file manager's root dir for user u, e.g. per-user
|
||||
// upload directories. NULL: file manager disabled
|
||||
bool (*files_dir)(const struct mg_dash_user *u, char *buf, size_t len);
|
||||
};
|
||||
|
||||
#define MG_DASH_ADD_FIELD_SET(dash_, set_) \
|
||||
@@ -121,43 +122,6 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data);
|
||||
// array size if *set->index < 0, or a single element update otherwise
|
||||
void mg_dash_send_change(struct mg_mgr *mgr, struct mg_field_set *);
|
||||
|
||||
// Default reader for file-backed array sets (set->get_dir != NULL)
|
||||
// Usage example - this is a complete implemenation of the file manager:
|
||||
// ```c
|
||||
// static struct file {
|
||||
// int index;
|
||||
// char name[64];
|
||||
// size_t size;
|
||||
// uint64_t checksum;
|
||||
// } s_file;
|
||||
// static struct mg_field_set set_files;
|
||||
//
|
||||
// static bool get_dir(const struct mg_dash_user *u, char *buf, size_t len) {
|
||||
// (void) u;
|
||||
// mkdir("/tmp/dashboard", 0755);
|
||||
// mg_snprintf(buf, len, "%s", "/tmp/dashboard");
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// static struct mg_field fields_files[] = {
|
||||
// {"name", MG_VAL_STR, s_file.name, sizeof(s_file.name)},
|
||||
// {"size", MG_VAL_UINT64, &s_file.size, 0},
|
||||
// {"checksum", MG_VAL_UINT64, &s_file.checksum, sizeof(s_file.checksum)},
|
||||
// {NULL, MG_VAL_INT, NULL, 0},
|
||||
// };
|
||||
//
|
||||
// static bool files_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
// if (op == MG_DASH_WRITE) return s_uploads_enabled && u->level >= 7;
|
||||
// if (op != MG_DASH_READ) return false;
|
||||
// if (!mg_dash_dir_read(&set_files, u)) return false;
|
||||
// s_file.checksum = 0; // Mock to show how to set custom fields
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// static struct mg_field_set set_files = {"files", fields_files, files_fn, &s_file.index, get_dir, NULL};
|
||||
// ```
|
||||
bool mg_dash_dir_read(struct mg_field_set *set, struct mg_dash_user *u);
|
||||
|
||||
// Helper forward declarations for Mongoose CMSIS pack modules
|
||||
extern struct mg_mgr g_mgr;
|
||||
extern void mg_dash_init(struct mg_mgr *);
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
#include "net_builtin.h"
|
||||
|
||||
#if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP && \
|
||||
defined(MG_ENABLE_DRIVER_NETC) && MG_ENABLE_DRIVER_NETC
|
||||
|
||||
// IMXRT1180 RM - Chapter 53 - Ethernet Controller (NETC)
|
||||
|
||||
#define ETH_DESC_CNT 8 // Descriptor count must be multiple of 8 (53.4.6.11.97)
|
||||
#define ETH_PKT_SIZE 1536
|
||||
|
||||
struct netc_pci_function { // 53.4.6.1.1
|
||||
volatile uint32_t DID_VID;
|
||||
volatile uint16_t CMD, STAT;
|
||||
volatile uint8_t reserved0[0x40];
|
||||
volatile uint16_t DEV_CTL, DEV_STAT;
|
||||
volatile uint8_t reserved1[0x34];
|
||||
volatile uint16_t MSIX_CAP_LIST, MSIX_MSG_CTL;
|
||||
};
|
||||
|
||||
struct netc_emdio { // 53.4.6.12
|
||||
volatile uint32_t EMDIO_CFG, EMDIO_CTL, EMDIO_DATA, EMDIO_ADDR, EMDIO_STAT;
|
||||
};
|
||||
|
||||
struct netc_enetc { // 53.4.6.6
|
||||
volatile uint32_t ECAPR0, ECAPR1, ECAPR2, reserved0, PMR;
|
||||
volatile uint8_t reserved1[0x1ec];
|
||||
volatile uint32_t PSIPMMR, PSIPVMR;
|
||||
volatile uint8_t reserved2[0x5f8];
|
||||
volatile uint32_t SMCAPR;
|
||||
volatile uint8_t reserved3[0x17fc];
|
||||
struct {
|
||||
volatile uint32_t PSIPMAR0, PSIPMAR1, PSIVLANR, reserved0, PSICFGR0,
|
||||
PSICFGR1, PSICFGR2;
|
||||
volatile uint8_t reserved1[0x3c];
|
||||
volatile uint32_t PSIMMHFR0, PSIMMHFR1;
|
||||
volatile uint8_t reserved2[0x20];
|
||||
} PSI[1];
|
||||
};
|
||||
|
||||
struct netc_port { // 53.4.6.8
|
||||
volatile uint32_t PCAPR, PMCAPR, PIOCAPR, reserved0, PCR;
|
||||
volatile uint8_t reserved1[0x0c];
|
||||
volatile uint32_t PMAR0, PMAR1;
|
||||
volatile uint8_t reserved2[0xd8];
|
||||
volatile uint32_t POR, PSR;
|
||||
volatile uint8_t reserved3[0x30];
|
||||
volatile uint32_t PDGSR;
|
||||
volatile uint8_t reserved4[0xc4];
|
||||
struct {
|
||||
volatile uint32_t PTGSTCSR, reserved0, PTCTMSDUR, reserved1, PTCCBSR0,
|
||||
PTCCBSR1;
|
||||
volatile uint8_t reserved2[8];
|
||||
} TCT[8];
|
||||
volatile uint8_t reserved5[0x220];
|
||||
volatile uint32_t BPSTGSR;
|
||||
};
|
||||
|
||||
struct netc_port_mac { // 53.4.6.9
|
||||
volatile uint8_t reserved0[8];
|
||||
volatile uint32_t COMMAND_CONFIG, MAC_ADDR_0, MAC_ADDR_1, MAXFRM, MINFRM;
|
||||
volatile uint8_t reserved1[0x24];
|
||||
volatile uint32_t IEVENT;
|
||||
volatile uint8_t reserved2[0x1dc];
|
||||
volatile uint64_t TFRMN;
|
||||
volatile uint8_t reserved3[0xd8];
|
||||
volatile uint32_t IF_MODE;
|
||||
volatile uint8_t reserved4[0xfc];
|
||||
};
|
||||
|
||||
struct netc_eth_link {
|
||||
struct netc_port_mac PM[2];
|
||||
};
|
||||
|
||||
struct netc_pseudo_link {
|
||||
volatile uint32_t PPMSR;
|
||||
volatile uint8_t reserved0[0x0c];
|
||||
volatile uint32_t PPMCR;
|
||||
};
|
||||
|
||||
struct netc_switch { // 53.4.6.5
|
||||
volatile uint8_t reserved0[0x400];
|
||||
volatile uint32_t MPCR;
|
||||
volatile uint8_t reserved1[0x1c0c];
|
||||
volatile uint32_t VFHTDECR0, VFHTDECR1, VFHTDECR2;
|
||||
};
|
||||
|
||||
struct netc_bdr {
|
||||
volatile uint32_t TBMR, TBSR;
|
||||
volatile uint8_t reserved0[8];
|
||||
volatile uint32_t TBBAR0, TBBAR1, TBPIR, TBCIR, TBLENR;
|
||||
volatile uint8_t reserved1[0x7c];
|
||||
volatile uint32_t TBIER, TBIDR, TBICR0, TBICR1;
|
||||
volatile uint8_t reserved2[0x50];
|
||||
volatile uint32_t RBMR, RBSR, RBBSR, RBCIR, RBBAR0, RBBAR1, RBPIR,
|
||||
reserved3, RBLENR;
|
||||
volatile uint8_t reserved4[0x5c];
|
||||
volatile uint32_t RBDCR;
|
||||
volatile uint8_t reserved5[0x1c];
|
||||
volatile uint32_t RBIER, RBIDR, RBICR0, RBICR1;
|
||||
volatile uint8_t reserved6[0x50];
|
||||
};
|
||||
|
||||
struct netc_si { // 53.4.6.11
|
||||
volatile uint32_t SIMR, SISR;
|
||||
volatile uint8_t reserved0[0x30];
|
||||
volatile uint32_t SIRBGCR;
|
||||
volatile uint8_t reserved1[0x2ec];
|
||||
volatile uint32_t SITFRM0;
|
||||
volatile uint8_t reserved2[0x6fc];
|
||||
volatile uint32_t SIRXIDR0;
|
||||
volatile uint8_t reserved3[0x154];
|
||||
volatile uint32_t SIMSIRRVR[1];
|
||||
volatile uint8_t reserved4[0x747c];
|
||||
struct netc_bdr BDR[1];
|
||||
};
|
||||
|
||||
struct netc_msix_entry { // 53.4.2.11
|
||||
volatile uint32_t MSG_ADDR, MSG_UPPER_ADDR, MSG_DATA, VECTOR_CTRL;
|
||||
};
|
||||
|
||||
struct netc_msgintr { // 54.4
|
||||
struct {
|
||||
volatile uint32_t MSIIR, MSIR;
|
||||
} MSI[3];
|
||||
};
|
||||
|
||||
#define NETC_EMDIO_PCI \
|
||||
((struct netc_pci_function *) (uintptr_t) 0x60001000U)
|
||||
#define NETC_SWITCH_PCI \
|
||||
((struct netc_pci_function *) (uintptr_t) 0x60002000U)
|
||||
#define NETC_ENETC1_PCI \
|
||||
((struct netc_pci_function *) (uintptr_t) 0x60004000U)
|
||||
#define NETC_EMDIO ((struct netc_emdio *) (uintptr_t) 0x60ba1c00U)
|
||||
|
||||
#define NETC_ENETC1 ((struct netc_enetc *) (uintptr_t) 0x60b50000U)
|
||||
#define NETC_ENETC1_PORT ((struct netc_port *) (uintptr_t) 0x60b54000U)
|
||||
#define NETC_ENETC1_PSEUDO_LINK \
|
||||
((struct netc_pseudo_link *) (uintptr_t) 0x60b55000U)
|
||||
#define NETC_ENETC1_SI0 ((struct netc_si *) (uintptr_t) 0x60b40000U)
|
||||
#define NETC_ENETC1_MSIX \
|
||||
((struct netc_msix_entry *) (uintptr_t) 0x60c00000U)
|
||||
|
||||
#define NETC_SWITCH ((struct netc_switch *) (uintptr_t) 0x60a00000U)
|
||||
#define NETC_SW0_PORT(link) \
|
||||
((struct netc_port *) (uintptr_t) (0x60a04000U + \
|
||||
(uint32_t) (link) * 0x4000U))
|
||||
#define NETC_SW0_ETH(link) \
|
||||
((struct netc_eth_link *) (uintptr_t) (0x60a05000U + \
|
||||
(uint32_t) (link) * 0x4000U))
|
||||
#define NETC_SW0_PORT4 ((struct netc_port *) (uintptr_t) 0x60a14000U)
|
||||
#define NETC_MSGINTR1 \
|
||||
((struct netc_msgintr *) (uintptr_t) 0x428a0000U)
|
||||
|
||||
enum {
|
||||
NETC_RX_MSIX_ENTRY = 0,
|
||||
NETC_RX_MSG_INDEX = 2,
|
||||
};
|
||||
|
||||
struct netc_tx_bd {
|
||||
uint64_t buffer_address;
|
||||
uint16_t buffer_length, frame_length;
|
||||
uint32_t control;
|
||||
};
|
||||
|
||||
struct netc_rx_descriptor {
|
||||
uint64_t buffer_address, reserved;
|
||||
};
|
||||
|
||||
struct netc_rx_writeback {
|
||||
uint16_t internet_checksum, parser_summary;
|
||||
uint32_t rss_hash;
|
||||
uint16_t buffer_length, vlan;
|
||||
uint32_t status;
|
||||
};
|
||||
|
||||
union netc_rx_bd {
|
||||
struct netc_rx_descriptor descriptor;
|
||||
struct netc_rx_writeback writeback;
|
||||
};
|
||||
|
||||
static volatile struct netc_tx_bd s_txdesc[ETH_DESC_CNT] MG_ETH_RAM
|
||||
__attribute__((aligned(128)));
|
||||
static volatile union netc_rx_bd s_rxdesc[ETH_DESC_CNT] MG_ETH_RAM
|
||||
__attribute__((aligned(128)));
|
||||
static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_ETH_RAM
|
||||
__attribute__((aligned(64)));
|
||||
static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_ETH_RAM
|
||||
__attribute__((aligned(64)));
|
||||
|
||||
static uint16_t s_tx_prod;
|
||||
static uint16_t s_tx_clean;
|
||||
static uint16_t s_rx_cons;
|
||||
static struct mg_tcpip_if *s_ifp;
|
||||
|
||||
static uint16_t enet_read_phy(uint8_t addr, uint8_t reg) {
|
||||
NETC_EMDIO->EMDIO_CFG &= ~MG_BIT(6); // ENC45: use Clause 22
|
||||
NETC_EMDIO->EMDIO_CTL = MG_BIT(15) | ((uint32_t) (addr & 0x1fU) << 5) |
|
||||
(reg & 0x1fU); // READ, PORT_ADDR, DEV_ADDR
|
||||
while (NETC_EMDIO->EMDIO_CFG & MG_BIT(31)) (void) 0; // BSY1
|
||||
return (uint16_t) (NETC_EMDIO->EMDIO_DATA & 0xffffU);
|
||||
}
|
||||
|
||||
static void enet_write_phy(uint8_t addr, uint8_t reg, uint16_t value) {
|
||||
NETC_EMDIO->EMDIO_CFG &= ~MG_BIT(6); // ENC45: use Clause 22
|
||||
NETC_EMDIO->EMDIO_CTL = ((uint32_t) (addr & 0x1fU) << 5) |
|
||||
(reg & 0x1fU); // PORT_ADDR, DEV_ADDR
|
||||
NETC_EMDIO->EMDIO_DATA = value;
|
||||
while (NETC_EMDIO->EMDIO_CFG & MG_BIT(31)) (void) 0; // BSY1
|
||||
}
|
||||
|
||||
static bool mg_tcpip_driver_netc_init(struct mg_tcpip_if *ifp) {
|
||||
struct mg_tcpip_driver_netc_data *d =
|
||||
(struct mg_tcpip_driver_netc_data *) ifp->driver_data;
|
||||
struct mg_phy phy = {enet_read_phy, enet_write_phy};
|
||||
struct netc_port *switch_port;
|
||||
struct netc_eth_link *eth_link;
|
||||
uint64_t tx_base = (uint64_t) (uintptr_t) s_txdesc;
|
||||
uint64_t rx_base = (uint64_t) (uintptr_t) s_rxdesc;
|
||||
uint32_t mac0 = (uint32_t) ifp->mac[0] |
|
||||
((uint32_t) ifp->mac[1] << 8) |
|
||||
((uint32_t) ifp->mac[2] << 16) |
|
||||
((uint32_t) ifp->mac[3] << 24);
|
||||
uint32_t mac1 = (uint32_t) ifp->mac[4] |
|
||||
((uint32_t) ifp->mac[5] << 8);
|
||||
uint32_t mdc_cr =
|
||||
(uint32_t) (d->mdc_cr < 0 ? MG_DRIVER_MDC_CR : d->mdc_cr);
|
||||
|
||||
switch_port = NETC_SW0_PORT(d->link);
|
||||
eth_link = NETC_SW0_ETH(d->link);
|
||||
s_ifp = ifp;
|
||||
for (int i = 0; i < ETH_DESC_CNT; i++) {
|
||||
s_txdesc[i].buffer_address = (uint64_t) (uintptr_t) s_txbuf[i];
|
||||
s_rxdesc[i].descriptor.buffer_address =
|
||||
(uint64_t) (uintptr_t) s_rxbuf[i];
|
||||
}
|
||||
|
||||
NETC_EMDIO_PCI->DEV_CTL |= MG_BIT(15); // INIT_FLR
|
||||
while (NETC_EMDIO_PCI->DEV_CTL & MG_BIT(15)) (void) 0;
|
||||
NETC_EMDIO_PCI->CMD |= MG_BIT(2) | MG_BIT(1); // BUS_MASTER_EN, MEM_ACCESS
|
||||
NETC_EMDIO->EMDIO_CFG =
|
||||
((mdc_cr & 0x1ffU) << 7) | MG_BIT(2); // MDIO_CLK_DIV, MDIO_HOLD
|
||||
mg_phy_init(&phy, d->phy_addr, 0);
|
||||
|
||||
// Initialize ENETC1 PSI0 and port
|
||||
NETC_ENETC1_PCI->CMD |= MG_BIT(2) | MG_BIT(1); // BUS_MASTER_EN, MEM_ACCESS
|
||||
NETC_ENETC1_PCI->MSIX_MSG_CTL = MG_BIT(14); // FUNC_MASK
|
||||
NETC_ENETC1_PORT->POR |= MG_BIT(1) | MG_BIT(0); // RXDIS, TXDIS
|
||||
NETC_ENETC1_PCI->DEV_CTL |= MG_BIT(15); // INIT_FLR
|
||||
while (NETC_ENETC1_PCI->DEV_CTL & MG_BIT(15)) (void) 0;
|
||||
NETC_ENETC1_PCI->CMD |= MG_BIT(2) | MG_BIT(1); // BUS_MASTER_EN, MEM_ACCESS
|
||||
NETC_ENETC1_PCI->MSIX_MSG_CTL = MG_BIT(14); // FUNC_MASK
|
||||
NETC_ENETC1_PORT->PCR = 99U << 16; // PSPEED: 1 Gbps
|
||||
NETC_ENETC1_PORT->PMAR0 = mac0;
|
||||
NETC_ENETC1_PORT->PMAR1 = mac1;
|
||||
NETC_ENETC1_PSEUDO_LINK->PPMCR = MG_BIT(16); // TXPAD
|
||||
NETC_ENETC1->PSIPMMR &= ~(MG_BIT(16) | MG_BIT(0));
|
||||
NETC_ENETC1_SI0->SIMR &=
|
||||
~(MG_BIT(31) | MG_BIT(3) | MG_BIT(2) | MG_BIT(1));
|
||||
NETC_ENETC1_SI0->SIRBGCR = 0;
|
||||
NETC_ENETC1->PSI[0].PSICFGR0 =
|
||||
MG_BIT(16) | MG_BIT(0); // one Rx BDR, one Tx BDR
|
||||
|
||||
NETC_ENETC1->PSI[0].PSICFGR2 = 0; // NUM_MSIX: one entry
|
||||
NETC_ENETC1_MSIX[NETC_RX_MSIX_ENTRY].VECTOR_CTRL = MG_BIT(0); // MASK
|
||||
NETC_ENETC1_MSIX[NETC_RX_MSIX_ENTRY].MSG_ADDR =
|
||||
(uint32_t) (uintptr_t) &NETC_MSGINTR1->MSI[0].MSIIR;
|
||||
NETC_ENETC1_MSIX[NETC_RX_MSIX_ENTRY].MSG_UPPER_ADDR = 0;
|
||||
NETC_ENETC1_MSIX[NETC_RX_MSIX_ENTRY].MSG_DATA = NETC_RX_MSG_INDEX;
|
||||
NETC_ENETC1_SI0->SIMSIRRVR[0] = NETC_RX_MSIX_ENTRY; // Rx ring 0 -> entry 0
|
||||
|
||||
// Initialize switch function 2 to drive the selected physical port
|
||||
NETC_SWITCH_PCI->CMD |= MG_BIT(2) | MG_BIT(1);
|
||||
NETC_SWITCH_PCI->MSIX_MSG_CTL = MG_BIT(14); // FUNC_MASK
|
||||
switch_port->POR |= MG_BIT(1) | MG_BIT(0);
|
||||
eth_link->PM[0].COMMAND_CONFIG |= MG_BIT(26); // SWR
|
||||
while (eth_link->PM[0].COMMAND_CONFIG & MG_BIT(26)) (void) 0;
|
||||
eth_link->PM[1].COMMAND_CONFIG |= MG_BIT(26); // SWR
|
||||
while (eth_link->PM[1].COMMAND_CONFIG & MG_BIT(26)) (void) 0;
|
||||
NETC_SWITCH_PCI->DEV_CTL |= MG_BIT(15); // INIT_FLR
|
||||
while (NETC_SWITCH_PCI->DEV_CTL & MG_BIT(15)) (void) 0;
|
||||
NETC_SWITCH_PCI->CMD |= MG_BIT(2) | MG_BIT(1);
|
||||
NETC_SWITCH_PCI->MSIX_MSG_CTL = MG_BIT(14); // FUNC_MASK
|
||||
|
||||
// Configure switch physical port and ethernet link (ETH_X)
|
||||
switch_port->PCR = 99U << 16; // PSPEED: 1 Gbps
|
||||
switch_port->PMAR0 = mac0;
|
||||
switch_port->PMAR1 = mac1;
|
||||
switch_port->TCT[0].PTCTMSDUR = MG_BIT(24) | MG_BIT(16) | ETH_PKT_SIZE;
|
||||
eth_link->PM[0].MAXFRM = ETH_PKT_SIZE;
|
||||
eth_link->PM[0].MINFRM = 64;
|
||||
eth_link->PM[0].IF_MODE = MG_BIT(14) | 4U; // 1G RGMII
|
||||
eth_link->PM[0].COMMAND_CONFIG =
|
||||
MG_BIT(15) | MG_BIT(1) | MG_BIT(0); // TXP, RX_EN, TX_EN
|
||||
eth_link->PM[1].MAXFRM = ETH_PKT_SIZE;
|
||||
eth_link->PM[1].MINFRM = 64;
|
||||
eth_link->PM[1].IF_MODE = MG_BIT(14) | 4U;
|
||||
eth_link->PM[1].COMMAND_CONFIG =
|
||||
MG_BIT(15) | MG_BIT(1) | MG_BIT(0);
|
||||
|
||||
// Bridge the selected physical port with management port 4 (54.4.1.1)
|
||||
NETC_SWITCH->VFHTDECR0 = MG_BIT(4) | MG_BIT(d->link);
|
||||
NETC_SWITCH->VFHTDECR2 = (1UL << 27) | (1UL << 24); // MFO=1, MLO=1
|
||||
switch_port->BPSTGSR = 2U; // STG0: forwarding
|
||||
NETC_SW0_PORT4->BPSTGSR = 2U; // STG0: forwarding
|
||||
switch_port->POR &= ~(MG_BIT(1) | MG_BIT(0));
|
||||
NETC_SW0_PORT4->POR &= ~(MG_BIT(1) | MG_BIT(0));
|
||||
|
||||
// Initialize Tx BD ring 0 (direct switch enqueue)
|
||||
NETC_ENETC1_SI0->BDR[0].TBBAR0 = (uint32_t) tx_base;
|
||||
NETC_ENETC1_SI0->BDR[0].TBBAR1 = (uint32_t) (tx_base >> 32);
|
||||
NETC_ENETC1_SI0->BDR[0].TBLENR = ETH_DESC_CNT;
|
||||
|
||||
// Initialize Rx BD ring 0
|
||||
NETC_ENETC1_SI0->BDR[0].RBICR0 =
|
||||
MG_BIT(31) | MG_BIT(0); // ICEN, interrupt after one frame
|
||||
NETC_ENETC1_SI0->BDR[0].RBBAR0 = (uint32_t) rx_base;
|
||||
NETC_ENETC1_SI0->BDR[0].RBBAR1 = (uint32_t) (rx_base >> 32);
|
||||
NETC_ENETC1_SI0->BDR[0].RBBSR = ETH_PKT_SIZE;
|
||||
NETC_ENETC1_SI0->BDR[0].RBLENR = ETH_DESC_CNT;
|
||||
|
||||
// Clear stale device and MSGINTR state before the ring becomes active
|
||||
NETC_ENETC1_SI0->SIRXIDR0 = MG_BIT(0); // RX0, W1C
|
||||
(void) NETC_MSGINTR1->MSI[0].MSIR; // clear pending messages
|
||||
NETC_ENETC1_SI0->BDR[0].RBIER = MG_BIT(0); // RXTIE
|
||||
NETC_ENETC1_SI0->BDR[0].TBMR = MG_BIT(31);
|
||||
NETC_ENETC1_SI0->BDR[0].RBMR = MG_BIT(31); // EN, CRC=0: strip FCS
|
||||
NETC_ENETC1_PORT->POR &= ~(MG_BIT(1) | MG_BIT(0));
|
||||
NETC_ENETC1->PMR |= MG_BIT(16); // SI0EN
|
||||
NETC_ENETC1_SI0->SIMR |= MG_BIT(31); // EN
|
||||
MG_DSB();
|
||||
if ((NETC_ENETC1->SMCAPR & MG_BIT(0)) == 0U ||
|
||||
(NETC_SWITCH->MPCR & 0x1fU) != 4U) {
|
||||
MG_ERROR(("NETC fixed management path unavailable: SMCAPR=%08lx MPCR=%08lx",
|
||||
(unsigned long) NETC_ENETC1->SMCAPR,
|
||||
(unsigned long) NETC_SWITCH->MPCR));
|
||||
return false;
|
||||
}
|
||||
|
||||
NETC_ENETC1_PCI->MSIX_MSG_CTL =
|
||||
MG_BIT(15); // Enable RX interrupt, MSIX_EN=1, FUNC_MASK=0
|
||||
MG_DSB();
|
||||
NETC_ENETC1_MSIX[NETC_RX_MSIX_ENTRY].VECTOR_CTRL = 0; // MASK=0, last
|
||||
MG_DSB();
|
||||
return true;
|
||||
}
|
||||
|
||||
static size_t mg_tcpip_driver_netc_tx(const void *buf, size_t len,
|
||||
struct mg_tcpip_if *ifp) {
|
||||
struct mg_tcpip_driver_netc_data *d =
|
||||
(struct mg_tcpip_driver_netc_data *) ifp->driver_data;
|
||||
uint16_t next;
|
||||
s_tx_clean =
|
||||
(uint16_t) (NETC_ENETC1_SI0->BDR[0].TBCIR & 0xffffU); // BDR_INDEX
|
||||
next = (uint16_t) (s_tx_prod + 1U);
|
||||
if (next >= ETH_DESC_CNT) next = 0;
|
||||
if (len > sizeof(s_txbuf[0])) {
|
||||
MG_ERROR(("Frame too big, %ld", (long) len));
|
||||
len = (size_t) -1; // fail
|
||||
} else if (next == s_tx_clean) {
|
||||
ifp->nerr++;
|
||||
MG_ERROR(("No descriptors available"));
|
||||
len = 0; // retry later
|
||||
} else {
|
||||
memcpy(s_txbuf[s_tx_prod], buf, len); // Copy data
|
||||
s_txdesc[s_tx_prod].buffer_address =
|
||||
(uint64_t) (uintptr_t) s_txbuf[s_tx_prod];
|
||||
s_txdesc[s_tx_prod].buffer_length = (uint16_t) len; // BUFF_LEN
|
||||
s_txdesc[s_tx_prod].frame_length = (uint16_t) len; // FRAME_LEN
|
||||
s_txdesc[s_tx_prod].control =
|
||||
MG_BIT(31) | (2UL << 24) | MG_BIT(23) | ((uint32_t) d->link << 16);
|
||||
// F=1, FLQ=2, SMSO=1, EGR_PORT=link, IPV=0, DR=0
|
||||
MG_DSB();
|
||||
if (++s_tx_prod >= ETH_DESC_CNT) s_tx_prod = 0;
|
||||
NETC_ENETC1_SI0->BDR[0].TBPIR = s_tx_prod; // BDR_INDEX
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
static void mg_tcpip_driver_netc_update_hash_table(struct mg_tcpip_if *ifp) {
|
||||
// mcast address has NETC XOR hash index 56 (RM 53.4.2.3.1.3.8.4.1)
|
||||
NETC_ENETC1->PSI[0].PSIMMHFR0 = 0;
|
||||
NETC_ENETC1->PSI[0].PSIMMHFR1 = MG_BIT(24);
|
||||
(void) ifp;
|
||||
}
|
||||
|
||||
static bool mg_tcpip_driver_netc_poll(struct mg_tcpip_if *ifp, bool s1) {
|
||||
if (ifp->update_mac_hash_table) {
|
||||
mg_tcpip_driver_netc_update_hash_table(ifp);
|
||||
ifp->update_mac_hash_table = false;
|
||||
}
|
||||
if (!s1) return false;
|
||||
struct mg_tcpip_driver_netc_data *d =
|
||||
(struct mg_tcpip_driver_netc_data *) ifp->driver_data;
|
||||
struct netc_port *switch_port = NETC_SW0_PORT(d->link);
|
||||
struct netc_eth_link *eth_link = NETC_SW0_ETH(d->link);
|
||||
uint8_t speed = MG_PHY_SPEED_10M;
|
||||
bool up, full_duplex = false;
|
||||
struct mg_phy phy = {enet_read_phy, enet_write_phy};
|
||||
|
||||
up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
|
||||
if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) {
|
||||
uint16_t port_speed = speed == MG_PHY_SPEED_1000M ? 99U
|
||||
: speed == MG_PHY_SPEED_100M ? 9U
|
||||
: 0U;
|
||||
uint32_t config = switch_port->PCR;
|
||||
uint32_t mode = eth_link->PM[0].IF_MODE;
|
||||
config &= ~(0x3fffU << 16); // PCR[29:16] PSPEED
|
||||
config |= (uint32_t) port_speed << 16;
|
||||
mode &= ~(MG_BIT(14) | MG_BIT(13) | MG_BIT(6)); // SSP, HD
|
||||
if (speed == MG_PHY_SPEED_1000M) {
|
||||
mode |= MG_BIT(14); // SSP: 1 Gbps, full duplex
|
||||
} else {
|
||||
if (speed == MG_PHY_SPEED_10M) mode |= MG_BIT(13); // SSP
|
||||
if (!full_duplex) mode |= MG_BIT(6); // HD
|
||||
}
|
||||
switch_port->PCR = config;
|
||||
eth_link->PM[0].IF_MODE = mode;
|
||||
eth_link->PM[1].IF_MODE = mode;
|
||||
|
||||
// TX_CSD, RX_CSD, and SPD_DUP are latched while the PHY is reset/down.
|
||||
eth_link->PM[0].IEVENT = MG_BIT(23) | MG_BIT(22) | MG_BIT(21);
|
||||
MG_DSB();
|
||||
MG_DEBUG(("Link is %uM %s-duplex",
|
||||
speed == MG_PHY_SPEED_1000M ? 1000U
|
||||
: speed == MG_PHY_SPEED_100M ? 100U
|
||||
: 10U,
|
||||
full_duplex ? "full" : "half"));
|
||||
}
|
||||
return up;
|
||||
}
|
||||
|
||||
void MSGINTR1_IRQHandler(void);
|
||||
void MSGINTR1_IRQHandler(void) {
|
||||
if (NETC_MSGINTR1->MSI[0].MSIR & MG_BIT(NETC_RX_MSG_INDEX)) {
|
||||
NETC_ENETC1_SI0->SIRXIDR0 = MG_BIT(0); // RX0, W1C
|
||||
MG_DSB();
|
||||
for (int i = 0; i < 10; i++) { // Read as they arrive but not forever
|
||||
uint32_t status;
|
||||
size_t len;
|
||||
if (s_rx_cons ==
|
||||
(uint16_t) (NETC_ENETC1_SI0->BDR[0].RBPIR & 0xffffU))
|
||||
break;
|
||||
status = s_rxdesc[s_rx_cons].writeback.status;
|
||||
if (!(status & MG_BIT(30))) break; // R: writeback is ready
|
||||
len = s_rxdesc[s_rx_cons].writeback.buffer_length;
|
||||
if ((status & (MG_BIT(31) | MG_BIT(30))) ==
|
||||
(MG_BIT(31) | MG_BIT(30)) && // F, R
|
||||
!(status & (0xffU << 16)) && // ERROR
|
||||
!(status & (0xfU << 2)) && // HR=0: regular frame
|
||||
len > 0 && len <= sizeof(s_rxbuf[0])) {
|
||||
mg_tcpip_qwrite(s_rxbuf[s_rx_cons], len, s_ifp); // FCS stripped
|
||||
}
|
||||
s_rxdesc[s_rx_cons].descriptor.buffer_address =
|
||||
(uint64_t) (uintptr_t) s_rxbuf[s_rx_cons];
|
||||
s_rxdesc[s_rx_cons].descriptor.reserved = 0;
|
||||
MG_DSB();
|
||||
if (++s_rx_cons >= ETH_DESC_CNT) s_rx_cons = 0;
|
||||
NETC_ENETC1_SI0->BDR[0].RBCIR = s_rx_cons;
|
||||
}
|
||||
}
|
||||
MG_DSB();
|
||||
}
|
||||
|
||||
struct mg_tcpip_driver mg_tcpip_driver_netc = {mg_tcpip_driver_netc_init,
|
||||
mg_tcpip_driver_netc_tx, NULL,
|
||||
mg_tcpip_driver_netc_poll};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP && \
|
||||
defined(MG_ENABLE_DRIVER_NETC) && MG_ENABLE_DRIVER_NETC
|
||||
|
||||
struct mg_tcpip_driver_netc_data {
|
||||
int mdc_cr;
|
||||
uint8_t phy_addr;
|
||||
|
||||
// Selects the physical Ethernet link (ETH0 through ETH3)
|
||||
// Its switch port is bridged to pseudo-port 4,
|
||||
// which connects internally to ENETC1
|
||||
// IMXRT1180 RM 53.4.1.1 NETC Block diagram
|
||||
uint8_t link;
|
||||
};
|
||||
|
||||
#ifndef MG_TCPIP_PHY_ADDR
|
||||
#define MG_TCPIP_PHY_ADDR 5
|
||||
#endif
|
||||
|
||||
#ifndef MG_DRIVER_MDC_CR
|
||||
#define MG_DRIVER_MDC_CR 48
|
||||
#endif
|
||||
|
||||
#ifndef MG_TCPIP_NETC_LINK
|
||||
#define MG_TCPIP_NETC_LINK 0
|
||||
#endif
|
||||
|
||||
struct mg_tcpip_driver;
|
||||
extern struct mg_tcpip_driver mg_tcpip_driver_netc;
|
||||
|
||||
#define MG_TCPIP_DRIVER_INIT(mgr) \
|
||||
do { \
|
||||
static struct mg_tcpip_driver_netc_data driver_data_; \
|
||||
static struct mg_tcpip_if mif_; \
|
||||
driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \
|
||||
driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \
|
||||
driver_data_.link = MG_TCPIP_NETC_LINK; \
|
||||
mif_.ip = MG_TCPIP_IP; \
|
||||
mif_.mask = MG_TCPIP_MASK; \
|
||||
mif_.gw = MG_TCPIP_GW; \
|
||||
mif_.driver = &mg_tcpip_driver_netc; \
|
||||
mif_.driver_data = &driver_data_; \
|
||||
MG_SET_MAC_ADDRESS(mif_.mac); \
|
||||
mg_tcpip_init(mgr, &mif_); \
|
||||
MG_INFO(("Driver: netc, MAC: %M", mg_print_mac, mif_.mac)); \
|
||||
} while (0)
|
||||
|
||||
#endif
|
||||
+30
-2
@@ -11,7 +11,9 @@ enum { // ID1 ID2
|
||||
MG_PHY_RTL8201 = 0xc816, // 001c c816 - RTL8201F
|
||||
MG_PHY_RTL8211 = 0xc916, // 001c c916 - RTL8211F
|
||||
MG_PHY_ICS1894x = 0x15,
|
||||
MG_PHY_ICS189432 = 0xf450 // 0015 f450 - ICS1894
|
||||
MG_PHY_ICS189432 = 0xf450, // 0015 f450 - ICS1894
|
||||
MG_PHY_YT85x = 0x4f51,
|
||||
MG_PHY_YT8531 = 0xe91a // 4f51 e91a - Motorcomm YT8531
|
||||
};
|
||||
|
||||
enum {
|
||||
@@ -29,7 +31,10 @@ enum {
|
||||
MG_PHY_RTL82x_REG_PAGESEL = 31,
|
||||
MG_PHY_RTL8201_REG_RMSR = 16, // in page 7
|
||||
MG_PHY_RTL8211_REG_PHYSR = 26, // in page a43
|
||||
MG_PHY_ICS189432_REG_POLL = 17
|
||||
MG_PHY_ICS189432_REG_POLL = 17,
|
||||
MG_PHY_YT8531_REG_PHYSTS = 17,
|
||||
MG_PHY_YT8531_REG_EXT_ADDR = 30,
|
||||
MG_PHY_YT8531_REG_EXT_DATA = 31
|
||||
};
|
||||
|
||||
static const char *mg_phy_id_to_str(uint16_t id1, uint16_t id2) {
|
||||
@@ -60,6 +65,8 @@ static const char *mg_phy_id_to_str(uint16_t id1, uint16_t id2) {
|
||||
}
|
||||
case MG_PHY_ICS1894x:
|
||||
return "ICS1894x";
|
||||
case MG_PHY_YT85x:
|
||||
return id2 == MG_PHY_YT8531 ? "YT8531" : "YT85x";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
@@ -75,6 +82,18 @@ void mg_phy_init(struct mg_phy *phy, uint8_t phy_addr, uint8_t config) {
|
||||
id2 = phy->read_reg(phy_addr, MG_PHY_REG_ID2);
|
||||
MG_INFO(("PHY ID: %#04x %#04x (%s)", id1, id2, mg_phy_id_to_str(id1, id2)));
|
||||
|
||||
if (id1 == MG_PHY_YT85x && id2 == MG_PHY_YT8531) {
|
||||
uint16_t value;
|
||||
// TODO (robertc2000): Autonegotiation remains disabled after PHY is reset
|
||||
// We temporarily force enabling autoneg, until a workaround is found.
|
||||
phy->write_reg(phy_addr, MG_PHY_REG_BCR, MG_BIT(12));
|
||||
phy->write_reg(phy_addr, MG_PHY_YT8531_REG_EXT_ADDR, 0xa003);
|
||||
value = phy->read_reg(phy_addr, MG_PHY_YT8531_REG_EXT_DATA);
|
||||
value &= (uint16_t) ~(MG_BIT(3) | MG_BIT(2) | MG_BIT(1) | MG_BIT(0));
|
||||
phy->write_reg(phy_addr, MG_PHY_YT8531_REG_EXT_DATA,
|
||||
(uint16_t) (value | MG_BIT(1))); // TXDLY: 2 * 150 ps
|
||||
}
|
||||
|
||||
if (id1 == MG_PHY_DP83x && id2 == MG_PHY_DP83867) {
|
||||
phy->write_reg(phy_addr, 0x0d, 0x1f); // write 0x10d to IO_MUX_CFG (0x0170)
|
||||
phy->write_reg(phy_addr, 0x0e, 0x170);
|
||||
@@ -168,6 +187,15 @@ bool mg_phy_up(struct mg_phy *phy, uint8_t phy_addr, bool *full_duplex,
|
||||
uint16_t poll_reg = phy->read_reg(phy_addr, MG_PHY_ICS189432_REG_POLL);
|
||||
*full_duplex = poll_reg & MG_BIT(14);
|
||||
*speed = (poll_reg & MG_BIT(15)) ? MG_PHY_SPEED_100M : MG_PHY_SPEED_10M;
|
||||
} else if (id1 == MG_PHY_YT85x) {
|
||||
uint16_t id2 = phy->read_reg(phy_addr, MG_PHY_REG_ID2);
|
||||
if (id2 == MG_PHY_YT8531) {
|
||||
uint16_t physts = phy->read_reg(phy_addr, MG_PHY_YT8531_REG_PHYSTS);
|
||||
*full_duplex = physts & MG_BIT(13);
|
||||
*speed = (physts & MG_BIT(15)) ? MG_PHY_SPEED_1000M
|
||||
: (physts & MG_BIT(14)) ? MG_PHY_SPEED_100M
|
||||
: MG_PHY_SPEED_10M;
|
||||
}
|
||||
}
|
||||
}
|
||||
return up;
|
||||
|
||||
@@ -34,8 +34,8 @@ typedef size_t (*mg_pm_t)(mg_pfn_t fn, void *arg, va_list *);
|
||||
// - mg_print_base64 - prints a buffer as a base64-encoded string
|
||||
// - mg_print_esc - prints a JSON-escaped string
|
||||
// - mg_print_hex - prints a buffer as a hex string
|
||||
// - mg_print_ip - prints an IP address in a struct mg_str
|
||||
// - mg_print_ip_port - prints IP address and port in a struct mg_str
|
||||
// - mg_print_ip - prints an IP address in a struct mg_addr
|
||||
// - mg_print_ip_port - prints IP address and port in a struct mg_addr
|
||||
// - mg_print_ip4 - prints an IPv4 address
|
||||
// - mg_print_ip6 - prints an IPv6 address
|
||||
// - mg_print_mac - prints a MAC address
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "fs.h"
|
||||
#include "log.h"
|
||||
#include "printf.h"
|
||||
#include "str.h"
|
||||
#include "util.h"
|
||||
@@ -47,6 +48,7 @@ bool mg_file_write(struct mg_fs *fs, const char *path, const void *buf,
|
||||
char tmp[MG_PATH_MAX], rnd[10];
|
||||
size_t path_len = mg_snprintf(tmp, sizeof(tmp), "%s..%s", path,
|
||||
mg_random_str(rnd, sizeof(rnd)));
|
||||
fs->rm(tmp);
|
||||
if (path_len < sizeof(tmp) &&
|
||||
(fd = mg_fs_open(fs, tmp, MG_FS_WRITE | MG_FS_EXCL)) != NULL) {
|
||||
result = fs->wr(fd->fd, buf, len) == len;
|
||||
@@ -54,8 +56,11 @@ bool mg_file_write(struct mg_fs *fs, const char *path, const void *buf,
|
||||
if (result) {
|
||||
fs->rm(path);
|
||||
result = fs->mv(tmp, path);
|
||||
MG_DEBUG(("mv %s -> %s result=%d", tmp, path, result));
|
||||
}
|
||||
fs->rm(tmp);
|
||||
} else {
|
||||
MG_ERROR(("mg_fs_open(%s) failed, path_len=%zu", tmp, path_len));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -67,8 +72,10 @@ bool mg_file_printf(struct mg_fs *fs, const char *path, const char *fmt, ...) {
|
||||
va_start(ap, fmt);
|
||||
data = mg_vmprintf(fmt, &ap);
|
||||
va_end(ap);
|
||||
result = mg_file_write(fs, path, data, strlen(data));
|
||||
mg_free(data);
|
||||
if (data != NULL) {
|
||||
result = mg_file_write(fs, path, data, strlen(data));
|
||||
mg_free(data);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "arch.h"
|
||||
#include "config.h"
|
||||
#include "lfs.h"
|
||||
|
||||
// Flags returned by mg_fs.st() and passed to mg_fs.open().
|
||||
enum { MG_FS_READ = 1, MG_FS_WRITE = 2, MG_FS_DIR = 4, MG_FS_EXCL = 8 };
|
||||
@@ -40,6 +41,7 @@ void mg_fs_close(struct mg_fd *fd);
|
||||
|
||||
// Sequential directory iterator. Call repeatedly with the same buf/len;
|
||||
// each call fills buf with the next entry name. Returns false when done.
|
||||
// Note: make sure buf[0] == 0 before the first call
|
||||
bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len);
|
||||
|
||||
// Reads the entire file into a heap-allocated buffer. The returned mg_str is
|
||||
|
||||
+2
-2
@@ -50,9 +50,9 @@ static void *ff_open(const char *path, int flags) {
|
||||
if (flags & MG_FS_WRITE) {
|
||||
mode |= FA_WRITE;
|
||||
if (flags & MG_FS_EXCL) {
|
||||
mode |= FA_OPEN_ALWAYS | FA_OPEN_APPEND;
|
||||
} else {
|
||||
mode |= FA_CREATE_NEW;
|
||||
} else {
|
||||
mode |= FA_OPEN_ALWAYS | FA_OPEN_APPEND;
|
||||
}
|
||||
}
|
||||
if ((fp = mg_calloc(1, sizeof(*fp))) != NULL &&
|
||||
|
||||
+4
-4
@@ -10,6 +10,10 @@
|
||||
#define MG_STAT_FUNC stat
|
||||
#endif
|
||||
|
||||
#if MG_ENABLE_LFS
|
||||
#include <dirent.h>
|
||||
#endif
|
||||
|
||||
static int p_stat(const char *path, size_t *size, time_t *mtime) {
|
||||
#if !defined(S_ISDIR)
|
||||
MG_ERROR(("stat() API is not supported. %p %p %p", path, size, mtime));
|
||||
@@ -161,7 +165,6 @@ struct dirent *readdir(DIR *d) {
|
||||
|
||||
static void p_list(const char *dir, void (*fn)(const char *, void *),
|
||||
void *userdata) {
|
||||
#if MG_ENABLE_DIRLIST
|
||||
struct dirent *dp;
|
||||
DIR *dirp;
|
||||
if ((dirp = (opendir(dir))) == NULL) return;
|
||||
@@ -170,9 +173,6 @@ static void p_list(const char *dir, void (*fn)(const char *, void *),
|
||||
fn(dp->d_name, userdata);
|
||||
}
|
||||
closedir(dirp);
|
||||
#else
|
||||
(void) dir, (void) fn, (void) userdata;
|
||||
#endif
|
||||
}
|
||||
|
||||
static void *p_open(const char *path, int flags) {
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "config.h"
|
||||
#include "health.h"
|
||||
|
||||
// The one health record. Lives in RAM that survives a warm reset, see
|
||||
// MG_HEALTH_RAM and the .mg_health region in the linker script
|
||||
struct mg_health mg_health_record MG_HEALTH_RAM;
|
||||
|
||||
// STM32 H723 support. Needs the _estack symbol from the linker script
|
||||
#if MG_ENABLE_HEALTH && defined(STM32H723xx_H)
|
||||
// Fault handler body. Runs in exception context: no printf, no malloc, no
|
||||
// blocking calls. Copies the unwind registers and raw stack into the health
|
||||
// record, then resets.
|
||||
// "used" keeps the linker from garbage-collecting this section: the only
|
||||
// reference is the "b fault_c" branch in the naked handler below
|
||||
__attribute__((used, noinline)) static void fault_c(uint32_t *frame,
|
||||
uint32_t exc_return) {
|
||||
extern uint32_t _estack;
|
||||
uint32_t *stack = frame + 8 + ((exc_return & (1U << 4)) ? 0 : 18);
|
||||
uint32_t *r = mg_health_record.data;
|
||||
|
||||
if (frame[7] & (1U << 9)) stack++; // Eight-byte stack alignment padding
|
||||
r[0] = (uint32_t) (uintptr_t) stack; // SP
|
||||
r[1] = frame[5]; // LR
|
||||
r[2] = frame[6]; // PC
|
||||
for (size_t i = 0; i < MG_HEALTH_DATA_SIZE - 3; i++) { // Raw stack
|
||||
r[3 + i] = stack + i < &_estack ? stack[i] : 0;
|
||||
}
|
||||
mg_health_record.cpuid = SCB->CPUID;
|
||||
mg_health_record.reset_reason = MG_HEALTH_RESET_FAULT;
|
||||
NVIC_SystemReset();
|
||||
}
|
||||
|
||||
// Common fault entry. EXC_RETURN bit 2 tells which stack was in use:
|
||||
// 0 = MSP, 1 = PSP. Load the faulting SP into r0 and hand it to fault_c()
|
||||
__attribute__((naked)) void HardFault_Handler(void) {
|
||||
__asm volatile(
|
||||
"mov r1, lr\n\t"
|
||||
"tst lr, #4\n\t"
|
||||
"ite eq\n\t"
|
||||
"mrseq r0, msp\n\t"
|
||||
"mrsne r0, psp\n\t"
|
||||
"b fault_c\n\t");
|
||||
}
|
||||
|
||||
// Route the other fault types through the same entry point
|
||||
void MemManage_Handler(void) __attribute__((alias("HardFault_Handler")));
|
||||
void BusFault_Handler(void) __attribute__((alias("HardFault_Handler")));
|
||||
void UsageFault_Handler(void) __attribute__((alias("HardFault_Handler")));
|
||||
#endif
|
||||
|
||||
static size_t print_uint32(void (*fn)(char, void *), void *arg, va_list *ap) {
|
||||
size_t n = va_arg(*ap, size_t);
|
||||
uint32_t *p = va_arg(*ap, uint32_t *);
|
||||
size_t len = 0;
|
||||
while (n--) len += mg_xprintf(fn, arg, "%s%lu", len == 0 ? "" : ",", *p++);
|
||||
return len;
|
||||
}
|
||||
|
||||
size_t mg_print_crash_record(void (*fn)(char, void *), void *arg, va_list *ap) {
|
||||
size_t len = 0;
|
||||
if (mg_health_valid() &&
|
||||
mg_health_record.reset_reason == MG_HEALTH_RESET_FAULT) {
|
||||
size_t n = sizeof(mg_health_record.data) / sizeof(mg_health_record.data[0]);
|
||||
len += mg_xprintf(fn, arg, "{%m:%hhu,%m:%u,%m:[%M]}", //
|
||||
MG_ESC("version"), mg_health_record.magic[3], //
|
||||
MG_ESC("cpuid"), mg_health_record.cpuid, //
|
||||
MG_ESC("data"), print_uint32, n, mg_health_record.data);
|
||||
} else {
|
||||
len += mg_xprintf(fn, arg, "{}");
|
||||
}
|
||||
(void) ap;
|
||||
return len;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// Device health monitoring
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "arch.h"
|
||||
#include "printf.h"
|
||||
|
||||
#ifndef MG_HEALTH_MAGIC
|
||||
#define MG_HEALTH_MAGIC {'M', 'G', 'H', '3'} // '3' is the layout version
|
||||
#endif
|
||||
|
||||
// Places the record in RAM that survives a reset. Define in mongoose_config.h
|
||||
// to match the linker script, e.g. __attribute__((section(".mg_health")))
|
||||
#ifndef MG_HEALTH_RAM
|
||||
#define MG_HEALTH_RAM
|
||||
#endif
|
||||
|
||||
// Why the device restarted. Hardware usually reports several flags at once,
|
||||
// so these are ordered by how much they tell you: the most specific cause a
|
||||
// device reports wins
|
||||
enum mg_health_reason {
|
||||
MG_HEALTH_RESET_UNKNOWN = 0, // Nothing reported, or no masks configured
|
||||
MG_HEALTH_RESET_POWER, // Power-on reset, RAM contents are lost
|
||||
MG_HEALTH_RESET_BROWNOUT, // Supply dipped below the brown-out level
|
||||
MG_HEALTH_RESET_PIN, // External reset pin, e.g. the reset button
|
||||
MG_HEALTH_RESET_SOFTWARE, // Firmware asked for it, e.g. NVIC_SystemReset
|
||||
MG_HEALTH_RESET_LOWPOWER, // Illegal or failed low-power transition
|
||||
MG_HEALTH_RESET_WATCHDOG, // Watchdog fired: the application stopped
|
||||
MG_HEALTH_RESET_FAULT // Fault handler ran, see regs[] and saved_stack
|
||||
};
|
||||
|
||||
#ifndef MG_HEALTH_DATA_SIZE
|
||||
#define MG_HEALTH_DATA_SIZE 20
|
||||
#endif
|
||||
|
||||
struct mg_health {
|
||||
char magic[4]; // MG_HEALTH_MAGIC when the record holds valid data
|
||||
uint32_t reset_reason; // enum mg_health_reason that started this boot
|
||||
uint32_t cpuid; // ARM CPU ID
|
||||
uint32_t data[MG_HEALTH_DATA_SIZE];
|
||||
};
|
||||
|
||||
extern struct mg_health mg_health_record; // Defined in health.c
|
||||
|
||||
// Return true if the record holds valid data, i.e. it survived the reset and
|
||||
// was written by this firmware layout
|
||||
static inline bool mg_health_valid(void) {
|
||||
static const char magic[] = MG_HEALTH_MAGIC;
|
||||
return memcmp(mg_health_record.magic, magic,
|
||||
sizeof(mg_health_record.magic)) == 0;
|
||||
}
|
||||
|
||||
static inline int mg_health_reason(void) {
|
||||
return mg_health_valid() ? (int) mg_health_record.reset_reason
|
||||
: MG_HEALTH_RESET_UNKNOWN;
|
||||
}
|
||||
|
||||
static inline const char *mg_health_reason_str(int reason) {
|
||||
switch (reason) {
|
||||
case MG_HEALTH_RESET_POWER: return "power";
|
||||
case MG_HEALTH_RESET_BROWNOUT: return "brownout";
|
||||
case MG_HEALTH_RESET_PIN: return "pin";
|
||||
case MG_HEALTH_RESET_SOFTWARE: return "software";
|
||||
case MG_HEALTH_RESET_LOWPOWER: return "lowpower";
|
||||
case MG_HEALTH_RESET_WATCHDOG: return "watchdog";
|
||||
case MG_HEALTH_RESET_FAULT: return "fault";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
// Start a new boot: validate the record, count the boot, store the reset
|
||||
// reason. The current boot moves to prev_* slots first, so the previous
|
||||
// boot's uptime and reason stay readable. Called by MG_HEALTH_INIT()
|
||||
static inline void mg_health_init(void) {
|
||||
char magic[] = MG_HEALTH_MAGIC;
|
||||
// struct mg_health *h = mg_health_get();
|
||||
if (!mg_health_valid()) { // First boot, or RAM lost its contents
|
||||
memset(&mg_health_record, 0, sizeof(mg_health_record));
|
||||
memcpy(mg_health_record.magic, magic, sizeof(mg_health_record.magic));
|
||||
}
|
||||
}
|
||||
|
||||
#define MG_HEALTH_INIT() mg_health_init()
|
||||
extern size_t mg_print_crash_record(mg_pfn_t, void *, va_list *);
|
||||
+232
-238
@@ -3,7 +3,6 @@
|
||||
#include "fmt.h"
|
||||
#include "log.h"
|
||||
#include "net.h"
|
||||
#include "ota.h"
|
||||
#include "printf.h"
|
||||
#include "ssi.h"
|
||||
#include "util.h"
|
||||
@@ -170,6 +169,7 @@ int mg_url_decode(const char *src, size_t src_len, char *dst, size_t dst_len,
|
||||
mg_str_to_num(mg_str_n(src + i + 1, 2), 16, &dst[j], sizeof(uint8_t));
|
||||
i += 2;
|
||||
} else {
|
||||
dst[0] = '\0';
|
||||
return -1;
|
||||
}
|
||||
} else if (is_form_url_encoded && src[i] == '+') {
|
||||
@@ -358,7 +358,7 @@ static void mg_http_vprintf_chunk(struct mg_connection *c, const char *fmt,
|
||||
if (c->send.len >= len + 10) {
|
||||
mg_snprintf((char *) c->send.buf + len, 9, "%08lx", c->send.len - len - 10);
|
||||
c->send.buf[len + 8] = '\r';
|
||||
if (c->send.len == len + 10) c->is_resp = 0; // Last chunk, reset marker
|
||||
if (c->send.len == len + 10) c->pfn_data = NULL; // Last chunk, done
|
||||
}
|
||||
if (!mg_send(c, "\r\n", 2)) mg_error(c, "OOM");
|
||||
}
|
||||
@@ -373,7 +373,7 @@ void mg_http_printf_chunk(struct mg_connection *c, const char *fmt, ...) {
|
||||
void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len) {
|
||||
mg_printf(c, "%lx\r\n", (unsigned long) len);
|
||||
if (!mg_send(c, buf, len) || !mg_send(c, "\r\n", 2)) mg_error(c, "OOM");
|
||||
if (len == 0) c->is_resp = 0;
|
||||
if (len == 0) c->pfn_data = NULL; // Last chunk, response done
|
||||
}
|
||||
|
||||
// clang-format off
|
||||
@@ -462,15 +462,14 @@ void mg_http_reply(struct mg_connection *c, int code, const char *headers,
|
||||
(unsigned long) (c->send.len - len));
|
||||
c->send.buf[len - 15 + n] = ' '; // Change ending 0 to space
|
||||
}
|
||||
c->is_resp = 0;
|
||||
c->pfn_data = NULL; // Response done
|
||||
}
|
||||
|
||||
static void http_cb(struct mg_connection *, int, void *);
|
||||
static void restore_http_cb(struct mg_connection *c) {
|
||||
mg_fs_close((struct mg_fd *) c->pfn_data);
|
||||
c->pfn_data = NULL;
|
||||
c->pfn_data = NULL; // Response done
|
||||
c->pfn = http_cb;
|
||||
c->is_resp = 0;
|
||||
}
|
||||
|
||||
char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime);
|
||||
@@ -658,7 +657,7 @@ void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm,
|
||||
etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "",
|
||||
range, hdrs);
|
||||
if (mg_strcasecmp(hm->method, mg_str("HEAD")) == 0 || c->is_closing) {
|
||||
c->is_resp = 0;
|
||||
c->pfn_data = NULL; // Response done
|
||||
mg_fs_close(fd);
|
||||
} else { // start serving static content only if not closing, see #3354
|
||||
// Track to-be-sent content length at the end of c->data, aligned
|
||||
@@ -676,159 +675,97 @@ struct printdirentrydata {
|
||||
struct mg_http_message *hm;
|
||||
const struct mg_http_serve_opts *opts;
|
||||
const char *dir;
|
||||
size_t count;
|
||||
};
|
||||
|
||||
#if MG_ENABLE_DIRLIST
|
||||
// Print file name, escaping HTML chars
|
||||
static size_t html_esc(void (*fn)(char, void *), void *arg, va_list *ap) {
|
||||
const char *s = va_arg(*ap, const char *);
|
||||
size_t i, len = 0;
|
||||
for (i = 0; s[i] != '\0'; i++) {
|
||||
if (s[i] == '<') {
|
||||
len += mg_xprintf(fn, arg, "%s", "<");
|
||||
} else if (s[i] == '>') {
|
||||
len += mg_xprintf(fn, arg, "%s", ">");
|
||||
} else if (s[i] == '&') {
|
||||
len += mg_xprintf(fn, arg, "%s", "&");
|
||||
} else {
|
||||
len += mg_xprintf(fn, arg, "%c", s[i]);
|
||||
}
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
static void printdirentry(const char *name, void *userdata) {
|
||||
struct printdirentrydata *d = (struct printdirentrydata *) userdata;
|
||||
struct mg_fs *fs = d->opts->fs == NULL ? &mg_fs_posix : d->opts->fs;
|
||||
size_t size = 0;
|
||||
time_t t = 0;
|
||||
char path[MG_PATH_MAX], sz[40], mod[40];
|
||||
int flags, n = 0;
|
||||
char path[MG_PATH_MAX];
|
||||
int flags;
|
||||
|
||||
// MG_DEBUG(("[%s] [%s]", d->dir, name));
|
||||
if (mg_snprintf(path, sizeof(path), "%s%c%s", d->dir, '/', name) >
|
||||
if (mg_snprintf(path, sizeof(path), "%s%c%s", d->dir, '/', name) >=
|
||||
sizeof(path)) {
|
||||
MG_ERROR(("%s truncated", name));
|
||||
} else if ((flags = fs->st(path, &size, &t)) == 0) {
|
||||
MG_ERROR(("%lu stat(%s)", d->c->id, path));
|
||||
} else {
|
||||
const char *slash = flags & MG_FS_DIR ? "/" : "";
|
||||
if (flags & MG_FS_DIR) {
|
||||
mg_snprintf(sz, sizeof(sz), "%s", "[DIR]");
|
||||
mg_printf(d->c, "%s\n {%m: %m, %m: true}", //
|
||||
d->count == 0 ? "" : ",", //
|
||||
MG_ESC("name"), MG_ESC(name), MG_ESC("dir"));
|
||||
} else {
|
||||
mg_snprintf(sz, sizeof(sz), "%lld", (uint64_t) size);
|
||||
mg_printf(d->c, "%s\n {%m: %m, %m: %zu, %m: %llu, %m: false}", //
|
||||
d->count == 0 ? "" : ",", //
|
||||
MG_ESC("name"), MG_ESC(name), //
|
||||
MG_ESC("size"), size, //
|
||||
MG_ESC("modified"), (uint64_t) t, MG_ESC("dir"));
|
||||
}
|
||||
#if defined(MG_HTTP_DIRLIST_TIME_FMT)
|
||||
{
|
||||
char time_str[40];
|
||||
struct tm *time_info = localtime(&t);
|
||||
strftime(time_str, sizeof time_str, "%Y/%m/%d %H:%M:%S", time_info);
|
||||
mg_snprintf(mod, sizeof(mod), "%s", time_str);
|
||||
}
|
||||
#else
|
||||
mg_snprintf(mod, sizeof(mod), "%lu", (unsigned long) t);
|
||||
#endif
|
||||
n = (int) mg_url_encode(name, strlen(name), path, sizeof(path));
|
||||
mg_printf(d->c,
|
||||
" <tr><td><a href=\"%.*s%s\">%M%s</a></td>"
|
||||
"<td name=%lu>%s</td><td name=%lld>%s</td></tr>\n",
|
||||
n, path, slash, html_esc, name, slash, (unsigned long) t, mod,
|
||||
flags & MG_FS_DIR ? (int64_t) -1 : (int64_t) size, sz);
|
||||
d->count++;
|
||||
}
|
||||
}
|
||||
|
||||
static void listdir(struct mg_connection *c, struct mg_http_message *hm,
|
||||
const struct mg_http_serve_opts *opts, char *dir) {
|
||||
const char *sort_js_code =
|
||||
"<script>function srt(tb, sc, so, d) {"
|
||||
"var tr = Array.prototype.slice.call(tb.rows, 0),"
|
||||
"tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
|
||||
"n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
|
||||
"t1 = a.cells[2].getAttribute('name'), "
|
||||
"t2 = b.cells[2].getAttribute('name'); "
|
||||
"return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
|
||||
"n1 ? parseInt(n2) - parseInt(n1) : "
|
||||
"c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
|
||||
const char *sort_js_code2 =
|
||||
"for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
|
||||
"if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
|
||||
"};"
|
||||
"window.onload = function() {"
|
||||
"var tb = document.getElementById('tb');"
|
||||
"var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
|
||||
"var sc = m[1], so = m[2]; document.onclick = function(ev) { "
|
||||
"var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
|
||||
"sc = c; ev.preventDefault();}};"
|
||||
"srt(tb, sc, so, true);"
|
||||
"}"
|
||||
"</script>";
|
||||
struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
|
||||
struct printdirentrydata d = {c, hm, opts, dir};
|
||||
char tmp[10], buf[MG_PATH_MAX];
|
||||
struct printdirentrydata d = {c, hm, opts, dir, 0};
|
||||
char tmp[10];
|
||||
size_t off, n;
|
||||
int len = mg_url_decode(hm->uri.buf, hm->uri.len, buf, sizeof(buf), 0);
|
||||
struct mg_str uri = len > 0 ? mg_str_n(buf, (size_t) len) : hm->uri;
|
||||
|
||||
mg_printf(c,
|
||||
"HTTP/1.1 200 OK\r\n"
|
||||
"Content-Type: text/html; charset=utf-8\r\n"
|
||||
"%s"
|
||||
"Content-Length: \r\n\r\n",
|
||||
opts->extra_headers == NULL ? "" : opts->extra_headers);
|
||||
"HTTP/1.1 200 OK\r\n"
|
||||
"Content-Type: application/json; charset=utf-8\r\n"
|
||||
"%s"
|
||||
"Content-Length: \r\n\r\n",
|
||||
opts->extra_headers == NULL ? "" : opts->extra_headers);
|
||||
off = c->send.len; // Start of body
|
||||
mg_printf(c,
|
||||
"<!DOCTYPE html><html><head><title>Index of %M</title>%s%s"
|
||||
"<style>th,td {text-align: left; padding-right: 1em; "
|
||||
"font-family: monospace; }</style></head>"
|
||||
"<body><h1>Index of %M</h1><table cellpadding=\"0\"><thead>"
|
||||
"<tr><th><a href=\"#\" rel=\"0\">Name</a></th><th>"
|
||||
"<a href=\"#\" rel=\"1\">Modified</a></th>"
|
||||
"<th><a href=\"#\" rel=\"2\">Size</a></th></tr>"
|
||||
"<tr><td colspan=\"3\"><hr></td></tr>"
|
||||
"</thead>"
|
||||
"<tbody id=\"tb\">\n",
|
||||
mg_print_html_esc, (int) uri.len, uri.buf, sort_js_code, sort_js_code2,
|
||||
mg_print_html_esc, (int) uri.len, uri.buf);
|
||||
mg_printf(c, "%s",
|
||||
" <tr><td><a href=\"..\">..</a></td>"
|
||||
"<td name=-1></td><td name=-1>[DIR]</td></tr>\n");
|
||||
mg_printf(c, "[");
|
||||
fs->ls(dir, printdirentry, &d);
|
||||
mg_printf(c,
|
||||
"</tbody><tfoot><tr><td colspan=\"3\"><hr></td></tr></tfoot>"
|
||||
"</table><address>Mongoose v.%s</address></body></html>\n",
|
||||
MG_VERSION);
|
||||
mg_printf(c, "\n]\n");
|
||||
n = mg_snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off));
|
||||
if (n > sizeof(tmp)) n = 0;
|
||||
memcpy(c->send.buf + off - 12, tmp, n); // Set content length
|
||||
c->is_resp = 0; // Mark response end
|
||||
c->pfn_data = NULL; // Response done
|
||||
}
|
||||
|
||||
// Map requested URI to the file path (buf,len). Use root directory r.
|
||||
// r could be a path optionally followed by map: PATH,/PREFIX1=PATH1,...
|
||||
static bool uri2path(const char *r, struct mg_str uri, char *buf, size_t len) {
|
||||
struct mg_str k, v, part, s = mg_str(r), u = {NULL, 0}, d = u;
|
||||
size_t n;
|
||||
while (mg_span(s, &part, &s, ',')) {
|
||||
if (!mg_span(part, &k, &v, '=')) k = part, v = mg_str_n(NULL, 0);
|
||||
if (v.len == 0) v = k, k = mg_str("/"), u = k, d = v;
|
||||
if (uri.len < k.len) continue;
|
||||
if (mg_strcmp(k, mg_str_n(uri.buf, k.len)) != 0) continue;
|
||||
u = k, d = v;
|
||||
}
|
||||
n = mg_snprintf(buf, len, "%.*s", (int) d.len, d.buf);
|
||||
if (len == 0 || n + 2 >= len) return false; // Path overflow
|
||||
if (n > 0 && buf[n - 1] != '/') buf[n++] = '/', buf[n] = '\0'; // Add slash
|
||||
if (mg_url_decode(uri.buf + u.len, uri.len - u.len, buf + n, len - n, 0) < 0) {
|
||||
return false;
|
||||
}
|
||||
buf[len - 1] = '\0'; // Double-check
|
||||
n = strlen(buf);
|
||||
if (!mg_path_is_sane(mg_str_n(buf, n))) return false;
|
||||
while (n > 1 && buf[n - 1] == '/') buf[--n] = 0; // Trim trailing slashes
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Resolve requested file into `path` and return its fs->st() result
|
||||
static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm,
|
||||
struct mg_fs *fs, struct mg_str url, struct mg_str dir,
|
||||
char *path, size_t path_size) {
|
||||
static int uri_to_file_status(struct mg_connection *c,
|
||||
struct mg_http_message *hm,
|
||||
struct mg_fs *fs, const char *root_dir,
|
||||
char *path, size_t path_size) {
|
||||
int flags, tmp;
|
||||
// Append URI to the root_dir, and sanitize it
|
||||
size_t n = mg_snprintf(path, path_size, "%.*s", (int) dir.len, dir.buf);
|
||||
if (n + 2 >= path_size) {
|
||||
mg_http_reply(c, 400, "", "Exceeded path size");
|
||||
return -1;
|
||||
}
|
||||
path[path_size - 1] = '\0';
|
||||
// Terminate root dir with slash
|
||||
if (n > 0 && path[n - 1] != '/') path[n++] = '/', path[n] = '\0';
|
||||
if (url.len < hm->uri.len) {
|
||||
mg_url_decode(hm->uri.buf + url.len, hm->uri.len - url.len, path + n,
|
||||
path_size - n, 0);
|
||||
}
|
||||
path[path_size - 1] = '\0'; // Double-check
|
||||
n = strlen(path);
|
||||
if (!mg_path_is_sane(mg_str_n(path, n))) {
|
||||
size_t n;
|
||||
if (!uri2path(root_dir, hm->uri, path, path_size)) {
|
||||
mg_http_reply(c, 400, "", "Invalid path");
|
||||
return -1;
|
||||
}
|
||||
while (n > 1 && path[n - 1] == '/') path[--n] = 0; // Trim trailing slashes
|
||||
n = strlen(path);
|
||||
flags = mg_strcmp(hm->uri, mg_str("/")) == 0 ? MG_FS_DIR
|
||||
: fs->st(path, NULL, NULL);
|
||||
MG_VERBOSE(("%lu %.*s -> %s %d", c->id, (int) hm->uri.len, hm->uri.buf, path,
|
||||
@@ -843,7 +780,7 @@ static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm,
|
||||
"Content-Length: 0\r\n"
|
||||
"\r\n",
|
||||
(int) hm->uri.len, hm->uri.buf);
|
||||
c->is_resp = 0;
|
||||
c->pfn_data = NULL; // Response done
|
||||
flags = -1;
|
||||
} else if (flags & MG_FS_DIR) {
|
||||
if (((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX) > 0 &&
|
||||
@@ -865,34 +802,36 @@ static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm,
|
||||
return flags;
|
||||
}
|
||||
|
||||
static int uri_to_path(struct mg_connection *c, struct mg_http_message *hm,
|
||||
const struct mg_http_serve_opts *opts, char *path,
|
||||
size_t path_size) {
|
||||
struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
|
||||
struct mg_str k, v, part, s = mg_str(opts->root_dir), u = {NULL, 0}, p = u;
|
||||
while (mg_span(s, &part, &s, ',')) {
|
||||
if (!mg_span(part, &k, &v, '=')) k = part, v = mg_str_n(NULL, 0);
|
||||
if (v.len == 0) v = k, k = mg_str("/"), u = k, p = v;
|
||||
if (hm->uri.len < k.len) continue;
|
||||
if (mg_strcmp(k, mg_str_n(hm->uri.buf, k.len)) != 0) continue;
|
||||
u = k, p = v;
|
||||
}
|
||||
return uri_to_path2(c, hm, fs, u, p, path, path_size);
|
||||
}
|
||||
|
||||
void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm,
|
||||
const struct mg_http_serve_opts *opts) {
|
||||
char path[MG_PATH_MAX];
|
||||
struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
|
||||
const char *sp = opts->ssi_pattern;
|
||||
int flags = uri_to_path(c, hm, opts, path, sizeof(path));
|
||||
int flags = uri_to_file_status(c, hm, fs, opts->root_dir, path, sizeof(path));
|
||||
if (flags < 0) {
|
||||
// Do nothing: the response has already been sent by uri_to_path()
|
||||
// Do nothing: the response has already been sent by uri_to_file_status()
|
||||
} else if (flags & MG_FS_DIR) {
|
||||
#if MG_ENABLE_DIRLIST
|
||||
listdir(c, hm, opts, path);
|
||||
#else
|
||||
mg_http_reply(c, 403, "", "Forbidden\n");
|
||||
#endif
|
||||
if (opts->enable_dir_listing) {
|
||||
listdir(c, hm, opts, path);
|
||||
} else {
|
||||
mg_http_reply(c, 403, "", "Forbidden\n");
|
||||
}
|
||||
} else if (opts->enable_delete &&
|
||||
mg_strcasecmp(hm->method, mg_str("DELETE")) == 0) {
|
||||
mg_http_reply(c, flags && fs->rm(path) ? 200 : 404, "", "");
|
||||
} else if (opts->enable_upload &&
|
||||
(mg_strcasecmp(hm->method, mg_str("POST")) == 0 ||
|
||||
mg_strcasecmp(hm->method, mg_str("PUT")) == 0)) {
|
||||
// Small or already fully buffered body. mg_http_serve_upload() handles
|
||||
// the same thing without buffering, for big uploads, from MG_EV_HTTP_HDRS
|
||||
void *fd;
|
||||
bool ok = false;
|
||||
fs->rm(path); // MG_FS_WRITE appends, not truncates: drop any old file
|
||||
if ((fd = fs->op(path, MG_FS_WRITE)) != NULL) {
|
||||
ok = fs->wr(fd, hm->body.buf, hm->body.len) == hm->body.len;
|
||||
fs->cl(fd);
|
||||
}
|
||||
mg_http_reply(c, ok ? 200 : 500, "", "");
|
||||
} else if (flags && sp != NULL && mg_match(mg_str(path), mg_str(sp), NULL)) {
|
||||
mg_http_serve_ssi(c, opts->root_dir, path);
|
||||
} else {
|
||||
@@ -900,6 +839,52 @@ void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm,
|
||||
}
|
||||
}
|
||||
|
||||
// mg_http_stream_body() callback for mg_http_serve_upload(). The file is
|
||||
// opened by the caller before streaming starts, so this only writes and closes
|
||||
static bool serve_upload_cb(struct mg_http_message *hm, struct mg_str *data,
|
||||
void **p) {
|
||||
struct mg_fd *fd = (struct mg_fd *) *p;
|
||||
if (hm != NULL) return fd != NULL; // Start
|
||||
if (data != NULL) { // Next chunk
|
||||
return fd != NULL && fd->fs->wr(fd->fd, data->buf, data->len) == data->len;
|
||||
}
|
||||
if (fd != NULL) mg_fs_close(fd); // End
|
||||
*p = NULL;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Starts a streaming upload for a big POST/PUT body, so it never sits fully
|
||||
// buffered in memory. Companion to mg_http_serve_dir(): call this from
|
||||
// MG_EV_HTTP_HDRS, and keep calling mg_http_serve_dir() from MG_EV_HTTP_MSG
|
||||
// as before - it handles uploads too, for bodies this function skips.
|
||||
// Does nothing unless opts->enable_upload is set, the method is POST or PUT,
|
||||
// and Content-Length is known and >= 2 * MG_IO_SIZE.
|
||||
void mg_http_serve_upload(struct mg_connection *c, struct mg_http_message *hm,
|
||||
const struct mg_http_serve_opts *opts) {
|
||||
char path[MG_PATH_MAX];
|
||||
struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
|
||||
if (!opts->enable_upload) {
|
||||
// Not enabled, nothing to do
|
||||
} else if (mg_strcasecmp(hm->method, mg_str("POST")) != 0 &&
|
||||
mg_strcasecmp(hm->method, mg_str("PUT")) != 0) {
|
||||
// Not an upload request, nothing to do
|
||||
} else if (hm->body.len == (size_t) ~0 || hm->body.len < 2 * MG_IO_SIZE) {
|
||||
// Unknown length, or small enough for mg_http_serve_dir() to buffer it
|
||||
} else if (!uri2path(opts->root_dir, hm->uri, path, sizeof(path))) {
|
||||
MG_ERROR(("Invalid upload path: %.*s", (int) hm->uri.len, hm->uri.buf));
|
||||
} else if (fs->st(path, NULL, NULL) & MG_FS_DIR) {
|
||||
// Target is a directory, let mg_http_serve_dir() list it
|
||||
} else {
|
||||
struct mg_fd *fd;
|
||||
fs->rm(path); // MG_FS_WRITE appends, not truncates: drop any old file
|
||||
if ((fd = mg_fs_open(fs, path, MG_FS_WRITE)) == NULL) {
|
||||
MG_ERROR(("Cannot open %s for upload", path));
|
||||
} else if (!mg_http_stream_body(c, hm, serve_upload_cb, fd)) {
|
||||
mg_fs_close(fd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static bool mg_is_url_safe(int c) {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
|
||||
(c >= 'A' && c <= 'Z') || c == '.' || c == '_' || c == '-' || c == '~';
|
||||
@@ -972,8 +957,14 @@ long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
|
||||
struct mg_fs *fs, const char *dir, size_t max_size) {
|
||||
char buf[20] = "0", file[MG_PATH_MAX], path[MG_PATH_MAX];
|
||||
long res = 0, offset;
|
||||
mg_http_get_var(&hm->query, "offset", buf, sizeof(buf));
|
||||
mg_http_get_var(&hm->query, "file", file, sizeof(file));
|
||||
if (mg_http_get_var(&hm->query, "offset", buf, sizeof(buf)) == -3) {
|
||||
mg_http_reply(c, 400, "", "invalid offset");
|
||||
return -3;
|
||||
}
|
||||
if (mg_http_get_var(&hm->query, "file", file, sizeof(file)) == -3) {
|
||||
mg_http_reply(c, 400, "", "invalid file");
|
||||
return -2;
|
||||
}
|
||||
offset = strtol(buf, NULL, 0);
|
||||
mg_snprintf(path, sizeof(path), "%s%c%s", dir, MG_DIRSEP, file);
|
||||
if (hm->body.len == 0) {
|
||||
@@ -1016,96 +1007,96 @@ int mg_http_status(const struct mg_http_message *hm) {
|
||||
return atoi(hm->uri.buf);
|
||||
}
|
||||
|
||||
struct mg_upload_priv {
|
||||
size_t expected;
|
||||
size_t received;
|
||||
struct mg_fd *fd; // non-NULL: file upload; NULL: OTA
|
||||
void (*fn)(struct mg_connection *, const char *);
|
||||
// State of a streamed request or response body, kept in c->data. The callback
|
||||
// is kept in c->fn_data, which is free because we own the connection
|
||||
struct mg_upload_state {
|
||||
size_t expected; // Number of body bytes to receive
|
||||
size_t received; // Number of body bytes received so far
|
||||
void *user_data; // Passed to cb, free for cb to use
|
||||
bool failed; // Set when cb returned false
|
||||
};
|
||||
|
||||
static void mg_upload_handler(struct mg_connection *c, int ev, void *ev_data) {
|
||||
struct mg_upload_priv *p = (struct mg_upload_priv *) c->data;
|
||||
if (p->fn == NULL) return;
|
||||
if (ev == MG_EV_READ && c->recv.len > 0) {
|
||||
size_t alignment = 512;
|
||||
size_t left = p->expected > p->received ? p->expected - p->received : 0;
|
||||
size_t aligned = c->recv.len < left ? MG_ROUND_DOWN(c->recv.len, alignment)
|
||||
: left;
|
||||
bool ok = true;
|
||||
if (aligned > 0) {
|
||||
if (p->fd != NULL) {
|
||||
ok = p->fd->fs->wr(p->fd->fd, c->recv.buf, aligned) == aligned;
|
||||
} else {
|
||||
ok = mg_ota_write(c->recv.buf, aligned);
|
||||
}
|
||||
}
|
||||
p->received += aligned;
|
||||
mg_iobuf_del(&c->recv, 0, aligned);
|
||||
if (!ok) {
|
||||
if (p->fd != NULL) { mg_fs_close(p->fd); p->fd = NULL; }
|
||||
else mg_ota_end();
|
||||
p->fn(c, "write error");
|
||||
mg_free(c->pfn_data); c->pfn_data = NULL; p->fn = NULL;
|
||||
} else if (p->received >= p->expected) {
|
||||
const char *errmsg = NULL;
|
||||
if (p->fd != NULL) { mg_fs_close(p->fd); p->fd = NULL; }
|
||||
else if (!mg_ota_end()) errmsg = "OTA finalize failed";
|
||||
p->fn(c, errmsg);
|
||||
mg_free(c->pfn_data); c->pfn_data = NULL; p->fn = NULL;
|
||||
}
|
||||
} else if (ev == MG_EV_ERROR || ev == MG_EV_CLOSE) {
|
||||
if (p->fd != NULL) { mg_fs_close(p->fd); p->fd = NULL; }
|
||||
else mg_ota_end();
|
||||
p->fn(c, ev == MG_EV_ERROR ? (const char *) ev_data : "connection closed");
|
||||
mg_free(c->pfn_data); c->pfn_data = NULL; p->fn = NULL;
|
||||
}
|
||||
// Event handler installed by mg_http_stream_body(). Feeds the body to the
|
||||
// callback, then replies (servers only). It does not restore the previous
|
||||
// handler: the connection is closed after the reply.
|
||||
static void mg_stream_handler(struct mg_connection *c, int ev, void *ev_data) {
|
||||
struct mg_upload_state *us = (struct mg_upload_state *) c->data;
|
||||
bool (*fn)(struct mg_http_message *, struct mg_str *, void **) =
|
||||
(bool (*)(struct mg_http_message *, struct mg_str *, void **))
|
||||
(ptrdiff_t) c->fn_data;
|
||||
(void) ev_data;
|
||||
if (ev == MG_EV_CLOSE || ev == MG_EV_ERROR) {
|
||||
if (us->received < us->expected) {
|
||||
// Connection dropped mid-upload. Let cb clean up, e.g. call mg_ota_end()
|
||||
us->received = us->expected; // MG_EV_ERROR is followed by MG_EV_CLOSE
|
||||
fn(NULL, NULL, &us->user_data);
|
||||
}
|
||||
} else if (ev == MG_EV_READ && !c->is_draining) {
|
||||
if (c->recv.len > 0 && us->received < us->expected) {
|
||||
// Got some uploaded data. Feed by 512-byte aligned chunks, for OTA
|
||||
size_t left = us->expected - us->received, r = c->recv.len;
|
||||
size_t aligned = r < left ? MG_ROUND_DOWN(r, 512) : left;
|
||||
struct mg_str data = mg_str_n((char *) c->recv.buf, aligned);
|
||||
if (data.len > 0 && !us->failed) {
|
||||
us->failed = !fn(NULL, &data, &us->user_data);
|
||||
}
|
||||
us->received += aligned;
|
||||
mg_iobuf_del(&c->recv, 0, aligned); // Shift the unprocessed tail
|
||||
}
|
||||
if (us->received >= us->expected) {
|
||||
// Finished upload. Always call cb, even after error, so it can clean up
|
||||
us->failed |= !fn(NULL, NULL, &us->user_data);
|
||||
if (!c->is_client) {
|
||||
mg_http_reply(c, us->failed ? 500 : 200, NULL, "%zu %s\n",
|
||||
us->received, us->failed ? "fail" : "ok");
|
||||
}
|
||||
c->is_draining = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void mg_upload_default_cb(struct mg_connection *c, const char *status) {
|
||||
MG_INFO(("%lu %s", c->id, status ? status : "ok"));
|
||||
mg_http_reply(c, status ? 500 : 200, "", "%s\n", status ? status : "ok");
|
||||
}
|
||||
bool mg_http_stream_body(struct mg_connection *c, struct mg_http_message *hm,
|
||||
bool (*cb)(struct mg_http_message *, struct mg_str *,
|
||||
void **user_data),
|
||||
void *user_data) {
|
||||
struct mg_upload_state *us = (struct mg_upload_state *) c->data;
|
||||
struct mg_str *te = mg_http_get_header(hm, "Transfer-Encoding");
|
||||
bool handled = false;
|
||||
|
||||
void mg_http_start_upload(struct mg_connection *c, struct mg_http_message *hm,
|
||||
struct mg_str name, struct mg_str dir,
|
||||
struct mg_fs *fs,
|
||||
void (*fn)(struct mg_connection *, const char *)) {
|
||||
struct mg_upload_priv *p = (struct mg_upload_priv *) c->data;
|
||||
char path[MG_PATH_MAX];
|
||||
struct mg_fd *fd;
|
||||
if (fn == NULL) fn = mg_upload_default_cb;
|
||||
if (sizeof(*p) > sizeof(c->data)) { fn(c, "data too small"); return; }
|
||||
if (!mg_path_is_sane(name)) { fn(c, "bad name"); return; }
|
||||
mg_snprintf(path, sizeof(path), "%.*s%c%.*s", (int) dir.len, dir.buf,
|
||||
MG_DIRSEP, (int) name.len, name.buf);
|
||||
fd = mg_fs_open(fs, path, MG_FS_WRITE);
|
||||
if (fd == NULL) { fn(c, "open failed"); return; }
|
||||
p->expected = hm->body.len;
|
||||
p->received = 0;
|
||||
p->fd = fd;
|
||||
p->fn = fn;
|
||||
c->fn = mg_upload_handler;
|
||||
c->pfn_data = strdup(path);
|
||||
c->pfn = NULL;
|
||||
mg_iobuf_del(&c->recv, 0, hm->head.len);
|
||||
mg_call(c, MG_EV_READ, &c->recv.len);
|
||||
}
|
||||
|
||||
void mg_http_start_ota(struct mg_connection *c, struct mg_http_message *hm,
|
||||
void (*fn)(struct mg_connection *, const char *)) {
|
||||
struct mg_upload_priv *p = (struct mg_upload_priv *) c->data;
|
||||
if (fn == NULL) fn = mg_upload_default_cb;
|
||||
if (sizeof(*p) > sizeof(c->data)) { fn(c, "data too small"); return; }
|
||||
if (!mg_ota_begin(hm->body.len)) { fn(c, "ota begin failed"); return; }
|
||||
p->expected = hm->body.len;
|
||||
p->received = 0;
|
||||
p->fd = NULL;
|
||||
p->fn = fn;
|
||||
c->fn = mg_upload_handler;
|
||||
c->pfn = NULL;
|
||||
mg_iobuf_del(&c->recv, 0, hm->head.len);
|
||||
mg_call(c, MG_EV_READ, &c->recv.len);
|
||||
// Catch upload requests early, without buffering whole body. Called on the
|
||||
// MG_EV_HTTP_HDRS event: we've received all HTTP headers but not necessarily
|
||||
// the full HTTP body
|
||||
if (hm->body.len == (size_t) ~0 ||
|
||||
(te != NULL && mg_strcasecmp(*te, mg_str("chunked")) == 0)) {
|
||||
// Unknown length or chunked, cannot stream. Leave it to the caller
|
||||
} else if (!c->is_client &&
|
||||
mg_strcmp(hm->method, mg_str("POST")) != 0 &&
|
||||
mg_strcmp(hm->method, mg_str("PUT")) != 0) {
|
||||
// Not an upload request. Leave it to the caller
|
||||
} else if (sizeof(*us) > sizeof(c->data)) {
|
||||
if (!c->is_client) { // Nobody to reply to on a client connection
|
||||
c->pfn = NULL;
|
||||
mg_http_reply(c, 500, NULL, "data too small\n");
|
||||
c->is_draining = 1;
|
||||
cb(NULL, NULL, &user_data); // Let cb release user_data, start skipped
|
||||
handled = true;
|
||||
}
|
||||
} else {
|
||||
c->pfn = NULL; // Silence HTTP protocol handler
|
||||
memset(us, 0, sizeof(*us));
|
||||
us->expected = hm->body.len; // Store number of bytes we expect
|
||||
us->user_data = user_data;
|
||||
us->failed = !cb(hm, NULL, &us->user_data); // Call before deleting headers
|
||||
if (mg_http_get_header(hm, "Expect") != NULL) {
|
||||
mg_http_reply(c, 100, NULL, ""); // If curl expects, we continue
|
||||
}
|
||||
mg_iobuf_del(&c->recv, 0, hm->head.len); // Delete HTTP headers
|
||||
c->fn = mg_stream_handler; // We own the connection from now
|
||||
c->fn_data = (void *) (ptrdiff_t) cb;
|
||||
mg_call(c, MG_EV_READ, &c->recv.len); // Process the body bytes we have
|
||||
handled = true;
|
||||
}
|
||||
return handled;
|
||||
}
|
||||
|
||||
static bool is_hex_digit(int c) {
|
||||
@@ -1134,7 +1125,9 @@ static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
|
||||
c->recv.len > 0)) { // see #2796
|
||||
struct mg_http_message hm;
|
||||
size_t ofs = 0; // Parsing offset
|
||||
while (c->is_resp == 0 && ofs < c->recv.len) {
|
||||
// c->pfn_data is the "response generation in progress" marker. While it
|
||||
// is set, don't parse the next pipelined request, to keep responses in order
|
||||
while (c->pfn_data == NULL && ofs < c->recv.len) {
|
||||
const char *buf = (char *) c->recv.buf + ofs;
|
||||
int n = mg_http_parse(buf, c->recv.len - ofs, &hm);
|
||||
struct mg_str *te; // Transfer - encoding header
|
||||
@@ -1183,8 +1176,9 @@ static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
|
||||
// contain a Content-length header (unless the body length is 0, in
|
||||
// which case it can be omitted). Other requests can also contain a
|
||||
// body, but their content has no defined semantics (RFC 7231)
|
||||
// It is a non-chunked request, so the offset (ofs) is updated after
|
||||
// exiting this branch.
|
||||
if (hm.body.len != 0) require_content_len = true;
|
||||
ofs += (size_t) n; // this request has been processed
|
||||
} else if (is_response) {
|
||||
// HTTP spec 7.2 Entity body: All other responses must include a body
|
||||
// or Content-Length header field defined with a value of 0.
|
||||
@@ -1226,9 +1220,9 @@ static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
|
||||
ofs += (size_t) n + hm.body.len;
|
||||
}
|
||||
|
||||
if (c->is_accepted) c->is_resp = 1; // Start generating response
|
||||
mg_call(c, MG_EV_HTTP_MSG, &hm); // User handler can clear is_resp
|
||||
if (c->is_accepted && !c->is_resp) {
|
||||
if (c->is_accepted) c->pfn_data = c; // Response started
|
||||
mg_call(c, MG_EV_HTTP_MSG, &hm); // Handler sets pfn_data NULL when done
|
||||
if (c->is_accepted && c->pfn_data == NULL) {
|
||||
struct mg_str *cc = mg_http_get_header(&hm, "Connection");
|
||||
if (cc != NULL && mg_strcasecmp(*cc, mg_str("close")) == 0) {
|
||||
c->is_draining = 1; // honor "Connection: close"
|
||||
|
||||
+47
-17
@@ -32,6 +32,9 @@ struct mg_http_serve_opts {
|
||||
const char *mime_types; // Additional MIME types: "ext1=type1,ext2=type2". NULL for defaults only
|
||||
const char *page404; // Path to a custom 404 page, e.g. "/404.html". NULL for built-in
|
||||
struct mg_fs *fs; // Filesystem to use. NULL defaults to POSIX
|
||||
bool enable_delete; // Allow to DELETE files
|
||||
bool enable_upload; // Allow to POST/PUT files
|
||||
bool enable_dir_listing; // Enable directory listing
|
||||
};
|
||||
|
||||
// A single part of a multipart/form-data body, filled by mg_http_next_multipart().
|
||||
@@ -105,8 +108,11 @@ struct mg_connection *mg_http_connect(struct mg_mgr *, const char *url,
|
||||
// mg_http_listen(), mg_http_serve_file(), mg_http_reply(), mg_match()
|
||||
// Notes:
|
||||
// Call from an MG_EV_HTTP_MSG handler. The uri in hm is mapped under
|
||||
// opts->root_dir. Directory listing depends on MG_ENABLE_DIRLIST; SSI uses
|
||||
// opts->ssi_pattern when configured.
|
||||
// opts->root_dir. opts->enable_dir_listing enables directory listing; SSI
|
||||
// uses opts->ssi_pattern when configured. opts->enable_delete enables
|
||||
// DELETE; opts->enable_upload enables POST/PUT, writing the whole body to
|
||||
// a file - see mg_http_serve_upload() to also stream big uploads without
|
||||
// buffering.
|
||||
void mg_http_serve_dir(struct mg_connection *, struct mg_http_message *hm,
|
||||
const struct mg_http_serve_opts *);
|
||||
|
||||
@@ -114,6 +120,15 @@ void mg_http_serve_dir(struct mg_connection *, struct mg_http_message *hm,
|
||||
void mg_http_serve_file(struct mg_connection *, struct mg_http_message *hm,
|
||||
const char *path, const struct mg_http_serve_opts *);
|
||||
|
||||
// Streams a big POST/PUT upload straight to a file, instead of buffering the
|
||||
// whole body. Optional companion to mg_http_serve_dir(): call this from
|
||||
// MG_EV_HTTP_HDRS with the same opts, and keep calling mg_http_serve_dir()
|
||||
// from MG_EV_HTTP_MSG as usual - it still handles uploads this function skips.
|
||||
// Does nothing unless opts->enable_upload is set, the method is POST or PUT,
|
||||
// and Content-Length is known and big enough.
|
||||
void mg_http_serve_upload(struct mg_connection *, struct mg_http_message *hm,
|
||||
const struct mg_http_serve_opts *);
|
||||
|
||||
// Sends a complete HTTP response with Content-Length.
|
||||
//
|
||||
// Example:
|
||||
@@ -160,20 +175,6 @@ void mg_http_creds(struct mg_http_message *, char *, size_t, char *, size_t);
|
||||
long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
|
||||
struct mg_fs *fs, const char *dir, size_t max_size);
|
||||
|
||||
// Streams the raw request body into dir/name via fs. Non-blocking: installs an
|
||||
// internal handler and returns immediately. fn is called with NULL on success
|
||||
// or an error string on failure.
|
||||
void mg_http_start_upload(struct mg_connection *c, struct mg_http_message *hm,
|
||||
struct mg_str name, struct mg_str dir,
|
||||
struct mg_fs *fs,
|
||||
void (*fn)(struct mg_connection *, const char *));
|
||||
|
||||
// Starts an OTA firmware update from an HTTP POST upload.
|
||||
// Calls mg_ota_begin/write/end internally; fn is called with NULL on success,
|
||||
// or an error string on failure.
|
||||
void mg_http_start_ota(struct mg_connection *c, struct mg_http_message *hm,
|
||||
void (*fn)(struct mg_connection *, const char *));
|
||||
|
||||
// Sends a 401 Unauthorized response with a Basic Auth WWW-Authenticate challenge.
|
||||
void mg_http_bauth(struct mg_connection *, const char *user, const char *pass);
|
||||
|
||||
@@ -192,7 +193,7 @@ struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v);
|
||||
// Full examples:
|
||||
// tutorials/http/file-upload-html-form, tutorials/http/http-server
|
||||
// Related APIs:
|
||||
// mg_http_listen(), mg_http_start_upload()
|
||||
// mg_http_listen(), mg_http_stream_body()
|
||||
// Notes:
|
||||
// Call from an MG_EV_HTTP_MSG handler after the full request body is
|
||||
// received. part.name, part.filename, and part.body are zero-copy slices into
|
||||
@@ -201,3 +202,32 @@ size_t mg_http_next_multipart(struct mg_str, size_t, struct mg_http_part *);
|
||||
|
||||
// Returns the HTTP status code from a parsed response message (e.g. 200, 404).
|
||||
int mg_http_status(const struct mg_http_message *hm);
|
||||
|
||||
// Streams a POST/PUT body to a callback as it arrives, without buffering it.
|
||||
// Call it from an MG_EV_HTTP_HDRS handler, after matching the request, e.g.
|
||||
// with mg_match(). Returns true if it took over the connection, false if the
|
||||
// request is not POST/PUT, is chunked, or has no Content-Length.
|
||||
//
|
||||
// Callback upload_fn(hm, data, user_data) is called:
|
||||
// - at start: hm is set. Open the file, set *user_data.
|
||||
// - per chunk: data is set, 512 byte aligned except the last. Not called
|
||||
// again after a failure.
|
||||
// - at end: both NULL. Always called once, also when the connection drops
|
||||
// early, so release resources here. A truncated body looks like a complete
|
||||
// one: validate before committing.
|
||||
// Return true on success, false on error.
|
||||
// Example:
|
||||
// if (ev == MG_EV_HTTP_HDRS && mg_match(hm->uri, mg_str("/fs/*"), NULL) {
|
||||
// mg_http_stream_body(c, hm, upload, NULL));
|
||||
// }
|
||||
// Full example:
|
||||
// tutorials/http/file-upload-single-post
|
||||
// Related APIs:
|
||||
// mg_http_listen(), mg_http_next_multipart()
|
||||
// Notes:
|
||||
// After it returns true, this function hijacks the connection. Existing event
|
||||
// handler not called, hm is invalid, c->data and c->fn_data are modified
|
||||
bool mg_http_stream_body(struct mg_connection *c, struct mg_http_message *hm,
|
||||
bool (*upload_fn)(struct mg_http_message *,
|
||||
struct mg_str *, void **user_data),
|
||||
void *user_data);
|
||||
@@ -135,6 +135,7 @@ bool mg_l2_eth_rx(struct mg_tcpip_if *ifp, enum mg_l2proto *proto,
|
||||
}
|
||||
pay->buf = ((char *) eth) + hdrlen;
|
||||
pay->len = len - hdrlen;
|
||||
if (len > ifp->framesize) return false; // Oversized
|
||||
for (i = 0; i < sizeof(eth_types) / sizeof(uint16_t); i++) {
|
||||
if (type == eth_types[i]) break;
|
||||
}
|
||||
|
||||
+4
-1
@@ -101,7 +101,7 @@ static uint16_t s_id;
|
||||
|
||||
void mg_l2_ppp_init(struct mg_tcpip_if *ifp) {
|
||||
ifp->l2mtu = 1500;
|
||||
ifp->framesize = 1500 + sizeof(struct ppp) + sizeof(struct hdlc_);
|
||||
ifp->framesize = ifp->l2mtu + sizeof(struct ppp) + sizeof(struct hdlc_) + 2;
|
||||
}
|
||||
|
||||
extern void mg_l2_eth_init(struct mg_tcpip_if *);
|
||||
@@ -466,6 +466,7 @@ bool mg_l2_ppp_rx(struct mg_tcpip_if *ifp, enum mg_l2proto *proto,
|
||||
pay->buf = (char *) raw->buf;
|
||||
pay->len = raw->len - 2;
|
||||
}
|
||||
if (pay->len > ifp->l2mtu + sizeof(struct ppp)) return false; // Oversized
|
||||
return ppp_rx(ifp, proto, pay, raw);
|
||||
}
|
||||
|
||||
@@ -548,6 +549,8 @@ bool mg_l2_pppoe_rx(struct mg_tcpip_if *ifp, enum mg_l2proto *proto,
|
||||
if (!mg_l2_eth_rx(ifp, ð_proto, pay, raw)) return false;
|
||||
pppoe = (struct pppoe *) pay->buf; // here we handle pay, not raw
|
||||
if (pay->len < sizeof(*pppoe)) return false; // Truncated
|
||||
if (pay->len - sizeof(*pppoe) > ifp->l2mtu + sizeof(struct ppp))
|
||||
return false; // Oversized
|
||||
if (eth_proto == MG_TCPIP_L2PROTO_PPPoE_DISC) {
|
||||
MG_VERBOSE(("PPPoE_DISC"));
|
||||
if (s_state == MG_PPPoE_ST_DISC && pppoe->code == MG_PPPoE_PADO &&
|
||||
|
||||
@@ -3,19 +3,18 @@
|
||||
|
||||
#include "flash.h"
|
||||
#include "util.h"
|
||||
#include "lfs.h"
|
||||
|
||||
#if MG_ENABLE_LFS
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <littlefs/lfs.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#ifndef LFS_USE_RAM
|
||||
#define LFS_USE_RAM 0 // If 1, use RAM FS. If 0, use flash
|
||||
#endif
|
||||
|
||||
#ifndef MG_LFS_SIZE
|
||||
#define MG_LFS_SIZE (64 * 1024)
|
||||
#endif
|
||||
|
||||
#ifndef MG_LFS_BUF_SIZE
|
||||
#define MG_LFS_BUF_SIZE 64 // Buffer size used for reads, writes, and cache
|
||||
#endif
|
||||
@@ -28,19 +27,6 @@
|
||||
#define MG_LFS_BLOCK_SIZE 8192
|
||||
#endif
|
||||
|
||||
#ifndef DT_DIR
|
||||
#define DT_DIR 4
|
||||
#endif
|
||||
#ifndef DT_REG
|
||||
#define DT_REG 8
|
||||
#endif
|
||||
|
||||
typedef struct mg_lfs_fd DIR;
|
||||
struct dirent {
|
||||
char d_name[LFS_NAME_MAX + 1];
|
||||
unsigned char d_type;
|
||||
};
|
||||
|
||||
struct mg_lfs_fd {
|
||||
struct mg_lfs_fd *next;
|
||||
bool isopen;
|
||||
@@ -52,7 +38,6 @@ struct mg_lfs_fd {
|
||||
static lfs_t s_lfs;
|
||||
static struct mg_lfs_fd *s_fds;
|
||||
static uint8_t *s_fs;
|
||||
static int s_next_fd = MG_LFS_FD_BASE;
|
||||
static bool s_lfs_ready;
|
||||
#if LFS_USE_RAM
|
||||
static uint8_t *s_ram_fs;
|
||||
@@ -110,29 +95,50 @@ static int lfs_driver_sync(const struct lfs_config *cfg) {
|
||||
}
|
||||
|
||||
bool mg_lfs_init(size_t size) {
|
||||
int result = 0;
|
||||
//bool ok = false;
|
||||
MG_DEBUG(("size: %zu", size));
|
||||
if (s_lfs_ready) return true;
|
||||
if (size == 0) return false;
|
||||
if (size == 0) {
|
||||
MG_ERROR(("invalidsize = 0"));
|
||||
} else {
|
||||
#if LFS_USE_RAM
|
||||
s_cfg.block_size = MG_LFS_BLOCK_SIZE;
|
||||
if (s_ram_fs == NULL) s_ram_fs = (uint8_t *) mg_calloc(1, size);
|
||||
s_fs = s_ram_fs;
|
||||
s_cfg.block_size = MG_LFS_BLOCK_SIZE;
|
||||
if (s_ram_fs == NULL) s_ram_fs = (uint8_t *) mg_calloc(1, size);
|
||||
s_fs = s_ram_fs;
|
||||
#else
|
||||
if (mg_flash == NULL || mg_flash->secsz == 0 || mg_flash->size < size) return false;
|
||||
if (mg_flash->write_fn == NULL) return false;
|
||||
s_cfg.block_size = mg_flash->secsz;
|
||||
s_fs = (uint8_t *) mg_flash->start + mg_flash->size - size;
|
||||
{
|
||||
// Some flash attributes may be initialised on ota_begin
|
||||
int lev = mg_log_level;
|
||||
mg_log_level = MG_LL_NONE;
|
||||
mg_ota_begin(1);
|
||||
mg_ota_end();
|
||||
mg_log_set(lev);
|
||||
}
|
||||
if (mg_flash == NULL || mg_flash->secsz == 0 || mg_flash->size < size) {
|
||||
MG_ERROR(("mg_flash %p secsz %zu flash_size %zu < size %zu", mg_flash, mg_flash->secsz, mg_flash->size, size));
|
||||
} else if (mg_flash->write_fn == NULL) {
|
||||
MG_ERROR(("flash write_fn == NULL"));
|
||||
} else {
|
||||
s_cfg.block_size = mg_flash->secsz;
|
||||
s_fs = (uint8_t *) mg_flash->start + mg_flash->size - size;
|
||||
}
|
||||
#endif
|
||||
if (s_fs == NULL || s_cfg.block_size == 0 || size % s_cfg.block_size != 0) {
|
||||
return false;
|
||||
if (s_fs == NULL || s_cfg.block_size == 0 || size % s_cfg.block_size != 0) {
|
||||
MG_ERROR(("s_fs %p blk_size %zu size %zu", s_fs, s_cfg.block_size));
|
||||
} else {
|
||||
s_cfg.block_count = (lfs_size_t) (size / s_cfg.block_size);
|
||||
if (s_cfg.block_count == 0) {
|
||||
MG_ERROR(("blk_count == 0"));
|
||||
} else {
|
||||
if (lfs_mount(&s_lfs, &s_cfg) != 0) lfs_format(&s_lfs, &s_cfg);
|
||||
if (lfs_mount(&s_lfs, &s_cfg) != 0) {
|
||||
MG_ERROR(("lfs_mount"));
|
||||
} else {
|
||||
s_lfs_ready = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s_cfg.block_count = (lfs_size_t) (size / s_cfg.block_size);
|
||||
if (s_cfg.block_count == 0) return false;
|
||||
if (lfs_mount(&s_lfs, &s_cfg) != 0) {
|
||||
lfs_format(&s_lfs, &s_cfg);
|
||||
if (lfs_mount(&s_lfs, &s_cfg) != 0) result = -1;
|
||||
}
|
||||
s_lfs_ready = result == 0;
|
||||
return s_lfs_ready;
|
||||
}
|
||||
|
||||
@@ -145,16 +151,12 @@ static struct mg_lfs_fd *find_fd(int fd) {
|
||||
}
|
||||
|
||||
static struct mg_lfs_fd *open_fd(void) {
|
||||
struct mg_lfs_fd *f = NULL;
|
||||
if (s_lfs_ready) {
|
||||
f = (struct mg_lfs_fd *) mg_calloc(1, sizeof(*f));
|
||||
if (f != NULL) {
|
||||
f->isopen = true;
|
||||
f->fd = s_next_fd++;
|
||||
f->next = s_fds;
|
||||
s_fds = f;
|
||||
if (s_next_fd < MG_LFS_FD_BASE) s_next_fd = MG_LFS_FD_BASE;
|
||||
}
|
||||
struct mg_lfs_fd *f = NULL, *p = s_fds;
|
||||
if (s_lfs_ready == false) mg_lfs_init(MG_LFS_SIZE);
|
||||
if (s_lfs_ready && (f = (struct mg_lfs_fd *) mg_calloc(1, sizeof(*f)))) {
|
||||
f->isopen = true, f->fd = MG_LFS_FD_BASE, f->next = s_fds;
|
||||
while (p != NULL) p = p->fd == f->fd ? (f->fd++, s_fds) : p->next;
|
||||
s_fds = f;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
@@ -173,6 +175,7 @@ int _open(const char *path, int flags, mode_t mode) {
|
||||
int err, lfs_flags = 0, fd = -1;
|
||||
struct mg_lfs_fd *f = open_fd();
|
||||
(void) mode;
|
||||
MG_DEBUG(("%s -> %p, lfs_ready %d", path, f, s_lfs_ready));
|
||||
if (f == NULL) return -1;
|
||||
fd = f->fd;
|
||||
if ((flags & 3) == O_RDONLY) lfs_flags |= LFS_O_RDONLY;
|
||||
@@ -214,11 +217,21 @@ int _lseek(int fd, int offset, int whence) {
|
||||
}
|
||||
|
||||
int _rename(const char *oldname, const char *newname) {
|
||||
if (s_lfs_ready == false) mg_lfs_init(MG_LFS_SIZE);
|
||||
return s_lfs_ready ? lfs_rename(&s_lfs, oldname, newname) : -1;
|
||||
}
|
||||
|
||||
int _unlink_r(void *r, const char *a) {
|
||||
(void) r;
|
||||
// Some libc rename() implementations have no atomic rename syscall and emulate
|
||||
// it as link() + unlink() instead of calling _rename() directly. LittleFS has
|
||||
// no real hard links, but forwarding to _rename() gives the same end result
|
||||
// (oldname becomes newname), which is all mg_file_write()'s atomic-write
|
||||
// pattern (write to a temp file, then rename it into place) needs
|
||||
int _link(const char *oldname, const char *newname) {
|
||||
return _rename(oldname, newname);
|
||||
}
|
||||
|
||||
int _unlink(const char *a) {
|
||||
if (s_lfs_ready == false) mg_lfs_init(MG_LFS_SIZE);
|
||||
return s_lfs_ready ? lfs_remove(&s_lfs, a) : -1;
|
||||
}
|
||||
|
||||
@@ -227,7 +240,7 @@ DIR *opendir(const char *name) {
|
||||
if (f == NULL) return NULL;
|
||||
if (lfs_dir_open(&s_lfs, &f->dir, name) != 0) {
|
||||
close_fd(f);
|
||||
return NULL;
|
||||
f = NULL;
|
||||
}
|
||||
return (DIR *) f;
|
||||
}
|
||||
@@ -254,7 +267,9 @@ struct dirent *readdir(DIR *dir) {
|
||||
|
||||
int _stat(const char *path, struct stat *st) {
|
||||
struct lfs_info info;
|
||||
if (s_lfs_ready == false) mg_lfs_init(MG_LFS_SIZE);
|
||||
if (!s_lfs_ready || lfs_stat(&s_lfs, path, &info) != 0) return -1;
|
||||
memset(st, 0, sizeof(*st));
|
||||
st->st_mode = info.type == LFS_TYPE_DIR ? S_IFDIR : S_IFREG;
|
||||
st->st_size = info.size;
|
||||
return 0;
|
||||
@@ -268,7 +283,7 @@ int _fstat(int fd, struct stat *st) {
|
||||
|
||||
int mkdir(const char *path, mode_t mode) {
|
||||
(void) mode;
|
||||
if (s_lfs_ready == false) mg_lfs_init(MG_LFS_SIZE);
|
||||
return s_lfs_ready ? lfs_mkdir(&s_lfs, path) : -1;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#if MG_ENABLE_LFS
|
||||
#include <fcntl.h>
|
||||
#include <lfs.h>
|
||||
|
||||
#ifndef DT_DIR
|
||||
#define DT_DIR 4
|
||||
#endif
|
||||
#ifndef DT_REG
|
||||
#define DT_REG 8
|
||||
#endif
|
||||
|
||||
struct dirent {
|
||||
char d_name[LFS_NAME_MAX + 1];
|
||||
unsigned char d_type;
|
||||
};
|
||||
|
||||
typedef struct mg_lfs_fd DIR;
|
||||
#endif
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
#include "mdash.h"
|
||||
|
||||
#if MG_ENABLE_MDASH
|
||||
|
||||
#include "base64.h"
|
||||
#include "health.h"
|
||||
#include "log.h"
|
||||
#include "ota.h"
|
||||
#include "printf.h"
|
||||
#include "rpc.h"
|
||||
#include "sntp.h"
|
||||
#include "tls.h"
|
||||
#include "url.h"
|
||||
#include "ws.h"
|
||||
|
||||
static const char *mg_mdash_ca_pem =
|
||||
"-----BEGIN CERTIFICATE-----\n"
|
||||
"MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n"
|
||||
"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n"
|
||||
"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n"
|
||||
"WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n"
|
||||
"ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n"
|
||||
"MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n"
|
||||
"h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n"
|
||||
"0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n"
|
||||
"A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n"
|
||||
"T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n"
|
||||
"B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n"
|
||||
"B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n"
|
||||
"KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n"
|
||||
"OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n"
|
||||
"jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n"
|
||||
"qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n"
|
||||
"rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
|
||||
"HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n"
|
||||
"hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n"
|
||||
"ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n"
|
||||
"3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n"
|
||||
"NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n"
|
||||
"ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n"
|
||||
"TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n"
|
||||
"jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n"
|
||||
"oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n"
|
||||
"4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n"
|
||||
"mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n"
|
||||
"emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n"
|
||||
"-----END CERTIFICATE-----\n";
|
||||
|
||||
static struct mg_connection *mg_mdash_conn = NULL;
|
||||
// static struct mg_str mg_mdash_key;
|
||||
// static void mg_connection *mg_mdash_conn = NULL;
|
||||
|
||||
static void mg_mdash_fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_CONNECT) {
|
||||
// c->is_hexdumping = true;
|
||||
if (mg_url_is_ssl(MG_MDASH_URL)) {
|
||||
struct mg_str host = mg_url_host(MG_MDASH_URL);
|
||||
struct mg_tls_opts opts;
|
||||
memset(&opts, 0, sizeof(struct mg_tls_opts));
|
||||
opts.ca = mg_str(mg_mdash_ca_pem);
|
||||
opts.name = host;
|
||||
mg_tls_init(c, &opts);
|
||||
}
|
||||
}
|
||||
if (ev == MG_EV_WS_OPEN) {
|
||||
MG_INFO(("Connected to %s", MG_MDASH_URL));
|
||||
// s_mDashState = MDASH_STATE_CLOUD_CONNECTED;
|
||||
// mDashTriggerEvent(s_mDashState, NULL);
|
||||
} else if (ev == MG_EV_WS_MSG) {
|
||||
struct mg_iobuf io = {0, 0, 0, 512};
|
||||
struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
|
||||
struct mg_str s = wm->data;
|
||||
struct mg_rpc_req r;
|
||||
while (s.len > 0 && isspace((uint8_t) s.buf[s.len - 1])) s.len--;
|
||||
MG_INFO(("RPC: %.*s", (int) s.len, s.buf));
|
||||
memset(&r, 0, sizeof(struct mg_rpc_req));
|
||||
r.head = &c->mgr->rpcs;
|
||||
r.rpc = NULL;
|
||||
r.pfn = mg_pfn_iobuf;
|
||||
r.pfn_data = &io;
|
||||
r.req_data = NULL;
|
||||
r.frame = s;
|
||||
mg_rpc_process(&r);
|
||||
if (io.buf != NULL) {
|
||||
MG_INFO((" %s", io.buf));
|
||||
mg_ws_send(c, (const char *) io.buf, io.len, WEBSOCKET_OP_TEXT);
|
||||
} else {
|
||||
MG_DEBUG(("%s", "RPC unhandled"));
|
||||
}
|
||||
mg_iobuf_free(&io);
|
||||
} else if (ev == MG_EV_CLOSE) {
|
||||
mg_mdash_conn = NULL;
|
||||
MG_INFO(("disconnected, ram %lu", 0));
|
||||
}
|
||||
(void) c;
|
||||
}
|
||||
|
||||
static void mg_mdash_rpc_get_info(struct mg_rpc_req *r) {
|
||||
const char *reset_reason = mg_health_reason_str(mg_health_reason());
|
||||
mg_rpc_ok(r, "{%m:%m,%m:%llu,%m:%m,%m:\"mws.%d\",%m:%M}", //
|
||||
MG_ESC("fw_version"), MG_ESC(MG_FIRMWARE_VERSION), //
|
||||
MG_ESC("uptime"), (uint64_t) (mg_millis() / 1000), //
|
||||
MG_ESC("reboot_reason"), MG_ESC(reset_reason), //
|
||||
MG_ESC("arch"), MG_ARCH, //
|
||||
MG_ESC("crash"), mg_print_crash_record);
|
||||
}
|
||||
|
||||
static void mg_mdash_rpc_ota_begin(struct mg_rpc_req *r) {
|
||||
size_t total = (size_t) mg_json_get_long(r->frame, "$.params.size", -1);
|
||||
if (mg_ota_begin(total)) {
|
||||
mg_rpc_ok(r, "true");
|
||||
} else {
|
||||
mg_rpc_err(r, 500, "%m", MG_ESC("failed"));
|
||||
}
|
||||
}
|
||||
|
||||
static void mg_mdash_rpc_ota_write(struct mg_rpc_req *r) {
|
||||
int len = 0, ofs = 0;
|
||||
if ((ofs = mg_json_get(r->frame, "$.params.data", &len)) <= 0 ||
|
||||
r->frame.buf[ofs] != '"') {
|
||||
mg_rpc_err(r, 500, "%m", MG_ESC("data required"));
|
||||
} else {
|
||||
struct mg_str s = mg_str_n(&r->frame.buf[ofs] + 1, (size_t) (len - 2));
|
||||
size_t n = mg_base64_decode(s.buf, s.len, s.buf, s.len); // Decode in-place
|
||||
if (n == 0) {
|
||||
mg_rpc_ok(r, "%m", MG_ESC("finished"));
|
||||
mg_ota_end();
|
||||
} else if (mg_ota_write(s.buf, n)) {
|
||||
mg_rpc_ok(r, "{%m:%d}", MG_ESC("queued"), n);
|
||||
} else {
|
||||
mg_rpc_err(r, 500, "%m", MG_ESC("write failed"));
|
||||
mg_ota_end();
|
||||
}
|
||||
// mDashNotify("State.Set", "{%m:{%m:%d}}", MG_ESC("ota"),
|
||||
// MG_ESC("percent"), (int) (s_ota_written * 100 / s_ota_size));
|
||||
}
|
||||
}
|
||||
|
||||
static void mg_mdash_rpc_ota_end(struct mg_rpc_req *r) {
|
||||
if (mg_ota_end()) {
|
||||
mg_rpc_ok(r, "true");
|
||||
} else {
|
||||
mg_rpc_err(r, 500, "%m", MG_ESC("failed"));
|
||||
}
|
||||
// mDashNotify("State.Set", "{%m:{%m:null}}", MG_ESC("ota"),
|
||||
// MG_ESC("percent"));
|
||||
}
|
||||
|
||||
void mg_mdash_init(struct mg_mgr *mgr) {
|
||||
MG_INFO(("Initialising mdash agent, key [%s]", MG_MDASH_KEY));
|
||||
mg_rpc_add(&mgr->rpcs, mg_str("RPC.List"), mg_rpc_list, NULL);
|
||||
mg_rpc_add(&mgr->rpcs, mg_str("Sys.GetInfo"), mg_mdash_rpc_get_info, NULL);
|
||||
mg_rpc_add(&mgr->rpcs, mg_str("OTA.Begin"), mg_mdash_rpc_ota_begin, NULL);
|
||||
mg_rpc_add(&mgr->rpcs, mg_str("OTA.Write"), mg_mdash_rpc_ota_write, NULL);
|
||||
mg_rpc_add(&mgr->rpcs, mg_str("OTA.End"), mg_mdash_rpc_ota_end, NULL);
|
||||
}
|
||||
|
||||
void mg_mdash_poll(struct mg_mgr *mgr) {
|
||||
static uint64_t timer = 0;
|
||||
if (mg_mdash_conn == NULL && mg_timer_expired(&timer, 1000, mg_millis())) {
|
||||
MG_INFO(("Connecting to %s", MG_MDASH_URL));
|
||||
mg_mdash_conn = mg_ws_connect(mgr, MG_MDASH_URL, mg_mdash_fn, NULL,
|
||||
"Origin: %s\r\n"
|
||||
"Authorization: Bearer %s\r\n",
|
||||
MG_MDASH_URL, MG_MDASH_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
void mg_mdash_free(struct mg_mgr *mgr) {
|
||||
mg_rpc_del(&mgr->rpcs, NULL);
|
||||
}
|
||||
|
||||
#else
|
||||
void mg_mdash_init(struct mg_mgr *mgr) {
|
||||
(void) mgr;
|
||||
}
|
||||
void mg_mdash_poll(struct mg_mgr *mgr) {
|
||||
(void) mgr;
|
||||
}
|
||||
void mg_mdash_free(struct mg_mgr *mgr) {
|
||||
(void) mgr;
|
||||
}
|
||||
#endif
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
// Cloud connector API to https://mdash.net - device management cloud
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "net.h"
|
||||
|
||||
#ifndef MG_MDASH_URL
|
||||
#define MG_MDASH_URL "wss://mdash.net/api/v2/rpc"
|
||||
#endif
|
||||
|
||||
#ifndef MG_MDASH_KEY
|
||||
#define MG_MDASH_KEY ""
|
||||
#endif
|
||||
|
||||
#ifndef MG_ENABLE_MDASH
|
||||
#define MG_ENABLE_MDASH 0
|
||||
#endif
|
||||
|
||||
void mg_mdash_init(struct mg_mgr *);
|
||||
void mg_mdash_poll(struct mg_mgr *);
|
||||
void mg_mdash_free(struct mg_mgr *);
|
||||
@@ -1,8 +1,8 @@
|
||||
#include "net.h"
|
||||
#include "dns.h"
|
||||
#include "fmt.h"
|
||||
#include "log.h"
|
||||
#include "ota.h"
|
||||
#include "mdash.h"
|
||||
#include "net.h"
|
||||
#include "printf.h"
|
||||
#include "profile.h"
|
||||
#include "timer.h"
|
||||
@@ -39,10 +39,10 @@ bool mg_dscp(struct mg_connection *c, uint8_t dscp) {
|
||||
int tos = dscp << 2, level = IPPROTO_IP, optname = IP_TOS;
|
||||
c->dscp = (unsigned) (dscp & 63);
|
||||
#if MG_ENABLE_IPV6 && !MG_ENABLE_LWIP
|
||||
if (c->loc.is_ip6)
|
||||
level = IPPROTO_IPV6, optname = IPV6_TCLASS;
|
||||
if (c->loc.is_ip6) level = IPPROTO_IPV6, optname = IPV6_TCLASS;
|
||||
#endif
|
||||
return setsockopt((MG_SOCKET_TYPE) (size_t) c->fd, level, optname, (char *) &tos, sizeof(tos)) == 0;
|
||||
return setsockopt((MG_SOCKET_TYPE) (size_t) c->fd, level, optname,
|
||||
(char *) &tos, sizeof(tos)) == 0;
|
||||
#endif
|
||||
#elif MG_ENABLE_TCPIP
|
||||
c->dscp = (unsigned) (dscp & 63);
|
||||
@@ -163,10 +163,13 @@ static bool mg_aton6(struct mg_str str, struct mg_addr *addr) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool mg_aton_(struct mg_str str, struct mg_addr *addr);
|
||||
bool mg_aton_(struct mg_str str, struct mg_addr *addr) {
|
||||
return mg_aton4(str, addr) || mg_aton6(str, addr);
|
||||
}
|
||||
|
||||
bool mg_aton(struct mg_str str, struct mg_addr *addr) {
|
||||
// MG_INFO(("[%.*s]", (int) str.len, str.buf));
|
||||
return mg_atone(str, addr) || mg_atonl(str, addr) || mg_aton4(str, addr) ||
|
||||
mg_aton6(str, addr);
|
||||
return mg_atone(str, addr) || mg_atonl(str, addr) || mg_aton_(str, addr);
|
||||
}
|
||||
|
||||
struct mg_connection *mg_alloc_conn(struct mg_mgr *mgr) {
|
||||
@@ -297,6 +300,9 @@ void mg_mgr_free(struct mg_mgr *mgr) {
|
||||
mgr->timers = NULL; // Important. Next call to poll won't touch timers
|
||||
for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1;
|
||||
mg_mgr_poll(mgr, 0);
|
||||
#if MG_ENABLE_MDASH
|
||||
mg_mdash_free(mgr);
|
||||
#endif
|
||||
#if MG_ENABLE_FREERTOS_TCP
|
||||
FreeRTOS_DeleteSocketSet(mgr->ss);
|
||||
#endif
|
||||
@@ -340,13 +346,18 @@ void mg_mgr_init(struct mg_mgr *mgr) {
|
||||
mgr->dns4.url = "udp://8.8.8.8:53";
|
||||
mgr->dns6.url = "udp://[2001:4860:4860::8888]:53";
|
||||
mg_tls_ctx_init(mgr);
|
||||
MG_DEBUG(("MG_IO_SIZE: %lu, TLS: %s", MG_IO_SIZE,
|
||||
MG_DEBUG(("MG_IO_SIZE: %lu, TLS: %s, conn size: %zu, mgr size: %zu",
|
||||
MG_IO_SIZE,
|
||||
MG_TLS == MG_TLS_NONE ? "none"
|
||||
: MG_TLS == MG_TLS_MBED ? "MbedTLS"
|
||||
: MG_TLS == MG_TLS_OPENSSL ? "OpenSSL"
|
||||
: MG_TLS == MG_TLS_BUILTIN ? "builtin"
|
||||
: MG_TLS == MG_TLS_WOLFSSL ? "WolfSSL"
|
||||
: "custom"));
|
||||
: "custom",
|
||||
sizeof(struct mg_connection), sizeof(struct mg_mgr)));
|
||||
#if MG_ENABLE_MDASH
|
||||
mg_mdash_init(mgr);
|
||||
#endif
|
||||
}
|
||||
|
||||
#if MG_ENABLE_TCPIP
|
||||
|
||||
@@ -50,6 +50,7 @@ struct mg_mgr {
|
||||
struct mg_tcpip_if *ifp; // Builtin TCP/IP stack: network interface pointer
|
||||
size_t extraconnsize; // Builtin TCP/IP stack: extra bytes allocated per connection
|
||||
union mg_pipe pipe; // Socketpair write-end / queue, used by mg_wakeup()
|
||||
struct mg_rpc *rpcs; // Linked list of registered RPC handlers
|
||||
#if MG_ENABLE_FREERTOS_TCP
|
||||
SocketSet_t ss; // FreeRTOS-TCP socket set
|
||||
#endif
|
||||
@@ -94,7 +95,6 @@ struct mg_connection {
|
||||
unsigned is_closing : 1; // Close and free immediately on next poll
|
||||
unsigned is_full : 1; // Pause incoming reads until cleared
|
||||
unsigned is_tls_throttled : 1; // TLS write was throttled; retry pending
|
||||
unsigned is_resp : 1; // HTTP: response is still being generated
|
||||
unsigned is_readable : 1; // Socket is ready to read (epoll/select)
|
||||
unsigned is_writable : 1; // Socket is ready to write (epoll/select)
|
||||
};
|
||||
|
||||
+217
-71
@@ -13,17 +13,32 @@
|
||||
#define MG_TCPIP_ARP_MS 100 // Timeout for ARP response
|
||||
#define MG_TCPIP_SYN_MS 15000 // Timeout for connection establishment
|
||||
#define MG_TCPIP_FIN_MS 1000 // Timeout for closing connection
|
||||
#define MG_TCPIP_RTX_MS 1000 // Initial retransmission timeout (RFC-6298, 2.1)
|
||||
#define MG_TCPIP_RTX_MAX_MS 60000 // Minimum permitted RTO cap (RFC-6298, 2.5)
|
||||
#define MG_TCPIP_RTX_R1 3 // Delivery-problem threshold (RFC-9293, 3.8.3)
|
||||
// No R2: MG_TCPIP_KEEPALIVE_MS eventually closes non-responsive peers
|
||||
|
||||
#ifndef MG_TCPIP_WIN
|
||||
#define MG_TCPIP_WIN 6000 // TCP window size
|
||||
#endif
|
||||
|
||||
#ifndef MG_TCPIP_MIN_MSS
|
||||
#define MG_TCPIP_MIN_MSS 64 // Minimum peer MSS
|
||||
#endif
|
||||
|
||||
#ifndef MG_TCPIP_TXQ_ALIGN
|
||||
#define MG_TCPIP_TXQ_ALIGN 1024 // Retransmit queue allocation quantum
|
||||
#endif
|
||||
|
||||
struct connstate {
|
||||
uint32_t seq, ack; // TCP seq/ack counters
|
||||
uint64_t timer; // TCP timer (see 'ttype' below)
|
||||
uint64_t txq_timer; // TCP retransmission timer (RFC-6298, 5)
|
||||
uint32_t acked; // Last ACK-ed number
|
||||
size_t unacked; // Not acked bytes
|
||||
uint32_t maxseq; // Max send seq (ack + window)
|
||||
uint32_t txq_seq; // Sequence of first txq record (RFC-9293, 3.8)
|
||||
uint32_t txq_una; // Oldest unacknowledged sequence (RFC-9293, 3.4)
|
||||
uint16_t win; // destination current window size
|
||||
uint16_t dmss; // destination MSS (from TCP opts)
|
||||
uint8_t mac[sizeof(struct mg_l2addr)]; // Peer hw address
|
||||
@@ -34,8 +49,12 @@ struct connstate {
|
||||
#define MIP_TTYPE_SYN 3 // SYN sent, waiting for response
|
||||
#define MIP_TTYPE_FIN 4 // FIN sent, waiting until terminating the connection
|
||||
uint8_t tmiss; // Number of keep-alive misses
|
||||
uint8_t txq_retries; // Retransmissions since ACK progress (RFC-9293, 3.8.3)
|
||||
bool fin_rcvd; // We have received FIN from the peer
|
||||
bool twclosure; // 3-way closure done
|
||||
bool retransmit; // Retain sent data until acknowledged
|
||||
bool is_full; // Advertise a zero receive window
|
||||
struct mg_iobuf txq; // Length-prefixed sent TCP segments (RFC-9293, 3.8)
|
||||
};
|
||||
|
||||
#if defined(__DCC__)
|
||||
@@ -292,7 +311,7 @@ static bool tcpcsum_ok(void *d, void *t) {
|
||||
}
|
||||
|
||||
#if MG_ENABLE_IPV6
|
||||
static uint16_t p6csum(void *d, void *p, size_t plen) {
|
||||
static uint16_t p6csum(void *d, void *p, uint8_t proto, size_t plen) {
|
||||
uint32_t sum;
|
||||
struct ip6 *ip6 = (struct ip6 *) d;
|
||||
#if defined(__DCC__)
|
||||
@@ -303,7 +322,7 @@ static uint16_t p6csum(void *d, void *p, size_t plen) {
|
||||
pip6.dst[0] = ip6->dst[0], pip6.dst[1] = ip6->dst[1];
|
||||
pip6.zero[0] = 0, pip6.zero[1] = 0, pip6.zero[2] = 0;
|
||||
pip6.plen = mg_htonl((uint32_t) plen);
|
||||
pip6.next = ip6->next;
|
||||
pip6.next = proto;
|
||||
sum = csumup(0, &pip6, sizeof(pip6)); // even length
|
||||
sum = csumup(sum, p, plen); // possibly odd length: last
|
||||
return csumfin(sum);
|
||||
@@ -313,17 +332,15 @@ static bool udp6csum_ok(void *d, void *u) {
|
||||
struct udp *udp = (struct udp *) u;
|
||||
if (udp->csum == 0) return false; // mandatory in IPv6
|
||||
if (udp->csum == 0xFFFF) udp->csum = 0;
|
||||
return (p6csum(d, u, (size_t) mg_ntohs(udp->len)) == 0);
|
||||
return (p6csum(d, u, 17, (size_t) mg_ntohs(udp->len)) == 0);
|
||||
}
|
||||
static bool tcp6csum_ok(void *d, void *t) {
|
||||
struct ip6 *ip6 = (struct ip6 *) d;
|
||||
return (p6csum(d, t, (size_t) mg_ntohs(ip6->plen)) == 0);
|
||||
}
|
||||
static bool icmp6csum_ok(void *d, void *i) {
|
||||
struct ip6 *ip6 = (struct ip6 *) d;
|
||||
return (p6csum(d, i, (size_t) mg_ntohs(ip6->plen)) == 0);
|
||||
static bool tcp6csum_ok(void *d, void *t, size_t len) {
|
||||
return p6csum(d, t, 6, len) == 0;
|
||||
}
|
||||
|
||||
static bool icmp6csum_ok(void *d, void *i, size_t len) {
|
||||
return p6csum(d, i, 58, len) == 0;
|
||||
}
|
||||
static void ip6sn(uint64_t *addr, uint64_t *sn_addr) {
|
||||
// Build solicited-node multicast address from a given unicast IP
|
||||
// RFC-4291 2.7
|
||||
@@ -468,7 +485,7 @@ static bool tx_udp(struct mg_tcpip_if *ifp, uint8_t *l2_dst,
|
||||
memmove(udp + 1, buf, len);
|
||||
#if MG_ENABLE_IPV6
|
||||
if (ip_dst->is_ip6) {
|
||||
udp->csum = p6csum(ip6, udp, sizeof(*udp) + len);
|
||||
udp->csum = p6csum(ip6, udp, 17, sizeof(*udp) + len);
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
@@ -816,7 +833,7 @@ static void tx_icmp6(struct mg_tcpip_if *ifp, uint8_t *l2_dst, uint64_t *ip_src,
|
||||
icmp6->code = code;
|
||||
memcpy(icmp6 + 1, buf, len); // Copy payload
|
||||
icmp6->csum = 0; // RFC-4443 2.3, RFC-8200 8.1
|
||||
icmp6->csum = p6csum(ip6, icmp6, sizeof(*icmp6) + len);
|
||||
icmp6->csum = p6csum(ip6, icmp6, 58, sizeof(*icmp6) + len);
|
||||
driver_output(ifp,
|
||||
mg_l2_trailer(ifp, sizeof(*ip6) + sizeof(*icmp6) + len,
|
||||
(uint8_t *) (ip6 + 1) + sizeof(*icmp6) + len));
|
||||
@@ -1055,7 +1072,8 @@ static void rx_ndp_ra(struct mg_tcpip_if *ifp, struct pkt *pkt) {
|
||||
}
|
||||
|
||||
static void rx_icmp6(struct mg_tcpip_if *ifp, struct pkt *pkt) {
|
||||
if (!icmp6csum_ok(pkt->ip6, pkt->icmp6)) return;
|
||||
if (!icmp6csum_ok(pkt->ip6, pkt->icmp6, sizeof(*pkt->icmp6) + pkt->pay.len))
|
||||
return;
|
||||
switch (pkt->icmp6->type) {
|
||||
case 128: { // Echo Request, RFC-4443 4.1
|
||||
uint64_t target[2];
|
||||
@@ -1211,7 +1229,7 @@ static bool rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
|
||||
static size_t tx_tcp(struct mg_tcpip_if *ifp, uint8_t *l2_dst,
|
||||
struct mg_addr *ip_src, struct mg_addr *ip_dst,
|
||||
uint8_t dscp, uint8_t flags, uint32_t seq, uint32_t ack,
|
||||
const void *buf, size_t len) {
|
||||
uint16_t win, const void *buf, size_t len) {
|
||||
uint8_t *l3p;
|
||||
struct ip *ip = NULL;
|
||||
struct tcp *tcp;
|
||||
@@ -1256,11 +1274,11 @@ static size_t tx_tcp(struct mg_tcpip_if *ifp, uint8_t *l2_dst,
|
||||
tcp->seq = seq;
|
||||
tcp->ack = ack;
|
||||
tcp->flags = flags;
|
||||
tcp->win = mg_htons(MG_TCPIP_WIN);
|
||||
tcp->win = mg_htons(win);
|
||||
tcp->off = (uint8_t) (hlen / 4 << 4);
|
||||
#if MG_ENABLE_IPV6
|
||||
if (ip_dst->is_ip6) {
|
||||
tcp->csum = p6csum(ip6, tcp, hlen + len);
|
||||
tcp->csum = p6csum(ip6, tcp, 6, hlen + len);
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
@@ -1294,7 +1312,8 @@ static size_t tx_tcp_ctrlresp(struct mg_tcpip_if *ifp, struct pkt *pkt,
|
||||
ipd.port = pkt->tcp->sport;
|
||||
if ((l2addr = get_return_l2addr(ifp, &ipd, false, pkt)) == NULL)
|
||||
return 0; // safety net for lousy networks
|
||||
return tx_tcp(ifp, l2addr, &ips, &ipd, 0, flags, seqno, ackno, NULL, 0);
|
||||
return tx_tcp(ifp, l2addr, &ips, &ipd, 0, flags, seqno, ackno, MG_TCPIP_WIN,
|
||||
NULL, 0);
|
||||
}
|
||||
|
||||
static size_t tx_tcp_rst(struct mg_tcpip_if *ifp, struct pkt *pkt, bool toack) {
|
||||
@@ -1313,6 +1332,8 @@ static struct mg_connection *accept_conn(struct mg_connection *lsn,
|
||||
return NULL;
|
||||
}
|
||||
s = (struct connstate *) (c + 1);
|
||||
s->retransmit = lsn->mgr->ifp->enable_tcp_retransmit;
|
||||
s->txq.align = MG_TCPIP_TXQ_ALIGN;
|
||||
s->dmss = mss; // from options in client SYN
|
||||
s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq);
|
||||
s->win = mg_ntohs(pkt->tcp->win), s->maxseq = (uint32_t) (s->seq + s->win);
|
||||
@@ -1403,6 +1424,26 @@ static bool udp_send(struct mg_connection *c, const void *buf, size_t len) {
|
||||
return tx_udp(ifp, s->mac, &ips, &c->rem, c->dscp, buf, len);
|
||||
}
|
||||
|
||||
static size_t txq_next(struct connstate *s, uint8_t **buf) {
|
||||
uint32_t len;
|
||||
if (s->txq.len == 0) return 0;
|
||||
assert(s->txq.len >= sizeof(len));
|
||||
memcpy(&len, s->txq.buf, sizeof(len));
|
||||
assert(len > 0 && len <= s->txq.len - sizeof(len));
|
||||
if (buf != NULL) *buf = s->txq.buf + sizeof(len);
|
||||
return len;
|
||||
}
|
||||
|
||||
static bool txq_add(struct connstate *s, const void *buf, size_t len) {
|
||||
uint32_t n = (uint32_t) len;
|
||||
size_t off = s->txq.len, total = sizeof(n) + len;
|
||||
assert(len > 0);
|
||||
if (mg_iobuf_add(&s->txq, off, NULL, total) != total) return false;
|
||||
memcpy(s->txq.buf + off, &n, sizeof(n));
|
||||
memcpy(s->txq.buf + off + sizeof(n), buf, len);
|
||||
return true;
|
||||
}
|
||||
|
||||
long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
len = trim_len(c, len);
|
||||
@@ -1412,19 +1453,35 @@ long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
|
||||
struct mg_tcpip_if *ifp = c->mgr->ifp;
|
||||
size_t sent;
|
||||
uint32_t room = s->maxseq - s->seq;
|
||||
if (room == 0) return MG_IO_WAIT;
|
||||
if (len > s->dmss) len = s->dmss; // RFC-6691: reduce if sending opts
|
||||
if ((uint32_t) len > room) len = room;
|
||||
sent = tx_tcp(ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_PUSH | TH_ACK,
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), buf, len);
|
||||
if (sent == 0) {
|
||||
return MG_IO_WAIT;
|
||||
} else if (sent == (size_t) -1) {
|
||||
return MG_IO_ERR;
|
||||
} else {
|
||||
s->seq += (uint32_t) len;
|
||||
if (s->ttype == MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_KEEPALIVE);
|
||||
bool was_empty = s->txq.len == 0;
|
||||
if (s->retransmit) {
|
||||
uint32_t in_flight = s->txq.len > 0 ? s->seq - s->txq_una : 0;
|
||||
uint32_t qroom = in_flight < MG_TCPIP_WIN ? MG_TCPIP_WIN - in_flight : 0;
|
||||
room = s->win > in_flight ? s->win - in_flight : 0;
|
||||
if (room > qroom) room = qroom;
|
||||
}
|
||||
if (room == 0) return MG_IO_WAIT;
|
||||
if (len > s->dmss) len = s->dmss; // RFC-6691, reduce if sending opts
|
||||
if (len > room) len = room;
|
||||
if (s->retransmit) {
|
||||
if (was_empty) s->txq_seq = s->txq_una = s->seq;
|
||||
if (!txq_add(s, buf, len)) return MG_IO_WAIT;
|
||||
}
|
||||
sent = tx_tcp(ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_PUSH | TH_ACK,
|
||||
mg_htonl(s->seq), mg_htonl(s->ack),
|
||||
s->is_full ? 0 : MG_TCPIP_WIN, buf, len);
|
||||
if (sent == 0 || sent == (size_t) -1) {
|
||||
if (s->retransmit)
|
||||
mg_iobuf_del(&s->txq, s->txq.len - len - sizeof(uint32_t),
|
||||
len + sizeof(uint32_t));
|
||||
return sent == 0 ? MG_IO_WAIT : MG_IO_ERR;
|
||||
}
|
||||
s->seq += (uint32_t) len;
|
||||
if (s->retransmit && was_empty) {
|
||||
s->txq_timer = ifp->now + MG_TCPIP_RTX_MS;
|
||||
s->txq_retries = 0;
|
||||
}
|
||||
if (s->ttype == MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_KEEPALIVE);
|
||||
}
|
||||
return (long) len;
|
||||
}
|
||||
@@ -1452,22 +1509,66 @@ static void handle_tls_recv(struct mg_connection *c) {
|
||||
}
|
||||
}
|
||||
|
||||
static void handle_ack(struct connstate *s, uint32_t ackno, uint16_t win) {
|
||||
if (ackno < (s->seq - s->win) || ackno > s->seq) return;
|
||||
static void handle_ack(struct connstate *s, uint32_t ackno, uint16_t win,
|
||||
uint64_t now) {
|
||||
if (ackno > s->seq) return;
|
||||
if (s->retransmit && s->txq.len > 0) {
|
||||
if (ackno < s->txq_una) return;
|
||||
if (ackno > s->txq_una) {
|
||||
size_t len;
|
||||
// Remove only entirely acknowledged segments (RFC-9293, 3.10.7.4)
|
||||
while ((len = txq_next(s, NULL)) > 0 && ackno >= s->txq_seq + len) {
|
||||
mg_iobuf_del(&s->txq, 0, len + sizeof(uint32_t));
|
||||
s->txq_seq += (uint32_t) len;
|
||||
}
|
||||
s->txq_una = ackno;
|
||||
s->txq_retries = 0;
|
||||
// Restart RTO when an ACK acknowledges new data (RFC-6298, 5.3)
|
||||
s->txq_timer = now + MG_TCPIP_RTX_MS;
|
||||
} // else: dup ack, ignore it but handle its window upddate
|
||||
} else if (ackno < (s->seq - s->win)) {
|
||||
return;
|
||||
}
|
||||
s->maxseq = (uint32_t) (ackno + win);
|
||||
s->win = win;
|
||||
}
|
||||
|
||||
static void retransmit(struct mg_connection *c) {
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
struct mg_tcpip_if *ifp = c->mgr->ifp;
|
||||
uint8_t *buf, i;
|
||||
uint64_t rto;
|
||||
size_t len = txq_next(s, &buf);
|
||||
// Send the front retransmission-queue segment only (RFC-9293, 3.10.8)
|
||||
if (len == 0 ||
|
||||
tx_tcp(ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_PUSH | TH_ACK,
|
||||
mg_htonl(s->txq_seq), mg_htonl(s->ack),
|
||||
s->is_full ? 0 : MG_TCPIP_WIN, buf, len) == (size_t) -1) {
|
||||
mg_error(c, "retransmit");
|
||||
return;
|
||||
}
|
||||
// Back off RTO after every timeout (RFC-6298, 5.5)
|
||||
for (i = 0, rto = MG_TCPIP_RTX_MS;
|
||||
i < s->txq_retries && rto < MG_TCPIP_RTX_MAX_MS; i++) {
|
||||
rto *= 2;
|
||||
if (rto > MG_TCPIP_RTX_MAX_MS) rto = MG_TCPIP_RTX_MAX_MS;
|
||||
}
|
||||
s->txq_timer = ifp->now + rto;
|
||||
}
|
||||
|
||||
static void read_conn(struct mg_connection *c, struct pkt *pkt) {
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
struct mg_iobuf *io = c->is_tls ? &c->rtls : &c->recv;
|
||||
uint32_t seq = mg_ntohl(pkt->tcp->seq);
|
||||
// Evaluation order is important: 1) process FIN, 2) process keep-alive,
|
||||
// 3) discard invalid SEG.SEQ, 4) process ACK and payload.
|
||||
if (pkt->tcp->flags & TH_FIN) {
|
||||
uint8_t flags = TH_ACK;
|
||||
if (mg_ntohl(pkt->tcp->seq) != s->ack) {
|
||||
MG_VERBOSE(("ignoring FIN, %x != %x", mg_ntohl(pkt->tcp->seq), s->ack));
|
||||
tx_tcp(c->mgr->ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_ACK,
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), s->is_full ? 0 : MG_TCPIP_WIN,
|
||||
"", 0);
|
||||
return;
|
||||
}
|
||||
// If we initiated the closure, we reply with ACK upon receiving FIN
|
||||
@@ -1489,36 +1590,40 @@ static void read_conn(struct mg_connection *c, struct pkt *pkt) {
|
||||
c->is_draining = 1;
|
||||
}
|
||||
tx_tcp(c->mgr->ifp, s->mac, &c->loc, &c->rem, c->dscp, flags,
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
|
||||
if (pkt->pay.len == 0) return; // if no data, we're done
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), s->is_full ? 0 : MG_TCPIP_WIN,
|
||||
"", 0);
|
||||
} else if (pkt->pay.len <= 1 && mg_ntohl(pkt->tcp->seq) == s->ack - 1) {
|
||||
// Keep-Alive (RFC-9293 3.8.4, allow erroneous implementations)
|
||||
MG_VERBOSE(("%lu keepalive ACK", c->id));
|
||||
tx_tcp(c->mgr->ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_ACK,
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
|
||||
return; // no data to process
|
||||
} else if (pkt->pay.len == 0) { // this is an ACK
|
||||
if (pkt->tcp->flags & TH_ACK)
|
||||
handle_ack(s, mg_ntohl(pkt->tcp->ack), mg_ntohs(pkt->tcp->win));
|
||||
if (s->fin_rcvd && s->ttype == MIP_TTYPE_FIN) s->twclosure = true;
|
||||
return; // no data to process
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), s->is_full ? 0 : MG_TCPIP_WIN,
|
||||
NULL, 0);
|
||||
return; // RFC-9293 3.10.7.4 discard (incorrect) payload, ACK, window
|
||||
} else if (seq != s->ack) {
|
||||
uint32_t ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
|
||||
if (s->ack == ack) {
|
||||
MG_VERBOSE(("ignoring duplicate pkt"));
|
||||
} else {
|
||||
MG_VERBOSE(("SEQ != ACK: %x %x %x", seq, s->ack, ack));
|
||||
tx_tcp(c->mgr->ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_ACK,
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
|
||||
}
|
||||
return; // drop it
|
||||
} else if (io->size - io->len < pkt->pay.len &&
|
||||
!mg_iobuf_resize(io, io->len + pkt->pay.len)) {
|
||||
tx_tcp(c->mgr->ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_ACK,
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), s->is_full ? 0 : MG_TCPIP_WIN,
|
||||
"", 0);
|
||||
return; // drop it, RFC-9293 3.10.7.4: ignore ACKno
|
||||
}
|
||||
// Now process the segment for ACK and payload
|
||||
if (pkt->tcp->flags & TH_ACK) {
|
||||
handle_ack(s, mg_ntohl(pkt->tcp->ack), mg_ntohs(pkt->tcp->win),
|
||||
c->mgr->ifp->now);
|
||||
if (pkt->pay.len == 0 && s->fin_rcvd && s->ttype == MIP_TTYPE_FIN)
|
||||
s->twclosure = true;
|
||||
}
|
||||
if (pkt->pay.len == 0) return;
|
||||
if (io->size - io->len < pkt->pay.len &&
|
||||
!mg_iobuf_resize(io, io->len + pkt->pay.len)) {
|
||||
mg_error(c, "oom");
|
||||
return; // drop it
|
||||
}
|
||||
if (pkt->tcp->flags & TH_ACK)
|
||||
handle_ack(s, mg_ntohl(pkt->tcp->ack), mg_ntohs(pkt->tcp->win));
|
||||
// Copy TCP payload into the IO buffer. If the connection is plain text,
|
||||
// we copy to c->recv. If the connection is TLS, this data is encrypted,
|
||||
// therefore we copy that encrypted data to the c->rtls iobuffer instead,
|
||||
@@ -1527,15 +1632,18 @@ static void read_conn(struct mg_connection *c, struct pkt *pkt) {
|
||||
memcpy(&io->buf[io->len], pkt->pay.buf, pkt->pay.len);
|
||||
io->len += pkt->pay.len;
|
||||
MG_VERBOSE(("%lu SEQ %x -> %x", c->id, mg_htonl(pkt->tcp->seq), s->ack));
|
||||
// Advance ACK counter
|
||||
s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
|
||||
s->unacked += pkt->pay.len;
|
||||
if (!(pkt->tcp->flags & TH_FIN)) { // FIN already advanced s->ack
|
||||
// Advance ACK counter
|
||||
s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
|
||||
s->unacked += pkt->pay.len;
|
||||
}
|
||||
// size_t diff = s->acked <= s->ack ? s->ack - s->acked : s->ack;
|
||||
if (s->unacked > MG_TCPIP_WIN / 2 && s->acked != s->ack) {
|
||||
// Send ACK immediately
|
||||
MG_VERBOSE(("%lu imm ACK %lu", c->id, s->acked));
|
||||
tx_tcp(c->mgr->ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_ACK,
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), s->is_full ? 0 : MG_TCPIP_WIN,
|
||||
NULL, 0);
|
||||
s->unacked = 0;
|
||||
s->acked = s->ack;
|
||||
if (s->ttype != MIP_TTYPE_KEEPALIVE) settmout(c, MIP_TTYPE_KEEPALIVE);
|
||||
@@ -1612,8 +1720,11 @@ static bool handle_opt(struct connstate *s, struct tcp *tcp, bool ip6) {
|
||||
if (kind == 0) break; // End of Option List
|
||||
if (len < 2 || opts[1] == 0 || opts[1] > len) return false; // Malformed
|
||||
optlen = opts[1];
|
||||
if (kind == 2 && optlen == 4) // set received MSS
|
||||
s->dmss = (uint16_t) (((uint16_t) opts[2] << 8) + opts[3]);
|
||||
if (kind == 2 && optlen == 4) { // set received MSS
|
||||
uint16_t mss = (uint16_t) (((uint16_t) opts[2] << 8) + opts[3]);
|
||||
if (mss == 0 || mss < MG_TCPIP_MIN_MSS) return false;
|
||||
s->dmss = mss;
|
||||
}
|
||||
}
|
||||
MG_VERBOSE(("kind: %u, optlen: %u, len: %d\n", kind, optlen, len));
|
||||
opts += optlen;
|
||||
@@ -1626,7 +1737,10 @@ static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
|
||||
struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
|
||||
struct connstate *s = c == NULL ? NULL : (struct connstate *) (c + 1);
|
||||
#if MG_ENABLE_IPV6 // matching of v4/v6 to dest is done by getpeer()
|
||||
if (pkt->ip6 != NULL && !tcp6csum_ok(pkt->ip6, pkt->tcp)) return;
|
||||
if (pkt->ip6 != NULL &&
|
||||
!tcp6csum_ok(pkt->ip6, pkt->tcp,
|
||||
PDIFF(pkt->tcp, pkt->pay.buf) + pkt->pay.len))
|
||||
return;
|
||||
#endif
|
||||
if (pkt->ip != NULL && !tcpcsum_ok(pkt->ip, pkt->tcp)) return;
|
||||
pkt->tcp->flags &= TH_STDFLAGS; // tolerate creative usage (ECN, ?)
|
||||
@@ -1657,6 +1771,12 @@ static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
|
||||
settmout(c,
|
||||
MIP_TTYPE_KEEPALIVE); // unless a former ACK timeout is pending
|
||||
read_conn(c, pkt); // Override timer with ACK timeout if needed
|
||||
if (c->is_full && !s->is_full) {
|
||||
// The receive handler paused the connection: advertise zero window now
|
||||
s->is_full = true;
|
||||
tx_tcp(ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_ACK, mg_htonl(s->seq),
|
||||
mg_htonl(s->ack), 0, NULL, 0);
|
||||
}
|
||||
} else
|
||||
// - we don't listen on that port; RFC-9293 3.5.2 Group 1
|
||||
// - check listening connections; RFC-9293 3.5.2 Group 2
|
||||
@@ -1761,7 +1881,8 @@ static void rx_ip(struct mg_tcpip_if *ifp, struct pkt *pkt) {
|
||||
pkt->tcp = (struct tcp *) (pkt->pay.buf);
|
||||
if (pkt->pay.len < sizeof(*pkt->tcp)) return;
|
||||
off = pkt->tcp->off >> 4; // account for opts
|
||||
if (pkt->pay.len < (uint16_t) (4 * off)) return;
|
||||
if (off < sizeof(*pkt->tcp) / 4 || pkt->pay.len < (uint16_t) (4 * off))
|
||||
return;
|
||||
mkpay(pkt, (uint32_t *) pkt->tcp + off);
|
||||
MG_VERBOSE(("TCP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
|
||||
mg_ntohs(pkt->tcp->sport), mg_print_ip4, &pkt->ip->dst,
|
||||
@@ -1857,7 +1978,8 @@ static void rx_ip6(struct mg_tcpip_if *ifp, struct pkt *pkt) {
|
||||
pkt->tcp = (struct tcp *) (pkt->pay.buf);
|
||||
if (pkt->pay.len < sizeof(*pkt->tcp)) return;
|
||||
off = pkt->tcp->off >> 4; // account for opts
|
||||
if (pkt->pay.len < (uint16_t) (4 * off)) return;
|
||||
if (off < sizeof(*pkt->tcp) / 4 || pkt->pay.len < (uint16_t) (4 * off))
|
||||
return;
|
||||
mkpay(pkt, (uint32_t *) pkt->tcp + off);
|
||||
MG_DEBUG(("TCP %M:%hu -> %M:%hu len %u", mg_print_ip6, &pkt->ip6->src,
|
||||
mg_ntohs(pkt->tcp->sport), mg_print_ip6, &pkt->ip6->dst,
|
||||
@@ -2056,6 +2178,19 @@ static void mg_tcpip_poll(struct mg_tcpip_if *ifp, uint64_t now) {
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
if ((c->is_udp && !c->is_arplooking) || c->is_listening || c->is_resolving)
|
||||
continue;
|
||||
if (!c->is_full && s->is_full) {
|
||||
// Application resumed the connection: advertise the restored window
|
||||
s->is_full = false;
|
||||
tx_tcp(ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_ACK, mg_htonl(s->seq),
|
||||
mg_htonl(s->ack), MG_TCPIP_WIN, NULL, 0);
|
||||
}
|
||||
if (s->retransmit && s->txq.len > 0 && ifp->now > s->txq_timer) {
|
||||
if (s->txq_retries < 255) s->txq_retries++;
|
||||
// R1 reports a delivery problem; it does not close (RFC-9293, 3.8.3).
|
||||
if (s->txq_retries == MG_TCPIP_RTX_R1)
|
||||
MG_ERROR(("%lu retransmit", c->id));
|
||||
retransmit(c);
|
||||
}
|
||||
if (ifp->now > s->timer) {
|
||||
if (s->ttype == MIP_TTYPE_ARP) {
|
||||
mg_error(c, "ARP timeout");
|
||||
@@ -2064,7 +2199,7 @@ static void mg_tcpip_poll(struct mg_tcpip_if *ifp, uint64_t now) {
|
||||
} else if (s->ttype == MIP_TTYPE_ACK && s->acked != s->ack) {
|
||||
MG_VERBOSE(("%lu ack %x %x", c->id, s->seq, s->ack));
|
||||
tx_tcp(ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_ACK, mg_htonl(s->seq),
|
||||
mg_htonl(s->ack), NULL, 0);
|
||||
mg_htonl(s->ack), s->is_full ? 0 : MG_TCPIP_WIN, NULL, 0);
|
||||
s->acked = s->ack;
|
||||
} else if (s->ttype == MIP_TTYPE_SYN) {
|
||||
mg_error(c, "Connection timeout");
|
||||
@@ -2077,7 +2212,8 @@ static void mg_tcpip_poll(struct mg_tcpip_if *ifp, uint64_t now) {
|
||||
} else {
|
||||
MG_VERBOSE(("%lu keepalive", c->id));
|
||||
tx_tcp(ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_ACK,
|
||||
mg_htonl(s->seq - 1), mg_htonl(s->ack), NULL, 0);
|
||||
mg_htonl(s->seq - 1), mg_htonl(s->ack),
|
||||
s->is_full ? 0 : MG_TCPIP_WIN, NULL, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2104,6 +2240,7 @@ void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) {
|
||||
// If L2 address is not set, make a random one; fill MTU
|
||||
mg_l2_init(ifp);
|
||||
ifp->mtu = ifp->l2mtu;
|
||||
if (MG_ENABLE_TCPIP_TCPRTX) ifp->enable_tcp_retransmit = true;
|
||||
|
||||
if (ifp->dhcp_name[0] == '\0') // If DHCP name is not set, use "mip"
|
||||
memcpy(ifp->dhcp_name, "mip", 4);
|
||||
@@ -2128,6 +2265,8 @@ void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) {
|
||||
ifp->eport |= MG_EPHEMERAL_PORT_BASE; // Random from
|
||||
// MG_EPHEMERAL_PORT_BASE to 65535
|
||||
if (ifp->tx.buf == NULL || ifp->recv_queue.buf == NULL) MG_ERROR(("OOM"));
|
||||
MG_DEBUG(("Builtin TCP/IP init done. Queue size: %zu, extra conn size: %zu",
|
||||
ifp->recv_queue.size, mgr->extraconnsize));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2140,8 +2279,8 @@ void mg_tcpip_free(struct mg_tcpip_if *ifp) {
|
||||
static void send_syn(struct mg_connection *c) {
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
uint32_t isn = mg_htonl((uint32_t) mg_ntohs(c->loc.port));
|
||||
tx_tcp(c->mgr->ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_SYN, isn, 0, NULL,
|
||||
0);
|
||||
tx_tcp(c->mgr->ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_SYN, isn, 0,
|
||||
MG_TCPIP_WIN, NULL, 0);
|
||||
}
|
||||
|
||||
static void l2addr_resolved(struct mg_connection *c) {
|
||||
@@ -2157,6 +2296,9 @@ static void l2addr_resolved(struct mg_connection *c) {
|
||||
void mg_connect_resolved(struct mg_connection *c) {
|
||||
struct mg_tcpip_if *ifp = c->mgr->ifp;
|
||||
uint8_t *l2addr;
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
s->retransmit = ifp->enable_tcp_retransmit;
|
||||
s->txq.align = MG_TCPIP_TXQ_ALIGN;
|
||||
c->is_resolving = 0;
|
||||
if (ifp->eport < MG_EPHEMERAL_PORT_BASE) ifp->eport = MG_EPHEMERAL_PORT_BASE;
|
||||
c->loc.port = mg_htons(ifp->eport++);
|
||||
@@ -2178,7 +2320,6 @@ void mg_connect_resolved(struct mg_connection *c) {
|
||||
mg_call(c, MG_EV_RESOLVE, NULL);
|
||||
c->is_connecting = 1;
|
||||
if (c->is_udp && (l2addr = tcpip_mapip(ifp, &c->rem)) != NULL) {
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
memcpy(s->mac, l2addr, sizeof(s->mac));
|
||||
l2addr_resolved(c); // broadcast or multicast
|
||||
#if MG_ENABLE_IPV6
|
||||
@@ -2193,7 +2334,6 @@ void mg_connect_resolved(struct mg_connection *c) {
|
||||
settmout(c, MIP_TTYPE_ARP);
|
||||
c->is_arplooking = 1;
|
||||
} else if (ifp->gw6_ready) {
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
memcpy(s->mac, ifp->gw6mac, sizeof(s->mac));
|
||||
l2addr_resolved(c);
|
||||
} else {
|
||||
@@ -2210,7 +2350,6 @@ void mg_connect_resolved(struct mg_connection *c) {
|
||||
settmout(c, MIP_TTYPE_ARP);
|
||||
c->is_arplooking = 1;
|
||||
} else if (ifp->gw_ready) {
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
memcpy(s->mac, ifp->gwmac, sizeof(s->mac));
|
||||
l2addr_resolved(c);
|
||||
} else {
|
||||
@@ -2242,18 +2381,18 @@ static void write_conn(struct mg_connection *c) {
|
||||
|
||||
static void init_closure(struct mg_connection *c) {
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
if (c->is_udp == false && c->is_listening == false &&
|
||||
c->is_connecting == false) { // For TCP conns,
|
||||
if (c->is_listening == false && c->is_connecting == false) {
|
||||
tx_tcp(c->mgr->ifp, s->mac, &c->loc, &c->rem, c->dscp, TH_FIN | TH_ACK,
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
|
||||
mg_htonl(s->seq), mg_htonl(s->ack), s->is_full ? 0 : MG_TCPIP_WIN,
|
||||
NULL, 0);
|
||||
settmout(c, MIP_TTYPE_FIN);
|
||||
}
|
||||
}
|
||||
|
||||
static void close_conn(struct mg_connection *c) {
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
mg_iobuf_free(&s->txq);
|
||||
mg_close_conn(c);
|
||||
(void) s;
|
||||
}
|
||||
|
||||
static bool can_write(struct mg_connection *c) {
|
||||
@@ -2266,10 +2405,12 @@ void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
|
||||
uint64_t now = mg_millis();
|
||||
mg_timer_poll(&mgr->timers, now);
|
||||
mg_ota_poll(mgr);
|
||||
mg_mdash_poll(mgr);
|
||||
if (mgr->ifp == NULL || mgr->ifp->driver == NULL) return;
|
||||
mg_tcpip_poll(mgr->ifp, now);
|
||||
for (c = mgr->conns; c != NULL; c = tmp) {
|
||||
struct connstate *s = (struct connstate *) (c + 1);
|
||||
long flush = 0;
|
||||
bool is_tls = c->is_tls && !c->is_resolving && !c->is_arplooking &&
|
||||
!c->is_listening && !c->is_connecting;
|
||||
tmp = c->next;
|
||||
@@ -2282,9 +2423,14 @@ void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
|
||||
if (is_tls && (c->rtls.len > 0 || mg_tls_pending(c) > 0))
|
||||
c->is_tls_hs ? mg_tls_handshake(c) : handle_tls_recv(c);
|
||||
if (can_write(c)) write_conn(c);
|
||||
if (is_tls && c->send.len == 0) mg_tls_flush(c);
|
||||
if (c->is_draining && c->send.len == 0 && s->ttype != MIP_TTYPE_FIN)
|
||||
init_closure(c);
|
||||
if (is_tls && c->send.len == 0) flush = mg_tls_flush(c);
|
||||
if (flush == MG_IO_ERR) mg_error(c, "tx err");
|
||||
if (c->is_draining && c->send.len == 0) {
|
||||
if (c->is_udp) c->is_closing = 1;
|
||||
if (!c->is_udp && flush == 0 && s->txq.len == 0 &&
|
||||
s->ttype != MIP_TTYPE_FIN)
|
||||
init_closure(c);
|
||||
}
|
||||
// For non-TLS, close immediately upon completing the 3-way closure
|
||||
// For TLS, handle any pending data (above) until MIP_TTYPE_FIN expires
|
||||
if (s->twclosure &&
|
||||
|
||||
@@ -59,6 +59,7 @@ struct mg_tcpip_if {
|
||||
bool enable_req_sntp; // DHCP client requests an SNTP server address
|
||||
bool enable_fcs_check; // Verify and strip FCS from received frames
|
||||
bool enable_mac_check; // Drop frames not addressed to this MAC
|
||||
bool enable_tcp_retransmit; // Enable optional TCP retransmission queue
|
||||
bool update_mac_hash_table; // Signal driver to refresh MAC multicast hash table
|
||||
bool is_ip_changed; // Set by stack when IP changes; triggers connection restart
|
||||
struct mg_tcpip_driver *driver; // Hardware driver; must be set before mg_tcpip_init()
|
||||
@@ -152,6 +153,7 @@ extern struct mg_tcpip_driver mg_tcpip_driver_cyw;
|
||||
extern struct mg_tcpip_driver mg_tcpip_driver_nxp_wifi;
|
||||
extern struct mg_tcpip_driver mg_tcpip_driver_st67w6;
|
||||
extern struct mg_tcpip_driver mg_tcpip_driver_atcmd;
|
||||
extern struct mg_tcpip_driver mg_tcpip_driver_netc;
|
||||
|
||||
// SPI bus abstraction for SPI-attached network chips (e.g. W5500).
|
||||
// Populate and assign to the driver's driver_data field.
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
// Scannable version tag embedded in every firmware binary, for server-side
|
||||
// version extraction. The version string starts after the "MG_VERSION:" prefix.
|
||||
static const char s_fw_version[] = "MG_VERSION:" MG_OTA_FIRMWARE_VERSION;
|
||||
static const char s_fw_version[] = "MG_VERSION:" MG_FIRMWARE_VERSION;
|
||||
|
||||
static bool s_autocommit_ok; // True after OTA server confirms "same version"
|
||||
|
||||
@@ -23,6 +23,9 @@ static struct mg_ota_state {
|
||||
size_t size;
|
||||
uint8_t sha256[32];
|
||||
void (*fn)(const char *error_message);
|
||||
size_t received; // Firmware bytes written so far
|
||||
bool open; // mg_ota_begin() succeeded, mg_ota_end() is pending
|
||||
const char *err; // First error during download, NULL if none
|
||||
} *s_ota;
|
||||
|
||||
static void s_firmware_fn(struct mg_connection *c, int ev, void *ev_data);
|
||||
@@ -143,11 +146,38 @@ static void status_fn(const char *errmsg) {
|
||||
if (errmsg) MG_ERROR(("OTA failed: %s", errmsg));
|
||||
}
|
||||
|
||||
static void status_fn_2(struct mg_connection *c, const char *errmsg) {
|
||||
if (s_ota) s_ota->fn(errmsg);
|
||||
// Firmware download callback for mg_http_stream_body(). Writes chunks to the
|
||||
// OTA target and reports the result via s_ota->fn(). The end call also happens
|
||||
// when the connection drops before the whole body arrived.
|
||||
static bool s_firmware_cb(struct mg_http_message *hm, struct mg_str *data,
|
||||
void **p) {
|
||||
bool finalized = false, ok;
|
||||
(void) p;
|
||||
if (s_ota == NULL) return false;
|
||||
if (hm != NULL) { // Start
|
||||
s_ota->received = 0;
|
||||
s_ota->open = mg_ota_begin(hm->body.len);
|
||||
if (!s_ota->open) s_ota->err = "OTA begin failed";
|
||||
return s_ota->open;
|
||||
} else if (data != NULL) { // Next chunk
|
||||
if (!mg_ota_write(data->buf, data->len)) {
|
||||
s_ota->err = "OTA write failed";
|
||||
return false;
|
||||
}
|
||||
s_ota->received += data->len;
|
||||
return true;
|
||||
}
|
||||
// End
|
||||
if (s_ota->open) finalized = mg_ota_end();
|
||||
if (s_ota->err == NULL && s_ota->received != s_ota->size) {
|
||||
s_ota->err = "Connection closed";
|
||||
}
|
||||
if (s_ota->err == NULL && !finalized) s_ota->err = "OTA finalize failed";
|
||||
ok = s_ota->err == NULL;
|
||||
s_ota->fn(s_ota->err);
|
||||
mg_free(s_ota);
|
||||
s_ota = NULL;
|
||||
mg_http_reply(c, errmsg ? 500 : 200, "", "%s\n", errmsg ? errmsg : "ok");
|
||||
return ok;
|
||||
}
|
||||
|
||||
static void s_firmware_fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
@@ -178,7 +208,9 @@ static void s_firmware_fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
(unsigned long) hm->body.len, (unsigned long) s_ota->size);
|
||||
} else {
|
||||
MG_DEBUG(("Beginning OTA (%lu bytes)", (unsigned long) s_ota->size));
|
||||
mg_http_start_ota(c, hm, status_fn_2);
|
||||
if (!mg_http_stream_body(c, hm, s_firmware_cb, NULL)) {
|
||||
mg_error(c, "Cannot stream firmware");
|
||||
}
|
||||
}
|
||||
} else if (ev == MG_EV_ERROR) {
|
||||
s_ota->fn((char *) ev_data);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// This is a low-level OTA API, not intended to be called directly by users.
|
||||
// Users are provided with a higher-level API:
|
||||
// - defining MG_OTA_URL enables HTTP or HTTPS pull-based updates
|
||||
// - mg_http_start_ota() enables push-based updates
|
||||
// - mg_http_stream_body() enables push-based updates
|
||||
//
|
||||
// However, it is possible to use the mg_ota_* API directly. Below is the
|
||||
// example code of a function that is called repeatedly. It expects the
|
||||
@@ -41,6 +41,7 @@
|
||||
#define MG_OTA_RT1060 302 // IMXRT1060
|
||||
#define MG_OTA_RT1064 303 // IMXRT1064
|
||||
#define MG_OTA_RT1170 304 // IMXRT1170
|
||||
#define MG_OTA_RT1180 305 // IMXRT1180
|
||||
#define MG_OTA_MCXN 310 // MCXN947
|
||||
#define MG_OTA_RW612 320 // FRDM-RW612
|
||||
#define MG_OTA_FLASH 900 // OTA via internal flash
|
||||
@@ -153,7 +154,7 @@ enum {
|
||||
// needs to be defined. Fetches metadata_url, which must
|
||||
// return a JSON object like:
|
||||
// { "version": "1.2.3", "url": "FIRMWARE_URL", "size": 324645 }
|
||||
// If the server version differs from MG_OTA_FIRMWARE_VERSION, downloads
|
||||
// If the server version differs from MG_FIRMWARE_VERSION, downloads
|
||||
// FIRMWARE_URL and performs the OTA update. fn is called on every outcome:
|
||||
// NULL on successful flash, "Same version" when already up to date, or an
|
||||
// error string on failure. Pass NULL to use the default handler which logs
|
||||
@@ -180,8 +181,8 @@ void mg_ota_url_check(struct mg_mgr *mgr, const char *metadata_url,
|
||||
#endif
|
||||
|
||||
// Firmware version for mg_ota_poll(). Settable in mongoose_config.h
|
||||
#ifndef MG_OTA_FIRMWARE_VERSION
|
||||
#define MG_OTA_FIRMWARE_VERSION "1.0.0"
|
||||
#ifndef MG_FIRMWARE_VERSION
|
||||
#define MG_FIRMWARE_VERSION "1.0.0"
|
||||
#endif
|
||||
|
||||
// Maximum version string length
|
||||
|
||||
+41
-10
@@ -2,7 +2,7 @@
|
||||
#include "log.h"
|
||||
#include "ota.h"
|
||||
|
||||
#if MG_OTA >= MG_OTA_RT1020 && MG_OTA <= MG_OTA_RT1170
|
||||
#if MG_OTA >= MG_OTA_RT1020 && MG_OTA <= MG_OTA_RT1180
|
||||
|
||||
static bool mg_imxrt_write(void *, const void *, size_t);
|
||||
static bool mg_imxrt_swap(void);
|
||||
@@ -13,9 +13,12 @@ static bool mg_imxrt_swap(void);
|
||||
#elif MG_OTA == MG_OTA_RT1064
|
||||
#define MG_IMXRT_FLASH_START 0x70000000
|
||||
#define FLEXSPI_NOR_INSTANCE 1
|
||||
#else // RT1170
|
||||
#elif MG_OTA == MG_OTA_RT1170
|
||||
#define MG_IMXRT_FLASH_START 0x30000000
|
||||
#define FLEXSPI_NOR_INSTANCE 1
|
||||
#else // RT1180 FlexSPI2
|
||||
#define MG_IMXRT_FLASH_START 0x04000000
|
||||
#define FLEXSPI_NOR_INSTANCE 2
|
||||
#endif
|
||||
|
||||
#if MG_OTA == MG_OTA_RT1050
|
||||
@@ -324,7 +327,7 @@ struct mg_flexspi_nor_driver_interface {
|
||||
uint32_t *option);
|
||||
};
|
||||
#else
|
||||
// RT117x support ROM API version 1.7
|
||||
// RT117x and RT118x
|
||||
struct mg_flexspi_nor_driver_interface {
|
||||
uint32_t version;
|
||||
int (*init)(uint32_t instance, struct mg_flexspi_nor_config *config);
|
||||
@@ -359,11 +362,16 @@ struct mg_flexspi_nor_driver_interface {
|
||||
#define flexspi_nor \
|
||||
(*((struct mg_flexspi_nor_driver_interface **) (*(uint32_t *) 0x0020001c + \
|
||||
16)))
|
||||
#else
|
||||
#elif MG_OTA == MG_OTA_RT1170
|
||||
#define MG_FLEXSPI_BASE 0x400CC000
|
||||
#define flexspi_nor \
|
||||
(*((struct mg_flexspi_nor_driver_interface **) (*(uint32_t *) 0x0021001c + \
|
||||
12)))
|
||||
#else
|
||||
#define MG_FLEXSPI_BASE 0x445E0000
|
||||
#define flexspi_nor \
|
||||
(*((struct mg_flexspi_nor_driver_interface **) (*(uint32_t *) 0x1000001c + \
|
||||
12)))
|
||||
#endif
|
||||
|
||||
static bool s_flash_irq_disabled;
|
||||
@@ -408,6 +416,13 @@ static struct mg_flexspi_nor_config default_config = {
|
||||
#else
|
||||
// Note: this QSPI configuration works for RTs supporting QSPI
|
||||
// Configuration for QSPI memory
|
||||
#if MG_OTA == MG_OTA_RT1180
|
||||
#define MG_FLEXSPI_QSPI_SERIAL_CLK_FREQ 5 // 100MHz
|
||||
#define MG_FLEXSPI_QSPI_FLASH_SIZE (16 * 1024 * 1024)
|
||||
#else
|
||||
#define MG_FLEXSPI_QSPI_SERIAL_CLK_FREQ 7 // 133MHz
|
||||
#define MG_FLEXSPI_QSPI_FLASH_SIZE (8 * 1024 * 1024)
|
||||
#endif
|
||||
static struct mg_flexspi_nor_config default_config = {
|
||||
.memConfig = {.tag = MG_FLEXSPI_CFG_BLK_TAG,
|
||||
.version = MG_FLEXSPI_CFG_BLK_VERSION,
|
||||
@@ -417,8 +432,8 @@ static struct mg_flexspi_nor_config default_config = {
|
||||
.controllerMiscOption = MG_BIT(4),
|
||||
.deviceType = 1, // serial NOR
|
||||
.sflashPadType = 4,
|
||||
.serialClkFreq = 7, // 133MHz
|
||||
.sflashA1Size = 8 * 1024 * 1024,
|
||||
.serialClkFreq = MG_FLEXSPI_QSPI_SERIAL_CLK_FREQ,
|
||||
.sflashA1Size = MG_FLEXSPI_QSPI_FLASH_SIZE,
|
||||
.lookupTable = MG_FLEXSPI_QSPI_LUT},
|
||||
.pageSize = 256,
|
||||
.sectorSize = 4 * 1024,
|
||||
@@ -453,6 +468,7 @@ MG_IRAM static int flexspi_nor_get_config(
|
||||
}
|
||||
#endif
|
||||
|
||||
#if MG_OTA == MG_OTA_RT1020 || MG_OTA == MG_OTA_RT1050
|
||||
MG_IRAM static void mg_spin(volatile uint32_t count) {
|
||||
while (count--) (void) 0;
|
||||
}
|
||||
@@ -461,6 +477,7 @@ MG_IRAM static void flash_wait(void) {
|
||||
while ((*((volatile uint32_t *) (MG_FLEXSPI_BASE + 0xE0)) & MG_BIT(1)) == 0)
|
||||
mg_spin(1);
|
||||
}
|
||||
#endif
|
||||
|
||||
MG_IRAM static bool flash_erase(struct mg_flexspi_nor_config *config,
|
||||
void *addr) {
|
||||
@@ -509,6 +526,8 @@ MG_IRAM static bool mg_imxrt_write(void *addr, const void *buf, size_t len) {
|
||||
uint32_t *dst = (uint32_t *) addr;
|
||||
uint32_t *src = (uint32_t *) buf;
|
||||
uint32_t *end = (uint32_t *) ((char *) buf + len);
|
||||
char *flash_start = (char *) s_mg_flash_imxrt.start;
|
||||
char *flash_end = flash_start + s_mg_flash_imxrt.size;
|
||||
ok = true;
|
||||
|
||||
while (ok && src < end) {
|
||||
@@ -516,20 +535,32 @@ MG_IRAM static bool mg_imxrt_write(void *addr, const void *buf, size_t len) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
uint32_t status;
|
||||
uint32_t status = 0;
|
||||
uint32_t dst_ofs = (uint32_t) dst - (uint32_t) s_mg_flash_imxrt.start;
|
||||
if ((char *) buf >= (char *) s_mg_flash_imxrt.start) {
|
||||
if ((char *) buf >= flash_start && (char *) buf < flash_end) {
|
||||
// If we copy from FLASH to FLASH, then we first need to copy the source
|
||||
// to RAM
|
||||
size_t tmp_buf_size = s_mg_flash_imxrt.align / sizeof(uint32_t);
|
||||
uint32_t tmp[tmp_buf_size];
|
||||
|
||||
#if MG_OTA == MG_OTA_RT1020 || MG_OTA == MG_OTA_RT1050
|
||||
// ROM API 1.4 does not provide flexspi_nor_flash_read().
|
||||
// Manually copy byte by byte into the RAM buffer.
|
||||
for (size_t i = 0; i < tmp_buf_size; i++) {
|
||||
flash_wait();
|
||||
tmp[i] = src[i];
|
||||
}
|
||||
status = flexspi_nor->program(FLEXSPI_NOR_INSTANCE, config_ptr,
|
||||
(uint32_t) dst_ofs, tmp);
|
||||
#else
|
||||
// When supported, prefer the read API call.
|
||||
uint32_t src_ofs =
|
||||
(uint32_t) src - (uint32_t) s_mg_flash_imxrt.start;
|
||||
status = flexspi_nor->read(FLEXSPI_NOR_INSTANCE, config_ptr, tmp,
|
||||
src_ofs, s_mg_flash_imxrt.align);
|
||||
#endif
|
||||
if (status == 0) {
|
||||
status = flexspi_nor->program(FLEXSPI_NOR_INSTANCE, config_ptr,
|
||||
dst_ofs, tmp);
|
||||
}
|
||||
} else {
|
||||
status = flexspi_nor->program(FLEXSPI_NOR_INSTANCE, config_ptr,
|
||||
(uint32_t) dst_ofs, src);
|
||||
|
||||
+5
-7
@@ -291,24 +291,22 @@ MG_IRAM static bool mg_frdm_write(void *addr, const void *buf, size_t len) {
|
||||
}
|
||||
uint32_t status;
|
||||
uint32_t dst_ofs = (uint32_t) dst - (uint32_t) s_mg_flash_frdm.start;
|
||||
size_t tmp_buf_size = s_mg_flash_frdm.align / sizeof(uint32_t);
|
||||
uint32_t tmp[tmp_buf_size];
|
||||
if ((char *) buf >= (char *) s_mg_flash_frdm.start &&
|
||||
(char *) buf <
|
||||
(char *) (s_mg_flash_frdm.start + s_mg_flash_frdm.size)) {
|
||||
// If we copy from FLASH to FLASH, then we first need to copy the source
|
||||
// to RAM
|
||||
size_t tmp_buf_size = s_mg_flash_frdm.align / sizeof(uint32_t);
|
||||
uint32_t tmp[tmp_buf_size];
|
||||
|
||||
for (size_t i = 0; i < tmp_buf_size; i++) {
|
||||
flash_wait();
|
||||
tmp[i] = src[i];
|
||||
}
|
||||
status = flexspi_nor->page_program(MG_FLEXSPI_NOR_INSTANCE, &config,
|
||||
(uint32_t) dst_ofs, tmp, false);
|
||||
} else {
|
||||
status = flexspi_nor->page_program(MG_FLEXSPI_NOR_INSTANCE, &config,
|
||||
(uint32_t) dst_ofs, src, false);
|
||||
memcpy(tmp, src, sizeof(tmp));
|
||||
}
|
||||
status = flexspi_nor->page_program(MG_FLEXSPI_NOR_INSTANCE, &config,
|
||||
(uint32_t) dst_ofs, tmp, false);
|
||||
src = (uint32_t *) ((char *) src + s_mg_flash_frdm.align);
|
||||
dst = (uint32_t *) ((char *) dst + s_mg_flash_frdm.align);
|
||||
if (status != 0) {
|
||||
|
||||
+3
-3
@@ -67,10 +67,10 @@ MG_IRAM static void flash_unlock(void) {
|
||||
}
|
||||
}
|
||||
|
||||
MG_IRAM static bool flash_page_start(volatile uint32_t *dst) {
|
||||
MG_IRAM static bool flash_page_start(uint32_t *dst) {
|
||||
char *base = (char *) s_mg_flash_stm32h7.start,
|
||||
*end = base + s_mg_flash_stm32h7.size;
|
||||
volatile char *p = (char *) dst;
|
||||
char *p = (char *) dst;
|
||||
return p >= base && p < end && ((p - base) % s_mg_flash_stm32h7.secsz) == 0;
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ MG_IRAM static uint32_t flash_bank(void *addr) {
|
||||
// read-while-write, no need to disable IRQs for standalone usage
|
||||
MG_IRAM static bool mg_stm32h7_erase(void *addr) {
|
||||
bool ok = false;
|
||||
if (flash_page_start(addr) == false) {
|
||||
if (flash_page_start((uint32_t *) addr) == false) {
|
||||
MG_ERROR(("%p is not on a sector boundary", addr));
|
||||
} else {
|
||||
uintptr_t diff = (char *) addr - (char *) s_mg_flash_stm32h7.start;
|
||||
|
||||
+3
-3
@@ -34,15 +34,15 @@ char *mg_mprintf(const char *fmt, ...);
|
||||
size_t mg_queue_printf(struct mg_queue *, const char *fmt, ...);
|
||||
|
||||
// Built-in %M/%m printer functions. Each reads its argument(s) from ap.
|
||||
size_t mg_print_base64(mg_pfn_t, void *arg, va_list *ap); // expects: const void *buf, size_t len
|
||||
size_t mg_print_base64(mg_pfn_t, void *arg, va_list *ap); // expects: int len, uint8_t *buf
|
||||
size_t mg_print_esc(mg_pfn_t, void *arg, va_list *ap); // expects: int len, const char *str -- use MG_ESC()
|
||||
size_t mg_print_hex(mg_pfn_t, void *arg, va_list *ap); // expects: const void *buf, size_t len
|
||||
size_t mg_print_hex(mg_pfn_t, void *arg, va_list *ap); // expects: int len, uint8_t *buf
|
||||
size_t mg_print_ip(mg_pfn_t, void *arg, va_list *ap); // expects: const struct mg_addr *
|
||||
size_t mg_print_ip_port(mg_pfn_t, void *arg, va_list *ap); // expects: const struct mg_addr *
|
||||
size_t mg_print_ip4(mg_pfn_t, void *arg, va_list *ap); // expects: uint32_t *ipv4
|
||||
size_t mg_print_ip6(mg_pfn_t, void *arg, va_list *ap); // expects: uint8_t[16] ipv6
|
||||
size_t mg_print_mac(mg_pfn_t, void *arg, va_list *ap); // expects: uint8_t[6] mac
|
||||
size_t mg_print_ieee64(mg_pfn_t, void *arg, va_list *ap); // expects: uint64_t
|
||||
size_t mg_print_ieee64(mg_pfn_t, void *arg, va_list *ap); // expects: uint8_t[8] ieee64
|
||||
size_t mg_print_l2addr(mg_pfn_t, void *arg, va_list *ap); // expects: uint8_t l2, uint8_t[n] n-byte l2-dependent address
|
||||
size_t mg_print_html_esc(mg_pfn_t, void *arg, va_list *ap); // expects: int len, const char *str -- use MG_ESC()
|
||||
|
||||
|
||||
+7
-8
@@ -1,6 +1,6 @@
|
||||
#include "dns.h"
|
||||
#include "event.h"
|
||||
#include "log.h"
|
||||
#include "mdash.h"
|
||||
#include "net.h"
|
||||
#include "printf.h"
|
||||
#include "str.h"
|
||||
@@ -768,15 +768,12 @@ void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
|
||||
now = mg_millis();
|
||||
mg_timer_poll(&mgr->timers, now);
|
||||
mg_ota_poll(mgr);
|
||||
mg_mdash_poll(mgr);
|
||||
|
||||
for (c = mgr->conns; c != NULL; c = tmp) {
|
||||
bool is_resp = c->is_resp;
|
||||
long flush = 0;
|
||||
tmp = c->next;
|
||||
mg_call(c, MG_EV_POLL, &now);
|
||||
if (is_resp && !c->is_resp) {
|
||||
long n = 0;
|
||||
mg_call(c, MG_EV_READ, &n);
|
||||
}
|
||||
MG_VERBOSE(("%lu %c%c %c%c%c%c%c %lu %lu", c->id,
|
||||
c->is_readable ? 'r' : '-', c->is_writable ? 'w' : '-',
|
||||
c->is_tls ? 'T' : 't', c->is_connecting ? 'C' : 'c',
|
||||
@@ -791,10 +788,12 @@ void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
|
||||
} else {
|
||||
if (c->is_readable) read_conn(c);
|
||||
if (c->is_writable) write_conn(c);
|
||||
if (c->is_tls && !c->is_tls_hs && c->send.len == 0) mg_tls_flush(c);
|
||||
if (c->is_tls && !c->is_tls_hs && c->send.len == 0)
|
||||
flush = mg_tls_flush(c);
|
||||
}
|
||||
|
||||
if (c->is_draining && c->send.len == 0) c->is_closing = 1;
|
||||
if (flush == MG_IO_ERR) mg_error(c, "tx err");
|
||||
if (c->is_draining && c->send.len == 0 && flush == 0) c->is_closing = 1;
|
||||
if (c->is_closing) close_conn(c);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ void mg_tls_free(struct mg_connection *);
|
||||
long mg_tls_send(struct mg_connection *, const void *buf, size_t len);
|
||||
long mg_tls_recv(struct mg_connection *, void *buf, size_t len);
|
||||
size_t mg_tls_pending(struct mg_connection *);
|
||||
void mg_tls_flush(struct mg_connection *);
|
||||
long mg_tls_flush(struct mg_connection *);
|
||||
void mg_tls_handshake(struct mg_connection *);
|
||||
void mg_tls_ctx_init(struct mg_mgr *);
|
||||
void mg_tls_ctx_free(struct mg_mgr *);
|
||||
|
||||
+149
-70
@@ -107,7 +107,8 @@ struct tls_data {
|
||||
uint8_t random[32]; // client random from ClientHello
|
||||
uint8_t session_id[32]; // client session ID between the handshake states
|
||||
uint8_t x25519_cli[32]; // client X25519 key between the handshake states
|
||||
uint8_t x25519_sec[32]; // x25519 secret between the handshake states
|
||||
uint8_t p256_cli[32]; // client P-256 key between the handshake states
|
||||
uint8_t x25519_sec[32]; // ECDHE secret (X25519 or P-256) between the states
|
||||
|
||||
bool skip_verification; // do not perform checks on server certificate
|
||||
bool cert_requested; // client received a CertificateRequest
|
||||
@@ -130,6 +131,7 @@ struct tls_data {
|
||||
// verify cert
|
||||
size_t pubkeysz; // size of the server public key
|
||||
uint8_t sighash[32]; // calculated signature verification hash
|
||||
uint8_t sighash384[48]; // same, SHA-384, for ecdsa_secp384r1_sha384
|
||||
|
||||
struct tls_enc enc; // actual keys in use at this time
|
||||
struct tls_enc app_keys; // storage during two-way auth handshake
|
||||
@@ -267,9 +269,14 @@ static void mg_der_debug(struct mg_der_tlv *tlv, int depth) {
|
||||
|
||||
// Did we receive a full TLS record in the c->rtls buffer?
|
||||
static bool mg_tls_got_record(struct mg_connection *c) {
|
||||
return c->rtls.len >= (size_t) TLS_RECHDR_SIZE &&
|
||||
c->rtls.len >=
|
||||
(size_t) (TLS_RECHDR_SIZE + MG_LOAD_BE16(c->rtls.buf + 3));
|
||||
uint16_t rl;
|
||||
if (c->rtls.len < (size_t) TLS_RECHDR_SIZE) return false;
|
||||
rl = MG_LOAD_BE16(c->rtls.buf + 3);
|
||||
if (rl > 16384 + 256) { // TLS 1.3 record max length (RFC-9846 5.1)
|
||||
mg_error(c, "TLS record too large");
|
||||
return false;
|
||||
}
|
||||
return c->rtls.len >= (size_t) (TLS_RECHDR_SIZE + rl);
|
||||
}
|
||||
|
||||
// Remove a single TLS record from the recv buffer
|
||||
@@ -339,6 +346,10 @@ static void mg_tls_generate_handshake_keys(struct mg_connection *c) {
|
||||
mg_hmac_sha256(tls->enc.handshake_secret, pre_extract_secret,
|
||||
sizeof(pre_extract_secret), tls->x25519_sec,
|
||||
sizeof(tls->x25519_sec));
|
||||
// ECDHE keys and secret are not needed anymore, wipe for forward secrecy
|
||||
mg_bzero(tls->x25519_cli, sizeof(tls->x25519_cli));
|
||||
mg_bzero(tls->p256_cli, sizeof(tls->p256_cli));
|
||||
mg_bzero(tls->x25519_sec, sizeof(tls->x25519_sec));
|
||||
mg_tls_hexdump("hs secret", tls->enc.handshake_secret, 32);
|
||||
|
||||
// mg_sha256_final is not idempotent, need to copy sha256 context to calculate
|
||||
@@ -621,8 +632,11 @@ static int mg_tls_recv_record(struct mg_connection *c) {
|
||||
return r;
|
||||
}
|
||||
|
||||
// Hash the CertificateVerify content: SHA-256 into hash, and if hash384 is not
|
||||
// NULL, SHA-384 into hash384 for ecdsa_secp384r1_sha384
|
||||
static void mg_tls_calc_cert_verify_hash(struct mg_connection *c,
|
||||
uint8_t hash[32], bool is_client) {
|
||||
uint8_t hash[32], uint8_t *hash384,
|
||||
bool is_client) {
|
||||
struct tls_data *tls = (struct tls_data *) c->tls;
|
||||
uint8_t sig_content[130];
|
||||
mg_sha256_ctx sha256;
|
||||
@@ -642,6 +656,7 @@ static void mg_tls_calc_cert_verify_hash(struct mg_connection *c,
|
||||
mg_sha256_init(&sha256);
|
||||
mg_sha256_update(&sha256, sig_content, sizeof(sig_content));
|
||||
mg_sha256_final(hash, &sha256);
|
||||
if (hash384 != NULL) mg_sha384(hash384, sig_content, sizeof(sig_content));
|
||||
}
|
||||
|
||||
// read and parse ClientHello record
|
||||
@@ -783,10 +798,15 @@ static bool mg_tls_server_send_ext(struct mg_connection *c) {
|
||||
return mg_tls_encrypt(c, ext, sizeof(ext), MG_TLS_HANDSHAKE);
|
||||
}
|
||||
|
||||
// signature algorithms we actually support:
|
||||
// rsa_pkcs1_sha256, rsa_pss_rsae_sha256 and ecdsa_secp256r1_sha256
|
||||
static const uint8_t secp256r1_sig_algs[12] = {
|
||||
// signature algorithms we actually support: ecdsa_secp256r1_sha256,
|
||||
// ecdsa_secp384r1_sha384 (if enabled), rsa_pss_rsae_sha256, rsa_pkcs1_sha256
|
||||
static const uint8_t secp256r1_sig_algs[] = {
|
||||
#if MG_UECC_SUPPORTS_secp384r1
|
||||
0x00, 0x0d, 0x00, 0x0a, 0x00, 0x08, 0x04, 0x03,
|
||||
0x05, 0x03, 0x08, 0x04, 0x04, 0x01};
|
||||
#else
|
||||
0x00, 0x0d, 0x00, 0x08, 0x00, 0x06, 0x04, 0x03, 0x08, 0x04, 0x04, 0x01};
|
||||
#endif
|
||||
|
||||
static bool mg_tls_server_send_cert_request(struct mg_connection *c) {
|
||||
struct tls_data *tls = (struct tls_data *) c->tls;
|
||||
@@ -1066,7 +1086,7 @@ static bool mg_tls_send_cert_verify(struct mg_connection *c, bool is_client) {
|
||||
struct tls_data *tls = (struct tls_data *) c->tls;
|
||||
uint8_t hash[32] = {0};
|
||||
|
||||
mg_tls_calc_cert_verify_hash(c, (uint8_t *) hash, is_client);
|
||||
mg_tls_calc_cert_verify_hash(c, (uint8_t *) hash, NULL, is_client);
|
||||
|
||||
if (tls->rsa.n.len > 0 && tls->rsa.d.len > 0) {
|
||||
// RSA certificate verify packet
|
||||
@@ -1194,6 +1214,7 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
|
||||
struct mg_iobuf *wio = &tls->send;
|
||||
|
||||
uint8_t x25519_pub[X25519_BYTES];
|
||||
uint8_t p256_pub[64]; // X || Y, sent as an uncompressed point 0x04 || X || Y
|
||||
|
||||
// - "signature algorithms we actually support", see above
|
||||
// uint8_t secp256r1_sig_algs[]
|
||||
@@ -1206,7 +1227,7 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
|
||||
0xfe, 0x00, 0x00, 0xfe};
|
||||
|
||||
// clang-format off
|
||||
uint8_t msg_client_hello[145] = {
|
||||
uint8_t msg_client_hello[216] = {
|
||||
// TLS Client Hello header reported as TLS1.2 (5)
|
||||
0x16, 0x03, 0x03, 0x00, 0xfe,
|
||||
// client hello, tls 1.2 (6)
|
||||
@@ -1227,15 +1248,17 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
|
||||
0x01, 0x00,
|
||||
// extensions + keyshare
|
||||
0x00, 0xfe,
|
||||
// x25519 keyshare
|
||||
0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20,
|
||||
// keyshare: x25519
|
||||
0x00, 0x33, 0x00, 0x6b, 0x00, 0x69, 0x00, 0x1d, 0x00, 0x20,
|
||||
PLACEHOLDER_32B,
|
||||
// supported groups (x25519)
|
||||
0x00, 0x0a, 0x00, 0x04, 0x00, 0x02, 0x00, 0x1d,
|
||||
// keyshare: secp256r1, uncompressed point
|
||||
0x00, 0x17, 0x00, 0x41, 0x04, PLACEHOLDER_32B, PLACEHOLDER_32B,
|
||||
// supported groups (x25519, secp256r1)
|
||||
0x00, 0x0a, 0x00, 0x06, 0x00, 0x04, 0x00, 0x1d, 0x00, 0x17,
|
||||
// supported versions (tls1.3 == 0x304)
|
||||
0x00, 0x2b, 0x00, 0x03, 0x02, 0x03, 0x04,
|
||||
// session ticket (none)
|
||||
0x00, 0x23, 0x00, 0x00, // 144 bytes till here
|
||||
0x00, 0x23, 0x00, 0x00, // 215 bytes till here
|
||||
};
|
||||
// clang-format on
|
||||
const char *hostname = tls->hostname;
|
||||
@@ -1248,11 +1271,11 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
|
||||
|
||||
// patch ClientHello with correct hostname ext length (if any)
|
||||
MG_STORE_BE16(msg_client_hello + 3,
|
||||
hostname_extsz + 183 - 9 - 34 + sig_alg_sz);
|
||||
hostname_extsz + 254 - 9 - 34 + sig_alg_sz);
|
||||
MG_STORE_BE16(msg_client_hello + 7,
|
||||
hostname_extsz + 179 - 9 - 34 + sig_alg_sz);
|
||||
hostname_extsz + 250 - 9 - 34 + sig_alg_sz);
|
||||
MG_STORE_BE16(msg_client_hello + 82,
|
||||
hostname_extsz + 104 - 9 - 34 + sig_alg_sz);
|
||||
hostname_extsz + 175 - 9 - 34 + sig_alg_sz);
|
||||
|
||||
if (hostnamesz > 0) {
|
||||
MG_STORE_BE16(server_name_ext + 2, hostnamesz + 5);
|
||||
@@ -1260,16 +1283,21 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
|
||||
MG_STORE_BE16(server_name_ext + 7, hostnamesz);
|
||||
}
|
||||
|
||||
// calculate keyshare
|
||||
// calculate keyshares
|
||||
if (!mg_random(tls->x25519_cli, sizeof(tls->x25519_cli))) mg_error(c, "RNG");
|
||||
mg_tls_x25519(x25519_pub, tls->x25519_cli, X25519_BASE_POINT, 1);
|
||||
if (!mg_uecc_make_key(p256_pub, tls->p256_cli, mg_uecc_secp256r1())) {
|
||||
mg_error(c, "P-256 key");
|
||||
return false; // Do not send uninitialised p256_pub
|
||||
}
|
||||
|
||||
// fill in the gaps: random + session ID + keyshare
|
||||
// fill in the gaps: random + session ID + keyshares
|
||||
if (!mg_random(tls->session_id, sizeof(tls->session_id))) mg_error(c, "RNG");
|
||||
if (!mg_random(tls->random, sizeof(tls->random))) mg_error(c, "RNG");
|
||||
memmove(msg_client_hello + 11, tls->random, sizeof(tls->random));
|
||||
memmove(msg_client_hello + 44, tls->session_id, sizeof(tls->session_id));
|
||||
memmove(msg_client_hello + 94, x25519_pub, sizeof(x25519_pub));
|
||||
memmove(msg_client_hello + 131, p256_pub, sizeof(p256_pub));
|
||||
|
||||
// client hello message
|
||||
if (mg_iobuf_add(wio, wio->len, msg_client_hello, sizeof(msg_client_hello)) ==
|
||||
@@ -1339,17 +1367,29 @@ static int mg_tls_client_recv_hello(struct mg_connection *c) {
|
||||
}
|
||||
if (ext_len2 < (2 + 2 + 32)) goto fail;
|
||||
group = MG_LOAD_BE16(ext + j + 4);
|
||||
if (group != 0x001d) {
|
||||
key_exchange_len = MG_LOAD_BE16(ext + j + 6);
|
||||
key_exchange = ext + j + 8;
|
||||
if (key_exchange_len > ext_len2 - 4) goto fail;
|
||||
if (group == 0x001d) { // x25519
|
||||
if (key_exchange_len != 32 ||
|
||||
mg_tls_x25519(tls->x25519_sec, tls->x25519_cli, key_exchange, 1) <
|
||||
0) {
|
||||
mg_error(c, "bad key");
|
||||
return -1;
|
||||
}
|
||||
} else if (group == 0x0017) { // secp256r1, uncompressed point 0x04 || X || Y
|
||||
if (key_exchange_len != 65 || key_exchange[0] != 0x04 ||
|
||||
!mg_uecc_valid_public_key(key_exchange + 1, mg_uecc_secp256r1()) ||
|
||||
!mg_uecc_shared_secret(key_exchange + 1, tls->p256_cli,
|
||||
tls->x25519_sec, mg_uecc_secp256r1())) {
|
||||
mg_error(c, "bad key");
|
||||
return -1;
|
||||
}
|
||||
} else {
|
||||
mg_error(c, "bad key exchange group");
|
||||
return -1;
|
||||
}
|
||||
key_exchange_len = MG_LOAD_BE16(ext + j + 6);
|
||||
key_exchange = ext + j + 8;
|
||||
if (key_exchange_len != 32 || mg_tls_x25519(tls->x25519_sec, tls->x25519_cli, key_exchange, 1) < 0) {
|
||||
mg_error(c, "bad key");
|
||||
return -1;
|
||||
}
|
||||
mg_tls_hexdump("c x25519 sec", tls->x25519_sec, 32);
|
||||
// mg_tls_hexdump("c ecdhe sec", tls->x25519_sec, 32);
|
||||
mg_tls_drop_record(c);
|
||||
/* generate handshake keys */
|
||||
mg_tls_generate_handshake_keys(c);
|
||||
@@ -1614,14 +1654,15 @@ static int countdots(struct mg_str s) {
|
||||
char *p = s.buf;
|
||||
while (len--) {
|
||||
if (*(p++) == '.') ++count;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
static int mg_tls_verify_cert_san(const uint8_t *der, size_t dersz,
|
||||
const char *server_name,
|
||||
struct mg_addr *server_ip) {
|
||||
struct mg_addr *ref_ip) {
|
||||
struct mg_der_tlv root, field, name;
|
||||
bool is_addr = ref_ip != NULL;
|
||||
if (mg_der_parse((uint8_t *) der, dersz, &root) < 0) {
|
||||
MG_ERROR(("failed to parse certificate"));
|
||||
return -1;
|
||||
@@ -1635,20 +1676,24 @@ static int mg_tls_verify_cert_san(const uint8_t *der, size_t dersz,
|
||||
return -1;
|
||||
}
|
||||
while (mg_der_next(&field, &name) > 0) {
|
||||
if (name.type == 0x87 && name.len == 4) { // this is an IPv4 address
|
||||
MG_VERBOSE(("Found SAN, IP: %M", mg_print_ip4, name.value));
|
||||
if (!server_ip->is_ip6 &&
|
||||
*((uint32_t *) name.value) == server_ip->addr.ip4)
|
||||
return 1; // and matches the one we're connected to
|
||||
if (is_addr) { // match ref IP to IP and name to DNS name (RFC-9525 6.2)
|
||||
if (name.type == 0x87 && name.len == 4) { // this is an IPv4 address
|
||||
uint32_t cert_ip;
|
||||
MG_VERBOSE(("Found SAN, IP: %M", mg_print_ip4, name.value));
|
||||
memcpy(&cert_ip, name.value, 4);
|
||||
if (!ref_ip->is_ip6 && cert_ip == ref_ip->addr.ip4) // RFC-9525 6.4
|
||||
return 1; // and byte-matches the one we wanted to connected to
|
||||
}
|
||||
#if MG_ENABLE_IPV6
|
||||
} else if (name.type == 0x87 && name.len == 16) { // is an IPv6 address
|
||||
MG_VERBOSE(("Found SAN, IPv6: %M", mg_print_ip6, name.value));
|
||||
if (server_ip->is_ip6 && memcmp(name.value, server_ip->addr.ip6, 16) == 0)
|
||||
return 1; // and matches the one we're connected to
|
||||
else if (name.type == 0x87 && name.len == 16) { // is an IPv6 address
|
||||
MG_VERBOSE(("Found SAN, IPv6: %M", mg_print_ip6, name.value));
|
||||
if (ref_ip->is_ip6 && memcmp(name.value, ref_ip->addr.ip6, 16) == 0)
|
||||
return 1; // and byte-matches the one we wanted to connected to
|
||||
}
|
||||
#endif
|
||||
} else { // this is a text SAN
|
||||
} else if (name.type == 0x82) { // this is a DNS name
|
||||
struct mg_str sn, tn;
|
||||
MG_VERBOSE(("Found SAN, (%u): %.*s", name.type, name.len, name.value));
|
||||
MG_VERBOSE(("Found SAN, DNS: %.*s", name.len, name.value));
|
||||
sn = mg_str(server_name), tn = mg_str_n((char *) name.value, name.len);
|
||||
if (countdots(sn) == countdots(tn) && mg_match(sn, tn, NULL))
|
||||
return 1; // and matches the host name
|
||||
@@ -1686,10 +1731,12 @@ static int mg_tls_verify_cert_signature(const struct mg_tls_cert *cert,
|
||||
#if MG_UECC_SUPPORTS_secp384r1
|
||||
if (issuer->pubkey.len == 96) {
|
||||
const uint32_t N = 48;
|
||||
if (a.len > N) a.value += (a.len - N), a.len = N;
|
||||
if (a.len > N) a.value += (a.len - N), a.len = N; // padding
|
||||
if (b.len > N) b.value += (b.len - N), b.len = N;
|
||||
memmove(sig, a.value, N);
|
||||
memmove(sig + N, b.value, N);
|
||||
memset(sig, 0, N - a.len); // short encoding
|
||||
memmove(sig + (N - a.len), a.value, a.len);
|
||||
memset(sig + N, 0, N - b.len);
|
||||
memmove(sig + N + (N - b.len), b.value, b.len);
|
||||
return mg_uecc_verify((uint8_t *) issuer->pubkey.buf, cert->tbshash,
|
||||
(unsigned) cert->tbshashsz, sig,
|
||||
mg_uecc_secp384r1());
|
||||
@@ -1735,17 +1782,18 @@ static int mg_tls_verify_cert_cn(struct mg_der_tlv *subj, const char *host) {
|
||||
return matched;
|
||||
}
|
||||
|
||||
// 1: found, 0: not found, < 0: parse error: -1: bundle (unused), -2: name
|
||||
static int tls_bundle_find(struct tls_data *tls, struct mg_der_tlv *name,
|
||||
struct mg_tls_cert *cert) {
|
||||
size_t i;
|
||||
struct mg_der_tlv v;
|
||||
struct mg_str *p = tls->ca_bundle_der, tgt;
|
||||
if (!mg_der_find_oid(name, (uint8_t *) "\x55\x04\x03", 3, &v)) return false;
|
||||
if (mg_der_find_oid(name, (uint8_t *) "\x55\x04\x03", 3, &v) <= 0) return -2;
|
||||
tgt = mg_str_n((const char *) v.value, v.len);
|
||||
for (i = 0; i < tls->ca_bundle_len; i++, p++) {
|
||||
struct mg_str subj;
|
||||
if (mg_tls_parse_cert_der(p->buf, p->len, cert) < 0 ||
|
||||
!mg_der_find_oid(&cert->subj, (uint8_t *) "\x55\x04\x03", 3, &v)) {
|
||||
mg_der_find_oid(&cert->subj, (uint8_t *) "\x55\x04\x03", 3, &v) <= 0) {
|
||||
MG_ERROR(("failed to parse certificate #%u in bundle", i + 1));
|
||||
continue; // skip this certificate but don't halt the process
|
||||
}
|
||||
@@ -1756,6 +1804,8 @@ static int tls_bundle_find(struct tls_data *tls, struct mg_der_tlv *name,
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool mg_aton_(struct mg_str str, struct mg_addr *addr);
|
||||
|
||||
static int mg_tls_recv_cert(struct mg_connection *c, bool is_client) {
|
||||
struct tls_data *tls = (struct tls_data *) c->tls;
|
||||
unsigned char *recv_buf;
|
||||
@@ -1842,11 +1892,16 @@ static int mg_tls_recv_cert(struct mg_connection *c, bool is_client) {
|
||||
if (ci == certs) {
|
||||
// First certificate in the chain is peer cert, check SAN if requested,
|
||||
// and store public key for further CertVerify step
|
||||
if (tls->hostname[0] != '\0' &&
|
||||
mg_tls_verify_cert_san(cert, certsz, tls->hostname, &c->rem) <= 0 &&
|
||||
mg_tls_verify_cert_cn(&ci->subj, tls->hostname) <= 0) {
|
||||
mg_error(c, "failed to verify hostname");
|
||||
return -1;
|
||||
if (tls->hostname[0] != '\0') {
|
||||
struct mg_addr addr; // use aton_ so localhost evals as a name
|
||||
bool is_addr = mg_aton_(mg_str_s(tls->hostname), &addr);
|
||||
if (mg_tls_verify_cert_san(cert, certsz, tls->hostname,
|
||||
is_addr ? &addr : NULL) <= 0 &&
|
||||
(!is_addr || // DNS CN fallback
|
||||
mg_tls_verify_cert_cn(&ci->subj, tls->hostname) <= 0)) {
|
||||
mg_error(c, "failed to verify hostname");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
if (ci->pubkey.len > sizeof(tls->pubkey)) {
|
||||
mg_error(c, "peer public key too large");
|
||||
@@ -1865,7 +1920,7 @@ static int mg_tls_recv_cert(struct mg_connection *c, bool is_client) {
|
||||
int r;
|
||||
MG_VERBOSE(("Search current cert in bundle"));
|
||||
r = tls_bundle_find(tls, &ci->subj, &ca); // find current cert ci
|
||||
if (r < 0) {
|
||||
if (r == -1) {
|
||||
mg_error(c, "failed to parse CA bundle");
|
||||
return -1;
|
||||
} else if (r > 0 && ca.pubkey.len == ci->pubkey.len &&
|
||||
@@ -1873,7 +1928,7 @@ static int mg_tls_recv_cert(struct mg_connection *c, bool is_client) {
|
||||
found_ca = true;
|
||||
MG_VERBOSE(("CA serial: %M", mg_print_hex, ca.sn.len, ca.sn.buf));
|
||||
break;
|
||||
} // else either r = 0 => subj not found or pubkey not matching
|
||||
} // else r = 0 or -2 => subj not found or pubkey not matching
|
||||
}
|
||||
|
||||
if (certnum == sizeof(certs) / sizeof(certs[0]) - 1) {
|
||||
@@ -1887,8 +1942,10 @@ static int mg_tls_recv_cert(struct mg_connection *c, bool is_client) {
|
||||
MG_VERBOSE(("Search bundle for issuer of last cert in chain"));
|
||||
r = tls_bundle_find(tls, &certs[certnum - 1].issuer, &ca);
|
||||
if (r <= 0) {
|
||||
mg_error(c, r < 0 ? "failed to parse CA bundle"
|
||||
: "failed to find issuing CA in bundle");
|
||||
mg_error(c, "failed to %s",
|
||||
r == 0 ? "find issuing CA in bundle"
|
||||
: r == -1 ? "parse CA bundle"
|
||||
: "parse name OID");
|
||||
return -1;
|
||||
} else if (!ca.is_ca || // candidate issuer found
|
||||
!mg_tls_verify_cert_signature(&certs[certnum - 1], &ca)) {
|
||||
@@ -1908,7 +1965,7 @@ static int mg_tls_recv_cert(struct mg_connection *c, bool is_client) {
|
||||
}
|
||||
}
|
||||
mg_tls_drop_message(c);
|
||||
mg_tls_calc_cert_verify_hash(c, tls->sighash, !is_client);
|
||||
mg_tls_calc_cert_verify_hash(c, tls->sighash, tls->sighash384, !is_client);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1971,11 +2028,20 @@ static int mg_tls_recv_cert_verify(struct mg_connection *c) {
|
||||
return -1;
|
||||
}
|
||||
MG_VERBOSE(("certificate verification successful (RSA)"));
|
||||
} else if (sigalg == 0x0403) { // ecdsa_secp256r1_sha256
|
||||
// Extract certificate signature and verify it using pubkey and sighash
|
||||
uint8_t sig[64];
|
||||
} else if (sigalg == 0x0403 ||
|
||||
(sigalg == 0x0503 && MG_UECC_SUPPORTS_secp384r1)) {
|
||||
// ecdsa_secp256r1_sha256 or ecdsa_secp384r1_sha384. Extract certificate
|
||||
// signature and verify it using pubkey and sighash
|
||||
bool is384 = sigalg == 0x0503;
|
||||
uint32_t N = is384 ? 48 : 32; // curve size: r and s are N bytes each
|
||||
int ok;
|
||||
uint8_t sig[96];
|
||||
struct mg_der_tlv seq, r, s;
|
||||
memset(sig, 0, 64);
|
||||
memset(sig, 0, sizeof(sig));
|
||||
if (tls->pubkeysz != 2 * N) {
|
||||
mg_error(c, "certverify scheme %04x does not match the key", sigalg);
|
||||
return -1;
|
||||
}
|
||||
if (mg_der_to_tlv(sigbuf, siglen, &seq) < 0) {
|
||||
mg_error(c, "verification message is not an ASN.1 DER sequence");
|
||||
return -1;
|
||||
@@ -1989,15 +2055,24 @@ static int mg_tls_recv_cert_verify(struct mg_connection *c) {
|
||||
return -1;
|
||||
}
|
||||
// Integers may be padded with zeroes
|
||||
if (r.len > 32) r.value = r.value + (r.len - 32), r.len = 32;
|
||||
if (s.len > 32) s.value = s.value + (s.len - 32), s.len = 32;
|
||||
if (r.len > N) r.value = r.value + (r.len - N), r.len = N;
|
||||
if (s.len > N) s.value = s.value + (s.len - N), s.len = N;
|
||||
|
||||
// r or s may be shorter than 32 bytes, "right-justify" (network order)
|
||||
memmove(sig + (32 - r.len), r.value, r.len);
|
||||
memmove(sig + 32 + (32 - s.len), s.value, s.len);
|
||||
// r or s may be shorter than N bytes, "right-justify" (network order)
|
||||
memmove(sig + (N - r.len), r.value, r.len);
|
||||
memmove(sig + N + (N - s.len), s.value, s.len);
|
||||
|
||||
if (mg_uecc_verify(tls->pubkey, tls->sighash, sizeof(tls->sighash), sig,
|
||||
mg_uecc_secp256r1()) != 1) {
|
||||
#if MG_UECC_SUPPORTS_secp384r1
|
||||
if (is384) {
|
||||
ok = mg_uecc_verify(tls->pubkey, tls->sighash384,
|
||||
sizeof(tls->sighash384), sig, mg_uecc_secp384r1());
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
ok = mg_uecc_verify(tls->pubkey, tls->sighash, sizeof(tls->sighash),
|
||||
sig, mg_uecc_secp256r1());
|
||||
}
|
||||
if (ok != 1) {
|
||||
mg_error(c, "failed to verify EC certificate (certverify)");
|
||||
return -1;
|
||||
}
|
||||
@@ -2738,7 +2813,7 @@ void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
|
||||
MG_INFO(("Parsed PKCS#8 RSA private key: %d bytes", (int) key.len));
|
||||
} else {
|
||||
mg_free((void *) key.buf);
|
||||
MG_INFO(("Parsed PKCS#8 EC private key"));
|
||||
MG_VERBOSE(("Parsed PKCS#8 EC private key"));
|
||||
}
|
||||
} else {
|
||||
mg_free((void *) key.buf);
|
||||
@@ -2789,6 +2864,7 @@ void mg_tls_free(struct mg_connection *c) {
|
||||
}
|
||||
mg_free((void *) tls->ca_der.buf);
|
||||
mg_free((void *) tls->rsa_key_der.buf);
|
||||
mg_bzero((unsigned char *) tls, sizeof(*tls)); // Wipe keys and secrets
|
||||
}
|
||||
mg_free(c->tls);
|
||||
c->tls = NULL;
|
||||
@@ -2846,13 +2922,16 @@ size_t mg_tls_pending(struct mg_connection *c) {
|
||||
return tls != NULL ? tls->recv_len : 0;
|
||||
}
|
||||
|
||||
void mg_tls_flush(struct mg_connection *c) {
|
||||
long mg_tls_flush(struct mg_connection *c) {
|
||||
struct tls_data *tls = (struct tls_data *) c->tls;
|
||||
long n;
|
||||
long n = 0;
|
||||
while (tls->send.len > 0 &&
|
||||
(n = mg_io_send(c, tls->send.buf, tls->send.len)) > 0) {
|
||||
mg_iobuf_del(&tls->send, 0, (size_t) n);
|
||||
}
|
||||
if (n == MG_IO_ERR) return n;
|
||||
c->is_tls_throttled = tls->send.len > 0;
|
||||
return c->is_tls_throttled ? MG_IO_WAIT : 0;
|
||||
}
|
||||
|
||||
void mg_tls_ctx_init(struct mg_mgr *mgr) {
|
||||
|
||||
+2
-1
@@ -21,8 +21,9 @@ size_t mg_tls_pending(struct mg_connection *c) {
|
||||
(void) c;
|
||||
return 0;
|
||||
}
|
||||
void mg_tls_flush(struct mg_connection *c) {
|
||||
long mg_tls_flush(struct mg_connection *c) {
|
||||
(void) c;
|
||||
return 0;
|
||||
}
|
||||
void mg_tls_ctx_init(struct mg_mgr *mgr) {
|
||||
(void) mgr;
|
||||
|
||||
+7
-4
@@ -249,17 +249,20 @@ long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
|
||||
return n;
|
||||
}
|
||||
|
||||
void mg_tls_flush(struct mg_connection *c) {
|
||||
long mg_tls_flush(struct mg_connection *c) {
|
||||
struct mg_tls *tls = (struct mg_tls *) c->tls;
|
||||
long n = 0;
|
||||
if (c->is_tls_throttled && c->is_draining) {
|
||||
long n =
|
||||
mbedtls_ssl_write(&tls->ssl, tls->throttled_buf, tls->throttled_len);
|
||||
n = mbedtls_ssl_write(&tls->ssl, tls->throttled_buf, tls->throttled_len);
|
||||
#if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
|
||||
if (n == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) return;
|
||||
if (n == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) return MG_IO_WAIT;
|
||||
#endif
|
||||
c->is_tls_throttled =
|
||||
(n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE);
|
||||
if (c->is_tls_throttled) return MG_IO_WAIT;
|
||||
if (n <= 0) return MG_IO_ERR;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void mg_tls_ctx_init(struct mg_mgr *mgr) {
|
||||
|
||||
+2
-1
@@ -335,8 +335,9 @@ long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
|
||||
return n;
|
||||
}
|
||||
|
||||
void mg_tls_flush(struct mg_connection *c) {
|
||||
long mg_tls_flush(struct mg_connection *c) {
|
||||
(void) c;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void mg_tls_ctx_init(struct mg_mgr *mgr) {
|
||||
|
||||
@@ -182,6 +182,12 @@ static void mg_ws_cb(struct mg_connection *c, int ev, void *ev_data) {
|
||||
op = msg.flags & 15;
|
||||
// MG_VERBOSE ("fin %d op %d len %d [%.*s]", final, op,
|
||||
// (int) m.data.len, (int) m.data.len, m.data.buf));
|
||||
if ((op == WEBSOCKET_OP_CONTINUE && ofs == 0) ||
|
||||
((op == WEBSOCKET_OP_TEXT || op == WEBSOCKET_OP_BINARY) &&
|
||||
ofs != 0)) {
|
||||
mg_error(c, "invalid WS fragment sequence");
|
||||
return;
|
||||
}
|
||||
switch (op) {
|
||||
case WEBSOCKET_OP_CONTINUE:
|
||||
mg_call(c, MG_EV_WS_CTL, &m);
|
||||
@@ -281,7 +287,7 @@ void mg_ws_upgrade(struct mg_connection *c, struct mg_http_message *hm,
|
||||
ws_handshake(c, wskey, wsproto, fmt, &ap);
|
||||
va_end(ap);
|
||||
c->is_websocket = 1;
|
||||
c->is_resp = 0;
|
||||
c->pfn_data = NULL; // HTTP response done; mg_ws_cb uses it as an offset
|
||||
mg_call(c, MG_EV_WS_OPEN, hm);
|
||||
}
|
||||
}
|
||||
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
SRCS = mongoose.c unit_test.c packed_fs.c
|
||||
HDRS = $(wildcard ../src/*.h) $(wildcard ../src/drivers/*.h)
|
||||
DEFS ?= -DMG_MAX_HTTP_HEADERS=7 -DMG_ENABLE_LINES -DMG_ENABLE_SSI=1 -DMG_ENABLE_ASSERT=1 -DMG_ENABLE_IPV6=$(IPV6)
|
||||
DEFS ?= -DMG_MAX_HTTP_HEADERS=7 -DMG_ENABLE_LINES -DMG_ENABLE_SSI=1 -DMG_ENABLE_ASSERT=1 -DMG_ENABLE_IPV6=$(IPV6) -DMG_ENABLE_MDASH=$(MDASH)
|
||||
WARN ?= -pedantic -W -Wall -Werror -Wshadow -Wdouble-promotion -fno-common -Wconversion -Wundef
|
||||
OPTS ?= -O3 -g3
|
||||
INCS ?= -Isrc -I.
|
||||
@@ -13,6 +13,7 @@ DOCKER_BIN ?= docker
|
||||
DOCKER ?= $(DOCKER_BIN) run --platform linux/amd64 --net=host --rm $(ENV) -v $(ROOT_DIR):$(ROOT_DIR) -w $(CWD)
|
||||
VCFLAGS ?= /nologo /W3 /O2 /MD /I.
|
||||
IPV6 ?= 1
|
||||
MDASH ?= 1
|
||||
ASAN ?= -fsanitize=address,undefined,alignment -fno-sanitize-recover=all -fno-omit-frame-pointer -fno-common
|
||||
ASAN_OPTIONS ?= detect_leaks=1
|
||||
# This does not include ESP32, ESP8266, Microchip; all examples that are directly placed under an OS tutorial. Also, it is needed that way...
|
||||
@@ -106,7 +107,7 @@ mongoose.c: Makefile $(wildcard ../src/*.c) $(wildcard ../src/drivers/*.c)
|
||||
cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#include "mongoose.h"' ; (for F in src/*.c src/drivers/*.c ; do echo; echo '#ifdef MG_ENABLE_LINES'; echo "#line 1 \"$$F\""; echo '#endif'; cat $$F | sed -e 's,#include ".*,,'; done))> $@
|
||||
|
||||
mongoose.h: $(HDRS) Makefile
|
||||
cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#ifndef MONGOOSE_H'; echo '#define MONGOOSE_H'; echo; cat src/version.h ; echo; echo '#ifdef __cplusplus'; echo 'extern "C" {'; echo '#endif'; cat src/arch.h src/arch_*.h src/os_*.h src/net_ft.h src/net_lwip.h src/net_rl.h src/config.h src/profile.h src/str.h src/queue.h src/fmt.h src/printf.h src/log.h src/timer.h src/fs.h src/util.h src/url.h src/iobuf.h src/base64.h src/md5.h src/sha1.h src/sha256.h src/event.h src/net.h src/http.h src/ssi.h src/tls.h src/tls_x25519.h src/tls_aes128.h src/tls_uecc.h src/tls_chacha20.h src/tls_rsa.h src/tls_mbed.h src/tls_openssl.h src/ws.h src/sntp.h src/mqtt.h src/dns.h src/modbus.h src/json.h src/jwt.h src/rpc.h src/dash.h src/ota.h src/flash.h src/wifi.h src/l2.h src/net_builtin.h src/bsd.h src/drivers/*.h | sed -e '/keep/! s,#include ".*,,' -e 's,^#pragma once,,'; echo; echo '#ifdef __cplusplus'; echo '}'; echo '#endif'; echo '#endif // MONGOOSE_H')> $@
|
||||
cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#ifndef MONGOOSE_H'; echo '#define MONGOOSE_H'; echo; cat src/version.h ; echo; echo '#ifdef __cplusplus'; echo 'extern "C" {'; echo '#endif'; cat src/arch.h src/arch_*.h src/os_*.h src/net_ft.h src/net_lwip.h src/net_rl.h src/config.h src/profile.h src/str.h src/queue.h src/fmt.h src/printf.h src/log.h src/timer.h src/fs.h src/lfs.h src/util.h src/url.h src/iobuf.h src/base64.h src/md5.h src/sha1.h src/sha256.h src/event.h src/net.h src/http.h src/ssi.h src/tls.h src/tls_x25519.h src/tls_aes128.h src/tls_uecc.h src/tls_chacha20.h src/tls_rsa.h src/tls_mbed.h src/tls_openssl.h src/ws.h src/sntp.h src/mqtt.h src/dns.h src/modbus.h src/json.h src/jwt.h src/rpc.h src/dash.h src/ota.h src/health.h src/mdash.h src/flash.h src/wifi.h src/l2.h src/net_builtin.h src/bsd.h src/drivers/*.h | sed -e '/keep/! s,#include ".*,,' -e 's,^#pragma once,,'; echo; echo '#ifdef __cplusplus'; echo '}'; echo '#endif'; echo '#endif // MONGOOSE_H')> $@
|
||||
|
||||
# Check that all external (exported) symbols have "mg_" prefix
|
||||
mg_prefix: mongoose.c mongoose.h
|
||||
@@ -269,6 +270,7 @@ clean: clean_tutorials clean_tutorials_embedded
|
||||
|
||||
# MIP (net_builtin + L2 + driver) TESTS
|
||||
|
||||
mip_test: MDASH = 0
|
||||
mip_test: mip_test.c mongoose.c mongoose.h packed_fs.c Makefile
|
||||
$(CC) mip_test.c packed_fs.c $(CFLAGS) $(LDFLAGS) -o $@
|
||||
ASAN_OPTIONS=$(ASAN_OPTIONS) $(RUN) ./$@
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
#define configUSE_MALLOC_FAILED_HOOK 0
|
||||
#define configUSE_COUNTING_SEMAPHORES 1
|
||||
#define configMINIMAL_STACK_SIZE 128
|
||||
#define configTOTAL_HEAP_SIZE (1024 * 128)
|
||||
#define configTOTAL_HEAP_SIZE (1024 * 256)
|
||||
#define INCLUDE_vTaskDelay 1
|
||||
#define INCLUDE_vTaskDelete 1
|
||||
#define INCLUDE_xTaskGetSchedulerState 1
|
||||
|
||||
@@ -19,7 +19,33 @@ static size_t sock_rx(void *buf, size_t len, struct mg_tcpip_if *ifp) {
|
||||
return (size_t) received;
|
||||
}
|
||||
|
||||
// ignore IPv6, testing segment loss under IPv4 is enough
|
||||
static bool is_tcp_segment(const void *buf, size_t len) {
|
||||
const struct eth *eth = (const struct eth *) buf;
|
||||
const struct ip *ip;
|
||||
const struct tcp *tcp;
|
||||
size_t hlen;
|
||||
if (len < sizeof(*eth)) return false;
|
||||
if (eth->type != mg_htons(0x800)) return false;
|
||||
ip = (const struct ip *) (eth + 1);
|
||||
if (len < sizeof(*eth) + sizeof(*ip)) return false;
|
||||
hlen = (size_t) (ip->ver & 15) * 4;
|
||||
if ((ip->ver >> 4) != 4 || ip->proto != 6 || hlen < sizeof(*ip) ||
|
||||
len < sizeof(*eth) + hlen + sizeof(*tcp))
|
||||
return false;
|
||||
tcp = (const struct tcp *) ((const char *) ip + hlen);
|
||||
return (tcp->flags & (TH_SYN | TH_FIN)) == 0;
|
||||
}
|
||||
|
||||
static size_t sock_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
|
||||
uint32_t random;
|
||||
if (ifp->enable_tcp_retransmit && is_tcp_segment(buf, len)) { // introduce a 30% segment loss
|
||||
mg_random(&random, sizeof(random));
|
||||
if (random % 10 < 3) {
|
||||
MG_DEBUG(("dropping TCP segment"));
|
||||
return len;
|
||||
}
|
||||
}
|
||||
ssize_t res = send(((struct port_driver_data *)ifp->driver_data)->sockfd, buf, len, 0);
|
||||
if (res < 0) {
|
||||
MG_ERROR(("sock_tx failed: %d", errno));
|
||||
@@ -113,6 +139,7 @@ int main(void) {
|
||||
}
|
||||
|
||||
// RUN TESTS
|
||||
mif.enable_tcp_retransmit = getenv("RTX") != NULL;
|
||||
result = mip_x_test(&mgr);
|
||||
close(pdd.sockfd);
|
||||
if (!result) return EXIT_FAILURE;
|
||||
|
||||
@@ -22,7 +22,33 @@ static size_t tap_rx(void *buf, size_t len, struct mg_tcpip_if *ifp) {
|
||||
return (size_t) received;
|
||||
}
|
||||
|
||||
// ignore IPv6, testing segment loss under IPv4 is enough
|
||||
static bool is_tcp_segment(const void *buf, size_t len) {
|
||||
const struct eth *eth = (const struct eth *) buf;
|
||||
const struct ip *ip;
|
||||
const struct tcp *tcp;
|
||||
size_t hlen;
|
||||
if (len < sizeof(*eth)) return false;
|
||||
if (eth->type != mg_htons(0x800)) return false;
|
||||
ip = (const struct ip *) (eth + 1);
|
||||
if (len < sizeof(*eth) + sizeof(*ip)) return false;
|
||||
hlen = (size_t) (ip->ver & 15) * 4;
|
||||
if ((ip->ver >> 4) != 4 || ip->proto != 6 || hlen < sizeof(*ip) ||
|
||||
len < sizeof(*eth) + hlen + sizeof(*tcp))
|
||||
return false;
|
||||
tcp = (const struct tcp *) ((const char *) ip + hlen);
|
||||
return (tcp->flags & (TH_SYN | TH_FIN)) == 0;
|
||||
}
|
||||
|
||||
static size_t tap_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
|
||||
uint32_t random;
|
||||
if (ifp->enable_tcp_retransmit && is_tcp_segment(buf, len)) { // introduce a 30% segment loss
|
||||
mg_random(&random, sizeof(random));
|
||||
if (random % 10 < 3) {
|
||||
MG_DEBUG(("dropping TCP segment"));
|
||||
return len;
|
||||
}
|
||||
}
|
||||
ssize_t res = write(*(int *) ifp->driver_data, buf, len);
|
||||
if (res < 0) {
|
||||
MG_ERROR(("tap_tx failed: %d", errno));
|
||||
@@ -125,6 +151,7 @@ int main(void) {
|
||||
}
|
||||
|
||||
// RUN TESTS
|
||||
mif.enable_tcp_retransmit = getenv("RTX") != NULL;
|
||||
result = mip_x_test(&mgr);
|
||||
close(fd);
|
||||
if (!result) return EXIT_FAILURE;
|
||||
|
||||
+290
-11
@@ -57,7 +57,7 @@ static void test_csum(void) {
|
||||
|
||||
#if !MG_ENABLE_IPV6
|
||||
#define udp6csum_ok(d, u) true
|
||||
#define tcp6csum_ok(d, t) true
|
||||
#define tcp6csum_ok(d, t, l) true
|
||||
#endif
|
||||
|
||||
static bool executed = false;
|
||||
@@ -119,6 +119,33 @@ static void tcpclosure_fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
(void) c, (void) ev_data;
|
||||
}
|
||||
|
||||
static struct mg_connection *s_drain_conn;
|
||||
static bool s_drain_tls;
|
||||
|
||||
static void tcpdrain_fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
static const char data[2 * TCP_TEST_WIN] = {0};
|
||||
if (ev == MG_EV_ACCEPT) {
|
||||
s_drain_conn = c;
|
||||
#if MG_TLS == MG_TLS_BUILTIN
|
||||
if (s_drain_tls) {
|
||||
struct mg_tls_opts opts;
|
||||
struct tls_data *tls;
|
||||
|
||||
memset(&opts, 0, sizeof(opts));
|
||||
mg_tls_init(c, &opts);
|
||||
tls = (struct tls_data *) c->tls;
|
||||
ASSERT(tls != NULL);
|
||||
ASSERT(mg_iobuf_add(&tls->send, 0, data, sizeof(data)) == sizeof(data));
|
||||
} else
|
||||
#endif
|
||||
mg_send(c, data, sizeof(data));
|
||||
c->is_draining = 1;
|
||||
} else if (ev == MG_EV_CLOSE && c == s_drain_conn) {
|
||||
s_drain_conn = NULL;
|
||||
}
|
||||
(void) ev_data;
|
||||
}
|
||||
|
||||
static void txwindow_fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_ACCEPT) {
|
||||
char bigdata[2 * TCP_TEST_WIN + 256];
|
||||
@@ -130,6 +157,15 @@ static void txwindow_fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
(void) c, (void) ev_data;
|
||||
}
|
||||
|
||||
static char s_rtx_data[MG_TCPIP_WIN];
|
||||
static size_t s_rtx_len;
|
||||
static uint16_t s_tcp_window;
|
||||
|
||||
static void rtx_fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_ACCEPT) mg_send(c, s_rtx_data, s_rtx_len);
|
||||
(void) ev_data;
|
||||
}
|
||||
|
||||
static void client_fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_ERROR || ev == MG_EV_CONNECT) (*(int *) c->fn_data) = ev;
|
||||
(void) c, (void) ev_data;
|
||||
@@ -183,6 +219,7 @@ static void test_poll(void) {
|
||||
struct driver_data {
|
||||
char buf[DRIVER_BUF_SIZE];
|
||||
size_t len;
|
||||
size_t tx_count;
|
||||
bool tx_ready; // data can be read from tx
|
||||
};
|
||||
|
||||
@@ -192,6 +229,7 @@ static size_t if_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
|
||||
struct driver_data *driver_data = (struct driver_data *) ifp->driver_data;
|
||||
if (len > DRIVER_BUF_SIZE) len = DRIVER_BUF_SIZE;
|
||||
driver_data->len = len;
|
||||
driver_data->tx_count++;
|
||||
memcpy(driver_data->buf, buf, len);
|
||||
driver_data->tx_ready = true;
|
||||
return len;
|
||||
@@ -228,7 +266,7 @@ static void create_tcp_seg(struct eth *e, struct ipp *ipp, uint32_t seq,
|
||||
t.ack = mg_htonl(ack);
|
||||
t.sport = mg_htons(sport);
|
||||
t.dport = mg_htons(dport);
|
||||
t.win = mg_htons(TCP_TEST_WIN);
|
||||
t.win = mg_htons(s_tcp_window);
|
||||
t.off = (uint8_t) ((sizeof(t) / 4) << 4) + (uint8_t) ((opts_len / 4) << 4);
|
||||
memcpy(s_driver_data.buf, e, sizeof(*e));
|
||||
#if MG_ENABLE_IPV6
|
||||
@@ -242,7 +280,7 @@ static void create_tcp_seg(struct eth *e, struct ipp *ipp, uint32_t seq,
|
||||
if (opts != NULL && opts_len)
|
||||
memcpy(s_driver_data.buf + sizeof(*e) + sizeof(*ip) + sizeof(t), opts,
|
||||
opts_len);
|
||||
tcp->csum = p6csum(ip, tcp, (4 * (t.off >> 4) + payload_len));
|
||||
tcp->csum = p6csum(ip, tcp, 6, (4 * (t.off >> 4) + payload_len));
|
||||
s_driver_data.len =
|
||||
sizeof(*e) + sizeof(*ip) + sizeof(t) + payload_len + opts_len;
|
||||
} else
|
||||
@@ -280,6 +318,7 @@ static void init_tests(struct mg_mgr *mgr, struct eth *e, struct ipp *ipp,
|
||||
mg_mgr_init(mgr);
|
||||
memset(mif, 0, sizeof(*mif));
|
||||
memset(&s_driver_data, 0, sizeof(struct driver_data));
|
||||
s_tcp_window = TCP_TEST_WIN;
|
||||
driver->init = NULL, driver->tx = if_tx, driver->poll = if_poll,
|
||||
driver->rx = if_rx;
|
||||
mif->driver = driver;
|
||||
@@ -404,7 +443,7 @@ static void test_tcp_basics(bool ipv6) {
|
||||
if (ipv6) {
|
||||
ASSERT(i6->src[0] == mg_htonll(0x100000000000000) && i6->src[1] == 0 &&
|
||||
i6->dst[0] == mg_htonll(0x200000000000000) && i6->dst[1] == 0);
|
||||
ASSERT(tcp6csum_ok(i6, t));
|
||||
ASSERT(tcp6csum_ok(i6, t, mg_ntohs(i6->plen)));
|
||||
} else {
|
||||
ASSERT(i->src == mg_htonl(0x1000000) && i->dst == mg_htonl(0x2000000));
|
||||
ASSERT(tcpcsum_ok(i, t));
|
||||
@@ -491,6 +530,20 @@ static void test_tcp_basics(bool ipv6) {
|
||||
// no MSS sent, so it must default to 536/1220 (RFC-9293 3.7.1)
|
||||
ASSERT(((struct connstate *) (mgr.conns + 1))->dmss == (ipv6 ? 1220 : 536));
|
||||
|
||||
// check c->is_full advertises a zero window and recovers
|
||||
mgr.conns->is_full = true;
|
||||
create_tcp_simpleseg(&e, &ipp, 1001, 2, TH_ACK, 0);
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
while (!received_response(&s_driver_data)) mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(t->flags == TH_ACK);
|
||||
ASSERT(t->win == 0);
|
||||
s_driver_data.len = 0;
|
||||
mgr.conns->is_full = false;
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(received_response(&s_driver_data));
|
||||
ASSERT(t->flags == TH_ACK);
|
||||
ASSERT(t->win == mg_htons(MG_TCPIP_WIN));
|
||||
|
||||
// segment with seq_no within window
|
||||
create_tcp_simpleseg(&e, &ipp, 1010, 2, TH_PUSH, 2);
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
@@ -536,6 +589,23 @@ static void test_tcp_basics(bool ipv6) {
|
||||
s_driver_data.len = 0;
|
||||
mg_mgr_free(&mgr);
|
||||
|
||||
// Initiate closure with FIN and payload
|
||||
init_tcp_tests(&mgr, &e, &ipp, &driver, &mif, fn);
|
||||
init_tcp_handshake(&e, &ipp, &mgr); // starts with seq_no=1000, ackno=2
|
||||
create_tcp_simpleseg(&e, &ipp, 1001, 2, TH_FIN | TH_ACK, 2);
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
while (!received_response(&s_driver_data)) mg_mgr_poll(&mgr, 0);
|
||||
ASSERT((t->flags == (TH_FIN | TH_ACK)));
|
||||
ASSERT((t->seq == mg_htonl(2)));
|
||||
ASSERT((t->ack == mg_htonl(1004)));
|
||||
create_tcp_simpleseg(&e, &ipp, 1004, 3, TH_ACK, 0);
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(!received_response(&s_driver_data));
|
||||
ASSERT(mgr.conns->next == NULL); // only one connection: the listener
|
||||
|
||||
s_driver_data.len = 0;
|
||||
mg_mgr_free(&mgr);
|
||||
|
||||
// Test client-initiated closure timeout, do not ACK
|
||||
init_tcp_tests(&mgr, &e, &ipp, &driver, &mif, fn);
|
||||
init_tcp_handshake(&e, &ipp, &mgr); // starts with seq_no=1000, ackno=2
|
||||
@@ -773,7 +843,7 @@ static void test_tcp_basics(bool ipv6) {
|
||||
if (ipv6) {
|
||||
ASSERT(i6->src[0] == mg_htonll(0x100000000000000) && i6->src[1] == 0 &&
|
||||
i6->dst[0] == mg_htonll(0x200000000000000) && i6->dst[1] == 0);
|
||||
ASSERT(tcp6csum_ok(i6, t));
|
||||
ASSERT(tcp6csum_ok(i6, t, mg_ntohs(i6->plen)));
|
||||
} else {
|
||||
ASSERT(i->src == mg_htonl(0x1000000) && i->dst == mg_htonl(0x2000000));
|
||||
ASSERT(tcpcsum_ok(i, t));
|
||||
@@ -862,11 +932,13 @@ static void test_tcp_retransmit(void) {
|
||||
now = mg_millis() - start;
|
||||
// we wait enough time for a reply
|
||||
if (now > 2 * MG_TCPIP_ACK_MS) {
|
||||
response_recv = false;
|
||||
response_recv = false; // response should have been received by now
|
||||
break;
|
||||
}
|
||||
}
|
||||
ASSERT((!response_recv)); // replies should not be sent for duplicate packets
|
||||
ASSERT((response_recv)); // retransmit the lost ACK for duplicate segs
|
||||
ASSERT((t->flags == TH_ACK));
|
||||
ASSERT((t->ack == mg_htonl(1003))); // dup ACK
|
||||
|
||||
// packet with seq_no = 1003 got lost/delayed, send seq_no = 1005
|
||||
create_tcp_simpleseg(&e, &ipp, 1005, 2, TH_PUSH | TH_ACK, 2);
|
||||
@@ -916,6 +988,128 @@ static void test_tcp_retransmit(void) {
|
||||
mg_mgr_free(&mgr);
|
||||
}
|
||||
|
||||
static void test_tcp_retransmit_queue(void) {
|
||||
struct mg_mgr mgr;
|
||||
struct eth e;
|
||||
struct ip ip;
|
||||
struct ipp ipp;
|
||||
struct tcp *t = (struct tcp *) (s_driver_data.buf + sizeof(e) + sizeof(ip));
|
||||
struct connstate *s;
|
||||
size_t i, first, off, retired;
|
||||
uint8_t *data;
|
||||
uint32_t qlen = 0;
|
||||
struct mg_tcpip_driver driver;
|
||||
struct mg_tcpip_if mif;
|
||||
|
||||
ipp.ip4 = &ip;
|
||||
ipp.ip6 = NULL;
|
||||
for (i = 0; i < sizeof(s_rtx_data); i++) s_rtx_data[i] = (char) i;
|
||||
s_rtx_len = sizeof(s_rtx_data);
|
||||
init_tcp_tests(&mgr, &e, &ipp, &driver, &mif, rtx_fn);
|
||||
mif.enable_tcp_retransmit = true;
|
||||
s_tcp_window = MG_TCPIP_WIN;
|
||||
init_tcp_handshake(&e, &ipp, &mgr);
|
||||
s = (struct connstate *) (mgr.conns + 1);
|
||||
|
||||
// Fill the retransmission queue and verify its hard cap
|
||||
while (s->seq - s->txq_una < s_rtx_len) {
|
||||
while (!received_response(&s_driver_data)) mg_mgr_poll(&mgr, 0);
|
||||
}
|
||||
ASSERT(s->txq_seq == 2);
|
||||
ASSERT(s->txq_una == 2);
|
||||
ASSERT(s->seq - s->txq_una == s_rtx_len);
|
||||
first = txq_next(s, &data);
|
||||
ASSERT(first == s->dmss);
|
||||
ASSERT(memcmp(data, s_rtx_data, first) == 0);
|
||||
ASSERT(mg_io_send(mgr.conns, s_rtx_data, 1) == MG_IO_WAIT);
|
||||
|
||||
// Timeout resends the first retained segment only
|
||||
s_driver_data.len = 0;
|
||||
s_driver_data.tx_ready = false;
|
||||
s_driver_data.tx_count = 0;
|
||||
s->txq_timer = 0;
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(s_driver_data.tx_count == 1);
|
||||
ASSERT(t->flags == (TH_PUSH | TH_ACK));
|
||||
ASSERT(t->seq == mg_htonl(2));
|
||||
ASSERT(s->txq_retries == 1);
|
||||
ASSERT(txq_next(s, &data) == first);
|
||||
ASSERT(memcmp(data, s_rtx_data, first) == 0);
|
||||
|
||||
// A piggybacked partial ACK advances SND.UNA but retains the segment
|
||||
retired = first / 2;
|
||||
create_tcp_simpleseg(&e, &ipp, 1001, 2 + (uint32_t) retired,
|
||||
TH_PUSH | TH_ACK, 2);
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(s->txq_seq == 2);
|
||||
ASSERT(s->txq_una == 2 + retired);
|
||||
ASSERT(s->seq - s->txq_una == s_rtx_len - retired);
|
||||
ASSERT(s->txq_retries == 0);
|
||||
ASSERT(txq_next(s, &data) == first);
|
||||
ASSERT(memcmp(data, s_rtx_data, first) == 0);
|
||||
ASSERT(mgr.conns->recv.len == 2);
|
||||
|
||||
// Timeout after partial ACK retains the segment's original SEQ and data
|
||||
s_driver_data.tx_count = 0;
|
||||
s->txq_timer = 0;
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(s_driver_data.tx_count == 1);
|
||||
ASSERT(t->seq == mg_htonl(2));
|
||||
ASSERT(s->txq_retries == 1);
|
||||
ASSERT(txq_next(s, &data) == first);
|
||||
ASSERT(memcmp(data, s_rtx_data, first) == 0);
|
||||
|
||||
// ACKing record one and part of two retires only record one
|
||||
create_tcp_simpleseg(&e, &ipp, 1003, 2 + (uint32_t) (first + retired),
|
||||
TH_ACK, 0);
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(s->txq_seq == 2 + first);
|
||||
ASSERT(s->txq_una == 2 + first + retired);
|
||||
ASSERT(s->txq_retries == 0);
|
||||
ASSERT(txq_next(s, &data) == first);
|
||||
ASSERT(memcmp(data, s_rtx_data + first, first) == 0);
|
||||
|
||||
// Timeout retransmits record two with its original SEQ and data
|
||||
s_driver_data.tx_count = 0;
|
||||
s->txq_timer = 0;
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(s_driver_data.tx_count == 1);
|
||||
ASSERT(t->seq == mg_htonl(2 + (uint32_t) first));
|
||||
ASSERT(s->txq_retries == 1);
|
||||
ASSERT(txq_next(s, &data) == first);
|
||||
ASSERT(memcmp(data, s_rtx_data + first, first) == 0);
|
||||
|
||||
// A complete ACK retires record two; appending restores the full flight
|
||||
create_tcp_simpleseg(&e, &ipp, 1003, 2 + (uint32_t) (2 * first), TH_ACK, 0);
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(s->txq_seq == 2 + 2 * first);
|
||||
ASSERT(s->txq_una == 2 + 2 * first);
|
||||
ASSERT(txq_next(s, &data) == first);
|
||||
ASSERT(memcmp(data, s_rtx_data + 2 * first, first) == 0);
|
||||
mg_send(mgr.conns, s_rtx_data, 2 * first);
|
||||
while (s->seq - s->txq_una < s_rtx_len) {
|
||||
while (!received_response(&s_driver_data)) mg_mgr_poll(&mgr, 0);
|
||||
}
|
||||
for (off = 0; off < s->txq.len; off += sizeof(qlen) + qlen) {
|
||||
memcpy(&qlen, s->txq.buf + off, sizeof(qlen));
|
||||
}
|
||||
ASSERT(off == s->txq.len);
|
||||
ASSERT(qlen == first);
|
||||
ASSERT(memcmp(s->txq.buf + off - qlen, s_rtx_data + first, qlen) == 0);
|
||||
|
||||
// Draining waits for the rebuilt flight to be acknowledged before FIN
|
||||
mgr.conns->is_draining = 1;
|
||||
s_driver_data.len = 0;
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(!received_response(&s_driver_data));
|
||||
create_tcp_simpleseg(&e, &ipp, 1003, s->seq, TH_ACK, 0);
|
||||
while (!received_response(&s_driver_data)) mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(t->flags == (TH_FIN | TH_ACK));
|
||||
ASSERT(s->txq.len == 0);
|
||||
s_driver_data.len = 0;
|
||||
mg_mgr_free(&mgr);
|
||||
}
|
||||
|
||||
|
||||
static void test_tcp_txwindow(void) {
|
||||
struct mg_mgr mgr;
|
||||
@@ -941,6 +1135,7 @@ static void test_tcp_txwindow(void) {
|
||||
seq = (uint32_t)(mg_htonl(t->seq) + s_driver_data.len - (size_t)((char *)((uint32_t *)t + (t->off >> 4)) - s_driver_data.buf));
|
||||
} while (seq < (TCP_TEST_WIN + 2));
|
||||
stallcount = count;
|
||||
ASSERT(((struct connstate *) (mgr.conns + 1))->txq.buf == NULL);
|
||||
mg_mgr_poll(&mgr, 0), s_driver_data.len = 0;
|
||||
mg_mgr_poll(&mgr, 0), s_driver_data.len = 0;
|
||||
ASSERT((stallcount == count));
|
||||
@@ -964,6 +1159,84 @@ static void test_tcp_txwindow(void) {
|
||||
mg_mgr_free(&mgr);
|
||||
}
|
||||
|
||||
static void test_tcp_ackseq(void) {
|
||||
struct mg_mgr mgr;
|
||||
struct eth e;
|
||||
struct ip ip;
|
||||
struct ipp ipp;
|
||||
struct tcp *t = (struct tcp *) (s_driver_data.buf + sizeof(e) + sizeof(ip));
|
||||
int count = 0, stallcount;
|
||||
uint32_t seq;
|
||||
struct mg_tcpip_driver driver;
|
||||
struct mg_tcpip_if mif;
|
||||
|
||||
ipp.ip4 = &ip;
|
||||
ipp.ip6 = NULL;
|
||||
init_tcp_tests(&mgr, &e, &ipp, &driver, &mif, txwindow_fn);
|
||||
mgr.conns->fn_data = &count;
|
||||
init_tcp_handshake(&e, &ipp, &mgr);
|
||||
do {
|
||||
while (!received_response(&s_driver_data)) mg_mgr_poll(&mgr, 0);
|
||||
seq = (uint32_t)(mg_htonl(t->seq) + s_driver_data.len - (size_t)((char *)((uint32_t *)t + (t->off >> 4)) - s_driver_data.buf));
|
||||
} while (seq < (TCP_TEST_WIN + 2));
|
||||
stallcount = count;
|
||||
mg_mgr_poll(&mgr, 0), s_driver_data.len = 0;
|
||||
ASSERT(stallcount == count);
|
||||
|
||||
// Keepalive probe
|
||||
create_tcp_simpleseg(&e, &ipp, 1000, seq, TH_ACK, 0);
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(stallcount == count);
|
||||
|
||||
// Invalid SEG.SEQ
|
||||
create_tcp_simpleseg(&e, &ipp, 1002, seq, TH_ACK, 0);
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(stallcount == count);
|
||||
|
||||
// Valid FIN+ACK
|
||||
create_tcp_simpleseg(&e, &ipp, 1001, seq, TH_FIN | TH_ACK, 0);
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
ASSERT(stallcount < count);
|
||||
|
||||
s_driver_data.len = 0;
|
||||
mg_mgr_free(&mgr);
|
||||
}
|
||||
|
||||
static void test_tcp_drain(bool tls) {
|
||||
struct mg_mgr mgr;
|
||||
struct eth e;
|
||||
struct ip ip;
|
||||
struct ipp ipp;
|
||||
struct tcp *t = (struct tcp *) (s_driver_data.buf + sizeof(e) + sizeof(ip));
|
||||
struct connstate *s;
|
||||
struct mg_tcpip_driver driver;
|
||||
struct mg_tcpip_if mif;
|
||||
|
||||
ipp.ip4 = &ip;
|
||||
ipp.ip6 = NULL;
|
||||
s_drain_conn = NULL;
|
||||
s_drain_tls = tls;
|
||||
init_tcp_tests(&mgr, &e, &ipp, &driver, &mif, tcpdrain_fn);
|
||||
init_tcp_handshake(&e, &ipp, &mgr); // Send until peer window closes
|
||||
ASSERT(s_drain_conn != NULL);
|
||||
while (received_response(&s_driver_data)) {
|
||||
s_driver_data.len = 0; // Do not feed Mongoose its own TX packet
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
}
|
||||
ASSERT((t->flags & TH_FIN) == 0);
|
||||
|
||||
ASSERT(s_drain_conn != NULL);
|
||||
s = (struct connstate *) (s_drain_conn + 1);
|
||||
create_tcp_simpleseg(&e, &ipp, 1001, s->seq, TH_ACK, 0); // Reopen window
|
||||
do {
|
||||
while (!received_response(&s_driver_data)) mg_mgr_poll(&mgr, 0);
|
||||
} while (t->flags != (TH_FIN | TH_ACK));
|
||||
ASSERT(t->flags == (TH_FIN | TH_ACK));
|
||||
|
||||
s_driver_data.len = 0;
|
||||
mg_mgr_free(&mgr);
|
||||
}
|
||||
|
||||
static void test_frag_recv_path(void) {
|
||||
struct mg_mgr mgr;
|
||||
struct eth e;
|
||||
@@ -1124,7 +1397,13 @@ static void test_tcp(bool ipv6) {
|
||||
if (!ipv6) {
|
||||
test_tcp_backlog();
|
||||
test_tcp_retransmit();
|
||||
test_tcp_retransmit_queue();
|
||||
test_tcp_txwindow();
|
||||
test_tcp_ackseq();
|
||||
test_tcp_drain(false);
|
||||
#if MG_TLS == MG_TLS_BUILTIN
|
||||
test_tcp_drain(true);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1154,7 +1433,7 @@ static void create_udp_dat(struct eth *e, struct ipp *ipp, uint16_t sport,
|
||||
memcpy(s_driver_data.buf + sizeof(*e), ip, sizeof(*ip));
|
||||
memcpy(udp, &u, sizeof(u));
|
||||
*(s_driver_data.buf + sizeof(*e) + sizeof(*ip) + sizeof(u)) = 'p';
|
||||
udp->csum = p6csum(ip, udp, (sizeof(u) + payload_len));
|
||||
udp->csum = p6csum(ip, udp, 17, (sizeof(u) + payload_len));
|
||||
s_driver_data.len = sizeof(*e) + sizeof(*ip) + sizeof(u) + payload_len;
|
||||
} else
|
||||
#endif
|
||||
@@ -1331,7 +1610,7 @@ static void create_icmp6_dat(struct eth *e, struct ipp *ipp, uint8_t type,
|
||||
memcpy(s_driver_data.buf, e, sizeof(*e));
|
||||
memcpy(s_driver_data.buf + sizeof(*e), ip6, sizeof(*ip6));
|
||||
memcpy(icmp6, &i6, sizeof(i6));
|
||||
icmp6->csum = p6csum(ip6, icmp6, sizeof(*icmp6) + payload_len);
|
||||
icmp6->csum = p6csum(ip6, icmp6, 58, sizeof(*icmp6) + payload_len);
|
||||
s_driver_data.len = sizeof(*e) + sizeof(*ip6) + sizeof(*icmp6) + payload_len;
|
||||
if (s_driver_data.len < 64) s_driver_data.len = 64; // add padding if needed
|
||||
}
|
||||
@@ -1367,7 +1646,7 @@ static void test_icmp6_basics(void) {
|
||||
ASSERT(i->plen == mg_htons(sizeof(*icmp6) + 0));
|
||||
ASSERT(icmp6->type == 129); // Echo Reply
|
||||
ASSERT(icmp6->code == 0);
|
||||
ASSERT(icmp6csum_ok(i, icmp6));
|
||||
ASSERT(icmp6csum_ok(i, icmp6, mg_ntohs(i->plen)));
|
||||
|
||||
create_icmp6_dat(&e, &ipp, 128, 0, NULL, 69); // Echo Request
|
||||
mg_mgr_poll(&mgr, 0); // make sure we clean former stuff in buffer
|
||||
@@ -1378,7 +1657,7 @@ static void test_icmp6_basics(void) {
|
||||
ASSERT(i->plen == mg_htons(sizeof(*icmp6) + 69));
|
||||
ASSERT(icmp6->type == 129); // Echo Reply
|
||||
ASSERT(icmp6->code == 0);
|
||||
ASSERT(icmp6csum_ok(i, icmp6));
|
||||
ASSERT(icmp6csum_ok(i, icmp6, mg_ntohs(i->plen)));
|
||||
|
||||
// Neighbor Solicitation
|
||||
memset(payload, 0, sizeof(payload));
|
||||
|
||||
+19
-6
@@ -75,6 +75,8 @@ static char *host_ip, *host_ip6;
|
||||
static int s_num_tests = 0;
|
||||
static bool s_error = false;
|
||||
|
||||
#define POLL_LIMIT(n) (mgr->ifp->enable_tcp_retransmit ? (n) * 10 : (n))
|
||||
|
||||
#ifdef NO_ABORT
|
||||
static int s_abort = 0;
|
||||
#define ABORT() ++s_abort, s_error = true
|
||||
@@ -205,7 +207,7 @@ static int fetch(struct mg_mgr *mgr, char *buf, const char *url,
|
||||
buf[0] = '\0';
|
||||
// - TLS: multiple (small) records: allow enough loops so mg_mgr_poll can
|
||||
// process buffered records when no more frames are coming in
|
||||
for (i = 0; i < 500 && buf[0] == '\0' && !fd.closed; i++) {
|
||||
for (i = 0; i < POLL_LIMIT(500) && buf[0] == '\0' && !fd.closed; i++) {
|
||||
mg_mgr_poll(mgr, 0);
|
||||
usleep(5000); // 5 ms. Slow down poll loop to ensure packet transit, but
|
||||
// allow enough loops to get the ARP response, otherwise,
|
||||
@@ -304,6 +306,7 @@ static void mqtt_fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
// close on farewell
|
||||
MG_INFO(("%lu CLOSING", c->id));
|
||||
mg_mqtt_disconnect(c, NULL);
|
||||
c->is_draining = true;
|
||||
data->passed = true;
|
||||
} else if (mm->data.len == 21098) {
|
||||
struct mg_mqtt_opts pub_opts;
|
||||
@@ -360,7 +363,9 @@ static void test_mqtt_connsubpub(struct mg_mgr *mgr) {
|
||||
mg_mgr_poll(mgr, 0);
|
||||
s_conn = mg_mqtt_connect(mgr, data.url, &opts, mqtt_fn, &data);
|
||||
ASSERT(s_conn != NULL);
|
||||
for (int i = 0; i < 1000 && s_conn != NULL && !s_conn->is_closing; i++) {
|
||||
for (int i = 0;
|
||||
i < POLL_LIMIT(1000) && s_conn != NULL && !s_conn->is_closing;
|
||||
i++) {
|
||||
mg_mgr_poll(mgr, 0);
|
||||
usleep(5000); // 5 ms (*) See fetch() above for reasons
|
||||
}
|
||||
@@ -406,7 +411,9 @@ static void test_mqtt_connsubpub(struct mg_mgr *mgr) {
|
||||
mg_mgr_poll(mgr, 0);
|
||||
s_conn = mg_mqtt_connect(mgr, data.url, &opts, mqtt_fn, &data);
|
||||
ASSERT(s_conn != NULL);
|
||||
for (int i = 0; i < 1000 && s_conn != NULL && !s_conn->is_closing; i++) {
|
||||
for (int i = 0;
|
||||
i < POLL_LIMIT(1000) && s_conn != NULL && !s_conn->is_closing;
|
||||
i++) {
|
||||
mg_mgr_poll(mgr, 0);
|
||||
usleep(5000); // 5 ms (*) See fetch() above for reasons
|
||||
}
|
||||
@@ -418,10 +425,12 @@ static void test_mqtt_connsubpub(struct mg_mgr *mgr) {
|
||||
|
||||
#ifndef NO_HTTPSERVER_TEST
|
||||
#include <pthread.h>
|
||||
static volatile bool s_poll_done;
|
||||
|
||||
static void *poll_thread(void *p) {
|
||||
struct mg_mgr *mgr = (struct mg_mgr *) p;
|
||||
int i;
|
||||
for (i = 0; i < 300; i++) {
|
||||
for (i = 0; i < POLL_LIMIT(300) && !s_poll_done; i++) {
|
||||
mg_mgr_poll(mgr, 0);
|
||||
usleep(10000); // 10 ms. Slow down poll loop to ensure packet transit
|
||||
}
|
||||
@@ -436,6 +445,7 @@ static void test_http_server(struct mg_mgr *mgr) {
|
||||
struct mg_connection *c;
|
||||
char *cmd;
|
||||
pthread_t thread_id = (pthread_t) 0;
|
||||
int rc;
|
||||
#if MG_TLS
|
||||
struct mg_tls_opts opts;
|
||||
memset(&opts, 0, sizeof(opts));
|
||||
@@ -455,12 +465,15 @@ static void test_http_server(struct mg_mgr *mgr) {
|
||||
#endif
|
||||
ASSERT(c != NULL);
|
||||
ASSERT (mg_send(c, "NADA", 0)); // check mg_send allows len=0
|
||||
s_poll_done = false;
|
||||
pthread_create(&thread_id, NULL, poll_thread,
|
||||
mgr); // simpler this way, no concurrency anyway
|
||||
MG_DEBUG(("CURL"));
|
||||
ASSERT(system(cmd) == 0); // wait for curl
|
||||
rc = system(cmd); // wait for curl
|
||||
MG_DEBUG(("MONGOOSE"));
|
||||
s_poll_done = true;
|
||||
pthread_join(thread_id, NULL); // wait for Mongoose
|
||||
ASSERT(rc == 0);
|
||||
MG_DEBUG(("DONE"));
|
||||
free(cmd);
|
||||
#endif
|
||||
@@ -529,7 +542,7 @@ static bool sntpms(struct mg_mgr *mgr, const char *url) {
|
||||
int64_t ms = 0;
|
||||
int i;
|
||||
mg_sntp_connect(mgr, url, sntpcb, &ms);
|
||||
for (i = 0; i < 50 && ms == 0; i++) {
|
||||
for (i = 0; i < POLL_LIMIT(50) && ms == 0; i++) {
|
||||
mg_mgr_poll(mgr, 0);
|
||||
usleep(10000); // 10 ms. Slow down poll loop to ensure packet transit
|
||||
}
|
||||
|
||||
+220
-73
@@ -156,6 +156,10 @@ static void test_http_get_var(void) {
|
||||
|
||||
body = mg_str("key=broken%2x");
|
||||
ASSERT(mg_http_get_var(&body, "key", buf, sizeof(buf)) == -3);
|
||||
memset(buf, 'x', sizeof(buf));
|
||||
body = mg_str("access_token=a%zz");
|
||||
ASSERT(mg_http_get_var(&body, "access_token", buf, sizeof(buf)) == -3);
|
||||
ASSERT(memchr(buf, '\0', sizeof(buf)) != NULL);
|
||||
ASSERT(mg_http_get_var(&body, "inexistent", buf, sizeof(buf)) == -4);
|
||||
body = mg_str("key=%");
|
||||
ASSERT(mg_http_get_var(&body, "key", buf, sizeof(buf)) == -3);
|
||||
@@ -822,7 +826,16 @@ static void test_mqtt(void) {
|
||||
static void eh1(struct mg_connection *c, int ev, void *ev_data) {
|
||||
struct mg_tls_opts *topts = (struct mg_tls_opts *) c->fn_data;
|
||||
if (ev == MG_EV_ACCEPT && topts != NULL) mg_tls_init(c, topts);
|
||||
if (ev == MG_EV_HTTP_MSG) {
|
||||
if (ev == MG_EV_HTTP_HDRS &&
|
||||
mg_match(((struct mg_http_message *) ev_data)->uri, mg_str("/big.bin"),
|
||||
NULL)) {
|
||||
// mg_http_serve_upload: streams big uploads, called from MG_EV_HTTP_HDRS
|
||||
struct mg_http_serve_opts sopts;
|
||||
memset(&sopts, 0, sizeof(sopts));
|
||||
sopts.root_dir = "./data";
|
||||
sopts.enable_upload = true;
|
||||
mg_http_serve_upload(c, (struct mg_http_message *) ev_data, &sopts);
|
||||
} else if (ev == MG_EV_HTTP_MSG) {
|
||||
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
||||
MG_INFO(("[%.*s %.*s] message len %d", (int) hm->method.len, hm->method.buf,
|
||||
(int) hm->uri.len, hm->uri.buf, (int) hm->message.len));
|
||||
@@ -853,6 +866,7 @@ static void eh1(struct mg_connection *c, int ev, void *ev_data) {
|
||||
memset(&sopts, 0, sizeof(sopts));
|
||||
sopts.root_dir = ".";
|
||||
sopts.extra_headers = "A: B\r\nE: F\r\n";
|
||||
sopts.enable_dir_listing = true;
|
||||
mg_http_serve_dir(c, hm, &sopts);
|
||||
} else if (mg_match(hm->uri, mg_str("/servefile"), NULL)) {
|
||||
struct mg_http_serve_opts sopts;
|
||||
@@ -870,6 +884,8 @@ static void eh1(struct mg_connection *c, int ev, void *ev_data) {
|
||||
sopts.root_dir = "./data";
|
||||
sopts.ssi_pattern = "#.shtml";
|
||||
sopts.extra_headers = "C: D\r\n";
|
||||
sopts.enable_delete = true;
|
||||
sopts.enable_upload = true;
|
||||
mg_http_serve_dir(c, hm, &sopts);
|
||||
}
|
||||
} else if (ev == MG_EV_WS_OPEN) {
|
||||
@@ -963,7 +979,7 @@ static void wcb(struct mg_connection *c, int ev, void *ev_data) {
|
||||
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
||||
struct mg_str *wsproto = mg_http_get_header(hm, "Sec-WebSocket-Protocol");
|
||||
ASSERT(wsproto != NULL);
|
||||
mg_ws_send(c, "hello", 0, 0);
|
||||
mg_ws_send(c, "", 0, WEBSOCKET_OP_TEXT);
|
||||
mg_ws_printf(c, WEBSOCKET_OP_BINARY, "%.3s", "boo!!!!");
|
||||
mg_ws_printf(c, WEBSOCKET_OP_BINARY, "%s", "foobar");
|
||||
mg_ws_send(c, "", 0, WEBSOCKET_OP_PING);
|
||||
@@ -979,6 +995,15 @@ static void wcb(struct mg_connection *c, int ev, void *ev_data) {
|
||||
}
|
||||
}
|
||||
|
||||
static void wbad(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_WS_OPEN) {
|
||||
mg_ws_send(c, "ABC", 3, WEBSOCKET_OP_CONTINUE);
|
||||
} else if (ev == MG_EV_CLOSE) {
|
||||
*(int *) c->fn_data = 1;
|
||||
}
|
||||
(void) ev_data;
|
||||
}
|
||||
|
||||
static void ew2(struct mg_connection *c, int ev, void *ev_data) {
|
||||
size_t size = 65 * 1024 + 737;
|
||||
if (ev == MG_EV_WS_OPEN) {
|
||||
@@ -1024,6 +1049,11 @@ static void test_ws(void) {
|
||||
for (i = 0; i < 1000 && done == 0; i++) mg_mgr_poll(&mgr, 1);
|
||||
ASSERT(done == 1);
|
||||
|
||||
done = 0;
|
||||
mg_ws_connect(&mgr, url, wbad, &done, NULL);
|
||||
for (i = 0; i < 30 && done == 0; i++) mg_mgr_poll(&mgr, 1);
|
||||
ASSERT(done == 1);
|
||||
|
||||
mg_mgr_free(&mgr);
|
||||
ASSERT(mgr.conns == NULL);
|
||||
}
|
||||
@@ -1279,16 +1309,39 @@ ASSERT(system("touch 'dirtest/a<b&c>.txt'") == 0);
|
||||
#endif
|
||||
ASSERT(fetch(&mgr, buf, url, "GET /dirtest/ HTTP/1.0\n\n") == 200);
|
||||
MG_DEBUG(("%s", buf));
|
||||
ASSERT(mgstrstr(mg_str(buf), mg_str(">Index of /dirtest/<")) != NULL);
|
||||
ASSERT(mgstrstr(mg_str(buf), mg_str(">fuzz.c<")) != NULL);
|
||||
ASSERT(mgstrstr(mg_str(buf), mg_str("fuzz.c")) != NULL);
|
||||
#if MG_ARCH == MG_ARCH_UNIX
|
||||
ASSERT(mgstrstr(mg_str(buf), mg_str(">a<b&c>.txt<")) != NULL);
|
||||
ASSERT(mgstrstr(mg_str(buf), mg_str("a<b&c>.txt")) != NULL);
|
||||
if (system("rm 'dirtest/a<b&c>.txt'") == 0) (void) 0;
|
||||
#endif
|
||||
ASSERT(cmpheader(buf, "A", "B"));
|
||||
ASSERT(!cmpheader(buf, "C", "D"));
|
||||
ASSERT(cmpheader(buf, "E", "F"));
|
||||
|
||||
{
|
||||
// mg_http_serve_dir: allow_upload, small file first (buffered), then a
|
||||
// big one (mg_http_serve_upload, streamed - see the MG_EV_HTTP_HDRS
|
||||
// branch in eh1), then allow_delete
|
||||
struct mg_str big = mg_file_read(&mg_fs_posix, "mongoose.c");
|
||||
struct mg_str got;
|
||||
ASSERT(big.len > MG_IO_SIZE);
|
||||
ASSERT(fetch(&mgr, buf, url,
|
||||
"POST /del_me.txt HTTP/1.0\r\nContent-Length: 1\r\n\r\nx") ==
|
||||
200);
|
||||
ASSERT(fetch(&mgr, buf, url, "GET /del_me.txt HTTP/1.0\n\n") == 200);
|
||||
ASSERT(fetch(&mgr, buf, url,
|
||||
"POST /big.bin HTTP/1.0\r\nContent-Length: %d\r\n\r\n%.*s",
|
||||
(int) big.len, (int) big.len, big.buf) == 200);
|
||||
got = mg_file_read(&mg_fs_posix, "data/big.bin");
|
||||
ASSERT(got.len == big.len && memcmp(got.buf, big.buf, big.len) == 0);
|
||||
mg_free((void *) got.buf);
|
||||
mg_free((void *) big.buf);
|
||||
remove("data/big.bin");
|
||||
ASSERT(fetch(&mgr, buf, url, "DELETE /del_me.txt HTTP/1.0\n\n") == 200);
|
||||
ASSERT(fetch(&mgr, buf, url, "GET /del_me.txt HTTP/1.0\n\n") == 404);
|
||||
ASSERT(fetch(&mgr, buf, url, "DELETE /del_me.txt HTTP/1.0\n\n") == 404);
|
||||
}
|
||||
|
||||
{
|
||||
// Credentials
|
||||
struct mg_http_message hm;
|
||||
@@ -1758,6 +1811,14 @@ static void test_http_pipeline(void) {
|
||||
for (i = 0; i < 20; i++) mg_mgr_poll(&mgr, 1);
|
||||
ASSERT(ok == 1);
|
||||
ASSERT(ok2 == 1);
|
||||
// A bodyless POST must not consume the following pipelined request
|
||||
ok = ok2 = 0;
|
||||
c = mg_http_connect(&mgr, url, f6, (void *) &ok2);
|
||||
mg_printf(c, "POST /x HTTP/1.1\r\nHost: h\r\n\r\n"
|
||||
"GET /next HTTP/1.1\r\nHost: h\r\n\r\n");
|
||||
for (i = 0; i < 20; i++) mg_mgr_poll(&mgr, 1);
|
||||
ASSERT(ok == 2);
|
||||
ASSERT(ok2 == 2);
|
||||
// MG_INFO(("-----> [%d] [%d]", ok, ok2));
|
||||
mg_mgr_free(&mgr);
|
||||
ASSERT(mgr.conns == NULL);
|
||||
@@ -3078,26 +3139,83 @@ static void uc(struct mg_connection *c, int ev, void *ev_data) {
|
||||
}
|
||||
}
|
||||
|
||||
static int s_su_done;
|
||||
static int s_su_done; // 1: upload ended, -1: upload rejected
|
||||
static int s_su_end; // Number of end calls
|
||||
|
||||
static void su_cb(struct mg_connection *c, const char *errmsg) {
|
||||
s_su_done = errmsg ? -1 : 1;
|
||||
mg_http_reply(c, errmsg ? 400 : 200, "", errmsg ? errmsg : "ok\n");
|
||||
c->is_draining = 1;
|
||||
// mg_http_stream_body() callback, saves the body to a file named as the URI
|
||||
static bool su_cb(struct mg_http_message *hm, struct mg_str *data, void **p) {
|
||||
if (hm != NULL) { // Start
|
||||
char path[100];
|
||||
struct mg_str name = mg_str_n(hm->uri.buf + 1, hm->uri.len - 1);
|
||||
*p = NULL;
|
||||
if (!mg_path_is_sane(name)) {
|
||||
s_su_done = -1;
|
||||
return false;
|
||||
}
|
||||
mg_snprintf(path, sizeof(path), "./%.*s", (int) name.len, name.buf);
|
||||
*p = mg_fs_open(&mg_fs_posix, path, MG_FS_WRITE);
|
||||
return *p != NULL;
|
||||
} else if (data != NULL) { // Next chunk
|
||||
struct mg_fd *fd = (struct mg_fd *) *p;
|
||||
return fd != NULL && fd->fs->wr(fd->fd, data->buf, data->len) == data->len;
|
||||
}
|
||||
s_su_end++; // End, also called when the connection drops
|
||||
if (*p != NULL) mg_fs_close((struct mg_fd *) *p);
|
||||
*p = NULL;
|
||||
if (s_su_done == 0) s_su_done = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void su(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_HTTP_HDRS) {
|
||||
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
||||
struct mg_str name = mg_str_n(hm->uri.buf + 1, hm->uri.len - 1);
|
||||
mg_http_start_upload(c, hm, name, mg_str("."), &mg_fs_posix, su_cb);
|
||||
mg_http_stream_body(c, (struct mg_http_message *) ev_data, su_cb, NULL);
|
||||
} else if (ev == MG_EV_HTTP_MSG) { // Only for requests that were not streamed
|
||||
mg_http_reply(c, 400, "", "not streamed\n");
|
||||
}
|
||||
}
|
||||
|
||||
static void cu(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_CONNECT)
|
||||
mg_printf(c, "POST %s HTTP/1.0\r\nContent-Length: 8\r\n\r\nfoo\nbar\n",
|
||||
(char *) c->fn_data);
|
||||
// Client that announces a large body, sends a few bytes and stays silent
|
||||
static void cd(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_CONNECT) {
|
||||
mg_printf(c, "POST /su_drop.txt HTTP/1.0\r\nContent-Length: 100000\r\n\r\nfoo\n");
|
||||
}
|
||||
(void) ev_data;
|
||||
}
|
||||
|
||||
static char s_cr_buf[4096]; // Response body streamed by the client
|
||||
static size_t s_cr_len;
|
||||
static int s_cr_end;
|
||||
|
||||
static bool cr_cb(struct mg_http_message *hm, struct mg_str *data, void **p) {
|
||||
(void) p;
|
||||
if (hm != NULL) {
|
||||
s_cr_len = 0;
|
||||
} else if (data != NULL) {
|
||||
ASSERT(s_cr_len + data->len <= sizeof(s_cr_buf));
|
||||
memcpy(s_cr_buf + s_cr_len, data->buf, data->len);
|
||||
s_cr_len += data->len;
|
||||
} else {
|
||||
s_cr_end++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Client that streams the response body with mg_http_stream_body()
|
||||
static void cr(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_CONNECT) {
|
||||
mg_printf(c, "GET / HTTP/1.0\r\n\r\n");
|
||||
} else if (ev == MG_EV_HTTP_HDRS) {
|
||||
ASSERT(mg_http_stream_body(c, (struct mg_http_message *) ev_data, cr_cb,
|
||||
NULL));
|
||||
}
|
||||
}
|
||||
|
||||
static void cs(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_HTTP_MSG) {
|
||||
char body[3000];
|
||||
memset(body, 'x', sizeof(body));
|
||||
mg_http_reply(c, 200, "", "%.*s", (int) sizeof(body), body);
|
||||
}
|
||||
(void) ev_data;
|
||||
}
|
||||
|
||||
@@ -3115,16 +3233,18 @@ static void test_http_upload(void) {
|
||||
mg_mgr_free(&mgr);
|
||||
ASSERT(mgr.conns == NULL);
|
||||
|
||||
// mg_http_start_upload: successful upload, file content verified
|
||||
// mg_http_stream_body: successful upload, file content verified
|
||||
{
|
||||
char buf[FETCH_BUF_SIZE];
|
||||
struct mg_str fc;
|
||||
remove("su_ok.txt");
|
||||
s_su_done = s_su_end = 0;
|
||||
mg_mgr_init(&mgr);
|
||||
mg_http_listen(&mgr, "http://127.0.0.1:12355", su, NULL);
|
||||
ASSERT(fetch(&mgr, buf, "http://127.0.0.1:12355",
|
||||
"POST /su_ok.txt HTTP/1.0\r\nContent-Length: 8\r\n\r\nfoo\nbar\n") ==
|
||||
200);
|
||||
ASSERT(s_su_done == 1 && s_su_end == 1);
|
||||
fc = mg_file_read(&mg_fs_posix, "su_ok.txt");
|
||||
ASSERT(mg_strcmp(fc, mg_str("foo\nbar\n")) == 0);
|
||||
mg_free((void *) fc.buf);
|
||||
@@ -3133,14 +3253,68 @@ static void test_http_upload(void) {
|
||||
ASSERT(mgr.conns == NULL);
|
||||
}
|
||||
|
||||
// mg_http_start_upload: path traversal rejected, callback gets error
|
||||
// mg_http_stream_body: path traversal rejected by the callback, "500" sent
|
||||
{
|
||||
s_su_done = 0;
|
||||
char buf[FETCH_BUF_SIZE];
|
||||
s_su_done = s_su_end = 0;
|
||||
mg_mgr_init(&mgr);
|
||||
mg_http_listen(&mgr, "http://127.0.0.1:12356", su, NULL);
|
||||
mg_http_connect(&mgr, "http://127.0.0.1:12356", cu, (void *) "/../evil.txt");
|
||||
for (i = 0; i < 50 && !s_su_done; i++) mg_mgr_poll(&mgr, 5);
|
||||
ASSERT(s_su_done == -1);
|
||||
ASSERT(fetch(&mgr, buf, "http://127.0.0.1:12356",
|
||||
"POST /../evil.txt HTTP/1.0\r\nContent-Length: 8\r\n\r\nfoo\nbar\n") ==
|
||||
500);
|
||||
ASSERT(s_su_done == -1 && s_su_end == 1);
|
||||
ASSERT(fopen("../evil.txt", "r") == NULL);
|
||||
mg_mgr_free(&mgr);
|
||||
ASSERT(mgr.conns == NULL);
|
||||
}
|
||||
|
||||
// mg_http_stream_body: chunked request is not streamed, caller replies "400"
|
||||
{
|
||||
char buf[FETCH_BUF_SIZE];
|
||||
s_su_done = s_su_end = 0;
|
||||
remove("su_chunked.txt");
|
||||
mg_mgr_init(&mgr);
|
||||
mg_http_listen(&mgr, "http://127.0.0.1:12393", su, NULL);
|
||||
ASSERT(fetch(&mgr, buf, "http://127.0.0.1:12393",
|
||||
"POST /su_chunked.txt HTTP/1.1\r\n"
|
||||
"Transfer-Encoding: chunked\r\n\r\n"
|
||||
"3\r\nfoo\r\n0\r\n\r\n") == 400);
|
||||
ASSERT(s_su_done == 0 && s_su_end == 0); // The callback was never called
|
||||
ASSERT(fopen("su_chunked.txt", "r") == NULL);
|
||||
mg_mgr_free(&mgr);
|
||||
ASSERT(mgr.conns == NULL);
|
||||
}
|
||||
|
||||
// mg_http_stream_body: connection drops mid-body, the end call still happens
|
||||
{
|
||||
struct mg_connection *cc;
|
||||
s_su_done = s_su_end = 0;
|
||||
remove("su_drop.txt");
|
||||
mg_mgr_init(&mgr);
|
||||
mg_http_listen(&mgr, "http://127.0.0.1:12391", su, NULL);
|
||||
cc = mg_http_connect(&mgr, "http://127.0.0.1:12391", cd, NULL);
|
||||
ASSERT(cc != NULL);
|
||||
for (i = 0; i < 20; i++) mg_mgr_poll(&mgr, 5);
|
||||
ASSERT(s_su_end == 0); // Still waiting for the rest of the body
|
||||
cc->is_closing = 1;
|
||||
for (i = 0; i < 20; i++) mg_mgr_poll(&mgr, 5);
|
||||
ASSERT(s_su_end == 1);
|
||||
remove("su_drop.txt");
|
||||
mg_mgr_free(&mgr);
|
||||
ASSERT(mgr.conns == NULL);
|
||||
}
|
||||
|
||||
// mg_http_stream_body on a client connection: response body is streamed
|
||||
{
|
||||
s_cr_end = 0;
|
||||
s_cr_len = 0;
|
||||
mg_mgr_init(&mgr);
|
||||
mg_http_listen(&mgr, "http://127.0.0.1:12392", cs, NULL);
|
||||
mg_http_connect(&mgr, "http://127.0.0.1:12392", cr, NULL);
|
||||
for (i = 0; i < 50 && s_cr_end == 0; i++) mg_mgr_poll(&mgr, 5);
|
||||
ASSERT(s_cr_end == 1);
|
||||
ASSERT(s_cr_len == 3000);
|
||||
ASSERT(s_cr_buf[0] == 'x' && s_cr_buf[2999] == 'x');
|
||||
mg_mgr_free(&mgr);
|
||||
ASSERT(mgr.conns == NULL);
|
||||
}
|
||||
@@ -3177,7 +3351,7 @@ static void eY(struct mg_connection *c, int ev, void *ev_data) {
|
||||
c->data[0]++;
|
||||
if (c->data[0] == 10) mg_send(c, "a", 1);
|
||||
if (c->data[0] == 12) mg_send(c, "bc", 2);
|
||||
if (c->data[0] == 30) mg_send(c, "d", 1), c->is_resp = 0, c->data[0] = 0;
|
||||
if (c->data[0] == 30) mg_send(c, "d", 1), c->pfn_data = NULL, c->data[0] = 0;
|
||||
}
|
||||
(void) ev_data;
|
||||
}
|
||||
@@ -3396,6 +3570,7 @@ static void eh7(struct mg_connection *c, int ev, void *ev_data) {
|
||||
memset(&sopts, 0, sizeof(sopts));
|
||||
sopts.root_dir = "/";
|
||||
sopts.fs = &mg_fs_packed;
|
||||
sopts.enable_dir_listing = true;
|
||||
mg_mem_files = mg_packed_files;
|
||||
mg_http_serve_dir(c, hm, &sopts);
|
||||
}
|
||||
@@ -3565,6 +3740,7 @@ static void h7(struct mg_connection *c, int ev, void *ev_data) {
|
||||
struct mg_http_serve_opts opts;
|
||||
memset(&opts, 0, sizeof(opts));
|
||||
opts.root_dir = "./data,/foo=./dirtest";
|
||||
opts.enable_dir_listing = true;
|
||||
mg_http_serve_dir(c, hm, &opts);
|
||||
}
|
||||
}
|
||||
@@ -4625,23 +4801,7 @@ static struct mg_field test_files_fields[] = {
|
||||
{NULL, MG_VAL_INT, NULL, 0},
|
||||
};
|
||||
static struct mg_field_set test_files_set = {
|
||||
"files", test_files_fields, NULL, &s_test_file_index, test_upload_dir, NULL};
|
||||
static struct test_file_entry s_delete_file;
|
||||
static char s_deleted_file[sizeof(s_delete_file.name)];
|
||||
static char s_uploaded_file[sizeof(s_delete_file.name)];
|
||||
static struct mg_field_set *s_delete_file_set;
|
||||
static bool delete_file_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
if (op == MG_DASH_READ) return mg_dash_dir_read(s_delete_file_set, u);
|
||||
if (op == MG_DASH_WRITE) {
|
||||
mg_snprintf(s_uploaded_file, sizeof(s_uploaded_file), "%s",
|
||||
s_delete_file.name);
|
||||
}
|
||||
if (op == MG_DASH_DELETE) {
|
||||
mg_snprintf(s_deleted_file, sizeof(s_deleted_file), "%s",
|
||||
s_delete_file.name);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
"files", test_files_fields, NULL, &s_test_file_index, NULL};
|
||||
static bool arr_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
(void) u;
|
||||
if (op == MG_DASH_READ) {
|
||||
@@ -4688,20 +4848,18 @@ static void test_dash(void) {
|
||||
{"admin", MG_VAL_INT, &admin, sizeof(admin)},
|
||||
{NULL, MG_VAL_INT, NULL, 0},
|
||||
};
|
||||
struct mg_field_set set1 = {"set1", fields1, set1_fn, NULL, NULL, NULL};
|
||||
struct mg_field_set set2 = {"set2", fields2, set2_fn, NULL, NULL, NULL};
|
||||
struct mg_field_set set3 = {"set3", fields3, set3_fn, NULL, NULL, NULL};
|
||||
struct mg_field_set set1 = {"set1", fields1, set1_fn, NULL, NULL};
|
||||
struct mg_field_set set2 = {"set2", fields2, set2_fn, NULL, NULL};
|
||||
struct mg_field_set set3 = {"set3", fields3, set3_fn, NULL, NULL};
|
||||
struct mg_field arr_fields[] = {
|
||||
{"val", MG_VAL_INT, &s_arr_val, sizeof(s_arr_val)},
|
||||
{NULL, MG_VAL_INT, NULL, 0},
|
||||
};
|
||||
struct mg_field_set arr_set = {"arr", arr_fields, arr_fn, &s_arr_index, NULL,
|
||||
NULL};
|
||||
struct mg_field_set arr_set = {"arr", arr_fields, arr_fn, &s_arr_index, NULL};
|
||||
const char *get_all_expected =
|
||||
"{\"arr\":17,\"set3\":{\"admin\":7},"
|
||||
"\"set2\":{\"two\":false},"
|
||||
"\"set1\":{\"one\":1,\"three\":\"t: 1\"},"
|
||||
"\"files\":0}\n";
|
||||
"\"set1\":{\"one\":1,\"three\":\"t: 1\"}}\n";
|
||||
const char *set1_req = "POST /api/set HTTP/1.0\nContent-Length: 18\n\n"
|
||||
"{\"set1\":{\"one\":2}}";
|
||||
const char *set1_set3_req = "POST /api/set HTTP/1.0\n"
|
||||
@@ -5054,51 +5212,40 @@ static void test_dash(void) {
|
||||
ASSERT(mg_http_listen(&mgr2, url2, mg_dash_ev_handler, &dash2) != NULL);
|
||||
ASSERT(fetch(&mgr2, buf, url2, "GET /api/get HTTP/1.0\n\n") == 200);
|
||||
ASSERT(strstr(buf, files_probe) == NULL); // no files fieldset
|
||||
ASSERT(fetch(&mgr2, buf, url2, "GET /fs/files/test.txt HTTP/1.0\n\n") == 404);
|
||||
ASSERT(fetch(&mgr2, buf, url2, "GET /fs/test.txt HTTP/1.0\n\n") == 404);
|
||||
ASSERT(fetch(&mgr2, buf, url2,
|
||||
"POST /fs/files/test.txt HTTP/1.0\nContent-Length: 5\n\nhello") ==
|
||||
"POST /fs/test.txt HTTP/1.0\nContent-Length: 5\n\nhello") ==
|
||||
404);
|
||||
mg_mgr_free(&mgr2);
|
||||
}
|
||||
|
||||
// Test files fieldset with get_dir: /fs/ endpoints active
|
||||
// Test the built-in file manager (struct mg_dash::files_dir): /fs/ active
|
||||
{
|
||||
const char *url3 = "http://localhost:26354";
|
||||
struct mg_mgr mgr3;
|
||||
struct mg_dash dash3;
|
||||
static int idx3;
|
||||
static struct mg_field ff3[] = {
|
||||
{"name", MG_VAL_STR, s_delete_file.name, sizeof(s_delete_file.name)},
|
||||
{"size", MG_VAL_UINT64, &s_delete_file.size, 0},
|
||||
{NULL, MG_VAL_INT, NULL, 0},
|
||||
};
|
||||
static struct mg_field_set fset3 = {"files", ff3, delete_file_fn, &idx3,
|
||||
test_upload_dir, NULL};
|
||||
struct mg_str uploaded;
|
||||
memset(&dash3, 0, sizeof(dash3));
|
||||
s_deleted_file[0] = '\0';
|
||||
s_uploaded_file[0] = '\0';
|
||||
s_delete_file_set = &fset3;
|
||||
MG_DASH_ADD_FIELD_SET(&dash3, &fset3);
|
||||
dash3.files_dir = test_upload_dir;
|
||||
mg_mgr_init(&mgr3);
|
||||
mg_mem_files = mg_packed_files;
|
||||
ASSERT(mg_http_listen(&mgr3, url3, mg_dash_ev_handler, &dash3) != NULL);
|
||||
ASSERT(fetch(&mgr3, buf, url3, "GET /api/get HTTP/1.0\n\n") == 200);
|
||||
ASSERT(strstr(buf, files_probe) != NULL); // files fieldset present
|
||||
ASSERT(strstr(buf, files_probe) == NULL); // files manager is not a fieldset
|
||||
ASSERT(fetch(&mgr3, buf, url3,
|
||||
"DELETE /fs/files/nofile.txt HTTP/1.0\n\n") == 200);
|
||||
ASSERT(strcmp(s_deleted_file, "nofile.txt") == 0);
|
||||
"DELETE /fs/nofile.txt HTTP/1.0\n\n") == 404);
|
||||
ASSERT(fetch(&mgr3, buf, url3,
|
||||
"DELETE /fs/files/..%2Fevil.txt HTTP/1.0\n\n") == 400);
|
||||
ASSERT(strcmp(s_deleted_file, "nofile.txt") == 0);
|
||||
"DELETE /fs/..%2Fevil.txt HTTP/1.0\n\n") == 400);
|
||||
ASSERT(fetch(&mgr3, buf, url3,
|
||||
"PUT /fs/files/test.bin HTTP/1.0\nContent-Length: 4\n\ndata") ==
|
||||
"PUT /fs/test.bin HTTP/1.0\nContent-Length: 4\n\ndata") ==
|
||||
200);
|
||||
ASSERT(strcmp(s_uploaded_file, "test.bin") == 0);
|
||||
uploaded = mg_file_read(&mg_fs_posix, "mongoose_dash_test/test.bin");
|
||||
ASSERT(mg_strcmp(uploaded, mg_str("data")) == 0);
|
||||
mg_free((void *) uploaded.buf);
|
||||
ASSERT(fetch(&mgr3, buf, url3,
|
||||
"PUT /fs/files/..%2Fevil.bin HTTP/1.0\nContent-Length: "
|
||||
"PUT /fs/..%2Fevil.bin HTTP/1.0\nContent-Length: "
|
||||
"4\n\ndata") == 400);
|
||||
ASSERT(strcmp(s_uploaded_file, "test.bin") == 0);
|
||||
ASSERT(fetch(&mgr3, buf, url3, "GET /api/get/files/0 HTTP/1.0\n\n") == 200);
|
||||
ASSERT(fetch(&mgr3, buf, url3, "GET /fs/ HTTP/1.0\n\n") == 200);
|
||||
ASSERT(strstr(buf, test_bin_probe) != NULL);
|
||||
mg_mgr_free(&mgr3);
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ static bool arr_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
}
|
||||
|
||||
static struct mg_field_set field_set_arr = {
|
||||
"event", fields_arr, arr_fn, &s_index, NULL, NULL,
|
||||
"event", fields_arr, arr_fn, &s_index, NULL,
|
||||
};
|
||||
|
||||
void mg_dash_init(struct mg_mgr *mgr) {
|
||||
|
||||
@@ -27,7 +27,7 @@ static struct mg_field fields_actions[] = {
|
||||
{NULL, MG_VAL_INT, NULL, 0},
|
||||
};
|
||||
static struct mg_field_set set_actions = {"actions", fields_actions, actions_fn,
|
||||
NULL, NULL, NULL};
|
||||
NULL, NULL};
|
||||
|
||||
// Control panel
|
||||
// s_led1, s_led2, s_led3 are used to communicate LED status
|
||||
@@ -43,7 +43,7 @@ static struct mg_field fields_leds[] = {
|
||||
{NULL, MG_VAL_INT, NULL, 0},
|
||||
};
|
||||
static struct mg_field_set set_leds = {"leds", fields_leds, leds_fn,
|
||||
NULL, NULL, NULL};
|
||||
NULL, NULL};
|
||||
|
||||
// Read-only device Metrics
|
||||
static int s_ram = 32, s_cpu = 7;
|
||||
@@ -66,7 +66,7 @@ static struct mg_field fields_metrics[] = {
|
||||
};
|
||||
|
||||
static struct mg_field_set set_metrics = {"metrics", fields_metrics, metrics_fn,
|
||||
NULL, NULL, NULL};
|
||||
NULL, NULL};
|
||||
|
||||
// Read-write device settings
|
||||
static bool s_enable_login = false;
|
||||
@@ -105,7 +105,7 @@ static struct mg_field fields_settings[] = {
|
||||
};
|
||||
|
||||
static struct mg_field_set set_settings = {
|
||||
"settings", fields_settings, settings_fn, NULL, NULL, NULL};
|
||||
"settings", fields_settings, settings_fn, NULL, NULL};
|
||||
|
||||
#define NUM_POINTS_GRAPH1 7 // How many graph1 data points to send
|
||||
|
||||
@@ -150,7 +150,7 @@ static bool graph1_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
return true;
|
||||
}
|
||||
static struct mg_field_set set_graph1 = {"graph1", fields_graph1, graph1_fn,
|
||||
NULL, NULL, NULL};
|
||||
NULL, NULL};
|
||||
|
||||
#define NUM_POINTS_GRAPH2 100 // How many graph2 data points to send
|
||||
static char s_graph2_data[NUM_POINTS_GRAPH2 * 4 + 2 + 1];
|
||||
@@ -187,7 +187,7 @@ static bool graph2_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
return op == MG_DASH_READ || op == MG_DASH_WRITE;
|
||||
}
|
||||
static struct mg_field_set set_graph2 = {"graph2", fields_graph2, graph2_fn,
|
||||
NULL, NULL, NULL};
|
||||
NULL, NULL};
|
||||
|
||||
static int authenticate(char *user, size_t userlen, const char *pass) {
|
||||
int level = 0; // Authentication failure
|
||||
@@ -201,42 +201,14 @@ static int authenticate(char *user, size_t userlen, const char *pass) {
|
||||
return level;
|
||||
}
|
||||
|
||||
static struct file {
|
||||
int index;
|
||||
char name[64];
|
||||
size_t size;
|
||||
uint64_t checksum;
|
||||
} s_file;
|
||||
static struct mg_field_set set_files;
|
||||
|
||||
static bool get_dir(const struct mg_dash_user *u, char *buf, size_t len) {
|
||||
(void) u;
|
||||
static bool files_dir(const struct mg_dash_user *u, char *buf, size_t len) {
|
||||
(void) u; // Same dir for every user. Key off u->name for per-user dirs
|
||||
mg_snprintf(buf, len, "%s", "/tmp/dashboard");
|
||||
return true;
|
||||
}
|
||||
|
||||
static struct mg_field fields_files[] = {
|
||||
{"name", MG_VAL_STR, s_file.name, sizeof(s_file.name)},
|
||||
{"size", MG_VAL_UINT64, &s_file.size, 0},
|
||||
{"checksum", MG_VAL_UINT64, &s_file.checksum, sizeof(s_file.checksum)},
|
||||
{NULL, MG_VAL_INT, NULL, 0},
|
||||
};
|
||||
|
||||
// Custom reader: let the framework fill "name" and "size", then add our
|
||||
// own field. A real implementation would hash the file instead of
|
||||
// hardcoding zero
|
||||
static bool files_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
if (op != MG_DASH_READ) return false;
|
||||
if (!mg_dash_dir_read(&set_files, u)) return false;
|
||||
s_file.checksum = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
static struct mg_field_set set_files = {"files", fields_files, files_fn,
|
||||
&s_file.index, get_dir, NULL};
|
||||
|
||||
void mg_dash_init(struct mg_mgr *mgr) {
|
||||
MG_DASH_ADD_FIELD_SET(&s_dash, &set_files);
|
||||
s_dash.files_dir = files_dir; // Built-in file manager, see mg_dash.h
|
||||
MG_DASH_ADD_FIELD_SET(&s_dash, &set_leds);
|
||||
MG_DASH_ADD_FIELD_SET(&s_dash, &set_metrics);
|
||||
MG_DASH_ADD_FIELD_SET(&s_dash, &set_settings);
|
||||
@@ -246,6 +218,7 @@ void mg_dash_init(struct mg_mgr *mgr) {
|
||||
|
||||
#if MG_ARCH == MG_ARCH_UNIX
|
||||
// Create demo files in the upload directory
|
||||
mkdir("/tmp", 0755);
|
||||
mkdir("/tmp/dashboard", 0755);
|
||||
mg_file_printf(&mg_fs_posix, "/tmp/dashboard/device-config.json",
|
||||
"{\"model\":\"example\",\"fw\":\"1.0\"}");
|
||||
@@ -255,6 +228,7 @@ void mg_dash_init(struct mg_mgr *mgr) {
|
||||
|
||||
mg_mem_files = mg_packed_files;
|
||||
mg_http_listen(mgr, MG_HTTP_ADDR, mg_dash_ev_handler, &s_dash);
|
||||
mg_http_listen(mgr, MG_HTTPS_ADDR, mg_dash_ev_handler, &s_dash);
|
||||
}
|
||||
|
||||
void mg_dash_poll(struct mg_mgr *mgr) {
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
leds: { led1: true, led2: false, led3: false },
|
||||
settings: { volume: 12, log_level: 3, name: 'Galway', enable_login: true, ota_version: '1.2.3', ota_status: 'No checks yet', ota_url: 'http://my-product.com/ota.json', ota_interval: 30 },
|
||||
metrics: { temperature: 1.2, cpu: 4, ram: 5, version: '1.2.3' },
|
||||
files: {start: 0, end: 100, data: [{name: 'device-log-2026-04-25.txt', size: 8625563}]},
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -110,6 +109,7 @@
|
||||
Dashboard.on('ready', function() {
|
||||
setupAutoLogout();
|
||||
document.body.style.visibility = 'visible';
|
||||
refreshFiles();
|
||||
});
|
||||
Dashboard.login().catch(err => showLogin(true));
|
||||
|
||||
@@ -170,13 +170,80 @@
|
||||
]);
|
||||
};
|
||||
|
||||
// Intercept change notifications: re-plot graphs, reload the file
|
||||
// list whenever its size changes (file uploaded or deleted)
|
||||
// Intercept change notifications: re-plot graphs
|
||||
Dashboard.on('change', args => {
|
||||
args?.graph1?.data && updateGraph1(args?.graph1?.data);
|
||||
args?.graph2?.data && updateGraph2(args?.graph2?.data);
|
||||
typeof args?.files === 'number' && Dashboard.call('get', { name: 'files', start: 0, end: 100 });
|
||||
});
|
||||
|
||||
// File manager: served directly by the built-in mg_dash file manager
|
||||
// (see struct mg_dash::files_dir), not by the generic data-repeat
|
||||
// binding, since the listing endpoint returns a plain JSON array
|
||||
const filesListEl = document.getElementById('files-list');
|
||||
const filesCountEl = document.getElementById('files-count');
|
||||
const filesUploadEl = document.getElementById('files-upload-input');
|
||||
|
||||
function renderFiles(list) {
|
||||
filesCountEl.textContent = list.length + ' Files';
|
||||
filesListEl.innerHTML = list.map(f => `
|
||||
<div class="file-row">
|
||||
<div class="file-info">
|
||||
<span class="file-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7Z" />
|
||||
<path d="M14 2v5h5" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="file-name">${f.name}</div>
|
||||
</div>
|
||||
<div class="file-size">${f.size}</div>
|
||||
<div class="file-actions">
|
||||
<a href="fs/${encodeURIComponent(f.name)}" target="_blank" class="btn btn-secondary">
|
||||
<svg viewBox="0 0 24 24" class="nav-icon" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M12 3v12" />
|
||||
<path d="m7 10 5 5 5-5" />
|
||||
<path d="M5 21h14" />
|
||||
</svg>
|
||||
</a>
|
||||
<button data-del="${encodeURIComponent(f.name)}" class="btn btn-secondary">
|
||||
<svg viewBox="0 0 24 24" class="nav-icon" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M3 6h18" />
|
||||
<path d="M8 6V4h8v2" />
|
||||
<path d="M19 6l-1 14H6L5 6" />
|
||||
<path d="M10 11v5" />
|
||||
<path d="M14 11v5" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>`).join('');
|
||||
filesListEl.querySelectorAll('[data-del]').forEach(btn => {
|
||||
btn.addEventListener('click', ev => {
|
||||
ev.preventDefault();
|
||||
fetch('fs/' + btn.dataset.del, { method: 'DELETE' }).then(refreshFiles);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function refreshFiles() {
|
||||
fetch('fs/')
|
||||
.then(r => r.ok ? r.json() : Promise.reject(r.statusText))
|
||||
.then(list => renderFiles(list.filter(f => !f.dir)))
|
||||
.catch(err => console.log('Files list failed', err));
|
||||
}
|
||||
|
||||
filesUploadEl.addEventListener('change', ev => {
|
||||
const f = ev.target.files[0];
|
||||
ev.target.value = '';
|
||||
if (!f) return;
|
||||
const reader = new FileReader();
|
||||
reader.readAsArrayBuffer(f);
|
||||
reader.onload = () => {
|
||||
fetch('fs/' + encodeURIComponent(f.name), { method: 'POST', body: reader.result })
|
||||
.then(refreshFiles)
|
||||
.catch(err => console.log('Upload failed', err));
|
||||
};
|
||||
});
|
||||
|
||||
});
|
||||
</script>
|
||||
<style>
|
||||
@@ -691,7 +758,7 @@ a, a:visited, a:link { text-decoration: none; }
|
||||
<div class="panel-title">
|
||||
<span>
|
||||
<span>File Manager</span>
|
||||
<span class="metric-status">${files.size ?? files.data.length} Files</span>
|
||||
<span class="metric-status" id="files-count">0 Files</span>
|
||||
</span>
|
||||
<div class="header-actions">
|
||||
<label class="btn btn-primary">
|
||||
@@ -701,56 +768,32 @@ a, a:visited, a:link { text-decoration: none; }
|
||||
<path d="M5 21h14" />
|
||||
</svg>
|
||||
Upload
|
||||
<input type="file" hidden data-upload="files" />
|
||||
<input type="file" hidden id="files-upload-input" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<div class="file-list" data-repeat="files.data" data-iterator="f">
|
||||
<div class="file-row">
|
||||
<div class="file-info">
|
||||
<span class="file-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7Z" />
|
||||
<path d="M14 2v5h5" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="file-name">${f.name}</div>
|
||||
</div>
|
||||
<div class="file-size">${f.size}</div>
|
||||
<div class="file-actions">
|
||||
<a href="fs/files/${encodeURIComponent(f.name)}" target="_blank" class="btn btn-secondary">
|
||||
<svg viewBox="0 0 24 24" class="nav-icon" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M12 3v12" />
|
||||
<path d="m7 10 5 5 5-5" />
|
||||
<path d="M5 21h14" />
|
||||
</svg>
|
||||
</a>
|
||||
<button onclick="fetch('fs/files/${encodeURIComponent(f.name)}', {method: 'DELETE'}); return false;" class="btn btn-secondary">
|
||||
<svg viewBox="0 0 24 24" class="nav-icon" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M3 6h18" />
|
||||
<path d="M8 6V4h8v2" />
|
||||
<path d="M19 6l-1 14H6L5 6" />
|
||||
<path d="M10 11v5" />
|
||||
<path d="M14 11v5" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="file-list" id="files-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="note">
|
||||
<p>The two default files are fake - you can delete them</p>
|
||||
<p>However the manager works - you can upload new files. They
|
||||
are uploaded to /tmp/ directory on the device.
|
||||
This requires stdio (fopen/fread/...) implemeneted.</p>
|
||||
<p>The easiest way to implement it is to use a filesystem like
|
||||
LittleFS on your internal or external flash
|
||||
and retarget the standard library to use it.</p>
|
||||
<p>See <a href="https://github.com/cpq/bare-metal-programming-guide/tree/main/templates/lfs/nucleo-h563zi">this example</a> on how LittleFS can be implemented on
|
||||
Nucleo-H563ZI internal flash partition.</p>
|
||||
<p>This file manager uses /tmp/dashboard/ directory.
|
||||
It works on any platform that supports
|
||||
standard file IO: fopen, fread, fwrite, fclose.
|
||||
This includes Linux/Mac/Windows.</p>
|
||||
<p>
|
||||
Mongoose provides a built-in LittleFS integration that
|
||||
makes stadard file IO work on embedded systems like STM32.
|
||||
For that, add "#define MG_ENABLE_LFS 1" to your
|
||||
mongoose_config.h
|
||||
</p>
|
||||
<p>See
|
||||
<a href="https://github.com/cesanta/embedded-web-file-manager">this ready-to-build example</a>
|
||||
which implements LittleFS on Nucleo-H563ZI internal flash. You
|
||||
can upload, delete and serve files on STM32 - which is
|
||||
a perfect use case for confuration files, keeping and viewing logs, etc.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -34,7 +34,7 @@ static struct mg_field fields_status[] = {
|
||||
};
|
||||
|
||||
static struct mg_field_set field_set_status = {
|
||||
"status", fields_status, status_fn, NULL, NULL, NULL,
|
||||
"status", fields_status, status_fn, NULL, NULL,
|
||||
};
|
||||
|
||||
void mg_dash_init(struct mg_mgr *mgr) {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# The following lines of boilerplate have to be in your project's
|
||||
# CMakeLists in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
project(mongoose-esp32-minimal)
|
||||
@@ -0,0 +1,23 @@
|
||||
THISDIR = $(realpath $(CURDIR))
|
||||
ROOTDIR = $(realpath $(CURDIR)/../../..)
|
||||
DOCKER ?= docker run --rm $(DA) -v $(ROOTDIR):$(ROOTDIR) -w $(THISDIR) espressif/idf
|
||||
CMD ?= idf.py build
|
||||
PORT ?= /dev/ttyUSB0
|
||||
|
||||
all: example
|
||||
|
||||
example:
|
||||
true
|
||||
|
||||
build: Makefile $(wildcard main/*)
|
||||
$(DOCKER) $(CMD)
|
||||
|
||||
flash:
|
||||
flash: CMD = idf.py flash
|
||||
flash: DA = --device $(PORT)
|
||||
flash: build
|
||||
|
||||
clean:
|
||||
test -d build && $(DOCKER) rm -rf build sdkconfig || true
|
||||
|
||||
.PHONY: build
|
||||
@@ -0,0 +1,74 @@
|
||||
# ESP32 minimal crash capture
|
||||
|
||||
ESP-IDF already captures the ESP32 equivalent of an ARM HardFault. Use the
|
||||
ESP-IDF panic handler and ESP-IDF core dump support instead of replacing the
|
||||
low-level exception path.
|
||||
|
||||
The panic handler captures the architecture-specific fault frame:
|
||||
|
||||
- Xtensa targets: PC, PS, A0..A15, SAR, EXCCAUSE, EXCVADDR, loop registers, and
|
||||
backtrace.
|
||||
- RISC-V targets: MEPC, RA, SP, MSTATUS, MCAUSE, MTVAL, MHARTID, GPRs, and
|
||||
backtrace.
|
||||
|
||||
Fatal classes include CPU exceptions, interrupt watchdog, task watchdog, cache
|
||||
errors, brownout, stack overflow, heap corruption, UBSAN checks, and assertions.
|
||||
|
||||
This example enables core dump to flash. No filesystem is involved: ESP-IDF
|
||||
writes directly to a raw partition table entry of type `data`, subtype
|
||||
`coredump`.
|
||||
|
||||
```csv
|
||||
coredump, data, coredump,, 128K
|
||||
```
|
||||
|
||||
At panic time, ESP-IDF serializes the crash state into that raw flash partition.
|
||||
On the next boot, the application can read it with the user-mode coredump APIs:
|
||||
|
||||
```c
|
||||
esp_reset_reason();
|
||||
esp_core_dump_get_panic_reason(reason, sizeof(reason));
|
||||
esp_core_dump_get_summary(summary);
|
||||
esp_core_dump_image_get(&addr, &size);
|
||||
esp_core_dump_image_erase();
|
||||
```
|
||||
|
||||
This example exposes:
|
||||
|
||||
- `/api/crash`: JSON metadata: reset reason, panic reason, crashed task, PC, and
|
||||
coredump size.
|
||||
- `/api/crash.bin`: raw ESP-IDF coredump image, suitable for offline decoding
|
||||
with the application ELF.
|
||||
|
||||
The raw coredump can include task stacks, TCBs, selected memory regions, and
|
||||
therefore customer-private data. Production upload must treat it as sensitive
|
||||
diagnostic material.
|
||||
|
||||
## Wizard integration notes
|
||||
|
||||
The Wizard ESP-IDF template should keep its existing `mongoose_init()` /
|
||||
`mongoose_poll()` structure and register the crash endpoints as custom API
|
||||
handlers. The relevant ESP-IDF pieces from this tutorial are:
|
||||
|
||||
```ini
|
||||
CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH=y
|
||||
CONFIG_ESP_COREDUMP_DATA_FORMAT_ELF=y
|
||||
CONFIG_ESP_COREDUMP_MAX_TASKS_NUM=16
|
||||
CONFIG_ESP_COREDUMP_STACK_SIZE=2048
|
||||
```
|
||||
|
||||
The ESP-IDF component needs `espcoredump` and `esp_partition`.
|
||||
|
||||
Wizard's current 4 MB OTA partition table leaves `0x10000` bytes after SPIFFS,
|
||||
so a 64 KB coredump partition fits without changing the app or SPIFFS sizes.
|
||||
The 128 KB partition used by this tutorial requires shrinking SPIFFS or one of
|
||||
the app slots.
|
||||
|
||||
```csv
|
||||
coredump, data, coredump,, 64K
|
||||
```
|
||||
|
||||
The WiFi code is not materially related to crash capture. Apart from where the
|
||||
credentials come from, the differences are retry policy, temporary event handler
|
||||
lifetime, WPA2/PMF station config, and whether the password is logged. Wizard
|
||||
can keep its existing WiFi code for this feature.
|
||||
@@ -0,0 +1,14 @@
|
||||
idf_component_register(SRCS "main.c"
|
||||
"wifi.c"
|
||||
"../../../../mongoose.c"
|
||||
INCLUDE_DIRS "."
|
||||
"../../../.."
|
||||
REQUIRES esp_event
|
||||
esp_netif
|
||||
esp_partition
|
||||
esp_wifi
|
||||
esp_timer
|
||||
espcoredump
|
||||
nvs_flash
|
||||
app_update)
|
||||
component_compile_options(-DHTTP_URL="http://0.0.0.0:80")
|
||||
@@ -0,0 +1,161 @@
|
||||
// Copyright (c) 2026 Cesanta Software Limited
|
||||
// All rights reserved
|
||||
|
||||
#include <stdlib.h>
|
||||
#include "esp_core_dump.h"
|
||||
#include "esp_err.h"
|
||||
#include "esp_partition.h"
|
||||
#include "esp_system.h"
|
||||
#include "mongoose.h"
|
||||
#include "sdkconfig.h"
|
||||
|
||||
#define WIFI_SSID "YOUR_WIFI_NETWORK_NAME" // SET THIS!
|
||||
#define WIFI_PASS "YOUR_WIFI_PASSWORD" // SET THIS!
|
||||
|
||||
#ifndef HTTP_URL
|
||||
#define HTTP_URL "http://0.0.0.0:80"
|
||||
#endif
|
||||
|
||||
#ifndef CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH
|
||||
#define CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH 0
|
||||
#endif
|
||||
|
||||
#ifndef ESP_PARTITION_SUBTYPE_DATA_COREDUMP
|
||||
#define ESP_PARTITION_SUBTYPE_DATA_COREDUMP 0x03
|
||||
#endif
|
||||
|
||||
struct crash_download {
|
||||
const esp_partition_t *partition;
|
||||
size_t offset;
|
||||
size_t size;
|
||||
size_t sent;
|
||||
};
|
||||
|
||||
static void crash_json(struct mg_connection *c) {
|
||||
#if CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH
|
||||
esp_core_dump_summary_t summary;
|
||||
char reason[200] = "";
|
||||
size_t address = 0, size = 0;
|
||||
esp_err_t err = esp_core_dump_image_get(&address, &size);
|
||||
esp_err_t sr = err == ESP_OK ? esp_core_dump_get_summary(&summary) : err;
|
||||
esp_err_t rr = err == ESP_OK ? esp_core_dump_get_panic_reason(
|
||||
reason, sizeof(reason)) : err;
|
||||
|
||||
mg_http_reply(c, 200, "Content-Type: application/json\r\n",
|
||||
"{%m:%s,%m:%d,%m:%u,%m:%u,%m:%m,%m:%m,%m:%d,%m:%d,%m:%m}\n",
|
||||
MG_ESC("present"), err == ESP_OK ? "true" : "false",
|
||||
MG_ESC("reset_reason"), (int) esp_reset_reason(),
|
||||
MG_ESC("address"), (unsigned) address, MG_ESC("size"),
|
||||
(unsigned) size, MG_ESC("panic_reason"),
|
||||
MG_ESC(rr == ESP_OK ? reason : ""), MG_ESC("task"),
|
||||
MG_ESC(sr == ESP_OK ? summary.exc_task : ""), MG_ESC("pc"),
|
||||
sr == ESP_OK ? (int) summary.exc_pc : 0, MG_ESC("error"),
|
||||
(int) err, MG_ESC("binary"), MG_ESC("/api/crash.bin"));
|
||||
#else
|
||||
mg_http_reply(c, 501, "Content-Type: application/json\r\n",
|
||||
"{%m:false,%m:%d,%m:%m}\n", MG_ESC("present"),
|
||||
MG_ESC("reset_reason"), (int) esp_reset_reason(),
|
||||
MG_ESC("error"), MG_ESC("coredump to flash is disabled"));
|
||||
#endif
|
||||
}
|
||||
|
||||
static void crash_send(struct mg_connection *c) {
|
||||
#if CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH
|
||||
struct crash_download *d = (struct crash_download *) c->fn_data;
|
||||
while (d != NULL && d->sent < d->size && c->send.len < 2048) {
|
||||
uint8_t buf[512];
|
||||
size_t left = d->size - d->sent;
|
||||
size_t len = left > sizeof(buf) ? sizeof(buf) : left;
|
||||
esp_err_t err = esp_partition_read(d->partition, d->offset + d->sent, buf,
|
||||
len);
|
||||
if (err != ESP_OK) {
|
||||
MG_ERROR(("esp_partition_read: %s", esp_err_to_name(err)));
|
||||
c->is_draining = 1;
|
||||
return;
|
||||
}
|
||||
mg_send(c, buf, len);
|
||||
d->sent += len;
|
||||
}
|
||||
if (d != NULL && d->sent >= d->size) {
|
||||
free(d);
|
||||
c->fn_data = NULL;
|
||||
c->is_draining = 1;
|
||||
}
|
||||
#else
|
||||
(void) c;
|
||||
#endif
|
||||
}
|
||||
|
||||
static void crash_bin(struct mg_connection *c) {
|
||||
#if CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH
|
||||
const esp_partition_t *p = esp_partition_find_first(
|
||||
ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_COREDUMP, NULL);
|
||||
struct crash_download *d;
|
||||
size_t address = 0, size = 0, offset = 0;
|
||||
esp_err_t err = esp_core_dump_image_get(&address, &size);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
mg_http_reply(c, 404, "Content-Type: application/json\r\n",
|
||||
"{%m:%m}\n", MG_ESC("error"), MG_ESC(esp_err_to_name(err)));
|
||||
} else if (p == NULL || address < p->address ||
|
||||
address + size > p->address + p->size) {
|
||||
mg_http_reply(c, 500, "Content-Type: application/json\r\n",
|
||||
"{%m:%m}\n", MG_ESC("error"),
|
||||
MG_ESC("invalid coredump partition"));
|
||||
} else if ((d = (struct crash_download *) calloc(1, sizeof(*d))) == NULL) {
|
||||
mg_http_reply(c, 500, "Content-Type: application/json\r\n",
|
||||
"{%m:%m}\n", MG_ESC("error"), MG_ESC("out of memory"));
|
||||
} else {
|
||||
offset = address - p->address;
|
||||
d->partition = p;
|
||||
d->offset = offset;
|
||||
d->size = size;
|
||||
c->fn_data = d;
|
||||
mg_printf(c,
|
||||
"HTTP/1.1 200 OK\r\n"
|
||||
"Content-Type: application/octet-stream\r\n"
|
||||
"Content-Length: %u\r\n"
|
||||
"Content-Disposition: attachment; filename=\"esp32-coredump."
|
||||
"bin\"\r\n"
|
||||
"\r\n",
|
||||
(unsigned) size);
|
||||
crash_send(c);
|
||||
}
|
||||
#else
|
||||
mg_http_reply(c, 501, "Content-Type: application/json\r\n",
|
||||
"{%m:%m}\n", MG_ESC("error"),
|
||||
MG_ESC("coredump to flash is disabled"));
|
||||
#endif
|
||||
}
|
||||
|
||||
static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_HTTP_MSG) {
|
||||
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
||||
if (mg_match(hm->uri, mg_str("/api/crash.bin"), NULL)) {
|
||||
crash_bin(c);
|
||||
} else if (mg_match(hm->uri, mg_str("/api/crash"), NULL)) {
|
||||
crash_json(c);
|
||||
} else {
|
||||
mg_http_reply(c, 200, "", "Hi from Mongoose\n");
|
||||
}
|
||||
} else if (ev == MG_EV_POLL && c->fn_data != NULL) {
|
||||
crash_send(c);
|
||||
} else if (ev == MG_EV_CLOSE && c->fn_data != NULL) {
|
||||
free(c->fn_data);
|
||||
c->fn_data = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void app_main(void) {
|
||||
void wifi_init(const char *ssid, const char *pass);
|
||||
wifi_init(WIFI_SSID, WIFI_PASS);
|
||||
|
||||
struct mg_mgr mgr;
|
||||
mg_log_set(MG_LL_INFO);
|
||||
mg_mgr_init(&mgr);
|
||||
MG_INFO(("Mongoose version : v%s", MG_VERSION));
|
||||
MG_INFO(("Listening on : %s", HTTP_URL));
|
||||
mg_http_listen(&mgr, HTTP_URL, http_ev_handler, NULL);
|
||||
|
||||
for (;;) mg_mgr_poll(&mgr, 1000);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
#define MG_ARCH MG_ARCH_ESP32
|
||||
|
||||
#define MG_TLS MG_TLS_NONE
|
||||
@@ -0,0 +1,104 @@
|
||||
// Code taken from the ESP32 IDF WiFi station Example
|
||||
|
||||
#include <string.h>
|
||||
#include "esp_event.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "freertos/task.h"
|
||||
#include "nvs_flash.h"
|
||||
|
||||
#include "lwip/err.h"
|
||||
#include "lwip/sys.h"
|
||||
|
||||
#include "mongoose.h"
|
||||
|
||||
static EventGroupHandle_t s_wifi_event_group;
|
||||
|
||||
/* The event group allows multiple bits for each event, but we only care about
|
||||
* two events:
|
||||
* - we are connected to the AP with an IP
|
||||
* - we failed to connect after the maximum amount of retries */
|
||||
#define WIFI_CONNECTED_BIT BIT0
|
||||
#define WIFI_FAIL_BIT BIT1
|
||||
|
||||
static int s_retry_num = 0;
|
||||
|
||||
static void event_handler(void *arg, esp_event_base_t event_base,
|
||||
int32_t event_id, void *event_data) {
|
||||
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
|
||||
esp_wifi_connect();
|
||||
} else if (event_base == WIFI_EVENT &&
|
||||
event_id == WIFI_EVENT_STA_DISCONNECTED) {
|
||||
if (s_retry_num < 10) {
|
||||
esp_wifi_connect();
|
||||
s_retry_num++;
|
||||
MG_INFO(("retry to connect to the AP"));
|
||||
} else {
|
||||
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
|
||||
}
|
||||
MG_ERROR(("connect to the AP fail"));
|
||||
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
|
||||
ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data;
|
||||
MG_INFO(("IP ADDRESS:" IPSTR, IP2STR(&event->ip_info.ip)));
|
||||
s_retry_num = 0;
|
||||
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
}
|
||||
}
|
||||
|
||||
void wifi_init(const char *ssid, const char *pass) {
|
||||
esp_err_t ret = nvs_flash_init();
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES ||
|
||||
ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
ret = nvs_flash_init();
|
||||
}
|
||||
ESP_ERROR_CHECK(ret);
|
||||
|
||||
s_wifi_event_group = xEventGroupCreate();
|
||||
|
||||
ESP_ERROR_CHECK(esp_netif_init());
|
||||
|
||||
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||
esp_netif_create_default_wifi_sta();
|
||||
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
|
||||
esp_event_handler_instance_t instance_any_id;
|
||||
esp_event_handler_instance_t instance_got_ip;
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(
|
||||
WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, &instance_any_id));
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(
|
||||
IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, &instance_got_ip));
|
||||
|
||||
wifi_config_t c = {.sta = {.threshold = {.authmode = WIFI_AUTH_WPA2_PSK},
|
||||
.pmf_cfg = {.capable = true, .required = false}}};
|
||||
snprintf((char *) c.sta.ssid, sizeof(c.sta.ssid), "%s", ssid);
|
||||
snprintf((char *) c.sta.password, sizeof(c.sta.password), "%s", pass);
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &c));
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
MG_DEBUG(("wifi_init_sta finished."));
|
||||
|
||||
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
|
||||
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
|
||||
pdFALSE, pdFALSE, portMAX_DELAY);
|
||||
|
||||
if (bits & WIFI_CONNECTED_BIT) {
|
||||
MG_INFO(("connected to ap SSID:%s", ssid));
|
||||
} else if (bits & WIFI_FAIL_BIT) {
|
||||
MG_ERROR(("Failed to connect to SSID:%s", ssid));
|
||||
} else {
|
||||
MG_ERROR(("UNEXPECTED EVENT"));
|
||||
}
|
||||
|
||||
/* The event will not be processed after unregister */
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_unregister(
|
||||
IP_EVENT, IP_EVENT_STA_GOT_IP, instance_got_ip));
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_unregister(
|
||||
WIFI_EVENT, ESP_EVENT_ANY_ID, instance_any_id));
|
||||
vEventGroupDelete(s_wifi_event_group);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Name, Type, SubType, Offset, Size, Flags
|
||||
nvs, data, nvs, , 0x6000
|
||||
phy_init, data, phy, , 0x1000
|
||||
factory, app, factory, , 1M
|
||||
coredump, data, coredump,, 128K
|
||||
|
@@ -0,0 +1,7 @@
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
|
||||
CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH=y
|
||||
CONFIG_ESP_COREDUMP_DATA_FORMAT_ELF=y
|
||||
CONFIG_ESP_COREDUMP_MAX_TASKS_NUM=16
|
||||
CONFIG_ESP_COREDUMP_STACK_SIZE=2048
|
||||
@@ -1,10 +1,11 @@
|
||||
// Copyright (c) 2020-2024 Cesanta Software Limited
|
||||
// All rights reserved
|
||||
//
|
||||
// Streaming upload example. Demonstrates how to use MG_EV_READ events
|
||||
// Streaming upload example. Demonstrates how to use mg_http_stream_body()
|
||||
// to save a large file without buffering it fully in memory.
|
||||
// The file is saved as /tmp/a.txt.
|
||||
//
|
||||
// curl http://localhost:8000/upload?name=a.txt --data-binary @large_file.txt
|
||||
// curl http://localhost:8000/fs/a.txt --data-binary @large_file.txt
|
||||
|
||||
#include "mongoose.h"
|
||||
|
||||
@@ -28,49 +29,26 @@ static const char *s_tls_key =
|
||||
"4hf5Gx17YJkq5/z3k6ogPDPpoAYWIw1/sw==\n"
|
||||
"-----END EC PRIVATE KEY-----\n";
|
||||
|
||||
struct upload_state {
|
||||
size_t expected; // POST data length, bytes
|
||||
size_t received; // Already received bytes
|
||||
void *fp; // Opened uploaded file
|
||||
};
|
||||
|
||||
static void handle_uploads(struct mg_connection *c, int ev, void *ev_data) {
|
||||
struct upload_state *us = (struct upload_state *) c->data;
|
||||
static bool upload(struct mg_http_message *hm, struct mg_str *data, void **p) {
|
||||
struct mg_fs *fs = &mg_fs_posix;
|
||||
|
||||
// Catch /upload requests early, without buffering whole body
|
||||
// When we receive MG_EV_HTTP_HDRS event, that means we've received all
|
||||
// HTTP headers but not necessarily full HTTP body
|
||||
if (ev == MG_EV_HTTP_HDRS) {
|
||||
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
||||
if (mg_match(hm->uri, mg_str("/upload/*"), NULL)) {
|
||||
char path[MG_PATH_MAX];
|
||||
mg_snprintf(path, sizeof(path), "%s/%.*s", UPLOAD_DIR, hm->uri.len - 8,
|
||||
hm->uri.buf + 8);
|
||||
us->expected = hm->body.len; // Store number of bytes we expect
|
||||
mg_iobuf_del(&c->recv, 0, hm->head.len); // Delete HTTP headers
|
||||
c->pfn = NULL; // Silence HTTP protocol handler, we'll use MG_EV_READ
|
||||
if (mg_path_is_sane(mg_str(path))) {
|
||||
fs->rm(path); // Delete file if it exists
|
||||
us->fp = fs->op(path, MG_FS_WRITE); // Open file for writing
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Catch uploaded file data for both MG_EV_READ and MG_EV_HTTP_HDRS
|
||||
if (us->expected > 0 && c->recv.len > 0) {
|
||||
us->received += c->recv.len;
|
||||
if (us->fp) fs->wr(us->fp, c->recv.buf, c->recv.len); // Write to file
|
||||
c->recv.len = 0; // Delete received data
|
||||
if (us->received >= us->expected) {
|
||||
// Uploaded everything. Send response back
|
||||
MG_INFO(("Uploaded %lu bytes", us->received));
|
||||
mg_http_reply(c, 200, NULL, "%lu ok\n", us->received);
|
||||
if (us->fp) fs->cl(us->fp); // Close file
|
||||
memset(us, 0, sizeof(*us)); // Cleanup upload state
|
||||
c->is_draining = 1; // Close connection when response gets sent
|
||||
if (hm != NULL) {
|
||||
char path[MG_PATH_MAX];
|
||||
MG_INFO(("UPLOAD BEGIN, URI %.*s ", hm->uri.len, hm->uri.buf));
|
||||
mg_snprintf(path, sizeof(path), "%s/%.*s", UPLOAD_DIR, hm->uri.len - 4,
|
||||
hm->uri.buf + 4);
|
||||
*p = NULL;
|
||||
if (mg_path_is_sane(mg_str(path))) {
|
||||
fs->rm(path); // Delete file if it exists
|
||||
*p = fs->op(path, MG_FS_WRITE); // Open file for writing
|
||||
}
|
||||
} else if (data != NULL) {
|
||||
MG_INFO(("UPLOAD DATA, %zu bytes", data->len));
|
||||
if (*p) fs->wr(*p, data->buf, data->len); // Write to file
|
||||
} else {
|
||||
MG_INFO(("UPLOAD END %p", p));
|
||||
if (*p) fs->cl(*p), *p = NULL;
|
||||
}
|
||||
return true; // signal success
|
||||
}
|
||||
|
||||
static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
@@ -78,13 +56,13 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
struct mg_tls_opts opts = {.cert = mg_str(s_tls_cert),
|
||||
.key = mg_str(s_tls_key)};
|
||||
mg_tls_init(c, &opts);
|
||||
}
|
||||
|
||||
handle_uploads(c, ev, ev_data);
|
||||
|
||||
// Non-upload requests, we serve normally
|
||||
// NOTE: handle_uploads() may delete request and reset c->pfn
|
||||
if (ev == MG_EV_HTTP_MSG && c->pfn != NULL) {
|
||||
} else if (ev == MG_EV_HTTP_HDRS) {
|
||||
// Handle upload requests to /fs/*
|
||||
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
||||
if (mg_match(hm->uri, mg_str("/fs/*"), NULL)) {
|
||||
mg_http_stream_body(c, hm, upload, NULL);
|
||||
}
|
||||
} else if (ev == MG_EV_HTTP_MSG && c->pfn != NULL) {
|
||||
struct mg_http_serve_opts opts = {.root_dir = "web_root"};
|
||||
mg_http_serve_dir(c, ev_data, &opts);
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
r.onload = function() {
|
||||
ev.target.value = '';
|
||||
document.getElementById('el3').innerText = 'Uploading...';
|
||||
fetch(`/upload/${encodeURIComponent(f.name)}`, {
|
||||
fetch(`/fs/${encodeURIComponent(f.name)}`, {
|
||||
method: 'POST',
|
||||
body: r.result,
|
||||
}).then(function(res) {
|
||||
|
||||
@@ -65,7 +65,7 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
}
|
||||
c->fn_data = c2;
|
||||
forward_request(hm, c2);
|
||||
c->is_resp = 0; // process further msgs in keep-alive connection
|
||||
c->pfn_data = NULL; // process further msgs in keep-alive connection
|
||||
c2->is_hexdumping = 1;
|
||||
}
|
||||
} else if (ev == MG_EV_CLOSE) {
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
PROG ?= example # Program we are building
|
||||
DELETE = rm -rf # Command to remove files
|
||||
OUT ?= -o $(PROG) # Compiler argument for output file
|
||||
SOURCES = main.c mongoose.c mongoose_mqtt.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
|
||||
CFLAGS = -W -Wall -Wextra -g -I. # Build options
|
||||
REPO_ROOT ?= ../../..
|
||||
PROG ?= example
|
||||
DELETE = rm -rf
|
||||
OUT ?= -o $(PROG)
|
||||
CFLAGS = -W -Wall -Wextra -g -I. -I$(REPO_ROOT)
|
||||
SOURCES = main.c mongoose_mqtt.c $(REPO_ROOT)/mongoose.c
|
||||
|
||||
# Mongoose build options. See https://mongoose.ws/docs/getting-started/build-options/
|
||||
CFLAGS_EXTRA ?= -DMG_TLS=MG_TLS_BUILTIN
|
||||
CFLAGS_MONGOOSE += -DMG_TLS=MG_TLS_BUILTIN
|
||||
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1
|
||||
|
||||
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
|
||||
PROG ?= example.exe # Use .exe suffix for the binary
|
||||
CC = gcc # Use MinGW gcc compiler
|
||||
CFLAGS += -lws2_32 # Link against Winsock library
|
||||
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
|
||||
OUT ?= -o $(PROG) # Build output
|
||||
MAKE += WINDOWS=1 CC=$(CC)
|
||||
# This is for Azure - it just cannot Chacha20
|
||||
CFLAGS_MONGOOSE += -DMG_ENABLE_CHACHA20=0
|
||||
|
||||
# Windows settings. Assume MinGW compiler.
|
||||
# To use VS compiler, run: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
|
||||
ifeq ($(OS),Windows_NT)
|
||||
PROG ?= example.exe
|
||||
CC = gcc
|
||||
CFLAGS += -lws2_32
|
||||
DELETE = cmd /C del /Q /F /S
|
||||
OUT ?= -o $(PROG)
|
||||
endif
|
||||
|
||||
all: $(PROG) # Default target. Build and run program
|
||||
all: $(PROG)
|
||||
$(RUN) ./$(PROG) $(ARGS)
|
||||
|
||||
$(PROG): $(SOURCES) # Build program from sources
|
||||
$(PROG): $(SOURCES)
|
||||
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
|
||||
|
||||
clean: # Cleanup. Delete built program and all build artifacts
|
||||
clean:
|
||||
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
|
||||
@@ -1 +1,97 @@
|
||||
See detailed tutorial at https://mongoose.ws/tutorials/mqtt/mqtt-client/
|
||||
# Mongoose MQTT client
|
||||
|
||||
This MQTT client implementation implements the following:
|
||||
|
||||
- Connects to the MQTT server specified by MQTT_SERVER_URL
|
||||
- When connected, subscribes to the topic MQTT_SUBSCRIBE_TOPIC
|
||||
- When it receives a message, echoes it back to MQTT_PUBLISH_TOPIC
|
||||
- Timer-based reconnection logic revives the connection when it is down
|
||||
- Ping server periodically. When disconnected, a last will is published
|
||||
- Implements "ota.update" for OTA updates, see https://mongoose.ws/mqtt/
|
||||
|
||||
By default, it uses HiveMQ public broker, and can be tested with
|
||||
the [HiveMQ Websocket Client](https://www.hivemq.com/demos/websocket-client/):
|
||||
|
||||
- Subscribe to `mg/123/#`
|
||||
- Send a message to `mg/123/rx`
|
||||
|
||||
## Integrating into an embedded project
|
||||
|
||||
1. Copy `mongoose_mqtt.c` to your embedded project and add it to the build
|
||||
2. Add `mg_mqtt_init(&mgr)` after `mg_mgr_init()`
|
||||
3. Add `mg_mqtt_poll(&mgr)` after `mg_mgr_poll()`
|
||||
|
||||
## Microsoft Azure IoT Hub
|
||||
|
||||
1. Create IoT Hub
|
||||
2. Generate device self-signed certificates:
|
||||
```sh
|
||||
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -pkeyopt ec_param_enc:named_curve -nodes -keyout device.key -out device.crt -days 3650 -subj "/CN=MYDEVICE"
|
||||
```
|
||||
3. Show certificate thumbprint:
|
||||
```sh
|
||||
openssl x509 -in device.crt -noout -fingerprint -sha256 | tr -d ':' | cut -d= -f2
|
||||
```
|
||||
4. Register a device with the thumbprint from above, and set the following:
|
||||
```c
|
||||
#define AZURE_HUB_NAME "HUB_NAME" // Change this
|
||||
#define AZURE_DEVICE_ID "DEVICE_ID" // Change this
|
||||
|
||||
// Do not change this
|
||||
#define MQTT_SERVER_URL "mqtts://" AZURE_HUB_NAME ".device.azure-devices.net"
|
||||
#define MQTT_CLIENT_ID AZURE_DEVICE_ID
|
||||
#define MQTT_USER AZURE_HUB_NAME ".azure-devices.net/" AZURE_DEVICE_ID "/?api-version=2021-04-12"
|
||||
#define MQTT_PUBLISH_TOPIC "devices/" AZURE_DEVICE_ID "/messages/events/"
|
||||
#define MQTT_SUBSCRIBE_TOPIC "devices/" AZURE_DEVICE_ID "/messages/devicebound/#"
|
||||
```
|
||||
|
||||
5. Set `TLS_CA`. Visit https://mongoose.ws/tls/, enter "HUB_NAME.device.azure-devices.nett:8883" into the CA field and click on the "Get CA Certificate" button. Enable the "Show as C/C++ constant", copy-paste to your code.
|
||||
6. Set `TLS_KEY` and `TLS_CRT` with the output of this commands:
|
||||
|
||||
```sh
|
||||
sed 's/\r$//; s/.*/ "&\\n"/; $!s/$/ \\/' device.key
|
||||
sed 's/\r$//; s/.*/ "&\\n"/; $!s/$/ \\/' device.crt
|
||||
```
|
||||
7. Add to your `mongoose_config.h`:
|
||||
```c
|
||||
#define MG_ENABLE_CHACHA20 0
|
||||
```
|
||||
|
||||
## Microsoft Azure Event Grid
|
||||
|
||||
1. Create Azure Event Grid (EG) instance
|
||||
|
||||
2. Generate device self-signed certificates:
|
||||
|
||||
```sh
|
||||
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -pkeyopt ec_param_enc:named_curve -nodes -keyout device.key -out device.crt -days 3650 -subj "/CN=MYDEVICE"
|
||||
```
|
||||
|
||||
3. Show certificate thumbprint:
|
||||
|
||||
```sh
|
||||
openssl x509 -in device.crt -noout -fingerprint -sha256 | tr -d ':' | cut -d= -f2
|
||||
```
|
||||
|
||||
4. Register a client on EG: choose a name, and use the thumbprint from above
|
||||
|
||||
5. Set URL, username and client ID:
|
||||
|
||||
```c
|
||||
#define MQTT_SERVER_URL "mqtts://INSTANCE.REGION.ts.eventgrid.azure.net:8883"
|
||||
#define MQTT_CLIENT_ID "CLIENT_NAME"
|
||||
#define MQTT_USER "CLIENT_NAME"
|
||||
```
|
||||
|
||||
6. Set `TLS_CA`. Visit https://mongoose.ws/tls/, enter "INSTANCE.REGION.ts.eventgrid.azure.net:8883" into the CA field and click on the "Get CA Certificate" button. Enable the "Show as C/C++ constant", copy-paste to your code.
|
||||
7. Set `TLS_KEY` and `TLS_CRT` with the output of this commands:
|
||||
|
||||
```sh
|
||||
sed 's/\r$//; s/.*/ "&\\n"/; $!s/$/ \\/' device.key
|
||||
sed 's/\r$//; s/.*/ "&\\n"/; $!s/$/ \\/' device.crt
|
||||
```
|
||||
|
||||
8. In Azure EG, go to Instance / MQTT Broker / Topic spaces, add "space1" with `mg/#` pattern
|
||||
9. In Azure EG, go to Instance / MQTT Broker / Permissions bindings, add binding1 and binding2:
|
||||
- $all , space1 , Publisher
|
||||
- $all , space1 , Subscriber
|
||||
@@ -1 +0,0 @@
|
||||
../../../mongoose.c
|
||||
@@ -1 +0,0 @@
|
||||
../../../mongoose.h
|
||||
@@ -1,24 +1,22 @@
|
||||
// Copyright (c) 2026 Cesanta Software Limited
|
||||
// All rights reserved
|
||||
//
|
||||
// Example MQTT client. It performs the following steps:
|
||||
// 1. Connects to the MQTT server specified by MQTT_SERVER_URL
|
||||
// 2. When connected, subscribes to the topic MQTT_SUBSCRIBE_TOPIC
|
||||
// 3. When it receives a message, echoes it back to MQTT_PUBLISH_TOPIC
|
||||
// 4. Timer-based reconnection logic revives the connection when it is down
|
||||
// 5. Ping server periodically. When disconnected, a last will is published
|
||||
// 6. Implements "ota.update" for OTA updates, see https://mongoose.ws/mqtt/
|
||||
|
||||
#include "mongoose.h"
|
||||
|
||||
#define MQTT_SERVER_URL "mqtt://broker.hivemq.com:1883"
|
||||
#define MQTT_PUBLISH_TOPIC "mg/123/tx"
|
||||
#define MQTT_SUBSCRIBE_TOPIC "mg/123/rx"
|
||||
#define MQTT_CLIENT_ID "d3"
|
||||
#define MQTT_USER MQTT_CLIENT_ID
|
||||
#define MQTT_PASS ""
|
||||
#define MQTT_PUBLISH_TOPIC "mg/" MQTT_CLIENT_ID "/tx"
|
||||
#define MQTT_SUBSCRIBE_TOPIC "mg/" MQTT_CLIENT_ID "/rx"
|
||||
#define MQTT_QOS 1
|
||||
#define RECONNECT_PERIOD_MS 3000
|
||||
#define MQTT_RECONNECT_PERIOD_MS 3000
|
||||
|
||||
#define TLS_CA ""
|
||||
#define TLS_KEY ""
|
||||
#define TLS_CRT ""
|
||||
|
||||
static struct mg_connection *s_mqtt_conn; // Client connection
|
||||
static struct mg_rpc *s_rpc = NULL; // List of registered RPC methods
|
||||
|
||||
static void subscribe(struct mg_connection *c, struct mg_str topic) {
|
||||
struct mg_mqtt_opts opts = {};
|
||||
@@ -69,7 +67,9 @@ static void mqtt_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
|
||||
// c->is_hexdumping = 1;
|
||||
} else if (ev == MG_EV_CONNECT) {
|
||||
if (c->is_tls) {
|
||||
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
|
||||
struct mg_tls_opts opts = {.ca = mg_str(TLS_CA),
|
||||
.cert = mg_str(TLS_CRT),
|
||||
.key = mg_str(TLS_KEY),
|
||||
.name = mg_url_host(MQTT_SERVER_URL)};
|
||||
mg_tls_init(c, &opts);
|
||||
}
|
||||
@@ -77,16 +77,31 @@ static void mqtt_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
|
||||
// On error, log error message
|
||||
MG_ERROR(("%lu ERROR %s", c->id, (char *) ev_data));
|
||||
} else if (ev == MG_EV_MQTT_OPEN) {
|
||||
// MQTT connect is successful
|
||||
MG_DEBUG(("%lu CONNECTED to %s", c->id, MQTT_SERVER_URL));
|
||||
subscribe(c, mg_str(MQTT_SUBSCRIBE_TOPIC));
|
||||
int status = *(int *) ev_data;
|
||||
MG_DEBUG(("%lu CONNECT status: %d", c->id, status));
|
||||
if (status == 0) {
|
||||
subscribe(c, mg_str(MQTT_SUBSCRIBE_TOPIC));
|
||||
if (mg_match(mg_str(MQTT_SERVER_URL), mg_str("#azure-devices.net"), 0)) {
|
||||
// This is Azure IoT Hub. Subscribe for DPS messages
|
||||
subscribe(c, mg_str("$iothub/methods/POST/#"));
|
||||
}
|
||||
}
|
||||
} else if (ev == MG_EV_MQTT_MSG) {
|
||||
// When we get echo response, print it
|
||||
char response[100];
|
||||
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
|
||||
mg_snprintf(response, sizeof(response), "Got %.*s -> %.*s", mm->topic.len,
|
||||
mm->topic.buf, mm->data.len, mm->data.buf);
|
||||
publish(c, mg_str(MQTT_PUBLISH_TOPIC), mg_str(response));
|
||||
struct mg_str caps[5]; // caps[0] = method name, caps[2] = request id
|
||||
if (mg_match(mm->topic, mg_str("$iothub/methods/POST/*/?$rid=*"), caps)) {
|
||||
// Azure direct method call. Construct a stub response, "{}"
|
||||
char topic[128];
|
||||
mg_snprintf(topic, sizeof(topic), "$iothub/methods/res/%d/?$rid=%.*s",
|
||||
200, (int) caps[2].len, caps[2].buf);
|
||||
publish(c, mg_str(topic), mg_str("{}"));
|
||||
} else {
|
||||
char response[100];
|
||||
mg_snprintf(response, sizeof(response), "Got %.*s -> %.*s", mm->topic.len,
|
||||
mm->topic.buf, mm->data.len, mm->data.buf);
|
||||
publish(c, mg_str(MQTT_PUBLISH_TOPIC), mg_str(response));
|
||||
}
|
||||
} else if (ev == MG_EV_MQTT_CMD) {
|
||||
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
|
||||
if (mm->cmd == MQTT_CMD_PINGREQ) mg_mqtt_pong(c);
|
||||
@@ -97,9 +112,7 @@ static void mqtt_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
|
||||
}
|
||||
|
||||
void mg_mqtt_init(struct mg_mgr *mgr) {
|
||||
(void) mgr;
|
||||
if (!s_rpc) mg_rpc_add(&s_rpc, mg_str("ota.update"), rpc_ota_update, NULL);
|
||||
mg_mem_files = mg_packed_files; // Use generated packed filesystem
|
||||
mg_rpc_add(&mgr->rpcs, mg_str("ota.update"), rpc_ota_update, NULL);
|
||||
}
|
||||
|
||||
void mg_mqtt_poll(struct mg_mgr *mgr) {
|
||||
@@ -107,18 +120,24 @@ void mg_mqtt_poll(struct mg_mgr *mgr) {
|
||||
|
||||
// Reconnect if connection is closed, and send MQTT PINGs to keep
|
||||
// the connection alive or to detect connection loss
|
||||
if (mg_timer_expired(&timer, RECONNECT_PERIOD_MS, mg_now())) {
|
||||
if (mg_timer_expired(&timer, MQTT_RECONNECT_PERIOD_MS, mg_now())) {
|
||||
if (s_mqtt_conn == NULL) {
|
||||
struct mg_mqtt_opts opts = {.clean = true,
|
||||
.qos = MQTT_QOS,
|
||||
.topic = mg_str(MQTT_PUBLISH_TOPIC),
|
||||
.keepalive = 5,
|
||||
.version = 4,
|
||||
.message = mg_str("bye")};
|
||||
struct mg_mqtt_opts opts = {
|
||||
.clean = true,
|
||||
.client_id = mg_str(MQTT_CLIENT_ID),
|
||||
.user = mg_str(MQTT_USER),
|
||||
.pass = mg_str(MQTT_PASS),
|
||||
.qos = MQTT_QOS,
|
||||
.keepalive = 5,
|
||||
.version = 4, // MQTT 3.1.1
|
||||
.topic = mg_str(MQTT_PUBLISH_TOPIC),
|
||||
.message = mg_str("bye"),
|
||||
};
|
||||
s_mqtt_conn =
|
||||
mg_mqtt_connect(mgr, MQTT_SERVER_URL, &opts, mqtt_ev_handler, NULL);
|
||||
} else {
|
||||
mg_mqtt_ping(s_mqtt_conn);
|
||||
// publish(s_mqtt_conn, mg_str(MQTT_PUBLISH_TOPIC), mg_str("hi"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
../../http/http-client/packed_fs.c
|
||||
@@ -0,0 +1 @@
|
||||
See the example at https://github.com/mongoose-examples/frdm-imxrt1186
|
||||
@@ -0,0 +1,48 @@
|
||||
# Environment setup: https://mongoose.ws/documentation/tutorials/tools/
|
||||
|
||||
CFLAGS = -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion
|
||||
CFLAGS += -Wformat-truncation -fno-common -Wno-conversion -Wno-sign-conversion
|
||||
CFLAGS += -g3 -Os -ffunction-sections -fdata-sections
|
||||
CFLAGS += -Wno-cast-function-type -Wno-old-style-declaration
|
||||
CFLAGS += -Wno-unused-parameter -Wno-unused-function
|
||||
CFLAGS += -I. -Imongoose -Icmsis_core/CMSIS/Core/Include/
|
||||
CFLAGS += -Icmsis_rt1186/devices/MIMXRT1186/ -Icmsis_rt1186/devices/MIMXRT1186/periph/ -Icmsis_rt1186/devices/MIMXRT1186/drivers/
|
||||
CFLAGS += -DCPU_MIMXRT1186CVJ8C_cm33 -DCPU_MIMXRT1186CVJ8C -DMIMXRT1186_cm33_SERIES
|
||||
CFLAGS += -DXIP_EXTERNAL_FLASH=1 -DXIP_BOOT_HEADER_ENABLE=1
|
||||
CFLAGS += -mcpu=cortex-m33 -mthumb -mfpu=fpv5-sp-d16 -mfloat-abi=hard $(CFLAGS_EXTRA)
|
||||
LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lgcc -Wl,--gc-sections -Wl,-Map=$@.map
|
||||
|
||||
SOURCES = main.c hal.c flash_image.c mongoose/mongoose.c
|
||||
SOURCES += cmsis_rt1186/devices/MIMXRT1186/gcc/startup_MIMXRT1186_cm33.S
|
||||
SOURCES += cmsis_rt1186/devices/MIMXRT1186/drivers/fsl_clock.c
|
||||
SOURCES += cmsis_rt1186/devices/MIMXRT1186/drivers/fsl_pmu.c
|
||||
SOURCES += cmsis_rt1186/devices/MIMXRT1186/drivers/fsl_common_arm.c
|
||||
SOURCES += cmsis_rt1186/devices/MIMXRT1186/drivers/fsl_ele_base_api.c
|
||||
SOURCES += cmsis_rt1186/devices/MIMXRT1186/drivers/fsl_s3mu.c
|
||||
SOURCES += cmsis_rt1186/devices/MIMXRT1186/drivers/fsl_trdc.c
|
||||
|
||||
CFLAGS += -D__ATOLLIC__ -D__STARTUP_CLEAR_BSS -DMG_HAL_DISABLE_RANDOM
|
||||
|
||||
all build: firmware.bin
|
||||
|
||||
mongoose/mongoose.c mongoose/mongoose.h:
|
||||
mkdir -p mongoose
|
||||
cp ../../../../mongoose.[ch] mongoose/
|
||||
|
||||
firmware.bin: firmware.elf
|
||||
arm-none-eabi-objcopy -O binary $< $@
|
||||
arm-none-eabi-size --format=berkeley $<
|
||||
|
||||
firmware.elf: cmsis_core cmsis_rt1186 $(SOURCES) $(wildcard *.h) link.ld Makefile
|
||||
arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@
|
||||
|
||||
cmsis_core:
|
||||
git clone -q -c advice.detachedHead=false --depth 1 -b 5.9.0 https://github.com/ARM-software/CMSIS_5 $@
|
||||
|
||||
cmsis_rt1186:
|
||||
curl -sL https://mcuxpresso.nxp.com/cmsis_pack/repo/NXP.MIMXRT1186_DFP.26.06.00.pack -o NXP.MIMXRT1186_DFP.26.06.00.pack
|
||||
unzip -q NXP.MIMXRT1186_DFP.26.06.00.pack -d $@
|
||||
rm NXP.MIMXRT1186_DFP.26.06.00.pack
|
||||
|
||||
clean:
|
||||
rm -rf firmware.* cmsis_* mongoose/mongoose.*
|
||||
@@ -0,0 +1,157 @@
|
||||
#include <stdint.h>
|
||||
|
||||
#define LUT_OPERAND0(x) ((uint32_t) (x) << 0)
|
||||
#define LUT_NUM_PADS0(x) ((uint32_t) (x) << 8)
|
||||
#define LUT_OPCODE0(x) ((uint32_t) (x) << 10)
|
||||
#define LUT_OPERAND1(x) ((uint32_t) (x) << 16)
|
||||
#define LUT_NUM_PADS1(x) ((uint32_t) (x) << 24)
|
||||
#define LUT_OPCODE1(x) ((uint32_t) (x) << 26)
|
||||
#define LUT_SEQ(cmd0, pads0, operand0, cmd1, pads1, operand1) \
|
||||
(LUT_OPERAND0(operand0) | LUT_NUM_PADS0(pads0) | LUT_OPCODE0(cmd0) | \
|
||||
LUT_OPERAND1(operand1) | LUT_NUM_PADS1(pads1) | LUT_OPCODE1(cmd1))
|
||||
|
||||
enum {
|
||||
LUT_STOP = 0x00,
|
||||
LUT_CMD_SDR = 0x01,
|
||||
LUT_RADDR_SDR = 0x02,
|
||||
LUT_WRITE_SDR = 0x08,
|
||||
LUT_READ_SDR = 0x09,
|
||||
LUT_DUMMY_SDR = 0x0c,
|
||||
LUT_1_PAD = 0,
|
||||
LUT_4_PADS = 2,
|
||||
};
|
||||
|
||||
// FlexSPI2 NOR configuration block for the FRDM-IMXRT1186 QSPI flash
|
||||
// The ROM expects this 512-byte structure at flash offset 0x400
|
||||
__attribute__((section(".boot_hdr.conf"), used))
|
||||
const uint32_t qspi_flash_nor_config[128] = {
|
||||
[0] = 0x42464346, // Tag: "FCFB"
|
||||
[1] = 0x56010400, // Version 1.4.0
|
||||
[3] = 0x00030301, // DQS loopback, CS hold/setup = 3
|
||||
[16] = 0x00000010, // Safe configuration
|
||||
[17] = 0x00050401, // Serial NOR, 4 pads, 100 MHz
|
||||
[20] = 16U * 1024U * 1024U,
|
||||
|
||||
// Read
|
||||
[32] =
|
||||
LUT_SEQ(LUT_CMD_SDR, LUT_1_PAD, 0xeb, LUT_RADDR_SDR, LUT_4_PADS, 0x18),
|
||||
[33] =
|
||||
LUT_SEQ(LUT_DUMMY_SDR, LUT_4_PADS, 0x06, LUT_READ_SDR, LUT_4_PADS, 0x04),
|
||||
|
||||
// Read status
|
||||
[36] =
|
||||
LUT_SEQ(LUT_CMD_SDR, LUT_1_PAD, 0x05, LUT_READ_SDR, LUT_1_PAD, 0x04),
|
||||
|
||||
// Write enable
|
||||
[44] =
|
||||
LUT_SEQ(LUT_CMD_SDR, LUT_1_PAD, 0x06, LUT_STOP, LUT_1_PAD, 0x00),
|
||||
|
||||
// Erase 4-KiB sector
|
||||
[52] =
|
||||
LUT_SEQ(LUT_CMD_SDR, LUT_1_PAD, 0x20, LUT_RADDR_SDR, LUT_1_PAD, 0x18),
|
||||
|
||||
// Erase 64-KiB block
|
||||
[64] =
|
||||
LUT_SEQ(LUT_CMD_SDR, LUT_1_PAD, 0xd8, LUT_RADDR_SDR, LUT_1_PAD, 0x18),
|
||||
|
||||
// Program page
|
||||
[68] =
|
||||
LUT_SEQ(LUT_CMD_SDR, LUT_1_PAD, 0x02, LUT_RADDR_SDR, LUT_1_PAD, 0x18),
|
||||
[69] =
|
||||
LUT_SEQ(LUT_WRITE_SDR, LUT_1_PAD, 0x04, LUT_STOP, LUT_1_PAD, 0x00),
|
||||
|
||||
// Erase chip
|
||||
[76] =
|
||||
LUT_SEQ(LUT_CMD_SDR, LUT_1_PAD, 0x60, LUT_STOP, LUT_1_PAD, 0x00),
|
||||
|
||||
[112] = 256, // Page size
|
||||
[113] = 4U * 1024U, // Sector size
|
||||
[114] = 1, // IP-command serial clock
|
||||
[116] = 64U * 1024U, // Block size
|
||||
};
|
||||
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint8_t version;
|
||||
uint16_t length;
|
||||
uint8_t tag;
|
||||
uint32_t flags;
|
||||
uint16_t software_version;
|
||||
uint8_t fuse_version;
|
||||
uint8_t image_count;
|
||||
uint16_t signature_block_offset;
|
||||
uint16_t reserved;
|
||||
} container_header_t;
|
||||
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint32_t offset;
|
||||
uint32_t size;
|
||||
uint32_t load_address;
|
||||
uint32_t reserved1;
|
||||
uint32_t entry_address;
|
||||
uint32_t reserved2;
|
||||
uint32_t flags;
|
||||
uint32_t metadata;
|
||||
uint8_t hash[64];
|
||||
uint8_t iv[32];
|
||||
} container_image_t;
|
||||
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint8_t version;
|
||||
uint16_t length;
|
||||
uint8_t tag;
|
||||
uint16_t certificate_offset;
|
||||
uint16_t srk_table_offset;
|
||||
uint16_t signature_offset;
|
||||
uint16_t blob_offset;
|
||||
uint32_t reserved;
|
||||
} signature_block_t;
|
||||
|
||||
typedef struct __attribute__((packed)) {
|
||||
container_header_t header;
|
||||
container_image_t image[1];
|
||||
signature_block_t signature;
|
||||
} boot_container_t;
|
||||
|
||||
extern const uint32_t _image_offset[];
|
||||
extern const uint32_t _image_size[];
|
||||
extern const uint32_t _image_loadaddr[];
|
||||
extern const uint32_t Reset_Handler[];
|
||||
|
||||
// RT1180 Program Image Container. The ROM expects it at flash offset 0x1000
|
||||
__attribute__((section(".boot_hdr.container"), used))
|
||||
const boot_container_t container_data = {
|
||||
.header = {
|
||||
.version = 0,
|
||||
.length = sizeof(boot_container_t),
|
||||
.tag = 0x87,
|
||||
.flags = 0,
|
||||
.software_version = 0,
|
||||
.fuse_version = 0,
|
||||
.image_count = 1,
|
||||
.signature_block_offset =
|
||||
sizeof(container_header_t) + sizeof(container_image_t),
|
||||
.reserved = 0,
|
||||
},
|
||||
.image = {{
|
||||
.offset = (uint32_t) _image_offset,
|
||||
.size = (uint32_t) _image_size,
|
||||
.load_address = (uint32_t) _image_loadaddr,
|
||||
.reserved1 = 0,
|
||||
.entry_address = (uint32_t) Reset_Handler,
|
||||
.reserved2 = 0,
|
||||
.flags = 0x00000213, // Plain SHA-512 CM33 executable image
|
||||
.metadata = 0,
|
||||
.hash = {0},
|
||||
.iv = {0},
|
||||
}},
|
||||
.signature = {
|
||||
.version = 0,
|
||||
.length = sizeof(signature_block_t),
|
||||
.tag = 0x90,
|
||||
.certificate_offset = 0,
|
||||
.srk_table_offset = 0,
|
||||
.signature_offset = 0,
|
||||
.blob_offset = 0,
|
||||
.reserved = 0,
|
||||
},
|
||||
};
|
||||
Loaded 100 of 2286 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user