Files
zoneminder/web/ajax/stream.php
T
Isaac ConnorandClaude Opus 4.8 64d3d772bb fix: let the UI tell zms which event is next/prev for gapless playback refs #4186
When an event is streamed by zms (the MJPEG/mpeg path, not the video.js MP4
player), zms advanced to the next/prev event itself with a hardcoded query:

  SELECT Id FROM Events WHERE MonitorId = <same> AND Id <>> <current> ...

That ignores the filter and sort the user is viewing, so gapless playback of a
cross-monitor filtered list skipped every event that did not belong to the
current event's monitor -- e.g. playing monitor A's event jumped straight to
A's next event, hopping over all the interleaved monitor B events. The earlier
getNearEvents fix only corrected the video.js path and the Prev/Next buttons;
this zms auto-advance was a separate path and still wrong.

Rather than reimplement filter/sort knowledge in C++, let the UI -- which
already computes the correct next/prev from the active filter via getNearEvents
-- tell zms which events those are. A new CMD_SET_EVENT command carries a
direction, a target event id, and the source event the hint was computed for;
EventStream stores them and checkEventLoaded loads the UI-provided event when
advancing. When the UI has not supplied a usable hint it falls back to the
existing by-monitor query, so behaviour is unchanged for clients that do not
send the command.

The event view sends CMD_SET_EVENT for both next and prev after each
getNearEvents response, but only when playback is served by zms (vid == null);
the video.js path already navigates correctly on its own.

Hardening in this path:

- Authorisation: zms only authorises the event the stream started on and loads
  forwarded targets without re-checking, so a client could hand it an event
  from a monitor it cannot view. ajax/stream.php now resolves the target's
  monitor and requires canView('Events', MonitorId) before forwarding (gated on
  ZM_OPT_USE_AUTH, matching zms).

- Filter boundaries: getNearEvents returns 0 when the filter has no neighbour
  in a direction. A hint now records whether the UI supplied a value, so an
  explicit 0 stops at the boundary instead of being treated as "no hint" and
  falling back to the same-monitor query (which would leave the filtered list).

- Stale hints: next and prev arrive as separate requests and can land out of
  order. Each hint carries the source event id; processCommand refuses to store
  one whose source is not the event playing (so a late command cannot overwrite
  a valid hint), and checkEventLoaded honours a stored hint only while its
  source still matches. The event view tags each hint with the getNearEvents
  response's own EventId, not the current event, so a slow response cannot send
  a self-referential hint that loops zms on one event.

- Deleted targets: a cached neighbour may be removed by retention or another
  user before it is used. checkEventLoaded checks existence first and falls back
  rather than hitting loadEventData's fatal "not found" path; ajax/stream.php
  treats a target that no longer exists as a filter boundary instead of
  returning an error that would flag the stream broken and stop UI polling.

- Cross-resolution MPEG: the mpeg encoder is created once at the first event's
  dimensions and cannot resize mid-stream. Frame and text-frame paths share a
  scaleToEncoder() helper that scales a later, differently sized image (a
  cross-monitor advance, or a boundary text frame built at another monitor's
  size) to the encoder's dimensions before encoding rather than overrunning its
  buffers.

- Portable packing: stream.php encodes the ids as big-endian 32-bit words
  instead of pack('J'), which 32-bit PHP (still supported in the status decode)
  cannot feed a 64-bit value.

Known limitation: in a multi-server install with non-shared storage a
cross-monitor neighbour can live on another server, whose recording this zms
cannot read. Such an advance degrades to failed frames; zms self-advance is
effectively same-server (or shared-storage) only. Routing it to the serving
server, as the video.js reload path does, is left to a separate change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 18:43:43 -04:00

299 lines
13 KiB
PHP

<?php
ini_set('display_errors', '');
$start_time = time();
$connkey = sprintf('%06d', $_REQUEST['connkey']);
define('MSG_TIMEOUT', ZM_WEB_AJAX_TIMEOUT/2);
define('MSG_DATA_SIZE', 4+256);
/* Failure classes reported to the client as 'reason'. The client needs to
* tell "zms is gone, start a new one" apart from "this particular exchange
* failed", because restarting the stream replaces the connkey and makes any
* still-running zms unreachable.
*
* no_socket - zms is not listening: it never started, or it has exited.
* The only class where restarting the stream is the right answer.
* timeout - the command went out but no reply came back in time. zms is
* most likely alive and busy.
* transient - a failure local to this php process (socket setup, a short
* read). Says nothing at all about zms.
* invalid - bad request or an unexpected reply. Retrying will not help.
*/
define('STREAM_ERR_NO_SOCKET', 'no_socket');
define('STREAM_ERR_TIMEOUT', 'timeout');
define('STREAM_ERR_TRANSIENT', 'transient');
define('STREAM_ERR_INVALID', 'invalid');
if ( !($_REQUEST['connkey'] && $_REQUEST['command']) ) {
ajaxError('No connkey or no command in stream ajax', HTTP_STATUS_OK, STREAM_ERR_INVALID);
}
@mkdir(ZM_PATH_SOCKS);
# The file that we point ftok to has to exist, and only exist if zms is running, so we are pointing it at the .sock
$key = $connkey;
$semaphore = sem_get($key, 1);
$have_semaphore = false;
if ($semaphore) {
$semaphore_tries = 10;
while ($semaphore_tries) {
if (version_compare( phpversion(), '5.6.1', '<')) {
# don't have support for non-blocking
$have_semaphore = sem_acquire($semaphore);
} else {
$have_semaphore = sem_acquire($semaphore, 1);
}
if ($have_semaphore !== false) break;
ZM\Debug('Failed to get semaphore for '.$connkey.' '.$key.', trying again');
usleep(100000);
$semaphore_tries -= 1;
}
} else {
ZM\Error("Failed to get semaphore for key $key. It is likely that your php does not have the sysv semaphore extension either installed or enabled.");
}
if (!($socket = @socket_create(AF_UNIX, SOCK_DGRAM, 0))) {
if ($semaphore) sem_release($semaphore);
ajaxError('socket_create() failed: '.socket_strerror(socket_last_error()), HTTP_STATUS_OK, STREAM_ERR_TRANSIENT);
}
$localSocketFile = ZM_PATH_SOCKS.'/zms-'.$connkey.'w.sock';
if (!socket_bind($socket, $localSocketFile)) {
if ($semaphore) sem_release($semaphore);
ajaxError("socket_bind( $localSocketFile ) failed: ".socket_strerror(socket_last_error()), HTTP_STATUS_OK, STREAM_ERR_TRANSIENT);
}
switch ($_REQUEST['command']) {
case CMD_VARPLAY :
ZM\Debug('Varplaying to '.$_REQUEST['rate']);
$msg = pack('lcn', MSG_CMD, $_REQUEST['command'], $_REQUEST['rate']+32768);
break;
case CMD_ZOOMIN :
ZM\Debug('Zooming to '.$_REQUEST['x'].','.$_REQUEST['y']);
$msg = pack('lcnn', MSG_CMD, $_REQUEST['command'], $_REQUEST['x'], $_REQUEST['y']);
break;
case CMD_PAN :
ZM\Debug('Panning to '.$_REQUEST['x'].','.$_REQUEST['y']);
$msg = pack('lcnn', MSG_CMD, $_REQUEST['command'], $_REQUEST['x'], $_REQUEST['y']);
break;
case CMD_SCALE :
ZM\Debug('Scaling to '.$_REQUEST['scale']);
$msg = pack('lcn', MSG_CMD, $_REQUEST['command'], $_REQUEST['scale']);
break;
case CMD_SEEK :
# Pack int two 32 bit integers instead of trying to deal with floats
$msg = pack('lcNN', MSG_CMD, $_REQUEST['command'],
intval($_REQUEST['offset']),
1000000*( $_REQUEST['offset']-intval($_REQUEST['offset'])));
break;
case CMD_MAXFPS :
if (!floatval($_REQUEST['maxfps'])) $_REQUEST['maxfps'] = 0;
ZM\Debug('Maxfps to '.$_REQUEST['maxfps']);
# Pack int two 32 bit integers instead of trying to deal with floats
$msg = pack('lcNN', MSG_CMD, $_REQUEST['command'],
intval($_REQUEST['maxfps']),
1000000*( $_REQUEST['maxfps']-intval($_REQUEST['maxfps'])));
break;
case CMD_SET_EVENT :
# Tell zms which event is next (dir=0) or prev (dir=1) in the UI's filter/sort
# (refs #4186). Payload: dir byte, target event id (big-endian uint64, 0 = no
# neighbour in the filter), then the source event id the hint was computed
# against (big-endian 48-bit) so zms can discard stale hints.
global $user;
$dir = intval($_REQUEST['dir']);
# Keep ids as strings so packEventId*() need not go through a 32-bit intval().
$eventid = isset($_REQUEST['eventid']) ? $_REQUEST['eventid'] : 0;
$srcid = isset($_REQUEST['srcid']) ? $_REQUEST['srcid'] : 0;
# zms authorises only the event the stream started on; it loads whatever
# target we forward without re-checking. So a client could hand us an event
# from a monitor it cannot view and advance into that footage. Resolve the
# target's monitor and require view permission here, where the session user is
# known. Gated on ZM_OPT_USE_AUTH to match zms, which only validates event
# access when auth is on; 0 carries no event (filter boundary) and needs no
# check.
if (ZM_OPT_USE_AUTH && $eventid) {
$monitorId = dbFetchOne('SELECT `MonitorId` FROM `Events` WHERE `Id`=?', 'MonitorId', array($eventid));
if (!$monitorId) {
# Retention or another user deleted the neighbour between getNearEvents and
# now. That is a benign race, not a privilege problem, so do not ajaxError:
# getCmdResponse() would set zmsBroke=true and can stop the UI's status
# polling even though zms is fine. Forward it as a filter boundary (0) so
# zms pauses cleanly instead of advancing.
ZM\Debug('SET_EVENT target '.$eventid.' no longer exists; treating as filter boundary');
$eventid = 0;
} else if (!canView('Events', $monitorId)) {
if ($semaphore) sem_release($semaphore);
ajaxError('Insufficient privileges for event '.$eventid, HTTP_STATUS_OK, STREAM_ERR_INVALID);
}
}
ZM\Debug('Setting '.($dir ? 'prev' : 'next').' event to '.$eventid.' (source '.$srcid.')');
$msg = pack('lcC', MSG_CMD, $_REQUEST['command'], $dir)
.packEventId64($eventid)
.packEventId48($srcid);
break;
default :
ZM\Debug('Sending command ' . $_REQUEST['command']);
$msg = pack('lc', MSG_CMD, $_REQUEST['command']);
break;
}
$remSockFile = ZM_PATH_SOCKS.'/zms-'.$connkey.'s.sock';
// Pi can take up to 3 seconds for zms to start up.
$max_socket_tries = 1000;
// FIXME This should not exceed web_ajax_timeout
while ( !file_exists($remSockFile) && $max_socket_tries-- ) {
//sometimes we are too fast for our own good, if it hasn't been setup yet give it a second.
// WHY? We will just send another one...
// ANSWER: Because otherwise we get a log of errors logged
//ZM\Debug("$remSockFile does not exist, waiting, current " . (time() - $start_time) . ' seconds' );
usleep(1000);
}
if (!file_exists($remSockFile)) {
if ($semaphore) sem_release($semaphore);
ajaxError("Socket $remSockFile does not exist. This file is created by zms, and since it does not exist, either zms did not run, or zms exited early. Please check your zms logs and ensure that CGI is enabled in apache and check that the PATH_ZMS is set correctly. Make sure that ZM is actually recording. If you are trying to view a live stream and the capture process (zmc) is not running then zms will exit. Please go to http://zoneminder.readthedocs.io/en/latest/faq.html#why-can-t-i-see-streamed-images-when-i-can-see-stills-in-the-zone-window-etc for more information.", HTTP_STATUS_OK, STREAM_ERR_NO_SOCKET);
} else {
if (!@socket_sendto($socket, $msg, strlen($msg), 0, $remSockFile)) {
if ($semaphore) sem_release($semaphore);
ajaxError("socket_sendto( $remSockFile ) failed: ".socket_strerror(socket_last_error()), HTTP_STATUS_OK, STREAM_ERR_NO_SOCKET);
}
}
$rSockets = array($socket);
$wSockets = NULL;
$eSockets = NULL;
$select_timed_out = false;
$timeout = MSG_TIMEOUT - ( time() - $start_time );
$numSockets = socket_select($rSockets, $wSockets, $eSockets, intval($timeout/1000), ($timeout%1000)*1000);
if ( $numSockets === false ) {
if ($semaphore) sem_release($semaphore);
ajaxError('socket_select failed: '.socket_strerror(socket_last_error()), HTTP_STATUS_OK, STREAM_ERR_TRANSIENT);
} else if ( $numSockets < 0 ) {
if ($semaphore) sem_release($semaphore);
ajaxError("Socket closed $remSockFile", HTTP_STATUS_OK, STREAM_ERR_NO_SOCKET);
} else if ( $numSockets == 0 ) {
ZM\Error("Timed out waiting for msg $remSockFile after waiting $timeout milliseconds");
socket_set_nonblock($socket);
// Not an error on its own: the socket is now non-blocking, so the recvfrom
// below returns immediately and reports this as a timeout rather than
// pretending zms had nothing to say.
$select_timed_out = true;
#ajaxError("Timed out waiting for msg $remSockFile");
} else if ( $numSockets > 0 ) {
if ( count($rSockets) != 1 ) {
if ($semaphore) sem_release($semaphore);
ajaxError('Bogus return from select, '.count($rSockets).' sockets available', HTTP_STATUS_OK, STREAM_ERR_TRANSIENT);
}
}
$nbytes = @socket_recvfrom($socket, $msg, MSG_DATA_SIZE, 0, $remSockFile);
if ($semaphore) sem_release($semaphore);
switch ($nbytes) {
case -1 :
ajaxError("socket_recvfrom( $remSockFile ) failed: ".socket_strerror(socket_last_error()), HTTP_STATUS_OK, STREAM_ERR_TRANSIENT);
break;
case 0 :
// socket_recvfrom() returns false on error, and false == 0 under switch's
// loose comparison, so a timed-out select lands here rather than on -1.
if ($select_timed_out) {
ajaxError("Timed out waiting for msg $remSockFile after waiting $timeout milliseconds",
HTTP_STATUS_OK, STREAM_ERR_TIMEOUT);
} else {
ajaxError('No data to read from socket', HTTP_STATUS_OK, STREAM_ERR_TRANSIENT);
}
break;
default :
if ( $nbytes != MSG_DATA_SIZE ) {
ajaxError("Got unexpected message size, got $nbytes, expected ".MSG_DATA_SIZE, HTTP_STATUS_OK, STREAM_ERR_TRANSIENT);
}
break;
}
$data = unpack('ltype', $msg);
switch ( $data['type'] ) {
case MSG_DATA_WATCH :
$data = unpack('ltype/imonitor/istate/dfps/dcapturefps/danalysisfps/ilevel/irate/ddelay/izoom/iscale/Cdelayed/Cpaused/Cenabled/Cforced/iscore/ianalysing/Canalysisimage/Cstopped', $msg);
$data['fps'] = round( $data['fps'], 2 );
$data['capturefps'] = round( $data['capturefps'], 2 );
$data['analysisfps'] = round( $data['analysisfps'], 2 );
$data['rate'] /= RATE_BASE;
$data['delay'] = round( $data['delay'], 2 );
$data['zoom'] = round( $data['zoom']/SCALE_BASE, 1 );
#$data['scale'] = $data['scale'];
if (ZM_OPT_USE_AUTH) {
if (ZM_AUTH_RELAY == 'hashed') {
# Send the hash unconditionally. Withholding it when it matched the hash
# the request carried meant a client whose copy had drifted could never be
# corrected, and reconnecting streams then baked the drifted hash into
# their <img> src and 403'd against zms indefinitely.
$data['auth'] = generateAuthHash(ZM_AUTH_HASH_IPS);
}
$data['auth_relay'] = get_auth_relay();
}
ajaxResponse(array('status'=>$data));
break;
case MSG_DATA_EVENT :
if ( PHP_INT_SIZE===4 || version_compare( phpversion(), '5.6.0', '<') ) {
ZM\Debug('Using old unpack methods to handle 64bit event id');
$data = unpack('ltype/ieventlow/ieventhigh/dduration/dprogress/dfps/irate/izoom/iscale/Cpaused/Cstopped', $msg);
$data['event'] = $data['eventhigh'] << 32 | $data['eventlow'];
} else {
$data = unpack('ltype/Qevent/dduration/dprogress/dfps/irate/izoom/iscale/Cpaused/Cstopped', $msg);
}
$data['rate'] /= RATE_BASE;
$data['zoom'] = round($data['zoom']/SCALE_BASE, 1);
$data['fps'] = round( $data['fps'], 2 );
if ( ZM_OPT_USE_AUTH ) {
if (ZM_AUTH_RELAY == 'hashed') {
# Unconditional, for the reason given in the MSG_DATA_WATCH branch above.
$data['auth'] = generateAuthHash(ZM_AUTH_HASH_IPS);
}
$data['auth_relay'] = get_auth_relay();
}
ajaxResponse(array('status'=>$data));
break;
default :
ajaxError('Unexpected received message type '.$data['type'], HTTP_STATUS_OK, STREAM_ERR_INVALID);
}
ajaxError('Unrecognised action or insufficient permissions in ajax/stream', HTTP_STATUS_OK, STREAM_ERR_INVALID);
function ajaxCleanup() {
global $socket, $localSocketFile;
if ( !empty($socket) )
@socket_close($socket);
if ( !empty($localSocketFile) )
@unlink($localSocketFile);
}
# Big-endian uint64 as two 32-bit words. Avoids pack('J') (needs a 64-bit PHP
# int) and intval() truncation on 32-bit PHP, which this endpoint still supports
# (see the two-word MSG_DATA_EVENT decode above). On 32-bit PHP an id above 2^31
# cannot be represented at all, so the high word is simply 0.
function packEventId64($value) {
if (PHP_INT_SIZE >= 8) {
$v = intval($value);
return pack('NN', ($v >> 32) & 0xFFFFFFFF, $v & 0xFFFFFFFF);
}
return pack('NN', 0, intval($value));
}
# Big-endian 48-bit id (16-bit high word + 32-bit low word = 6 bytes), used for
# the source event id, which only needs to match zms' current event; see
# packEventId64 for the 32/64-bit handling.
function packEventId48($value) {
if (PHP_INT_SIZE >= 8) {
$v = intval($value);
return pack('nN', ($v >> 32) & 0xFFFF, $v & 0xFFFFFFFF);
}
return pack('nN', 0, intval($value));
}
?>