Refuse cross-origin POSTs, add LICENSE, fix PS4 errno check and page races

This commit is contained in:
mortyzip committed 2026-10-09 00:50:52 +00:00
1 parent c0d09937b6
commit 0f0cdc34b4
9 files changed
+232 -133

No files matched your search

+2
View File
@@ -1,3 +1,5 @@
*.o
*.elf
*.bin
.DS_Store
build/
+45
View File
@@ -0,0 +1,45 @@
MIT License
Copyright (c) 2026 mortyzip
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
----------------------------------------------------------------------------
The QR code encoder in src/index.html is based on the QR Code generator
library by Project Nayuki (https://www.nayuki.io/page/qr-code-generator-library),
used under the following terms:
Copyright (c) Project Nayuki. (MIT License)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
- The Software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties of merchantability,
fitness for a particular purpose and noninfringement. In no event shall the
authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising from,
out of or in connection with the Software or the use or other dealings in the
Software.
+1
View File
@@ -61,6 +61,7 @@ $(PS4_BIN): src/ps4.c $(DEPS)
# Runs the PS5 code on this computer with the console calls stubbed out, for
# working on the control page: make host && ./build/keepawake_host
# Needs BSD network headers (struct if_data), so macOS or BSD only.
host: build/keepawake_host
build/keepawake_host: src/ps5.c tools/host_stubs.c $(DEPS)
+9 -3
View File
@@ -13,7 +13,7 @@ Download the payloads from the [Releases](https://github.com/mortyzip/KeepAwake/
| PS5 | `keepawake_ps5_v<version>.elf` | ELF loader, port 9021 |
| PS4 | `keepawake_ps4_v<version>.bin` | GoldHEN BinLoader, port 9090 |
- **Start:** send the payload. The control page opens in the console's browser, and the toast shows its address for other devices, for example "Keep Awake v<version> enabled / Control it at http://192.168.1.50:9031". To stop the page opening on the console, switch off "Open on the PS5 at start" on the page. The setting is saved to `/data/keepawake.cfg`.
- **Start:** send the payload. The control page opens in the console's browser, and the toast shows its address for other devices, for example "Keep Awake v<version> enabled / Control it at http://192.168.1.50:9031". To stop the page opening on the console, switch off "Open on the PS5/PS4 at start" on the page. The setting is saved to `/data/keepawake.cfg`.
- **Turn off and on:** use the control page. Turning it off lets the console go into rest mode, but the payload keeps running, so you can turn it back on from the page without sending the payload again.
- **Timer:** pick 30 min, 1 hour, 2 hours or 4 hours on the page, or set your own (up to 7 days). When the time is up, Keep Awake turns itself off and shows a toast. The payload keeps running, so you can turn it back on from the page.
- **While transferring:** keeps the console awake only while the network is busy, such as a download, an FTP transfer or a PKG install, then lets it rest. Rest mode suspends payloads, so this stops homebrew transfers from being cut off. See [While transferring](#while-transferring).
@@ -21,6 +21,8 @@ Download the payloads from the [Releases](https://github.com/mortyzip/KeepAwake/
Only one copy runs at a time. It uses TCP port 9031 to know whether it's already running.
There is no password. Anyone on your network can open the page and use the API. Browsers on other sites can't, since POSTs with a foreign `Origin` header are refused, but don't expose port 9031 outside your LAN.
### Control page
While it's running, open `http://<console-ip>:9031` in a browser. The page shows:
@@ -78,7 +80,7 @@ The page is [src/index.html](src/index.html). The build embeds it into both payl
make host && ./build/keepawake_host
```
Then open http://localhost:9031.
Then open http://localhost:9031. This needs BSD network headers, so it builds on macOS or BSD, not Linux.
## Releasing
@@ -94,8 +96,12 @@ The workflow builds the payloads and creates the GitHub Release with them attach
- [src/ps5.c](src/ps5.c): built with the [ps5-payload-sdk](https://github.com/ps5-payload-dev/sdk).
- [src/ps4.c](src/ps4.c): built against libPS4 from the [Scene-Collective ps4-payload-sdk](https://github.com/Scene-Collective/ps4-payload-sdk). libPS4 has no `select()`, so this version checks for connections ten times a second.
- [src/web.h](src/web.h): the HTTP server for the control page, shared by both.
- [src/index.html](src/index.html): the control page, including a small QR code encoder (byte mode, error correction level M, up to 106 bytes).
- [src/index.html](src/index.html): the control page, including a small QR code encoder (byte mode, error correction level M, up to 106 bytes) based on [Project Nayuki's](https://www.nayuki.io/page/qr-code-generator-library).
## Support
Keep Awake is free. If it's useful to you, you can [buy me a coffee](https://buymeacoffee.com/mortyzip). The control page has a link too, or a QR code when it's open on the console.
## License
[MIT](LICENSE).
+42 -42
View File
@@ -173,9 +173,9 @@ button.link.confirm { color: var(--danger); font-weight: 600; }
.settings { padding: 20px 20px 6px; }
.setting { display: flex; align-items: center; gap: 16px; padding: 14px 0; border-top: 1px solid var(--line); cursor: pointer; }
.settings h2 + .setting { border-top: 0; margin-top: 4px; }
.setting div { flex: 1; min-width: 0; }
.setting .text { flex: 1; min-width: 0; }
.setting strong { display: block; font-weight: 600; }
.setting span { display: block; color: var(--muted); font-size: 14px; margin-top: 2px; }
.setting small { display: block; color: var(--muted); font-size: 14px; margin-top: 2px; }
.setting select {
flex: none;
font: inherit;
@@ -314,37 +314,31 @@ button.link.confirm { color: var(--danger); font-weight: 600; }
<section class="card settings" id="settings" hidden>
<h2>Settings</h2>
<div class="setting" id="open-setting">
<label for="open-on-start" style="display:contents">
<div>
<strong id="open-on-start-title">Open on the console at start</strong>
<span id="open-on-start-note">Shows this page on the TV each time you send the payload</span>
</div>
</label>
<label class="setting">
<span class="text">
<strong id="open-on-start-title">Open on the console at start</strong>
<small id="open-on-start-note">Shows this page on the TV each time you send the payload</small>
</span>
<input type="checkbox" class="switch" id="open-on-start" role="switch"
aria-labelledby="open-on-start-title" aria-describedby="open-on-start-note">
</div>
<div class="setting" id="threshold-setting">
<label for="threshold" style="display:contents">
<div>
<strong>Counts as transferring above</strong>
<span>For "While transferring", in either direction</span>
</div>
</label>
</label>
<label class="setting" id="threshold-setting">
<span class="text">
<strong>Counts as transferring above</strong>
<small>For "While transferring", in either direction</small>
</span>
<select id="threshold">
<option value="100">100 KB/s</option>
<option value="500">500 KB/s</option>
<option value="1024">1 MB/s</option>
<option value="5120">5 MB/s</option>
</select>
</div>
<div class="setting" id="quiet-setting">
<label for="quiet" style="display:contents">
<div>
<strong>Stay awake after a transfer</strong>
<span>Covers pauses between files before the console can rest</span>
</div>
</label>
</label>
<label class="setting" id="quiet-setting">
<span class="text">
<strong>Stay awake after a transfer</strong>
<small>Covers pauses between files before the console can rest</small>
</span>
<select id="quiet">
<option value="2">2 minutes</option>
<option value="5">5 minutes</option>
@@ -352,7 +346,7 @@ button.link.confirm { color: var(--danger); font-weight: 600; }
<option value="15">15 minutes</option>
<option value="30">30 minutes</option>
</select>
</div>
</label>
<p class="settings-error" id="settings-error" hidden>Couldn't save that setting. Try again.</p>
</section>
@@ -370,11 +364,12 @@ button.link.confirm { color: var(--danger); font-weight: 600; }
</main>
<script>
/* QR-BEGIN
Minimal QR code encoder: byte mode, error correction level M,
versions 1-6 (up to 106 bytes). Follows the structure of Project Nayuki's
QR Code generator. qrEncode(text, mask?) returns a square array of rows of
booleans (true = dark). */
/* Small QR code encoder: byte mode, error correction level M, versions 1-6
(up to 106 bytes). Based on Project Nayuki's QR Code generator,
Copyright (c) Project Nayuki, MIT License (see LICENSE).
https://www.nayuki.io/page/qr-code-generator-library
qrEncode(text) returns rows of booleans, true = dark. Throws if the text
doesn't fit. */
var qrEncode = (function () {
var ECC = [0, 10, 16, 26, 18, 24, 16]; // EC codewords per block, level M
var BLOCKS = [0, 1, 1, 1, 2, 2, 4]; // number of blocks, level M
@@ -409,7 +404,7 @@ var qrEncode = (function () {
return r;
}
return function (text, forceMask) {
return function (text) {
var bytes = Array.prototype.slice.call(new TextEncoder().encode(text));
for (var v = 1; v <= 6 && bytes.length + 2 > dataCodewords(v); v++);
if (v > 6) throw new Error("text too long for QR");
@@ -532,20 +527,17 @@ var qrEncode = (function () {
return score;
}
var best = forceMask, bestScore = Infinity;
if (best === undefined) {
for (var m = 0; m < 8; m++) {
applyMask(m); drawFormat(m);
var s = penalty();
if (s < bestScore) { best = m; bestScore = s; }
applyMask(m);
}
var best = 0, bestScore = Infinity;
for (var m = 0; m < 8; m++) {
applyMask(m); drawFormat(m);
var s = penalty();
if (s < bestScore) { best = m; bestScore = s; }
applyMask(m);
}
applyMask(best); drawFormat(best);
return mod;
};
})();
/* QR-END */
</script>
<script>
(function () {
@@ -780,7 +772,13 @@ var qrEncode = (function () {
if (!url || url === shownUrl) return;
shownUrl = url;
$("qr").innerHTML = qrSvg(url);
try {
$("qr").innerHTML = qrSvg(url);
} catch (e) {
// Address too long for the encoder: show the link only.
$("qr").innerHTML = "";
}
$("qr").hidden = !$("qr").innerHTML;
setText("url", url.replace(/\/$/, ""));
}
@@ -815,10 +813,12 @@ var qrEncode = (function () {
.then(function (r) { if (!r.ok) throw r; return r.json(); });
}
// A failed poll stops polling and shows "Not running"; "Check again" restarts it.
function poll() {
clearTimeout(pollTimer);
request("GET", "/status")
.then(function (data) {
if (view === "closed") return;
if (!busy) { apply(data); render(); }
pollTimer = setTimeout(poll, 3000);
})
+5 -10
View File
@@ -1,8 +1,4 @@
/* KeepAwake (PS4) - keep the PS4 out of rest mode while this payload is running.
Same behaviour as the PS5 build: the idle timer is reset by periodically
calling sceSystemServicePowerTick(), and a control page is served on TCP
port 9031 (see web.h).
/* KeepAwake (PS4) - same as the PS5 build, see ps5.c.
libPS4 has no select(), so the control socket is non-blocking and polled
ten times a second. */
@@ -14,8 +10,6 @@
#define KEEPAWAKE_VERSION "dev"
#endif
#define KEEPAWAKE_PORT 9031
#define KEEPAWAKE_TICK_SECONDS 10
#define KEEPAWAKE_POLL_MS 100
#define SCE_NET_SO_RCVTIMEO 0x1006
@@ -43,7 +37,9 @@ resolve_power_tick(void) {
static int
would_block(int rc) {
return (unsigned int)rc == SCE_NET_ERROR_EAGAIN || sce_net_errno == SCE_NET_EAGAIN;
// Only a plain -1 leaves the reason in errno; anything else is a full code.
return (unsigned int)rc == SCE_NET_ERROR_EAGAIN ||
(rc == -1 && sce_net_errno == SCE_NET_EAGAIN);
}
@@ -171,8 +167,7 @@ make_addr(struct sockaddr_in *addr, unsigned int ip) {
}
/* Runs on its own thread, so the control page is served even if launching
the browser blocks. */
/* On its own thread so a slow browser launch doesn't hold up the page. */
static void*
open_browser_thread(void *arg) {
static char url[64];
+8 -12
View File
@@ -1,12 +1,9 @@
/* KeepAwake - keep the PS5 out of rest mode while this payload is running.
The console's idle timer is reset by periodically calling
sceSystemServicePowerTick(). The payload also serves a control page on
TCP port 9031 (see web.h), which
- shows the status and turns Keep Awake on and off from a browser
(and opens in the PS5's browser at start, unless turned off),
- guarantees only one instance runs at a time, and
- lets a second copy of the payload close the running one. */
The idle timer is reset by calling sceSystemServicePowerTick() every few
seconds. A control page is served on TCP port 9031 (see web.h). Holding
that port also means only one instance runs, and a second copy of the
payload asks the running one to quit. */
#include <arpa/inet.h>
#include <errno.h>
@@ -29,9 +26,6 @@
#define KEEPAWAKE_VERSION "dev"
#endif
#define KEEPAWAKE_PORT 9031
#define KEEPAWAKE_TICK_SECONDS 10
typedef struct notify_request {
char useless1[45];
@@ -166,8 +160,7 @@ web_notify(const char *msg) {
}
/* Runs on its own thread, so the control page is served even if launching
the browser blocks. */
/* On its own thread so a slow browser launch doesn't hold up the page. */
static void*
open_browser_thread(void *arg) {
char url[64];
@@ -315,6 +308,9 @@ main(void) {
if(rc > 0 && FD_ISSET(srv, &fds)) {
if((cli = accept(srv, NULL, NULL)) < 0) {
if(errno != EINTR && errno != ECONNABORTED) {
usleep(100 * 1000); // e.g. out of descriptors: don't spin
}
continue;
}
fcntl(cli, F_SETFL, fcntl(cli, F_GETFL) | O_NONBLOCK);
+117 -66
View File
@@ -1,14 +1,13 @@
/* State and tiny HTTP server for the KeepAwake control page, shared by the
PS5 and PS4 builds.
Keep Awake can be on (resetting the idle timer) or off (paused, payload
still running so it can be turned back on from the page). When on, it
runs in one of three modes:
always with no time limit
Keep Awake is either on (resetting the idle timer) or off (payload still
running, so the page can turn it back on). When on it runs in one of
three modes:
always no time limit
timer for a set time, then it turns itself off
auto only while the network is busy (a download, FTP transfer,
PKG install...), plus a quiet period after it stops
Quitting ends the payload.
auto only while the network is busy (download, FTP, PKG install),
plus a quiet period after it stops
Routes:
GET / the control page (src/index.html)
@@ -22,17 +21,24 @@
change any of the settings (saved to
KEEPAWAKE_SETTINGS)
POSTs that carry an Origin header from another host are refused, so a web
page open elsewhere on the network can't drive the console.
The platform source defines WEB_CONSOLE ("PS5" or "PS4") before including
this file, and implements the functions declared below. Client sockets are
expected to be non-blocking. */
this file and implements the functions declared below. Client sockets must
be non-blocking. */
#include "index_html.h"
#define KEEPAWAKE_PORT 9031
#define KEEPAWAKE_TICK_SECONDS 10
#define WEB_AGAIN -1
#define WEB_ERROR -2
#define WEB_TIMEOUT_MS 2000
// Requests are handled one at a time, so don't let a slow client hold on long.
#define WEB_TIMEOUT_MS 1000
#define WEB_POLL_MS 10
@@ -44,15 +50,15 @@ static int web_send(int fd, const void *buf, size_t len);
static void web_sleep_ms(int ms);
/* Seconds and milliseconds since the payload started. */
/* Time since the payload started. */
static long long web_uptime(void);
static long long web_uptime_ms(void);
/* The console's LAN IP address as text, or an empty string if unknown. */
/* The console's LAN IP address, or an empty string if unknown. */
static void web_get_ip(char *buf, size_t size);
/* Total bytes received and sent on all non-loopback interfaces.
Returns 0, or -1 if the counters can't be read. */
/* Bytes received and sent on all non-loopback interfaces. Returns -1 if the
counters can't be read. */
static int web_net_bytes(unsigned long long *rx, unsigned long long *tx);
/* Show a toast on the console. */
@@ -84,9 +90,7 @@ static long long ka_quiet_minutes = 5; // stay awake this long after a trans
#define KA_MAX_QUIET_MINUTES 120
/* --- Settings ------------------------------------------------------------ */
/* Find "key=<number>" in the settings text. Returns 1 if found. */
/* Find "key=<number>" at the start of a line. Returns 1 if found. */
static int
ka_cfg_number(const char *buf, const char *key, long long *value) {
const char *p = buf;
@@ -94,16 +98,18 @@ ka_cfg_number(const char *buf, const char *key, long long *value) {
long long n = 0;
int digits = 0;
while((p = strstr((char*)p, (char*)key))) {
while((p = strstr(p, key))) {
if((p == buf || p[-1] == '\n') && p[k] == '=') {
for(p += k + 1; *p >= '0' && *p <= '9' && digits < 9; p++, digits++) {
for(p += k + 1; *p >= '0' && *p <= '9'; p++) {
if(++digits > 9) {
return 0;
}
n = n * 10 + (*p - '0');
}
if(digits) {
*value = n;
return 1;
}
return 0;
return digits > 0;
}
p += k;
}
@@ -164,12 +170,10 @@ ka_save_settings(void) {
}
/* --- Transfer detection --------------------------------------------------
Every KA_SAMPLE_MS the interface byte counters are sampled. The speed is
the change across the last KA_SAMPLES samples (about 10 seconds), which
smooths out bursty traffic. The network counts as busy while either
direction is at or above the threshold. */
/* Transfer detection: the interface byte counters are sampled every
KA_SAMPLE_MS and the speed is the change over the last KA_SAMPLES samples
(about 10 seconds), which smooths out bursty traffic. The network counts
as busy while either direction is at or above the threshold. */
#define KA_SAMPLES 6
#define KA_SAMPLE_MS 2000
@@ -249,8 +253,7 @@ ka_sample(void) {
}
/* Seconds auto mode will keep the console awake for if nothing else is
transferred: the quiet period counting down since the last busy sample. */
/* Seconds left of the quiet period since the last busy sample. */
static long long
ka_quiet_left(void) {
long long left;
@@ -263,8 +266,6 @@ ka_quiet_left(void) {
}
/* --- On and off ---------------------------------------------------------- */
/* "1 hour 30 minutes", "2 hours", "45 minutes" */
static void
ka_format_minutes(char *buf, size_t size, long long minutes) {
@@ -292,8 +293,8 @@ ka_set_on(void) {
}
/* Turn on, for the given minutes or with no time limit (0). Also used to
change or remove the timer while already on. */
/* Turn on for the given minutes, or with no time limit (0). Also changes or
removes the timer while already on. */
static void
ka_turn_on(long long minutes) {
int was_plain_on = ka_active && !ka_until && !ka_auto;
@@ -316,7 +317,6 @@ ka_turn_on(long long minutes) {
}
/* Turn on in auto mode: awake only while transferring. */
static void
ka_turn_on_auto(void) {
if(ka_active && ka_auto) {
@@ -351,10 +351,8 @@ ka_turn_off(const char *msg) {
}
/* --- HTTP ---------------------------------------------------------------- */
/* Does the request line start with "<method> <path>", followed by a query
string or the end of the path? */
/* Does the request line start with "<method> <path>", followed by a query or
the end of the path? */
static int
web_route(const char *req, size_t len, const char *method, const char *path) {
size_t m = strlen(method);
@@ -370,8 +368,8 @@ web_route(const char *req, size_t len, const char *method, const char *path) {
}
/* Read a whole-number query parameter from the request line.
Returns 1 and sets *value if present and valid, 0 if absent, -1 if invalid. */
/* Read a whole-number query parameter. Returns 1 and sets *value if it's
there and valid, 0 if absent, -1 if invalid. */
static int
web_query_number(const char *req, size_t len, const char *key, long long *value) {
size_t k = strlen(key);
@@ -379,7 +377,7 @@ web_query_number(const char *req, size_t len, const char *key, long long *value)
long long n = 0;
int digits = 0;
// The query string runs from '?' to the space before "HTTP/1.x".
// The query runs from '?' to the space before "HTTP/1.x".
for(i = 0; i < len && req[i] != '?' && req[i] != '\r'; i++);
if(i >= len || req[i] != '?') {
return 0;
@@ -513,11 +511,15 @@ web_handle_settings(int fd, const char *req, size_t len) {
long long open_on_start = ka_open_on_start;
long long threshold = ka_threshold_kb;
long long quiet = ka_quiet_minutes;
int a = web_query_number(req, len, "open_on_start", &open_on_start);
int b = web_query_number(req, len, "auto_threshold_kb", &threshold);
int c = web_query_number(req, len, "auto_quiet_minutes", &quiet);
int old_open_on_start = ka_open_on_start;
long long old_threshold = ka_threshold_kb;
long long old_quiet = ka_quiet_minutes;
int got_open = web_query_number(req, len, "open_on_start", &open_on_start);
int got_threshold = web_query_number(req, len, "auto_threshold_kb", &threshold);
int got_quiet = web_query_number(req, len, "auto_quiet_minutes", &quiet);
if(a < 0 || b < 0 || c < 0 || (a + b + c) == 0 ||
if(got_open < 0 || got_threshold < 0 || got_quiet < 0 ||
(got_open + got_threshold + got_quiet) == 0 ||
open_on_start > 1 ||
threshold < KA_MIN_THRESHOLD_KB || threshold > KA_MAX_THRESHOLD_KB ||
quiet < KA_MIN_QUIET_MINUTES || quiet > KA_MAX_QUIET_MINUTES) {
@@ -527,10 +529,6 @@ web_handle_settings(int fd, const char *req, size_t len) {
return;
}
int old_open_on_start = ka_open_on_start;
long long old_threshold = ka_threshold_kb;
long long old_quiet = ka_quiet_minutes;
ka_open_on_start = (int)open_on_start;
ka_threshold_kb = threshold;
ka_quiet_minutes = quiet;
@@ -548,8 +546,8 @@ web_handle_settings(int fd, const char *req, size_t len) {
}
/* Read the request headers, giving up after WEB_TIMEOUT_MS so a slow or idle
client can't hold up the keep-awake loop. Returns the bytes read. */
/* Read the request headers, giving up after WEB_TIMEOUT_MS. Returns the
bytes read. */
static size_t
web_read_request(int fd, char *buf, size_t size) {
size_t len = 0;
@@ -580,20 +578,75 @@ web_read_request(int fd, char *buf, size_t size) {
}
/* Does the line at p start with "<name>:", ignoring case? */
static int
web_header_is(const char *p, const char *name) {
for(; *name; p++, name++) {
if((*p | 0x20) != (*name | 0x20)) {
return 0;
}
}
return *p == ':';
}
/* Copy the value of a request header into out. Returns 1 if it's present. */
static int
web_header(const char *req, const char *name, char *out, size_t size) {
const char *p = req;
size_t i;
while((p = strstr(p, "\r\n"))) {
p += 2;
if(web_header_is(p, name)) {
for(p += strlen(name) + 1; *p == ' '; p++);
for(i = 0; *p && *p != '\r' && i < size - 1; i++, p++) {
out[i] = *p;
}
out[i] = 0;
return 1;
}
}
return 0;
}
/* A browser sends Origin on cross-site POSTs. Refuse one that doesn't match
the host it was sent to; curl and the other instance send none. */
static int
web_origin_ok(const char *req) {
char origin[128];
char host[128];
const char *o;
if(!web_header(req, "Origin", origin, sizeof origin)) {
return 1;
}
o = strstr(origin, "://");
return o && web_header(req, "Host", host, sizeof host) &&
strlen(o + 3) == strlen(host) && memcmp(o + 3, host, strlen(host)) == 0;
}
/* Handle one client connection. Returns 1 if the payload should quit. */
static int
web_handle_client(int fd) {
char req[1024];
char req[2048];
long long minutes = 0;
long long autom = 0;
long long auto_arg = 0;
size_t len;
int rc;
int rc_auto;
int minutes_rc;
int auto_rc;
if(!(len = web_read_request(fd, req, sizeof req))) {
return 0;
}
if(memcmp(req, "POST ", 5) == 0 && !web_origin_ok(req)) {
web_respond_json(fd, "403 Forbidden", "{\"error\":\"cross-origin request\"}");
return 0;
}
if(web_route(req, len, "GET", "/") ||
web_route(req, len, "GET", "/index.html")) {
web_respond(fd, "200 OK", "text/html; charset=utf-8",
@@ -603,14 +656,14 @@ web_handle_client(int fd) {
web_respond_status(fd);
} else if(web_route(req, len, "POST", "/on")) {
rc = web_query_number(req, len, "minutes", &minutes);
rc_auto = web_query_number(req, len, "auto", &autom);
if(rc < 0 || minutes > KA_MAX_MINUTES || rc_auto < 0 || autom > 1 ||
(autom && minutes)) {
minutes_rc = web_query_number(req, len, "minutes", &minutes);
auto_rc = web_query_number(req, len, "auto", &auto_arg);
if(minutes_rc < 0 || minutes > KA_MAX_MINUTES || auto_rc < 0 ||
auto_arg > 1 || (auto_arg && minutes)) {
web_respond_json(fd, "400 Bad Request",
"{\"error\":\"use minutes=0-10080 or auto=1\"}");
} else {
if(autom) {
if(auto_arg) {
ka_turn_on_auto();
} else {
ka_turn_on(minutes);
@@ -648,11 +701,9 @@ web_handle_client(int fd) {
}
/* --- Main loop ----------------------------------------------------------- */
/* Call regularly from the main loop: samples the network, resets the idle
timer when it's due, and handles the timer and auto mode. Returns the
seconds until it next needs calling. */
/* Call from the main loop. Samples the network, resets the idle timer when
it's due and handles the timer and auto mode. Returns the seconds until it
next needs calling. */
static int
ka_tick(void) {
long long now = web_uptime();
@@ -698,7 +749,7 @@ ka_tick(void) {
}
/* The request a new instance sends to make the running one quit. */
/* What a new instance sends to make the running one quit. */
static const char web_quit_request[] =
"POST /quit HTTP/1.0\r\n"
"Host: localhost\r\n"
+3
View File
@@ -7,6 +7,7 @@
int
sceKernelSendNotificationRequest(int device, void *req, size_t size, int blocking) {
(void)device; (void)req; (void)size; (void)blocking;
return 0;
}
@@ -21,12 +22,14 @@ sceSystemServicePowerTick(void) {
int
sceUserServiceInitialize(void *param) {
(void)param;
return 0;
}
int
sceSystemServiceLaunchWebBrowser(const char *uri, void *param) {
(void)param;
printf("[KeepAwake] open browser: %s\n", uri);
fflush(stdout);
return 0;